diff --git a/workflow/engine/bin/reindex_solr.php b/workflow/engine/bin/reindex_solr.php index bcc230176..5558831c8 100644 --- a/workflow/engine/bin/reindex_solr.php +++ b/workflow/engine/bin/reindex_solr.php @@ -1,6 +1,6 @@ 3) { if($argv [$argNumber] == '-appuid') { //use skip option $appUid = $argv [$argNumber + 1]; - } + } } else { print $commandLineSyntaxMsg; @@ -73,11 +73,19 @@ if(count ($argv) > 3) { } } +$debug = 1; ini_set ('display_errors', 1); -error_reporting (E_ALL); +//error_reporting (E_ALL); ini_set ('memory_limit', '256M'); // set enough memory for the script +$e_all = defined( 'E_DEPRECATED' ) ? E_ALL & ~ E_DEPRECATED : E_ALL; +$e_all = defined( 'E_STRICT' ) ? $e_all & ~ E_STRICT : $e_all; +$e_all = $debug ? $e_all : $e_all & ~ E_NOTICE; + +ini_set( 'error_reporting', $e_all ); + + if (! defined ('SYS_LANG')) { define ('SYS_LANG', 'en'); } @@ -98,13 +106,16 @@ if (! defined ('PATH_HOME')) { array_pop ($docuroot); $pathOutTrunk = implode (PATH_SEP, $docuroot) . PATH_SEP; // to do: check previous algorith for Windows $pathTrunk = "c:/home/"; - + define ('PATH_HOME', $pathhome); define ('PATH_TRUNK', $pathTrunk); define ('PATH_OUTTRUNK', $pathOutTrunk); - + require_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php'); - + require_once (PATH_GULLIVER . "class.bootstrap.php"); + Bootstrap::registerSystemClasses(); + spl_autoload_register(array('Bootstrap', 'autoloadClass')); + G::LoadThirdParty ('pear/json', 'class.json'); G::LoadThirdParty ('smarty/libs', 'Smarty.class'); G::LoadSystem ('error'); @@ -129,23 +140,10 @@ if (! defined ('PATH_HOME')) { require_once ("creole/Creole.php"); } -if (file_exists(PATH_HOME . "engine" . PATH_SEP . "config" . PATH_SEP . "paths_installed.php")) { - require_once (PATH_HOME . "engine" . PATH_SEP . "config" . PATH_SEP . "paths_installed.php"); -} - -require_once (PATH_HOME . "engine" . PATH_SEP . "config" . PATH_SEP . "paths.php"); -require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.system.php"); - -require_once (PATH_GULLIVER . "class.bootstrap.php"); - -spl_autoload_register(array("Bootstrap", "autoloadClass")); - -Bootstrap::registerSystemClasses(); - -//require_once 'classes/model/AppDelegation.php'; -//require_once 'classes/model/Event.php'; -//require_once 'classes/model/AppEvent.php'; -//require_once 'classes/model/CaseScheduler.php'; +require_once 'classes/model/AppDelegation.php'; +require_once 'classes/model/Event.php'; +require_once 'classes/model/AppEvent.php'; +require_once 'classes/model/CaseScheduler.php'; // G::loadClass('pmScript'); // //default values @@ -171,36 +169,36 @@ if (! defined ('SYS_SYS')) { $sObject = $workspaceName; $sNow = ''; // $argv[2]; $sFilter = ''; - + for ($i = 3; $i < count ($argv); $i++) { $sFilter .= ' ' . $argv [$i]; } - + $oDirectory = dir (PATH_DB); - + if (is_dir (PATH_DB . $sObject)) { saveLog ('main', 'action', "checking folder " . PATH_DB . $sObject); if (file_exists (PATH_DB . $sObject . PATH_SEP . 'db.php')) { - + define ('SYS_SYS', $sObject); - + // **************************************** // read initialize file - //require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; + require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; $config = System::getSystemConfiguration ('', '', SYS_SYS); define ('MEMCACHED_ENABLED', $config ['memcached']); define ('MEMCACHED_SERVER', $config ['memcached_server']); define ('TIME_ZONE', $config ['time_zone']); - + date_default_timezone_set (TIME_ZONE); print "TIME_ZONE: " . TIME_ZONE . "\n"; print "MEMCACHED_ENABLED: " . MEMCACHED_ENABLED . "\n"; print "MEMCACHED_SERVER: " . MEMCACHED_SERVER . "\n"; // **************************************** - - //include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths_installed.php'); - //include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php'); - + + include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths_installed.php'); + include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php'); + // ***************** PM Paths DATA ************************** define ('PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/'); define ('PATH_DOCUMENT', PATH_DATA_SITE . 'files/'); @@ -210,7 +208,7 @@ if (! defined ('SYS_SYS')) { define ('PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/'); define ('PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP); define ('PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP); - + // server info file if (is_file (PATH_DATA_SITE . PATH_SEP . '.server_info')) { $SERVER_INFO = file_get_contents (PATH_DATA_SITE . PATH_SEP . '.server_info'); @@ -222,10 +220,10 @@ if (! defined ('SYS_SYS')) { else { eprintln ("WARNING! No server info found!", 'red'); } - + // read db configuration $sContent = file_get_contents (PATH_DB . $sObject . PATH_SEP . 'db.php'); - + $sContent = str_replace ('', '', $sContent); @@ -233,7 +231,7 @@ if (! defined ('SYS_SYS')) { $sContent = str_replace ("('", "$", $sContent); $sContent = str_replace ("',", '=', $sContent); $sContent = str_replace (");", ';', $sContent); - + eval ($sContent); $dsn = $DB_ADAPTER . '://' . $DB_USER . ':' . $DB_PASS . '@' . $DB_HOST . '/' . $DB_NAME; $dsnRbac = $DB_ADAPTER . '://' . $DB_RBAC_USER . ':' . $DB_RBAC_PASS . '@' . $DB_RBAC_HOST . '/' . $DB_RBAC_NAME; @@ -265,7 +263,7 @@ if (! defined ('SYS_SYS')) { fclose ($oFile); Propel::init (PATH_CORE . 'config/_databases_.php'); // Creole::registerDriver('dbarray', 'creole.contrib.DBArrayConnection'); - + eprintln ("Processing workspace: " . $sObject, 'green'); try { processWorkspace (); @@ -295,16 +293,16 @@ function processWorkspace() global $SkipRecords; global $TrunkSize; global $appUid; - + try { - + if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { G::LoadClass ('AppSolr'); print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; print "solr_host: " . $solrConf ['solr_host'] . "\n"; print "solr_instance: " . $solrConf ['solr_instance'] . "\n"; - + $oAppSolr = new AppSolr ($solrConf ['solr_enabled'], $solrConf ['solr_host'], $solrConf ['solr_instance']); if ($ScriptAction == "reindexall") { $oAppSolr->reindexAllApplications ($SkipRecords, $TrunkSize); @@ -319,13 +317,13 @@ function processWorkspace() if($appUid == ""){ print "Missing -appuid parameter. please complete it with this option.\n"; } - $oAppSolr->updateApplicationSearchIndex ($appUid); + $oAppSolr->updateApplicationSearchIndex ($appUid, false); } } else { print "Incomplete Solr configuration. See configuration file: " . PATH_DATA_SITE . "env.ini"; } - + } catch (Exception $oError) { saveLog ("main", "error", "Error processing workspace : " . $oError->getMessage () . "\n"); @@ -339,7 +337,7 @@ function saveLog($sSource, $sType, $sDescription) if ($isDebug) print date ('H:i:s') . " ($sSource) $sType $sDescription
\n"; @fwrite ($oFile, date ('Y-m-d H:i:s') . '(' . $sSource . ') ' . $sDescription . "\n"); - + G::verifyPath (PATH_DATA . 'log' . PATH_SEP, true); if ($sType == 'action') { $oFile = @fopen (PATH_DATA . 'log' . PATH_SEP . 'cron.log', 'a+'); @@ -360,7 +358,7 @@ function setExecutionMessage($m) $len = strlen ($m); $linesize = 60; $rOffset = $linesize - $len; - + eprint ("* $m"); for ($i = 0; $i < $rOffset; $i++) eprint ('.'); @@ -375,4 +373,3 @@ function setExecutionResultMessage($m, $t = '') $c = 'yellow'; eprintln ("[$m]", $c); } - diff --git a/workflow/engine/bin/verify_solr.php b/workflow/engine/bin/verify_solr.php new file mode 100644 index 000000000..5d5147a16 --- /dev/null +++ b/workflow/engine/bin/verify_solr.php @@ -0,0 +1,554 @@ +. + * + * For more information, contact Colosa Inc, 5304 Ventura Drive, + * Delray Beach, FL, 33484, USA, or email info@colosa.com. + * + */ + +// check script parameters +// php reindex_solr.php workspacename [reindexall|reindexmissing|optimizeindex] [-skip 1005] [-reindextrunksize 1000] +// var_dump($argv); +//(count ($argv) == 4) || ((count ($argv) == 5) && ($argv [3] != '-skip')) +$commandLineSyntaxMsg = "Invalid command line arguments: \n " . + "Verify the list of cases comparing db vs solr lists by user if usr_uid is specify only verify one user otherwhise all users ". + "syntax: ". + "php verify_solr.php [workspace_name] [-usruid {USR_UID}]\n" . + " Where \n". + " workspace_name : is the workspace that is being verified. \n" . + " Optional Options: \n" . + " -usruid {USR_UID}: verify only one user with the specified user uid. \n "; + +if ( (count ($argv) < 2) || ((count ($argv) > 2) && ((count ($argv) % 2) != 0))) { + print $commandLineSyntaxMsg; + die (); +} +$workspaceName = $argv [1]; +$usrUid = ""; + +if((count ($argv) > 2)){ + $usrUid = $argv [3]; +} + +ini_set ('display_errors', 1); +error_reporting (E_ALL); +ini_set ('memory_limit', '256M'); // set enough memory for the script + +if (! defined ('SYS_LANG')) { + define ('SYS_LANG', 'en'); +} + +if (! defined ('PATH_HOME')) { + if (! defined ('PATH_SEP')) { + define ('PATH_SEP', (substr (PHP_OS, 0, 3) == 'WIN') ? '\\' : '/'); + } + $docuroot = explode (PATH_SEP, str_replace ('engine' . PATH_SEP . 'methods' . PATH_SEP . 'services', '', dirname (__FILE__))); + array_pop ($docuroot); + array_pop ($docuroot); + $pathhome = implode (PATH_SEP, $docuroot) . PATH_SEP; + // try to find automatically the trunk directory where are placed the RBAC and + // Gulliver directories + // in a normal installation you don't need to change it. + array_pop ($docuroot); + $pathTrunk = implode (PATH_SEP, $docuroot) . PATH_SEP; + array_pop ($docuroot); + $pathOutTrunk = implode (PATH_SEP, $docuroot) . PATH_SEP; + // to do: check previous algorith for Windows $pathTrunk = "c:/home/"; + + define ('PATH_HOME', $pathhome); + define ('PATH_TRUNK', $pathTrunk); + define ('PATH_OUTTRUNK', $pathOutTrunk); + + require_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php'); + + G::LoadThirdParty ('pear/json', 'class.json'); + G::LoadThirdParty ('smarty/libs', 'Smarty.class'); + G::LoadSystem ('error'); + G::LoadSystem ('dbconnection'); + G::LoadSystem ('dbsession'); + G::LoadSystem ('dbrecordset'); + G::LoadSystem ('dbtable'); + G::LoadSystem ('rbac'); + G::LoadSystem ('publisher'); + G::LoadSystem ('templatePower'); + G::LoadSystem ('xmlDocument'); + G::LoadSystem ('xmlform'); + G::LoadSystem ('xmlformExtension'); + G::LoadSystem ('form'); + G::LoadSystem ('menu'); + G::LoadSystem ("xmlMenu"); + G::LoadSystem ('dvEditor'); + G::LoadSystem ('table'); + G::LoadSystem ('pagedTable'); + G::LoadClass ('system'); + require_once ("propel/Propel.php"); + require_once ("creole/Creole.php"); +} + +require_once 'classes/model/AppDelegation.php'; +require_once 'classes/model/Event.php'; +require_once 'classes/model/AppEvent.php'; +require_once 'classes/model/CaseScheduler.php'; +// G::loadClass('pmScript'); + +// //default values +// $bCronIsRunning = false; +// $sLastExecution = ''; +// if ( file_exists(PATH_DATA . 'cron') ) { +// $aAux = unserialize( trim( @file_get_contents(PATH_DATA . 'cron')) ); +// $bCronIsRunning = (boolean)$aAux['bCronIsRunning']; +// $sLastExecution = $aAux['sLastExecution']; +// } +// else { +// //if not exists the file, just create a new one with current date +// @file_put_contents(PATH_DATA . 'cron', serialize(array('bCronIsRunning' => +// '1', 'sLastExecution' => date('Y-m-d H:i:s')))); +// } + +print "PATH_HOME: " . PATH_HOME . "\n"; +print "PATH_DB: " . PATH_DB . "\n"; +print "PATH_CORE: " . PATH_CORE . "\n"; + +// define the site name (instance name) +if (! defined ('SYS_SYS')) { + $sObject = $workspaceName; + $sNow = ''; // $argv[2]; + /* + $sFilter = ''; + + for ($i = 3; $i < count ($argv); $i++) { + $sFilter .= ' ' . $argv [$i]; + }*/ + + $oDirectory = dir (PATH_DB); + + if (is_dir (PATH_DB . $sObject)) { + saveLog ('main', 'action', "checking folder " . PATH_DB . $sObject); + if (file_exists (PATH_DB . $sObject . PATH_SEP . 'db.php')) { + + define ('SYS_SYS', $sObject); + + // **************************************** + // read initialize file + require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; + $config = System::getSystemConfiguration ('', '', SYS_SYS); + define ('MEMCACHED_ENABLED', $config ['memcached']); + define ('MEMCACHED_SERVER', $config ['memcached_server']); + define ('TIME_ZONE', $config ['time_zone']); + + date_default_timezone_set (TIME_ZONE); + print "TIME_ZONE: " . TIME_ZONE . "\n"; + print "MEMCACHED_ENABLED: " . MEMCACHED_ENABLED . "\n"; + print "MEMCACHED_SERVER: " . MEMCACHED_SERVER . "\n"; + // **************************************** + + include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths_installed.php'); + include_once (PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths.php'); + + // ***************** PM Paths DATA ************************** + define ('PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/'); + define ('PATH_DOCUMENT', PATH_DATA_SITE . 'files/'); + define ('PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/'); + define ('PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/'); + define ('PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/'); + define ('PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/'); + define ('PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP); + define ('PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP); + + // server info file + if (is_file (PATH_DATA_SITE . PATH_SEP . '.server_info')) { + $SERVER_INFO = file_get_contents (PATH_DATA_SITE . PATH_SEP . '.server_info'); + $SERVER_INFO = unserialize ($SERVER_INFO); + // print_r($SERVER_INFO); + define ('SERVER_NAME', $SERVER_INFO ['SERVER_NAME']); + define ('SERVER_PORT', $SERVER_INFO ['SERVER_PORT']); + } + else { + eprintln ("WARNING! No server info found!", 'red'); + } + + // read db configuration + $sContent = file_get_contents (PATH_DB . $sObject . PATH_SEP . 'db.php'); + + $sContent = str_replace ('', '', $sContent); + $sContent = str_replace ('define', '', $sContent); + $sContent = str_replace ("('", "$", $sContent); + $sContent = str_replace ("',", '=', $sContent); + $sContent = str_replace (");", ';', $sContent); + + eval ($sContent); + $dsn = $DB_ADAPTER . '://' . $DB_USER . ':' . $DB_PASS . '@' . $DB_HOST . '/' . $DB_NAME; + $dsnRbac = $DB_ADAPTER . '://' . $DB_RBAC_USER . ':' . $DB_RBAC_PASS . '@' . $DB_RBAC_HOST . '/' . $DB_RBAC_NAME; + $dsnRp = $DB_ADAPTER . '://' . $DB_REPORT_USER . ':' . $DB_REPORT_PASS . '@' . $DB_REPORT_HOST . '/' . $DB_REPORT_NAME; + switch ($DB_ADAPTER) { + case 'mysql' : + $dsn .= '?encoding=utf8'; + $dsnRbac .= '?encoding=utf8'; + break; + case 'mssql' : + // $dsn .= '?sendStringAsUnicode=false'; + // $dsnRbac .= '?sendStringAsUnicode=false'; + break; + default : + break; + } + // initialize db + $pro ['datasources'] ['workflow'] ['connection'] = $dsn; + $pro ['datasources'] ['workflow'] ['adapter'] = $DB_ADAPTER; + $pro ['datasources'] ['rbac'] ['connection'] = $dsnRbac; + $pro ['datasources'] ['rbac'] ['adapter'] = $DB_ADAPTER; + $pro ['datasources'] ['rp'] ['connection'] = $dsnRp; + $pro ['datasources'] ['rp'] ['adapter'] = $DB_ADAPTER; + // $pro['datasources']['dbarray']['connection'] = + // 'dbarray://user:pass@localhost/pm_os'; + // $pro['datasources']['dbarray']['adapter'] = 'dbarray'; + $oFile = fopen (PATH_CORE . 'config/_databases_.php', 'w'); + fwrite ($oFile, ''); + fclose ($oFile); + Propel::init (PATH_CORE . 'config/_databases_.php'); + // Creole::registerDriver('dbarray', 'creole.contrib.DBArrayConnection'); + + eprintln ("Processing workspace: " . $sObject, 'green'); + try { + processWorkspace (); + } + catch (Exception $e) { + echo $e->getMessage (); + eprintln ("Problem in workspace: " . $sObject . ' it was omitted.', 'red'); + } + eprintln (); + unlink (PATH_CORE . 'config/_databases_.php'); + } + } + +} +else { + processWorkspace (); +} + +// finally update the file +// @file_put_contents(PATH_DATA . 'cron', serialize(array('bCronIsRunning' => +// '0', 'sLastExecution' => date('Y-m-d H:i:s')))); + +function processWorkspace() +{ + global $sLastExecution; + global $ScriptAction; + //global $SkipRecords; + //global $TrunkSize; + global $usrUid; + + try { + + //if $usrUid is not set get all the users + + //verify inbox + verifyInboxList($usrUid); + + //verify draft + verifyDraftList($usrUid); + + //verify participated list + verifyParticipatedList($usrUid); + + //verify unassigned list + verifyUnassignedList($usrUid); + + } + catch (Exception $oError) { + saveLog ("main", "error", "Error processing workspace : " . $oError->getMessage () . "\n"); + } +} + +function verifyInboxList($usrUid) +{ + print "***********************\n"; + print "Verify Inbox list: \n"; + print "***********************\n"; + + $result = getListUids($usrUid, 'todo'); + + $aAppUidsDB = $result['aDBAppUids']; + $aAppUidsSolr = $result['aSolrAppUids']; + + displayMissingCases($aAppUidsDB, $aAppUidsSolr); +} + +function verifyDraftList($usrUid) +{ + print "***********************\n"; + print "Verify Draft list: \n"; + print "***********************\n"; + + $result = getListUids($usrUid, 'draft'); + + $aAppUidsDB = $result['aDBAppUids']; + $aAppUidsSolr = $result['aSolrAppUids']; + + displayMissingCases($aAppUidsDB, $aAppUidsSolr); +} + +function verifyParticipatedList($usrUid) +{ + print "******************************\n"; + print "Verify Participated list: \n"; + print "******************************\n"; + + $result = getListUids($usrUid, 'sent'); + + $aAppUidsDB = $result['aDBAppUids']; + $aAppUidsSolr = $result['aSolrAppUids']; + + displayMissingCases($aAppUidsDB, $aAppUidsSolr); +} + +function verifyUnassignedList($usrUid) +{ + print "******************************\n"; + print "Verify Unassigned list: \n"; + print "******************************\n"; + + $result = getListUids($usrUid, 'unassigned'); + + $aAppUidsDB = $result['aDBAppUids']; + $aAppUidsSolr = $result['aSolrAppUids']; + + displayMissingCases($aAppUidsDB, $aAppUidsSolr); +} + +function displayMissingCases($aAppUidsDB, $aAppUidsSolr) +{ + //verify missing records + //verify size + print " Number of cases: DB:" . count($aAppUidsDB) . " Solr:" . count($aAppUidsSolr) . "\n"; + // + if( count($aAppUidsDB) != count($aAppUidsSolr) ){ + print " Different number of cases !!! \n"; + } + + $casesInDBNotSolr = array_diff($aAppUidsDB, $aAppUidsSolr); + $casesInSolrNotDB = array_diff($aAppUidsSolr, $aAppUidsDB); + + print " Cases in DB but not in Solr: \n"; + foreach($casesInDBNotSolr as $caseDB){ + print " ". $caseDB . " \n"; + } + print " Cases in Solr but not in DB: \n"; + foreach($casesInSolrNotDB as $caseSolr){ + print " ". $caseSolr . " \n"; + } +} + +function getListUids($usrUid, $action) +{ + if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { + G::LoadClass ('AppSolr'); + print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; + print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; + print "solr_host: " . $solrConf ['solr_host'] . "\n"; + print "solr_instance: " . $solrConf ['solr_instance'] . "\n"; + + $oAppSolr = new AppSolr ($solrConf ['solr_enabled'], $solrConf ['solr_host'], $solrConf ['solr_instance']); + + G::LoadClass("applications"); + $apps = new Applications(); + } + else { + print "Incomplete Solr configuration. See configuration file: " . PATH_DATA_SITE . "env.ini"; + return; + } + //get the list of id's + $userUid = $usrUid; + $start = 0; + $limit = 1; + $action = $action; //todo, + $filter = ''; + $search = ''; + $process = ''; + $user = ''; + $status = ''; + $type = 'extjs'; + $dateFrom = ''; + $dateTo = ''; + $callback = 'stcCallback1001'; + $dir = 'DESC'; + $sort = 'APP_NUMBER'; + $category = ''; + + $dataSolr = $oAppSolr->getAppGridData( + $userUid, + $start, + $limit, + $action, + $filter, + $search, + $process, + $user, + $status, + $type, + $dateFrom, + $dateTo, + $callback, + $dir, + $sort + ); + + + $dataDB = $apps->getAll( + $userUid, + $start, + $limit, + $action, + $filter, + $search, + $process, + $user, + $status, + $type, + $dateFrom, + $dateTo, + $callback, + $dir, + $sort, + $category + ); + + $aAppUidsSolr = array(); + $aAppUidsDB = array(); + $trunkSize = 1000; + + //get DB uids + print "Get DB Uids \n"; + $totalCasesDB = $dataDB["totalCount"]; + $loops = ((($totalCasesDB % $trunkSize) > 0 )? ($totalCasesDB / $trunkSize)+1: ($totalCasesDB / $trunkSize)); + for ($i = 0; $i < $loops; $i++) { + $start = $i * $trunkSize; + $limit = $trunkSize; + //print " Loop $start to " . (String)($start + $trunkSize) . " \n"; + + $dataDB = $apps->getAll( + $userUid, + $start, + $limit, + $action, + $filter, + $search, + $process, + $user, + $status, + $type, + $dateFrom, + $dateTo, + $callback, + $dir, + $sort, + $category + ); + foreach($dataDB["data"] as $caseDB){ + $aAppUidsDB[] = $caseDB["APP_UID"]; + } + } + + //get Solr uids + print "Get Solr Uids \n"; + $totalCasesSolr = $dataSolr["totalCount"]; + $loops = ((($totalCasesSolr % $trunkSize) > 0 )? ($totalCasesSolr / $trunkSize)+1: ($totalCasesSolr / $trunkSize)); + for ($i = 0; $i < $loops; $i++) { + $start = $i * $trunkSize; + $limit = $trunkSize; + //print " Loop $start to " . (String)($start + $trunkSize) . " \n"; + + $dataSolr = $oAppSolr->getAppGridData( + $userUid, + $start, + $limit, + $action, + $filter, + $search, + $process, + $user, + $status, + $type, + $dateFrom, + $dateTo, + $callback, + $dir, + $sort + ); + + foreach($dataSolr["data"] as $caseSolr){ + $aAppUidsSolr[] = $caseSolr["APP_UID"]; + } + } + + $result = array(); + $result['total_cases_db'] = $totalCasesDB; + $result['aDBAppUids'] = $aAppUidsDB; + $result['total_cases_solr'] = $totalCasesSolr; + $result['aSolrAppUids'] = $aAppUidsSolr; + + + return $result; +} + +function saveLog($sSource, $sType, $sDescription) +{ + try { + global $isDebug; + if ($isDebug) + print date ('H:i:s') . " ($sSource) $sType $sDescription
\n"; + @fwrite ($oFile, date ('Y-m-d H:i:s') . '(' . $sSource . ') ' . $sDescription . "\n"); + + G::verifyPath (PATH_DATA . 'log' . PATH_SEP, true); + if ($sType == 'action') { + $oFile = @fopen (PATH_DATA . 'log' . PATH_SEP . 'cron.log', 'a+'); + } + else { + $oFile = @fopen (PATH_DATA . 'log' . PATH_SEP . 'cronError.log', 'a+'); + } + @fwrite ($oFile, date ('Y-m-d H:i:s') . '(' . $sSource . ') ' . $sDescription . "\n"); + @fclose ($oFile); + } + catch (Exception $oError) { + // CONTINUE + } +} + +function setExecutionMessage($m) +{ + $len = strlen ($m); + $linesize = 60; + $rOffset = $linesize - $len; + + eprint ("* $m"); + for ($i = 0; $i < $rOffset; $i++) + eprint ('.'); +} + +function setExecutionResultMessage($m, $t = '') +{ + $c = 'green'; + if ($t == 'error') + $c = 'red'; + if ($t == 'info') + $c = 'yellow'; + eprintln ("[$m]", $c); +} diff --git a/workflow/engine/classes/class.AppSolr.php b/workflow/engine/classes/class.AppSolr.php index aa8ddec2e..e64d51a10 100644 --- a/workflow/engine/classes/class.AppSolr.php +++ b/workflow/engine/classes/class.AppSolr.php @@ -1,6 +1,6 @@ code}]: {$this->message}\n"; - } + // Redefine the exception so message isn't optional + public function __construct($message, $code = 0) + { + // some code + // make sure everything is assigned properly + parent::__construct ($message, $code); + } + + // custom string representation of object + public function __toString() + { + return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; + } } /** * Application without Delegations exception * * @author Herbert Saal Gutierrez - * + * * @category Colosa * @copyright Copyright (c) 2005-2012 Colosa Inc. (http://www.colosa.com) */ class ApplicationWithoutDelegationRecordsException extends Exception { - // Redefine the exception so message isn't optional - public function __construct ($message, $code = 0) - { - // some code - // make sure everything is assigned properly - parent::__construct( $message, $code ); - } - - // custom string representation of object - public function __toString () - { - return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; - } + // Redefine the exception so message isn't optional + public function __construct($message, $code = 0) + { + // some code + // make sure everything is assigned properly + parent::__construct ($message, $code); + } + + // custom string representation of object + public function __toString() + { + return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; + } } /** @@ -95,19 +95,19 @@ class ApplicationWithoutDelegationRecordsException extends Exception */ class ApplicationWithCorruptDynaformException extends Exception { - // Redefine the exception so message isn't optional - public function __construct ($message, $code = 0) - { - // some code - // make sure everything is assigned properly - parent::__construct( $message, $code ); - } + // Redefine the exception so message isn't optional + public function __construct($message, $code = 0) + { + // some code + // make sure everything is assigned properly + parent::__construct ($message, $code); + } - // custom string representation of object - public function __toString () - { - return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; - } + // custom string representation of object + public function __toString() + { + return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; + } } /** @@ -120,20 +120,38 @@ class ApplicationWithCorruptDynaformException extends Exception */ class ApplicationAPP_DATAUnserializeException extends Exception { - // Redefine the exception so message isn't optional - public function __construct ($message, $code = 0) - { - // some code - // make sure everything is assigned properly - parent::__construct( $message, $code ); - } + // Redefine the exception so message isn't optional + public function __construct($message, $code = 0) + { + // some code + // make sure everything is assigned properly + parent::__construct ($message, $code); + } - // custom string representation of object - public function __toString () - { - return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; - } + // custom string representation of object + public function __toString() + { + return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; + } } +/* +class CheckSolrAvailability +{ + private static _classInstance = null; + private static _SolrIsAvailable = true; + + private function __construct($SolrEnabled, $SolrHost, $SolrInstance) + { + // define solr availability + $this->_solrIsEnabled = $SolrEnabled; + $this->_solrHost = $SolrHost; + $this->_solrInstance = $SolrInstance; + } + + public function getInstance(){ + if() + } +}*/ /** * Implementation to display application data in the PMOS2 grids using Solr @@ -146,1653 +164,2163 @@ class ApplicationAPP_DATAUnserializeException extends Exception */ class AppSolr { - private $_solrIsEnabled = false; - private $_solrHost = ""; - private $_solrInstance = ""; - private $debug = false; //false - private $debugAppInfo = false; + private $_solrIsEnabled = false; + private $_solrHost = ""; + private $_solrInstance = ""; + private $debug = false; //false + private $debugAppInfo = false; + + public function __construct($SolrEnabled, $SolrHost, $SolrInstance) + { + // define solr availability + $this->_solrIsEnabled = $this->isSolrEnabled(); + $this->_solrHost = $SolrHost; + $this->_solrInstance = $SolrInstance; + } + + /** + * Return if the Solr server is currently working. + * @return boolean true:enabled functionality, false:disabled functionality + */ + public function isSolrEnabled() + { + G::LoadClass ('searchIndex'); + $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + // execute query + $solrStatusResult = $searchIndex->isEnabled ($this->_solrInstance); + return $solrStatusResult; + } + + /** + * Gets the information of Grids using Solr server. + * + * Returns the list of records for the grid depending of the function + * conditions + * If doCount is true only the count of records is returned. + * + * @param string $userUid + * current logged user. + * @param int $start + * the offset to return the group of records. Used for pagination. + * @param int $limit + * The number of records to return in the set. + * @param string $action + * the action: todo, participated, draft, unassigned + * @param string $filter + * filter the results posible values ('read', 'unread', 'started', + * 'completed') + * @param string $search + * search string + * @param string $process + * PRO_UID to filter results by specified process. + * @param string $user + * USR_UID to filter results by specified user. + * @param string $status + * filter by an application Status : TO_DO, COMPLETED, DRAFT + * @param string $type + * default extjs + * @param string $dateFrom + * filter by DEL_DELEGATE_DATE, not used + * @param string $dateTo + * filter by DEL_DELEGATE_DATE, not used + * @param string $callback + * default stcCallback1001 not used + * @param string $dir + * sort direction ASC, DESC + * @param string $sort + * sort field + * @param boolean $doCount + * default=false, if true only the count of records is returned. + * @return array return the list of cases + */ + public function getAppGridData( + $userUid, + $start = null, + $limit = null, + $action = null, + $filter = null, + $search = null, + $process = null, + $status = null, + $type = null, + $dateFrom = null, + $dateTo = null, + $callback = null, + $dir = null, + $sort = 'APP_CACHE_VIEW.APP_NUMBER', + $category = null, + $doCount = false + ) { + + $callback = isset ($callback) ? $callback : 'stcCallback1001'; + $dir = isset ($dir) ? $dir : 'DESC'; // direction of sort column + // (ASC, DESC) + $sort = isset ($sort) ? $sort : ''; // sort column (APP_NUMBER, + // CASE_SUMMARY, + // CASE_NOTES_COUNT, APP_TITLE, + // APP_PRO_TITLE, APP_TAS_TITLE, + // APP_DEL_PREVIOUS_USER, + // DEL_TASK_DUE_DATE, + // APP_UPDATE_DATE, DEL_PRIORITY) + $start = isset ($start) ? $start : '0'; + $limit = isset ($limit) ? $limit : '25'; + $filter = isset ($filter) ? $filter : ''; // posible values ('read', + // 'unread', 'started', + // 'completed') + $search = isset ($search) ? $search : ''; // search in fields, plain text + $process = isset ($process) ? $process : ''; // filter by an specific + // process + // uid + $user = $userUid; // filter by an specific user uid + $status = isset ($status) ? strtoupper ($status) : ''; // filter by an + // specific + // app_status + $action = isset ($action) ? $action : 'todo'; // todo, paused + $type = isset ($type) ? $type : 'extjs'; + $dateFrom = isset ($dateFrom) ? $dateFrom : ''; // filter by + // DEL_DELEGATE_DATE + $dateTo = isset ($dateTo) ? $dateTo : ''; // filter by DEL_DELEGATE_DATE + + $swErrorInSearchText = false; + $solrQueryResult = null; + $aPriorities = array('1'=>'VL', '2'=>'L', '3'=>'N', '4'=>'H', '5'=>'VH'); + $delegationIndexes = array(); + + $result = array (); + $result ['totalCount'] = 0; + $result ['data'] = array (); + $result ['success'] = false; + $result ['message'] = "Error description."; + + G::LoadClass ('searchIndex'); + + try { + if($this->debug) + { + $this->initTimeAll = microtime (true); + } + + // the array of data that must be returned with placeholders + /*$columsToInclude = array ( + 'APP_CREATE_DATE', + 'APP_NUMBER', + 'APP_PRO_TITLE', + 'APP_STATUS', + 'APP_TITLE', + 'APP_UID', + 'DEL_LAST_UPDATE_DATE', + 'DEL_MAX_PRIORITY', + 'PRO_UID' + );*/ - public function __construct ($SolrEnabled, $SolrHost, $SolrInstance) - { - // define solr availability - $this->_solrIsEnabled = $SolrEnabled; - $this->_solrHost = $SolrHost; - $this->_solrInstance = $SolrInstance; - } + $columsToInclude = array ( + 'APP_PRO_TITLE', + 'APP_TITLE', + 'APP_UID', + 'DEL_MAX_PRIORITY' + ); - /** - * Return if the Solr server is currently working. - * - * @return boolean true:enabled functionality, false:disabled functionality - */ - public function isSolrEnabled () - { - G::LoadClass("searchIndex"); + // create pagination data + $solrSearchText = ""; + $sortableCols = array (); + $sortCols = array (); + $sortDir = array (); + $numSortingCols = 0; + + // define sort conditions, default APP_NUMBER, desc + // only one column is sorted + $dir = strtolower ($dir); + + if (! empty ($sort)) { + switch ($sort) { + case 'APP_CACHE_VIEW.APP_NUMBER' : + case 'APP_NUMBER' : + $sortCols [0] = 'APP_NUMBER'; //4; + //$sortableCols [0] = 'true'; + $sortDir [0] = $dir; + break; + // multivalue field can't be ordered + case 'APP_TITLE' : + $sortCols [0] = 'APP_TITLE'; //10; + //$sortableCols [0] = 'true'; + $sortDir [0] = $dir; + break; + case 'APP_PRO_TITLE' : + $sortCols [0] = 'APP_PRO_TITLE'; //6; + //$sortableCols [0] = 'true'; + $sortDir [0] = $dir; + break; + case 'APP_UPDATE_DATE' : + $sortCols [0] = 'DEL_LAST_UPDATE_DATE'; //12; + //$sortableCols [0] = 'true'; + $sortDir [0] = $dir; + break; + default : + $sortCols [0] = 'APP_NUMBER'; //4; + //$sortableCols [0] = 'true'; + $sortDir [0] = 'desc'; + break; + } + $numSortingCols ++; + } + + // get del_index field + $delIndexDynaField = ""; + // process filter + if ($process != '') { + $solrSearchText .= "PRO_UID:" . $process . " AND "; + } + // status filter + if ($status != '') { + $solrSearchText .= "APP_STATUS:" . $status . " AND "; + } + //Category filter + if (!empty($category)) { + $solrSearchText .= "PRO_CATEGORY_UID_s:" . $category . " AND "; + } + + // todo list, add condition + if ($userUid != null && $action == 'todo') { + if ($filter == 'read') { + $solrSearchText .= "APP_ASSIGNED_USERS_READ:" . $userUid . " AND "; + $delegationIndexes[] = "APP_ASSIGNED_USER_READ_DEL_INDEX_" . trim ($userUid) . '_txt'; + } + elseif ($filter == 'unread') { + $solrSearchText .= "APP_ASSIGNED_USERS_UNREAD:" . $userUid . " AND "; + $delegationIndexes[] = "APP_ASSIGNED_USER_UNREAD_DEL_INDEX_" . trim ($userUid) . '_txt'; + } + else { + $solrSearchText .= "APP_ASSIGNED_USERS:" . $userUid . " AND "; + $delegationIndexes[] = "APP_ASSIGNED_USER_DEL_INDEX_" . trim ($userUid) . '_txt'; + } + } + // participated, add condition + if ($userUid != null && $action == 'sent') { + if ($filter == 'started') { + $solrSearchText .= "APP_PARTICIPATED_USERS_STARTED:" . $userUid . " AND "; + $delegationIndexes[] = "APP_PARTICIPATED_USER_STARTED_DEL_INDEX_" . trim ($userUid) . '_txt'; + } + elseif ($filter == 'completed') { + $solrSearchText .= "APP_PARTICIPATED_USERS_COMPLETED:" . $userUid . " AND "; + $delegationIndexes[] = "APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_" . trim ($userUid) . '_txt'; + } + else { + $solrSearchText .= "APP_PARTICIPATED_USERS:" . $userUid . " AND "; + //$delegationIndexes[] = "APP_PARTICIPATED_USER_DEL_INDEX_" . trim ($userUid) . '_txt'; + //show the last index of the case + $delegationIndexes[] = "DEL_LAST_INDEX"; + } + } + // draft, add condition + if ($userUid != null && $action == 'draft') { + $solrSearchText .= "APP_DRAFT_USER:" . $userUid . " AND "; + // index is allways 1 + } + // unassigned, add condition + if ($userUid != null && $action == 'unassigned') { + // get the list of groups to which belongs the user. + $userGroups = $this->getUserGroups ($userUid); - $searchIndex = new BpmnEngine_Services_SearchIndex($this->_solrIsEnabled, $this->_solrHost); + $solrSearchText .= "(APP_UNASSIGNED_USERS:" . $userUid; + if (count ($userGroups) > 0) { + $solrSearchText .= " OR "; + + foreach ($userGroups as $group) { + $solrSearchText .= "APP_UNASSIGNED_GROUPS:" . $group ['GRP_UID'] . " OR "; + } + + // remove last OR in condition + if ($solrSearchText != '') + $solrSearchText = substr_replace ($solrSearchText, "", - 4); + } + $solrSearchText .= ") AND "; + + $delegationIndexes[] = "APP_UNASSIGNED_USER_GROUP_DEL_INDEX_" . trim ($userUid) . '_txt'; + foreach ($userGroups as $group) { + $delegationIndexes[] = "APP_UNASSIGNED_USER_GROUP_DEL_INDEX_" . trim ($group ['GRP_UID']) . '_txt'; + } + } + + //search action + if ($action == 'search'){ + if($dateFrom != "" || $dateTo != "") { + $fromDate = ($dateFrom != '')? date ("Y-m-d", strtotime ($dateFrom)): '*'; + $toDate = ($dateTo != '') ? date ("Y-m-d", strtotime ($dateTo)): '*'; + + $searchDateOriginal = "DEL_LAST_UPDATE_DATE:[" . $fromDate . " TO " . $toDate . "]"; + //FechaRegistro:[2011-04-15 TO 2011-04-30] + + $searchDateFormatedSolr = $this->getSearchText ($searchDateOriginal); + + $solrSearchText .= "(" . $searchDateFormatedSolr . ") AND "; + } - //Execute query - $solrStatusResult = $searchIndex->isEnabled($this->_solrInstance); + //verify if we need to filter by user + if($user != ''){ + $solrSearchText .= "(APP_PARTICIPATED_USERS:" . $user . ") AND "; + } + //in all cases of search show the last index of the case + $delegationIndexes[] = "DEL_LAST_INDEX"; + } + + // remove last AND in condition + if ($solrSearchText != '') + $solrSearchText = substr_replace ($solrSearchText, "", - 5); + + // add parenthesis to Solr search text + if ($solrSearchText != "") + $solrSearchText = "(" . $solrSearchText . ")"; + + // create query string, add query conditions + if ($search != '') { + // format search string + // return exception in case of invalid text + $search = $this->getSearchText ($search); + + if ($solrSearchText != "" && $search != "") + $solrSearchText .= " AND "; + if ($search != "") + $solrSearchText .= "(" . $search . ")"; + } + // add del_index dynamic fields to list of resulting columns + $columsToIncludeFinal = array(); + $columsToIncludeFinal = array_merge ($columsToInclude, $delegationIndexes); + + // if is a counter no records are returned + if ($doCount) { + $start = 0; + $limit = 0; + $numSortingCols = 0; + $columsToIncludeFinal = array (); + } + + $data = array ( + 'workspace' => $this->_solrInstance, // solr instance + 'startAfter' => intval ($start), + 'pageSize' => intval ($limit), + 'searchText' => $solrSearchText, + 'filterText' => '', // $filter, //ex:'field1:value1,field2:[value2.1 + // TO value2.2],field3:value3' + 'numSortingCols' => $numSortingCols, + 'sortableCols' => $sortableCols, + 'sortCols' => $sortCols, + 'sortDir' => $sortDir, + 'includeCols' => $columsToIncludeFinal, + 'resultFormat' => 'json' + ); + + $solrRequestData = Entity_SolrRequestData::createForRequestPagination ($data); + // use search index to return list of cases + $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + // execute query + $solrQueryResult = $searchIndex->getDataTablePaginatedList ($solrRequestData); + + if($this->debug) + { + $this->afterSolrQueryTime = microtime (true); + } + //return inmediatelly + if ($doCount) { + $result ['totalCount'] = $solrQueryResult->iTotalDisplayRecords; + $result ['data'] = array(); + $result ['success'] = true; + $result ['result'] = true; + $result ['message'] = ""; + + return $result; + } + // complete return data, complete list of columns in grid + $resultColumns = array ( + "APP_CREATE_DATE", + "APP_CURRENT_USER", + "APP_DEL_PREVIOUS_USER", + "APP_FINISH_DATE", + "APP_NUMBER", + "APP_OVERDUE_PERCENTAGE", + "APP_PRO_TITLE", + "APP_STATUS", + "APP_TAS_TITLE", + "APP_THREAD_STATUS", + "APP_TITLE", + "APP_UID", + "APP_UPDATE_DATE", + "DEL_DELAYED", + "DEL_DELAY_DURATION", + "DEL_DELEGATE_DATE", + "DEL_DURATION", + "DEL_FINISHED", + "DEL_FINISH_DATE", + "DEL_INDEX", + "DEL_INIT_DATE", + "DEL_PRIORITY", + "DEL_QUEUE_DURATION", + "DEL_STARTED", + "DEL_TASK_DUE_DATE", + "DEL_THREAD_STATUS", + "PREVIOUS_USR_UID", + "PRO_UID", + "TAS_UID", + "USR_UID" + ); + + $rows = array (); + // number of found records + $result ['totalCount'] = $solrQueryResult->iTotalDisplayRecords; - return $solrStatusResult; - } + //var_dump($solrQueryResult->aaData); die; - /** - * Gets the Solr string for todo cases - * - * Return the Solr string for todo cases - * - * @param string $userUid The user ID - * @param string $filter Filter the results posible values ("read", "unread") - * @return string Solr string - */ - public function getToDoSolrString($userUid, $filter) - { - $strSolr = "APP_STATUS:TO_DO"; - $strDelgIndex = null; + //get the missing data from database + $appUids = array(); + foreach ($solrQueryResult->aaData as $i => $data) { + $appUids[] = $data ['APP_UID'];//APP_UID + } + + $aaappsDBData = $this->getListApplicationDelegationData ($appUids); + + if($this->debug) + { + $this->afterDbQueryTime = microtime (true); + } + //**************************************************************** + //Begin the list of Cases and define which delegations are display + //to complete the data for each delegation + //**************************************************************** + // complete the missing data to display it in the grid. + $delIndexes = array(); //store all the delegation indexes + foreach ($solrQueryResult->aaData as $i => $data) { + //initialize array + $delIndexes = array(); + // complete empty values + $appUID = $data ['APP_UID'];//APP_UID + //get all the indexes returned by Solr as columns + for($i = count($columsToInclude) ; $i < count($data) ; $i++) { + //var_dump($data [$columsToIncludeFinal[$i]]); - if (!empty($userUid)) { - switch ($filter) { - case "read": - $strSolr = "APP_ASSIGNED_USERS_READ:" . $userUid; - $strDelgIndex = "APP_ASSIGNED_USER_READ_DEL_INDEX_" . $userUid . "_txt"; - break; - case "unread": - $strSolr = "APP_ASSIGNED_USERS_UNREAD:" . $userUid; - $strDelgIndex = "APP_ASSIGNED_USER_UNREAD_DEL_INDEX_" . $userUid . "_txt"; - break; - default: - $strSolr = "APP_ASSIGNED_USERS:" . $userUid; - $strDelgIndex = "APP_ASSIGNED_USER_DEL_INDEX_" . $userUid . "_txt"; - break; + if (is_array ($data [$columsToIncludeFinal[$i]])) { + foreach($data [$columsToIncludeFinal[$i]] as $delIndex){ + $delIndexes[] = $delIndex; } + } } + // verify if the delindex is an array + // if is not check different types of repositories + // the delegation index must always be defined. + if (count($delIndexes) == 0) { + // if is draft + if ($action == 'draft') { + $delIndexes [] = 1; // the first default index + } + /*elseif ($action == 'search') { + // get all the indexes - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for draft cases - * - * Return the Solr string for draft cases - * - * @param string $userUid The user ID - * @return string Solr string - */ - public function getDraftSolrString($userUid) - { - $strSolr = "APP_STATUS:DRAFT"; - $strDelgIndex = null; - - if (!empty($userUid)) { - $strSolr = "APP_DRAFT_USER:" . $userUid; - $strDelgIndex = "APP_DRAFT_USER_DEL_INDEX_" . $userUid . "_txt"; - } - - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for paused cases - * - * Return the Solr string for paused cases - * - * @param string $userUid The user ID - * @return string Solr string - */ - public function getPausedSolrString($userUid) - { - $strSolr = "APP_STATUS:PAUSED"; - $strDelgIndex = null; - - if (!empty($userUid)) { - $strSolr = "APP_PAUSED_USERS:" . $userUid; - $strDelgIndex = "APP_PAUSED_USERS_DEL_INDEX_" . $userUid . "_txt"; - } - - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for cancelled cases - * - * Return the Solr string for cancelled cases - * - * @param string $userUid The user ID - * @return string Solr string - */ - public function getCancelledSolrString($userUid) - { - $strSolr = "APP_STATUS:CANCELLED"; - $strDelgIndex = null; - - if (!empty($userUid)) { - $strSolr = "APP_CANCELLED_USER_txt:" . $userUid; - $strDelgIndex = "APP_CANCELLED_USER_DEL_INDEX_" . $userUid . "_txt"; - } - - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for completed cases - * - * Return the Solr string for completed cases - * - * @param string $userUid The user ID - * @return string Solr string - */ - public function getCompletedSolrString($userUid) - { - $strSolr = "APP_STATUS:COMPLETED"; - $strDelgIndex = null; - - if (!empty($userUid)) { - $strSolr = "APP_PARTICIPATED_USERS_COMPLETED:" . $userUid; - $strDelgIndex = "APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_" . $userUid . "_txt"; - } - - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for sent cases - * - * Return the Solr string for sent cases - * - * @param string $userUid The user ID - * @param string $filter Filter the results posible values ("started", "completed") - * @return string Solr string - */ - public function getSentSolrString($userUid, $filter) - { - $strSolr = null; - $strDelgIndex = null; - - if (!empty($userUid)) { - switch ($filter) { - case "started": - $strSolr = "APP_PARTICIPATED_USERS_STARTED:" . $userUid; - $strDelgIndex = "APP_PARTICIPATED_USER_STARTED_DEL_INDEX_" . $userUid . "_txt"; - break; - case "completed": - $strSolr = "APP_PARTICIPATED_USERS_COMPLETED:" . $userUid; - $strDelgIndex = "APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_" . $userUid . "_txt"; - break; - default: - $strSolr = "APP_PARTICIPATED_USERS:" . $userUid; - $strDelgIndex = "APP_PARTICIPATED_USER_DEL_INDEX_" . $userUid . "_txt"; - break; - } - } - - return array($strSolr, $strDelgIndex); - } - - /** - * Gets the Solr string for all cases - * - * Return the Solr string for all cases - * - * @param string $userUid The user ID - * @return string Solr string - */ - public function getAllSolrString($userUid) - { - $strSolr = "(APP_STATUS:TO_DO OR - APP_STATUS:DRAFT OR - APP_STATUS:PAUSED OR - APP_STATUS:CANCELLED OR - APP_STATUS:COMPLETED - )"; - $arrayDelgIndex = array(); - - if (!empty($userUid)) { - $strSolr = "("; - - //ToDo - $strSolr = $strSolr . "APP_ASSIGNED_USERS:" . $userUid; - $arrayDelgIndex[] = "APP_ASSIGNED_USER_DEL_INDEX_" . $userUid . "_txt"; - - $strSolr = $strSolr . " OR "; - - //Draft - $strSolr = $strSolr . "APP_DRAFT_USER:" . $userUid; - $arrayDelgIndex[] = "APP_DRAFT_USER_DEL_INDEX_" . $userUid . "_txt"; - - $strSolr = $strSolr . " OR "; - - //Paused - $strSolr = $strSolr . "APP_PAUSED_USERS:" . $userUid; - $arrayDelgIndex[] = "APP_PAUSED_USERS_DEL_INDEX_" . $userUid . "_txt"; - - $strSolr = $strSolr . " OR "; - - //Cancelled - $strSolr = $strSolr . "APP_CANCELLED_USER_txt:" . $userUid; - $arrayDelgIndex[] = "APP_CANCELLED_USER_DEL_INDEX_" . $userUid . "_txt"; - - $strSolr = $strSolr . " OR "; - - //Completed - $strSolr = $strSolr . "APP_PARTICIPATED_USERS_COMPLETED:" . $userUid; - $arrayDelgIndex[] = "APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_" . $userUid . "_txt"; - - $strSolr = $strSolr . ")"; - } - - return array($strSolr, $arrayDelgIndex); - } - - /** - * Gets the information of Grids using Solr server. - * - * Returns the list of records for the grid depending of the function - * conditions - * If doCount is true only the count of records is returned. - * - * @param string $userUid current logged user. - * @param int $start the offset to return the group of records. Used for pagination. - * @param int $limit The number of records to return in the set. - * @param string $action the action: todo, participated, draft, unassigned - * @param string $filter filter the results posible values ('read', 'unread', 'started', - * 'completed') - * @param string $search search string - * @param string $process PRO_UID to filter results by specified process. - * @param string $user USR_UID to filter results by specified user. - * @param string $status filter by an application Status : TO_DO, COMPLETED, DRAFT - * @param string $type default extjs - * @param string $dateFrom filter by DEL_DELEGATE_DATE, not used - * @param string $dateTo filter by DEL_DELEGATE_DATE, not used - * @param string $callback default stcCallback1001 not used - * @param string $dir sort direction ASC, DESC - * @param string $sort sort field - * @param boolean $doCount default=false, if true only the count of records is returned. - * @return array return the list of cases - */ - public function getAppGridData( - $userUid, - $start = null, - $limit = null, - $action = null, - $filter = null, - $search = null, - $process = null, - $status = null, - $type = null, - $dateFrom = null, - $dateTo = null, - $callback = null, - $dir = null, - $sort = "APP_CACHE_VIEW.APP_NUMBER", - $category = null, - $doCount = false - ) { - $callback = isset( $callback ) ? $callback : 'stcCallback1001'; - $dir = isset( $dir ) ? $dir : 'DESC'; // direction of sort column - // (ASC, DESC) - $sort = isset( $sort ) ? $sort : ''; // sort column (APP_NUMBER, - // CASE_SUMMARY, - // CASE_NOTES_COUNT, APP_TITLE, - // APP_PRO_TITLE, APP_TAS_TITLE, - // APP_DEL_PREVIOUS_USER, - // DEL_TASK_DUE_DATE, - // APP_UPDATE_DATE, DEL_PRIORITY) - $start = isset( $start ) ? $start : '0'; - $limit = isset( $limit ) ? $limit : '25'; - $filter = isset( $filter ) ? $filter : ''; // posible values ('read', - // 'unread', 'started', - // 'completed') - $search = isset( $search ) ? $search : ''; // search in fields, plain text - $process = isset( $process ) ? $process : ''; // filter by an specific - // process - // uid - $status = isset( $status ) ? strtoupper( $status ) : ''; // filter by an - // specific - // app_status - $action = isset( $action ) ? $action : 'todo'; // todo, paused - $type = isset( $type ) ? $type : 'extjs'; - $dateFrom = isset( $dateFrom ) ? $dateFrom : ''; // filter by - // DEL_DELEGATE_DATE - $dateTo = isset( $dateTo ) ? $dateTo : ''; // filter by DEL_DELEGATE_DATE - - $swErrorInSearchText = false; - $solrQueryResult = null; - $aPriorities = array ('1' => 'VL','2' => 'L','3' => 'N','4' => 'H','5' => 'VH' - ); - $delegationIndexes = array (); - - $result = array (); - $result['totalCount'] = 0; - $result['data'] = array (); - $result['success'] = false; - $result['message'] = "Error description."; - - G::LoadClass( 'searchIndex' ); - - try { - if ($this->debug) { - $this->initTimeAll = microtime( true ); + //$delIndexes = $this->getApplicationDelegationsIndex ($appUID); + $indexes = $this->aaSearchRecords ($aaappsDBData, array ( + 'APP_UID' => $appUID + )); + + foreach ($indexes as $index) { + $delIndexes[] = $aaappsDBData [$index]['DEL_INDEX']; } - // the array of data that must be returned with placeholders - $columsToInclude = array( - "APP_CREATE_DATE", - "APP_NUMBER", - "APP_PRO_TITLE", - "APP_STATUS", - "APP_TITLE", - "APP_UID", - "DEL_LAST_UPDATE_DATE", - "DEL_MAX_PRIORITY", - "PRO_UID" - ); - - // create pagination data - $solrSearchText = null; - $sortableCols = array (); - $sortCols = array (); - $sortDir = array (); - $numSortingCols = 0; - - // define sort conditions, default APP_NUMBER, desc - // only one column is sorted - $dir = strtolower( $dir ); - - if (! empty( $sort )) { - switch ($sort) { - case 'APP_CACHE_VIEW.APP_NUMBER': - case 'APP_NUMBER': - $sortCols[0] = 1; //4; - $sortableCols[0] = 'true'; - $sortDir[0] = $dir; - break; - // multivalue field can't be ordered - case 'APP_TITLE': - $sortCols[0] = 4; //10; - $sortableCols[0] = 'true'; - $sortDir[0] = $dir; - break; - case 'APP_PRO_TITLE': - $sortCols[0] = 2; //6; - $sortableCols[0] = 'true'; - $sortDir[0] = $dir; - break; - case 'APP_UPDATE_DATE': - $sortCols[0] = 6; //12; - $sortableCols[0] = 'true'; - $sortDir[0] = $dir; - break; - default: - $sortCols[0] = 1; //4; - $sortableCols[0] = 'true'; - $sortDir[0] = 'desc'; - break; - } - $numSortingCols ++; - } - - //Define conditions for the $action - $arrayAux = array(); - - switch ($action) { - case "todo": - $arrayAux = $this->getToDoSolrString($userUid, $filter); - break; - case "draft": - $arrayAux = $this->getDraftSolrString($userUid); - break; - case "paused": - $arrayAux = $this->getPausedSolrString($userUid); - break; - case "selfservice": - case "unassigned": - if (!empty($userUid)) { - //Get the list of groups to which belongs the user. - $userGroups = $this->getUserGroups($userUid); - - $solrSearchText = $solrSearchText . "(APP_UNASSIGNED_USERS:" . $userUid; - - if (count($userGroups) > 0) { - $solrSearchText = $solrSearchText . " OR "; - - foreach ($userGroups as $group) { - $solrSearchText = $solrSearchText . "APP_UNASSIGNED_GROUPS:" . $group["GRP_UID"] . " OR "; - } - - //Remove last OR in condition - if ($solrSearchText != null) { - $solrSearchText = substr_replace($solrSearchText, null, -4); - } - } - - $solrSearchText = $solrSearchText . ") AND "; - - $delegationIndexes[] = "APP_UNASSIGNED_USER_GROUP_DEL_INDEX_" . $userUid . "_txt"; - - foreach ($userGroups as $group) { - $delegationIndexes[] = "APP_UNASSIGNED_USER_GROUP_DEL_INDEX_" . $group["GRP_UID"] . "_txt"; - } - } - break; - case "sent": - $arrayAux = $this->getSentSolrString($userUid, $filter); - break; - case "search": - switch ($status) { - case "TO_DO": - $arrayAux = $this->getToDoSolrString($userUid, $filter); - break; - case "DRAFT": - $arrayAux = $this->getDraftSolrString($userUid); - break; - case "PAUSED": - $arrayAux = $this->getPausedSolrString($userUid); - break; - case "CANCELLED": - $arrayAux = $this->getCancelledSolrString($userUid); - break; - case "COMPLETED": - $arrayAux = $this->getCompletedSolrString($userUid); - break; - default: - //All status - $arrayAux = $this->getAllSolrString($userUid); - break; - } - break; - } - - if (count($arrayAux) > 0) { - switch ($action) { - case "sent": - if (!empty($status)) { - $solrSearchText = $solrSearchText . "APP_STATUS:" . $status . " AND "; - } - break; - } - - $solrSearchText = $solrSearchText . ((!empty($arrayAux[0]))? $arrayAux[0] . " AND " : null); - - if (is_array($arrayAux[1])) { - foreach ($arrayAux[1] as $index => $value) { - $delegationIndexes[] = $value; - } - } else { - $delegationIndexes[] = $arrayAux[1]; - } - } - - //Get DEL_INDEX field - $delIndexDynaField = null; - - //Process filter - if (!empty($process)) { - $solrSearchText = $solrSearchText . "PRO_UID:" . $process . " AND "; - } - - //Category filter - if (!empty($category)) { - $solrSearchText = $solrSearchText . "PRO_CATEGORY_UID_s:" . $category . " AND "; - } - - //search action - if (!empty($dateFrom) && !empty($dateTo)) { - $fromDate = date( "Y-m-d", strtotime( $dateFrom ) ); - $toDate = date( "Y-m-d", strtotime( $dateTo ) ); - - $searchDateOriginal = "DEL_LAST_UPDATE_DATE:[" . $fromDate . " TO " . $toDate . "]"; - //FechaRegistro:[2011-04-15 TO 2011-04-30] - - - $searchDateFormatedSolr = $this->getSearchText( $searchDateOriginal ); - - $solrSearchText .= "(" . $searchDateFormatedSolr . ") AND "; - - } - - // remove last AND in condition - if ($solrSearchText != '') { - $solrSearchText = substr_replace( $solrSearchText, "", - 5 ); - } - - // add parenthesis to Solr search text - if ($solrSearchText != "") { - $solrSearchText = "(" . $solrSearchText . ")"; - } - // create query string, add query conditions - if ($search != '') { - // format search string - // return exception in case of invalid text - $search = $this->getSearchText( $search ); - - if ($solrSearchText != "" && $search != "") { - $solrSearchText .= " AND "; - } - if ($search != "") { - $solrSearchText .= "(" . $search . ")"; - } - } - - // add del_index dynamic fields to list of resulting columns - $columsToIncludeFinal = array(); - $columsToIncludeFinal = array_merge($columsToInclude, $delegationIndexes); - - // if is a counter no records are returned - if ($doCount) { - $start = 0; - $limit = 0; - $numSortingCols = 0; - $columsToIncludeFinal = array(); - } - - $data = array( - "workspace" => $this->_solrInstance, // solr instance - "startAfter" => intval($start), - "pageSize" => intval($limit), - "searchText" => $solrSearchText, - "filterText" => "", // $filter, //ex:"field1:value1,field2:[value2.1 - // TO value2.2],field3:value3" - "numSortingCols" => $numSortingCols, - "sortableCols" => $sortableCols, - "sortCols" => $sortCols, - "sortDir" => $sortDir, - "includeCols" => $columsToIncludeFinal, - "resultFormat" => "json" - ); - - $solrRequestData = Entity_SolrRequestData::createForRequestPagination( $data ); - - // use search index to return list of cases - $searchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - - // execute query - $solrQueryResult = $searchIndex->getDataTablePaginatedList( $solrRequestData ); - - if ($this->debug) { - $this->afterSolrQueryTime = microtime( true ); - } - //return inmediatelly - if ($doCount) { - $result['totalCount'] = $solrQueryResult->iTotalDisplayRecords; - $result['data'] = array (); - $result['success'] = true; - $result['result'] = true; - $result['message'] = ""; - - return $result; - } - // complete return data, complete list of columns in grid - $resultColumns = array ("APP_CREATE_DATE","APP_CURRENT_USER","APP_DEL_PREVIOUS_USER","APP_FINISH_DATE","APP_NUMBER","APP_OVERDUE_PERCENTAGE","APP_PRO_TITLE","APP_STATUS","APP_TAS_TITLE","APP_THREAD_STATUS","APP_TITLE","APP_UID","APP_UPDATE_DATE","DEL_DELAYED","DEL_DELAY_DURATION","DEL_DELEGATE_DATE","DEL_DURATION","DEL_FINISHED","DEL_FINISH_DATE","DEL_INDEX","DEL_INIT_DATE","DEL_PRIORITY","DEL_QUEUE_DURATION","DEL_STARTED","DEL_TASK_DUE_DATE","DEL_THREAD_STATUS","PREVIOUS_USR_UID","PRO_UID","TAS_UID","USR_UID" - ); - - $rows = array (); - // number of found records - $result['totalCount'] = $solrQueryResult->iTotalDisplayRecords; - - // get the missing data from database - $appUids = array (); - foreach ($solrQueryResult->aaData as $i => $data) { - $appUids[] = $data["APP_UID"]; //APP_UID - } - - $aaappsDBData = $this->getListApplicationDelegationData($appUids, $action, $status); - - if ($this->debug) { - $this->afterDbQueryTime = microtime( true ); - } - - // complete the missing data to display it in the grid. - //$delIndexes = array (); //store all the delegation indexes - foreach ($solrQueryResult->aaData as $i => $data) { - //initialize array - $delIndexes = array (); - - // complete empty values - $appUID = $data["APP_UID"]; //APP_UID - - //get all the delindexes - for ($i = count($columsToInclude); $i <= count($data) - 1; $i++) { - if (is_array($data[$columsToIncludeFinal[$i]])) { - foreach ($data[$columsToIncludeFinal[$i]] as $delIndex) { - $delIndexes[] = $delIndex; - } - } - } - // verify if the delindex is an array - // if is not check different types of repositories - // the delegation index must always be defined. - if (count( $delIndexes ) == 0) { - if ($action == "search") { - //Get all the indexes - - //$delIndexes = $this->getApplicationDelegationsIndex ($appUID); - $indexes = $this->aaSearchRecords( $aaappsDBData, array ('APP_UID' => $appUID - ) ); - - foreach ($indexes as $index) { - $delIndexes[] = $aaappsDBData[$index]['DEL_INDEX']; - } - - } else { - //error an index must always be defined - print "Delegation not defined\n"; - } - /* - * elseif ($action == 'unassigned'){ $delIndexes = $this->getApplicationDelegationsIndex ($appUID); } - */ - } - - $arrayRowAux = array(); - - foreach ($resultColumns as $j => $columnName) { - if (isset($data[$columnName])) { - $arrayRowAux[$columnName] = $data[$columnName]; - } else { - if ($columnName == "DEL_PRIORITY") { - $arrayRowAux[$columnName] = $data["DEL_MAX_PRIORITY"]; //different name - } else { - $arrayRowAux[$columnName] = ""; //placeholder - } - } - } - - //Remove duplicated - $delIndexes = array_unique($delIndexes); - - //Current delegation - if (($action == "sent" || $action == "search" || $action == "simple_search" || $action == "to_revise" || $action == "to_reassign") && ($status != "TO_DO")) { - //Gets the last DEL_INDEX - sort($delIndexes); - $delIndexAux = array_pop($delIndexes); - - $delIndexes = array($delIndexAux); - } - - //Set register - foreach ($delIndexes as $delIndex) { - $aRow = $arrayRowAux; - - // convert date from solr format UTC to local time in MySQL format - $solrdate = $data["APP_CREATE_DATE"]; - $localDate = date( 'Y-m-d H:i:s', strtotime( $solrdate ) ); - $aRow['APP_CREATE_DATE'] = $localDate; - - //$solrdate = $data["DEL_LAST_UPDATE_DATE"]; - //$localDate = date( 'Y-m-d H:i:s', strtotime( $solrdate ) ); - //$aRow['APP_UPDATE_DATE'] = $localDate; - - // get delegation data from DB - //filter data from db - $indexes = $this->aaSearchRecords( $aaappsDBData, array ('APP_UID' => $appUID,'DEL_INDEX' => $delIndex - ) ); - - foreach ($indexes as $index) { - $row = $aaappsDBData[$index]; - } - - if (! isset( $row )) { - $fh = fopen( "SolrAppWhitoutDelIndex.txt", 'a' ) or die( "can't open file to store Solr search time." ); - fwrite( $fh, sprintf( "Solr AppUid: %s DelIndex: %s not found.\r\n", $appUID, $delIndex ) ); - fclose( $fh ); - continue; - } - //$row = $this->getAppDelegationData ($appUID, $delIndex); - - - $aRow['APP_FINISH_DATE'] = null; - $aRow["APP_CURRENT_USER"] = (!empty($row["USR_NAME"]) || !empty($row["USR_LAST"]))? $row["USR_NAME"] . " " . $row["USR_LAST"] : "[" . strtoupper(G::LoadTranslation("ID_UNASSIGNED")) . "]"; - $aRow['APP_DEL_PREVIOUS_USER'] = $row['USR_PREV_NAME'] . " " . $row['USR_PREV_LAST']; - $aRow['APP_OVERDUE_PERCENTAGE'] = $row['APP_OVERDUE_PERCENTAGE']; - $aRow['APP_TAS_TITLE'] = $row['APP_TAS_TITLE']; - $aRow['APP_THREAD_STATUS'] = $row['APP_THREAD_STATUS']; - $aRow['DEL_DELAYED'] = $row['DEL_DELAYED']; - $aRow['DEL_DELAY_DURATION'] = $row['DEL_DELAY_DURATION']; - $aRow['DEL_DELEGATE_DATE'] = $row['DEL_DELEGATE_DATE']; - $aRow['DEL_DURATION'] = $row['DEL_DURATION']; - $aRow['DEL_FINISHED'] = (isset( $row['DEL_FINISH_DATE'] ) && $row['DEL_FINISH_DATE'] != '') ? 1 : 0; - $aRow['DEL_FINISH_DATE'] = $row['DEL_FINISH_DATE']; - $aRow['DEL_INDEX'] = $row['DEL_INDEX']; - $aRow['DEL_INIT_DATE'] = $row['DEL_INIT_DATE']; - $aRow['DEL_QUEUE_DURATION'] = $row['DEL_QUEUE_DURATION']; - $aRow['DEL_STARTED'] = (isset( $row['DEL_INIT_DATE'] ) && $row['DEL_INIT_DATE'] != '') ? 1 : 0; - $aRow['DEL_TASK_DUE_DATE'] = $row['DEL_TASK_DUE_DATE']; - $aRow['DEL_THREAD_STATUS'] = $row['DEL_THREAD_STATUS']; - $aRow['PREVIOUS_USR_UID'] = $row['PREVIOUS_USR_UID']; - $aRow['TAS_UID'] = $row['TAS_UID']; - $aRow['USR_UID'] = $userUid; - $aRow['DEL_PRIORITY'] = G::LoadTranslation( "ID_PRIORITY_{$aPriorities[$aRow['DEL_PRIORITY']]}" ); - - if (isset($aRow["APP_STATUS"])) { - $aRow["APP_STATUS"] = G::LoadTranslation("ID_" . $aRow["APP_STATUS"]); - } - - $aRow["APP_UPDATE_DATE"] = $row["APP_UPDATE_DATE"]; - - $rows[] = $aRow; - } - } - - $result['data'] = $rows; - $result['success'] = true; - $result['result'] = true; - $result['message'] = ""; - - /** - * ****************************************** - */ - if ($this->debug) { - $this->afterPrepareResultTime = microtime( true ); - - $fh = fopen( "SolrSearchTime.txt", 'a' ) or die( "can't open file to store Solr search time." ); - //fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s \n", gmdate ('H:i:s:u', ($this->afterSolrQueryTime - $this->initTimeAll)), gmdate ('H:i:s:u', ($this->afterDbQueryTime - $this->afterSolrQueryTime)), gmdate ('H:i:s:u', ($this->afterPrepareResultTime - $this->afterDbQueryTime)) )); - fwrite( $fh, sprintf( "Solr Query time: %s DB Query time: %s Prepare result time: %s Total:%s \r\n", ($this->afterSolrQueryTime - $this->initTimeAll), ($this->afterDbQueryTime - $this->afterSolrQueryTime), ($this->afterPrepareResultTime - $this->afterDbQueryTime), ($this->afterPrepareResultTime - $this->initTimeAll) ) ); - fclose( $fh ); - } - /** - * ************************************ - */ - - return $result; - - } catch (InvalidIndexSearchTextException $ex) { - // return empty result with description of error - $result = array (); - $result['totalCount'] = 0; - $result['data'] = array (); - $result['success'] = true; - $result['result'] = false; - $result['message'] = $ex->getMessage(); - return $result; + }*/ + else { + //error an index must always be defined + print date('Y-m-d H:i:s:u') . " Delegation not defined\n"; + } + /* + elseif ($action == 'unassigned'){ + $delIndexes = $this->getApplicationDelegationsIndex ($appUID); + }*/ } - } - - /** - * Get the array of counters of cases - * - * @param string $userUid the current logged user uid identifier - */ - public function getCasesCount ($userUid) - { - $casesCount = array (); - - // get number of records in todo list - $data = $this->getAppGridData( $userUid, 0, 0, 'todo', null, null, null, null, null, null, null, null, null, null, null, true ); - $casesCount['to_do'] = $data['totalCount']; - // get number of records in participated list - $data = $this->getAppGridData( $userUid, 0, 0, 'sent', null, null, null, null, null, null, null, null, null, null, null, true ); - $casesCount['sent'] = $data['totalCount']; - // get number of records in draft list - $data = $this->getAppGridData( $userUid, 0, 0, 'draft', null, null, null, null, null, null, null, null, null, null, null, true ); - $casesCount['draft'] = $data['totalCount']; - // get number of records in unassigned list - $data = $this->getAppGridData( $userUid, 0, 0, 'unassigned', null, null, null, null, null, null, null, null, null, null, null, true ); - $casesCount['selfservice'] = $data['totalCount']; - - return $casesCount; - } - - /** - * Get the user groups - * - * @param string $usrUID the user identifier - * @return array of user groups - */ - public function getUserGroups ($usrUID) - { - $gu = new GroupUser(); - $rows = $gu->getAllUserGroups( $usrUID ); - return $rows; - } - - /** - * Get the application delegation record from database - * - * @param string $arrayAppUid array of Application identifiers - * @param string $action Action (todo, draft, paused, sent, selfservice, unassigned, search) - * @param string $appStatus Status of Application - * @return array of arrays with delegation information. - */ - public function getListApplicationDelegationData($arrayAppUid, $action, $appStatus) - { - $appCacheView = new AppCacheView(); - - $c = new Criteria(); - - $c->addSelectColumn( AppDelegationPeer::APP_UID ); - $c->addSelectColumn( AppDelegationPeer::DEL_INDEX ); - - $c->addAsColumn( 'USR_NAME', 'u.USR_FIRSTNAME' ); - $c->addAsColumn( 'USR_LAST', 'u.USR_LASTNAME' ); - - $c->addAsColumn( 'USR_PREV_NAME', 'uprev.USR_FIRSTNAME' ); - $c->addAsColumn( 'USR_PREV_LAST', 'uprev.USR_LASTNAME' ); - $c->addAsColumn( 'PREVIOUS_USR_UID', 'uprev.USR_UID' ); - - $c->addAsColumn( 'APP_TAS_TITLE', 'ctastitle.CON_VALUE' ); - $c->addAsColumn( 'APP_THREAD_STATUS', 'at.APP_THREAD_STATUS' ); - - $c->addSelectColumn( AppDelegationPeer::APP_OVERDUE_PERCENTAGE ); - - $c->addSelectColumn( AppDelegationPeer::DEL_DELAYED ); - $c->addSelectColumn( AppDelegationPeer::DEL_DELAY_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_DELEGATE_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_FINISH_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_INIT_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_QUEUE_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_TASK_DUE_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_THREAD_STATUS ); - $c->addSelectColumn( AppDelegationPeer::TAS_UID ); - $c->addSelectColumn(ApplicationPeer::APP_UPDATE_DATE); - - $c->addAlias("u", UsersPeer::TABLE_NAME); - $c->addAlias("uprev", UsersPeer::TABLE_NAME); - $c->addAlias("adprev", AppDelegationPeer::TABLE_NAME); - $c->addAlias("ctastitle", ContentPeer::TABLE_NAME); - $c->addAlias("at", AppThreadPeer::TABLE_NAME); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::APP_UID, ApplicationPeer::APP_UID); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::USR_UID, "u.USR_UID"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::APP_UID, "adprev.APP_UID"); - $arrayCondition[] = array(AppDelegationPeer::DEL_PREVIOUS, "adprev.DEL_INDEX"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::TAS_UID, "ctastitle.CON_ID"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array("adprev.USR_UID", "uprev.USR_UID"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::APP_UID, "at.APP_UID"); - $arrayCondition[] = array(AppDelegationPeer::DEL_THREAD, "at.APP_THREAD_INDEX"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - //Current delegation - $c->addAsColumn("USRCR_USR_UID", "USRCR.USR_UID"); - $c->addAsColumn("USRCR_USR_FIRSTNAME", "USRCR.USR_FIRSTNAME"); - $c->addAsColumn("USRCR_USR_LASTNAME", "USRCR.USR_LASTNAME"); - $c->addAsColumn("USRCR_USR_USERNAME", "USRCR.USR_USERNAME"); - - $c->addAlias("APPDELCR", AppDelegationPeer::TABLE_NAME); - $c->addAlias("USRCR", UsersPeer::TABLE_NAME); - - $arrayCondition = array(); - $arrayCondition[] = array(AppDelegationPeer::APP_UID, "APPDELCR.APP_UID"); - $arrayCondition[] = array("APPDELCR.DEL_LAST_INDEX", 1); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array("APPDELCR.USR_UID", "USRCR.USR_UID"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $c->addAsColumn("CONTASKCR_APP_TAS_TITLE", "CONTASKCR.CON_VALUE"); - - $c->addAlias("CONTASKCR", ContentPeer::TABLE_NAME); - - $arrayCondition = array(); - $arrayCondition[] = array("APPDELCR.TAS_UID", "CONTASKCR.CON_ID"); - $arrayCondition[] = array("CONTASKCR.CON_CATEGORY", DBAdapter::getStringDelimiter() . "TAS_TITLE" . DBAdapter::getStringDelimiter()); - $arrayCondition[] = array("CONTASKCR.CON_LANG", DBAdapter::getStringDelimiter() . "en" . DBAdapter::getStringDelimiter()); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $c->add(AppDelegationPeer::APP_UID, $arrayAppUid, Criteria::IN); - //$c->add (AppDelegationPeer::DEL_INDEX, $delIndex); - - switch ($action) { - case "sent": - if (!empty($appStatus)) { - $c->add(ApplicationPeer::APP_STATUS, $appStatus); - } - break; - default: - //Paused - $sqlAppDelay = $appCacheView->getAppDelaySql(AppDelegationPeer::APP_UID, AppDelegationPeer::DEL_INDEX); - - //Criterions - $criterionToDo = $c->getNewCriterion(ApplicationPeer::APP_STATUS, "TO_DO", CRITERIA::EQUAL)->addAnd( - $c->getNewCriterion(AppDelegationPeer::DEL_FINISH_DATE, null, Criteria::ISNULL))->addAnd( - $c->getNewCriterion("at.APP_THREAD_STATUS", "OPEN"))->addAnd( - $c->getNewCriterion(AppDelegationPeer::DEL_THREAD_STATUS, "OPEN")); - - $criterionDraft = $c->getNewCriterion(ApplicationPeer::APP_STATUS, "DRAFT", CRITERIA::EQUAL)->addAnd( - $c->getNewCriterion("at.APP_THREAD_STATUS", "OPEN"))->addAnd( - $c->getNewCriterion(AppDelegationPeer::DEL_THREAD_STATUS, "OPEN")); - - $criterionPaused = $c->getNewCriterion(ApplicationPeer::APP_STATUS, "PAUSED")->addAnd( - $c->getNewCriterion(AppDelegationPeer::APP_UID, AppDelegationPeer::APP_UID . " IN ($sqlAppDelay)", Criteria::CUSTOM)); - - $criterionCancelled = $c->getNewCriterion(ApplicationPeer::APP_STATUS, "CANCELLED", CRITERIA::EQUAL)->addAnd( - $c->getNewCriterion(AppDelegationPeer::DEL_THREAD_STATUS, "CLOSED")); - - $criterionCompleted = $c->getNewCriterion(ApplicationPeer::APP_STATUS, "COMPLETED"); - - switch ($appStatus) { - case "TO_DO": - //ToDo - $c->add($criterionToDo); - break; - case "DRAFT": - //Draft - $c->add($criterionDraft); - break; - case "PAUSED": - //Paused - $c->add($criterionPaused); - break; - case "CANCELLED": - //Cancelled - $c->add($criterionCancelled); - break; - case "COMPLETED": - //Completed - $c->add($criterionCompleted); - break; - default: - //All status - $c->add( - //ToDo - $criterionToDo - )->addOr( - //Draft - $criterionDraft - )->addOr( - //Paused - $criterionPaused - )->addOr( - //Cancelled - $criterionCancelled - )->addOr( - //Completed - $criterionCompleted - ); - break; - } - break; - } - - $c->add( 'ctastitle.CON_CATEGORY', 'TAS_TITLE' ); - $c->add( 'ctastitle.CON_LANG', 'en' ); - - $rs = AppDelegationPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - // echo $c->toString(); - $rs->next(); - $row = $rs->getRow(); - - $appDataRows = array (); - while (is_array( $row )) { - //Current delegation - if (($action == "sent" || $action == "search" || $action == "simple_search" || $action == "to_revise" || $action == "to_reassign") && ($appStatus != "TO_DO")) { - //Current task - $row["APP_TAS_TITLE"] = $row["CONTASKCR_APP_TAS_TITLE"]; - - //Current user - $row["USR_NAME"] = $row["USRCR_USR_FIRSTNAME"]; - $row["USR_LAST"] = $row["USRCR_USR_LASTNAME"]; - } - - //Set data - $appDataRows[] = $row; - - $rs->next(); - $row = $rs->getRow(); - } - - return $appDataRows; - } - - /** - * Get the application delegation record from database - * - * @param string $appUID Application identifier - * @param string $delIndex delegation index - * @return array with delegation record. - */ - public function getAppDelegationData ($appUID, $delIndex) - { - - $c = new Criteria(); - - $c->addSelectColumn( AppDelegationPeer::APP_UID ); - $c->addSelectColumn( AppDelegationPeer::DEL_INDEX ); - - $c->addAsColumn( 'USR_NAME', 'u.USR_FIRSTNAME' ); - $c->addAsColumn( 'USR_LAST', 'u.USR_LASTNAME' ); - - $c->addAsColumn( 'USR_PREV_NAME', 'uprev.USR_FIRSTNAME' ); - $c->addAsColumn( 'USR_PREV_LAST', 'uprev.USR_LASTNAME' ); - $c->addAsColumn( 'PREVIOUS_USR_UID', 'uprev.USR_UID' ); - - $c->addAsColumn( 'APP_TAS_TITLE', 'ctastitle.CON_VALUE' ); - $c->addAsColumn( 'APP_THREAD_STATUS', 'at.APP_THREAD_STATUS' ); - - $c->addSelectColumn( AppDelegationPeer::APP_OVERDUE_PERCENTAGE ); - - $c->addSelectColumn( AppDelegationPeer::DEL_DELAYED ); - $c->addSelectColumn( AppDelegationPeer::DEL_DELAY_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_DELEGATE_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_FINISH_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_INIT_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_QUEUE_DURATION ); - $c->addSelectColumn( AppDelegationPeer::DEL_TASK_DUE_DATE ); - $c->addSelectColumn( AppDelegationPeer::DEL_THREAD_STATUS ); - $c->addSelectColumn( AppDelegationPeer::TAS_UID ); - - $c->addAlias("u", UsersPeer::TABLE_NAME); - $c->addAlias("uprev", UsersPeer::TABLE_NAME); - $c->addAlias("adprev", AppDelegationPeer::TABLE_NAME); - $c->addAlias("ctastitle", ContentPeer::TABLE_NAME); - $c->addAlias("at", AppThreadPeer::TABLE_NAME); - - $aConditions = array (); - $aConditions[] = array (AppDelegationPeer::USR_UID,'u.USR_UID' - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $aConditions = array (); - $aConditions[] = array (AppDelegationPeer::APP_UID,'adprev.APP_UID' - ); - $aConditions[] = array (AppDelegationPeer::DEL_PREVIOUS,'adprev.DEL_INDEX' - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $aConditions = array (); - $aConditions[] = array (AppDelegationPeer::TAS_UID,'ctastitle.CON_ID' - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $aConditions = array (); - $aConditions[] = array ('adprev.USR_UID','uprev.USR_UID' - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $aConditions = array (); - $aConditions[] = array (AppDelegationPeer::APP_UID,'at.APP_UID' - ); - $aConditions[] = array (AppDelegationPeer::DEL_THREAD,'at.APP_THREAD_INDEX' - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $c->add( AppDelegationPeer::APP_UID, $appUID ); - $c->add( AppDelegationPeer::DEL_INDEX, $delIndex ); - - $c->add( 'ctastitle.CON_CATEGORY', 'TAS_TITLE' ); - $c->add( 'ctastitle.CON_LANG', 'en' ); - - $rs = AppDelegationPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - // echo $c->toString(); - $rs->next(); - $row = $rs->getRow(); - - return $row; - } - - /** - * return the correct search text for solr. - * if a field is included only search in this field. - * - * @param string $plainSearchText - * @return string formated Solr search string. - */ - public function getSearchText ($plainSearchText) - { - $formattedSearchText = ""; - // if an error is found in string null is returned - $includeToken = true; - - // prepare string to separate and join parentesis - // " " => " " - $count = 1; - while ($count > 0) { - $plainSearchText = preg_replace( '/\s\s+/', ' ', $plainSearchText, - 1, $count ); - } - // "text0( text1" => "text0 (text1"; "text0 )text1" => "text0) text1"; - $plainSearchText = preg_replace( '/\s\[\s/', '[', $plainSearchText ); - $plainSearchText = preg_replace( '/\s\]\s/', '] ', $plainSearchText ); - $plainSearchText = preg_replace( '/\s"\s/', '" ', $plainSearchText ); - - // print "format search string: " . $plainSearchText . "\n"; - // format - // 1: plain text that is used to search in text field: concat field - // 2: a field is specified [field_name]:["phrase search"] - // [field_name]:["phrase search"] [field_name]:[word_search] word_search - // "phrase search" - // to scape a reserved character use a double value: "::", """" - // ex: (APP_ASSIGNED_USERS:7091676694d9269da75c254003021135) AND - // (contrato_t:76* AND Causal_t:1021 AND Materiales AND 143073) - // ex: date search => APP_CREATE_DATE:[2012-03-12T00:00:00Z TO - // 2012-04-12T00:00:00Z] - // ex: phrase => TEXT:"This is a lazy dog" - - - // search the first - - - // cache the index fields - G::LoadClass( 'PMmemcached' ); - $oMemcache = PMmemcached::getSingleton( $this->_solrInstance ); - $ListFieldsInfo = $oMemcache->get( 'Solr_Index_Fields' ); - if (! $ListFieldsInfo) { - G::LoadClass( 'searchIndex' ); - - $searchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - // execute query - $ListFieldsInfo = $searchIndex->getIndexFields( $this->_solrInstance ); - - //var_dump($ListFieldsInfo); - // cache - $oMemcache->set( 'Solr_Index_Fields', $ListFieldsInfo ); - - } - - $tok = strtok( $plainSearchText, " " ); - - while ($tok !== false) { - $fieldName = substr( $tok, 0, strpos( $tok, ":" ) ); // strstr ( $tok, - // ":", - // true ); php 5.3 - $searchText = strstr( $tok, ":" ); - - // verify if there's a field definition - if ($fieldName === false || $fieldName == "") { - // it's not a field - // the token is not a field - // add it completelly - $includeToken = true; - // no field found - $formattedSearchText .= $tok; // used to search in the general default - // text field - } else { - // it's a field - // verify if is complete - if ($fieldName == "" || $searchText == ":") { - $includeToken = false; - throw new InvalidIndexSearchTextException( "Invalid search text, verify the syntax. Expected format = {variable_name}:{search_text}" ); - } - - // field name found - // search index field name - $indexFieldName = ""; - if (array_key_exists( $fieldName, $ListFieldsInfo )) { - $indexFieldName = $ListFieldsInfo[$fieldName]; - } else { - // no field name found - // don't include field search - // return message about it - $includeToken = false; - throw new InvalidIndexSearchTextException( "Invalid search text, variable not found." ); - } - - // The token is part of a phrase, date or a word? - if ($searchText[1] == "[" || $searchText[1] == "\"") { - // expecting date interval we must search the end of the phrase - // the phrase is complete? - if ($searchText[1] == "[" && $searchText[strlen( $searchText ) - 1] == "]") { - // complete phrase ok, the date must be validated - // throw new InvalidIndexSearchTextException("Invalid search text. - // Expected date interval format => - // {variable_name}:[YYYY-MM-DDThh:mm:ssZ TO YYYY-MM-DDThh:mm:ssZ]"); - } elseif ($searchText[1] == "\"" && $searchText[strlen( $searchText ) - 1] == "\"") { - // the phrase is complete and is ok. - } else { - // search end of phrase - $tok = strtok( " " ); - $found = false; - while ($tok !== false) { - if ((($searchText[1] == "[") && ($tok[strlen( $tok ) - 1] == "]")) || (($searchText[1] == "\"") && ($tok[strlen( $tok ) - 1] == "\""))) { - // end of phrase found - $found = true; - $searchText .= " " . $tok; - break; - } else { - // continue adding text - $searchText .= " " . $tok; - } - $tok = strtok( " " ); - } - if (! $found) { - // error invalid text - // Expected date interval format => {variable_name}:[YYYY-MM-DDThh:mm:ssZ TO YYYY-MM-DDThh:mm:ssZ] - throw new InvalidIndexSearchTextException( "Invalid search text. The date or phase is not completed" ); - } - } - } - - // validate phrase in case of date - if (($searchText[1] == "[")) { - // validate date range format - // use regular expresion to validate it [yyyy-mm-dd TO yyyy-mm-dd] - $reg = "/:\[(\d\d\d\d-\d\d-\d\d|\*)\sTO\s(\d\d\d\d-\d\d-\d\d|\*)\]/"; - // convert date to utc - $matched = preg_match( $reg, $searchText, $matches ); - if ($matched == 1) { - // the date interval is valid - // convert to SOlr format - $fromDateOriginal = $matches[1]; - $fromDate = $matches[1]; - - $toDateOriginal = $matches[2]; - $toDate = $matches[2]; - - if ($fromDateOriginal != '*') { - // TODO complete date creation - // list($year, $month, $day) = sscanf($fromDateOriginal, - // '%04d/%02d/%02d'); - // $fromDateDatetime = new DateTime($fromDateOriginal); - // $fromDateDatetime = date_create_from_format ( 'Y-m-d', - // $fromDateOriginal ); - // $fromDateDatetime->getTimestamp () - $fromDate = gmdate( "Y-m-d\T00:00:00\Z", strtotime( $fromDateOriginal ) ); - } - if ($toDateOriginal != '*') { - // list($year, $month, $day) = sscanf($fromDateOriginal, - // '%04d/%02d/%02d'); - // $toDateDatetime = new DateTime($toDateOriginal); - // $toDateDatetime = date_create_from_format ( 'Y-m-d', - // $toDateOriginal ); - $toDate = gmdate( "Y-m-d\T23:59:59.999\Z", strtotime( $toDateOriginal ) ); - } - $searchText = ":[" . $fromDate . " TO " . $toDate . "]"; - } else { - throw new InvalidIndexSearchTextException( "Invalid search text. Expected date interval format => {variable_name}:[YYYY-MM-DD TO YYYY-MM-DD]" ); - } - } - - $formattedSearchText .= $indexFieldName . $searchText; - $includeToken = true; - } - - if ($includeToken) { - $formattedSearchText .= " AND "; - } - // next token - $tok = strtok( " " ); - } - // remove last AND - $formattedSearchText = substr_replace( $formattedSearchText, "", - 5 ); - return $formattedSearchText; - } - - /** - * Get all the application delegation records from database - * - * @param string $appUID Application identifier - * @return array delegation records - */ - public function getApplicationDelegationsIndex ($appUID) - { - $delIndexes = array (); - - $c = new Criteria(); - - $c->addSelectColumn( AppDelegationPeer::DEL_INDEX ); - $c->add( AppDelegationPeer::APP_UID, $appUID ); - - $rs = AppDelegationPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - - $rs->next(); - $row = $rs->getRow(); - - while (is_array( $row )) { - $delIndexes[] = $row['DEL_INDEX']; - $rs->next(); - $row = $rs->getRow(); - } - - return $delIndexes; - - } - - /** - * Update the information of the specified applications in Solr - * - * @param array $aaAPPUIDs Array of arrays of App_UID that must be updated, - * APP_UID is permitted also - */ - public function updateApplicationSearchIndex($aaAPPUIDs, $saveDBRecord = true) - { - if (empty( $aaAPPUIDs )) { - return; - } - - if (! is_array( $aaAPPUIDs )) { - // convert to array - $APPUID = $aaAPPUIDs; - $aaAPPUIDs = array (); - $aaAPPUIDs[] = array ('APP_UID' => $APPUID - ); - } - - //Check if index server is available - if ($saveDBRecord) { - if ($this->isSolrEnabled()) { - //Store update in table but with status updated - foreach ($aaAPPUIDs as $aAPPUID) { - $this->applicationChangedUpdateSolrQueue($aAPPUID["APP_UID"], 0); - } - } else{ - //Store update in table and return - foreach ($aaAPPUIDs as $aAPPUID) { - $this->applicationChangedUpdateSolrQueue($aAPPUID["APP_UID"], true); - } - - return; - } - } - - if ($this->debug) { - $this->getApplicationDataDBTime = 0; - $this->getPreparedApplicationDataDBTime = 0; - $this->getBuilXMLDocTime = 0; - $this->afterUpdateSolrXMLDocTime = 0; - $this->beforeCreateSolrXMLDocTime = microtime( true ); - } - // create XML document - $xmlDoc = $this->createSolrXMLDocument( $aaAPPUIDs ); - - if ($this->debug) { - $this->afterCreateSolrXMLDocTime = microtime( true ); - } - // update document - $data = array ('workspace' => $this->_solrInstance,'document' => $xmlDoc - ); - - $oSolrUpdateDocument = Entity_SolrUpdateDocument::createForRequest( $data ); - - G::LoadClass( 'searchIndex' ); - - $oSearchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - - try { - $oSearchIndex->updateIndexDocument( $oSolrUpdateDocument ); - - if ($this->debug) { - $this->afterUpdateSolrXMLDocTime = microtime( true ); - } - // commit changes - //$oSearchIndex->commitIndexChanges( $this->_solrInstance ); - - } catch (Exception $ex) { - //print "Excepcion indexing data: " . $ex->getMessage() . "\n"; die; - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, $ex->getMessage() ); - fclose( $fh ); - } - if ($this->debug) { - - $fh = fopen("SolrIndexTime.txt", 'a') or die("can't open file to store Solr index time."); - //fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s \n", gmdate ('H:i:s:u', ($this->afterSolrQueryTime - $this->initTimeAll)), gmdate ('H:i:s:u', ($this->afterDbQueryTime - $this->afterSolrQueryTime)), gmdate ('H:i:s:u', ($this->afterPrepareResultTime - $this->afterDbQueryTime)) )); - $trunkSize = count($aaAPPUIDs); - $this->trunkSizeAcumulated += $trunkSize; - $this->totalTimeAcumulated += ($this->afterUpdateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime); - - //Solr App trunk size| Get Data from DB (s)| Prepare DB data (s) | Create XML file (s)| Create XML Document total (s)| Update Solr Document (s) - fwrite($fh, sprintf("%s|%s|%s|%s|%s|%s|%s|%s\r\n", - $this->trunkSizeAcumulated, - $this->totalTimeAcumulated, - $this->getApplicationDataDBTime, - $this->getPreparedApplicationDataDBTime, - $this->getBuilXMLDocTime, - ($this->afterCreateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime), - ($this->afterUpdateSolrXMLDocTime - $this->afterCreateSolrXMLDocTime), - ($this->afterUpdateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime) - )); - - fclose($fh); - - /* - $this->afterCommitSolrDocTime = microtime( true ); - - $fh = fopen( "SolrIndexTime.txt", 'a' ) or die( "can't open file to store Solr index time." ); - //fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s \n", gmdate ('H:i:s:u', ($this->afterSolrQueryTime - $this->initTimeAll)), gmdate ('H:i:s:u', ($this->afterDbQueryTime - $this->afterSolrQueryTime)), gmdate ('H:i:s:u', ($this->afterPrepareResultTime - $this->afterDbQueryTime)) )); - fwrite( $fh, sprintf( "Solr Create XML Document time: %s Update Solr Document time: %s Commit Solr Changes time: %s Total:%s \r\n", ($this->afterCreateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime), ($this->afterUpdateSolrXMLDocTime - $this->afterCreateSolrXMLDocTime), ($this->afterCommitSolrDocTime - $this->afterUpdateSolrXMLDocTime), ($this->afterCommitSolrDocTime - $this->beforeCreateSolrXMLDocTime) ) ); - fclose( $fh );*/ - } - } - - /** - * Delete the specified application record from Solr - * - * @param string $appUID Application identifier - */ - public function deleteApplicationSearchIndex($appUID, $saveDBRecord = true) - { - if (empty( $appUID )) { - return; - } - - // check if index server is available - if ($saveDBRecord) { - // store update in table and return - $this->applicationChangedUpdateSolrQueue( $appUID['APP_UID'], 2 ); // delete - - //return; - } - - $idQuery = "APP_UID:" . $appUID; - - G::LoadClass( 'searchIndex' ); - - $oSearchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - - $oSearchIndex->deleteDocumentFromIndex( $this->_solrInstance, $idQuery ); - - // commit changes - $oSearchIndex->commitIndexChanges( $this->_solrInstance ); - } - - /** - * Create XML data in Solr format of the specified applications - * this function uses the buildSearchIndexDocumentPMOS2 function to create - * each record - * - * @param array $aaAPPUIDs array of arrays of application identifiers - * @return string The resulting XML document in Solr format - */ - public function createSolrXMLDocument ($aaAPPUIDs) - { - if ($this->debug) { - $this->getApplicationDataDBTime = 0; - $this->getPreparedApplicationDataDBTime = 0; - $this->getBuilXMLDocTime = 0; - } - // search data from DB - $xmlDoc = "\n"; - $xmlDoc .= "\n"; - - //get all application data from DB of all applications and delegations - $aAPPUIDs = array (); - foreach ($aaAPPUIDs as $aAPPUID) { - $aAPPUIDs[] = $aAPPUID['APP_UID']; - } - if ($this->debug) { - $this->beforeGetApplicationDataDBTime = microtime( true ); - } - $aaAllAppDelData = $this->getListApplicationUpdateDelegationData( $aAPPUIDs ); - if ($this->debug) { - $this->afterGetApplicationDataDBTime = microtime (true); - - $this->getApplicationDataDBTime = $this->afterGetApplicationDataDBTime - $this->beforeGetApplicationDataDBTime; - } - foreach ($aaAPPUIDs as $aAPPUID) { - try { - - if ($this->debug) { - $this->beforePrepareApplicationDataDBTime = microtime( true ); - } - //filter data, include all the rows of the application - // get delegation data from DB - $aaAppData = array (); - //filter data from db - $indexes = $this->aaSearchRecords($aaAllAppDelData, array("APP_UID" => $aAPPUID["APP_UID"])); - - foreach ($indexes as $index) { - $aaAppData[] = $aaAllAppDelData[$index]; - } - - $result = $this->getApplicationIndexData( $aAPPUID['APP_UID'], $aaAppData ); - - if ($this->debug) { - - $this->afterPrepareApplicationDataDBTime = microtime (true); - - $this->getPreparedApplicationDataDBTime += $this->afterPrepareApplicationDataDBTime - $this->beforePrepareApplicationDataDBTime; - } - - } catch (ApplicationWithoutDelegationRecordsException $ex) { - // exception trying to get application information - // skip and continue with the next application - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, $ex->getMessage() ); - fclose( $fh ); - continue; - } catch (ApplicationWithCorruptDynaformException $ex) { - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, $ex->getMessage() ); - fclose( $fh ); - continue; - } catch (Exception $ex) { - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, "getApplicationIndexData " . $aAPPUID['APP_UID'] . ":" . $ex->getMessage() . "\n" ); - fclose( $fh ); - continue; - } - - $documentInformation = $result[0]; - $dynaformFieldTypes = $result[1]; - $lastUpdateDate = $result[2]; - $maxPriority = $result[3]; - $assignedUsers = $result[4]; - $assignedUsersRead = $result[5]; - $assignedUsersUnread = $result[6]; - $draftUser = $result[7]; - $participatedUsers = $result[8]; - $participatedUsersStartedByUser = $result[9]; - $participatedUsersCompletedByUser = $result[10]; - $unassignedUsers = $result[11]; - $unassignedGroups = $result[12]; - $pausedUser = $result[13]; - $cancelledUser = $result[14]; - - try { - - // create document - $xmlDoc = $xmlDoc . $this->buildSearchIndexDocumentPMOS2( - $documentInformation, - $dynaformFieldTypes, - $lastUpdateDate, - $maxPriority, - $assignedUsers, - $assignedUsersRead, - $assignedUsersUnread, - $draftUser, - $participatedUsers, - $participatedUsersStartedByUser, - $participatedUsersCompletedByUser, - $unassignedUsers, - $unassignedGroups, - $pausedUser, - $cancelledUser - ); - - if ($this->debug) { - $this->afterBuilXMLDocTime = microtime (true); - - $this->getBuilXMLDocTime += $this->afterBuilXMLDocTime - $this->afterPrepareApplicationDataDBTime; - } - } catch (ApplicationAPP_DATAUnserializeException $ex) { - // exception trying to get application information - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, $ex->getMessage() ); - fclose( $fh ); - // skip and continue with the next application - continue; - } catch (Exception $ex) { - $fh = fopen( "./SolrIndexErrors.txt", 'a' ) or die( "can't open file to store Solr index errors." ); - fwrite( $fh, "buildSearchIndexDocumentPMOS2 " . $aAPPUID['APP_UID'] . ":" . $ex->getMessage() . "\n" ); - fclose( $fh ); - continue; - } - - if($this->debugAppInfo) - { - $fh = fopen("SolrAPPUIDIndexSize.txt", 'a') or die("can't open file to store Solr index time."); - //fwrite($fh, sprintf("APP UID %s => doc size: %s\r\n", - // $aAPPUID['APP_UID'], strlen($xmlCurrentDoc))); - fwrite($fh, sprintf("%s|%s|%s\r\n", - $documentInformation ['APP_NUMBER'], $aAPPUID['APP_UID'], strlen($xmlCurrentDoc))); - fclose($fh); + //remove duplicated + $delIndexes = array_unique($delIndexes); + + //var_dump($delIndexes); + + + foreach ($delIndexes as $delIndex) { + $aRow = array (); + + //copy result values to new row from Solr server + $aRow ['APP_UID'] = $data['APP_UID']; + $aRow ['DEL_PRIORITY'] = $data['DEL_MAX_PRIORITY'];//different name + $aRow ['APP_PRO_TITLE'] = $data['APP_PRO_TITLE']; + $aRow ['APP_TITLE'] = $data['APP_TITLE']; + +/* + foreach ($resultColumns as $j => $columnName) { + if(isset($data [$columnName])) + $aRow [$columnName] = $data [$columnName]; + else if($columnName = 'DEL_PRIORITY') + $aRow [$columnName] = $data['DEL_MAX_PRIORITY'];//different name + else + $aRow [$columnName] = '';//placeholder } - }//end foreach + //var_dump($aRow); - $xmlDoc .= "\n"; + // convert date from solr format UTC to local time in MySQL format + $solrdate = $data ['APP_CREATE_DATE']; + $localDate = date ('Y-m-d H:i:s', strtotime ($solrdate)); + $aRow ['APP_CREATE_DATE'] = $localDate; + + $solrdate = $data ['DEL_LAST_UPDATE_DATE']; + $localDate = date ('Y-m-d H:i:s', strtotime ($solrdate)); + $aRow ['APP_UPDATE_DATE'] = $localDate; + */ + + // get delegation data from DB + //filter data from db + $indexes = $this->aaSearchRecords ($aaappsDBData, array ( + 'APP_UID' => $appUID, + 'DEL_INDEX' => $delIndex + )); + + foreach ($indexes as $index) { + $row = $aaappsDBData [$index]; + } + + if(!isset($row)) + { + $fh = fopen("SolrAppWithoutDelIndex.txt", 'a') or die("can't open file to store Solr search time."); + fwrite($fh, sprintf("Solr AppUid: %s DelIndex: %s not found.\r\n", $appUID, $delIndex)); + fclose($fh); + continue; + } + //$row = $this->getAppDelegationData ($appUID, $delIndex); + $aRow ['APP_CREATE_DATE'] = $row ['APP_CREATE_DATE']; + $aRow ['APP_UPDATE_DATE'] = $row ['APP_UPDATE_DATE']; + $aRow ['APP_NUMBER'] = $row ['APP_NUMBER']; + $aRow ['APP_STATUS'] = $row ['APP_STATUS']; + $aRow ['PRO_UID'] = $row ['PRO_UID']; - /* - if ($this->debug) { - $fh = fopen( "SolrIndexTime.txt", 'a' ) or die( "can't open file to store Solr index time." ); - fwrite( $fh, sprintf( "Get Data DB time: %s Prepare DB data Time: %s Create XML file time: %s \r\n", $this->getApplicationDataDBTime, $this->getPreparedApplicationDataDBTime, $this->getBuilXMLDocTime ) ); - fclose( $fh ); - }*/ + $aRow ['APP_FINISH_DATE'] = null; + $aRow ['APP_CURRENT_USER'] = $row ['USR_NAME'] . " " . $row ['USR_LAST']; + $aRow ['APP_DEL_PREVIOUS_USER'] = $row ['USR_PREV_NAME'] . " " . $row ['USR_PREV_LAST']; + $aRow ['APP_OVERDUE_PERCENTAGE'] = $row ['APP_OVERDUE_PERCENTAGE']; + $aRow ['APP_TAS_TITLE'] = $row ['APP_TAS_TITLE']; + $aRow ['APP_THREAD_STATUS'] = $row ['APP_THREAD_STATUS']; + $aRow ['DEL_DELAYED'] = $row ['DEL_DELAYED']; + $aRow ['DEL_DELAY_DURATION'] = $row ['DEL_DELAY_DURATION']; + $aRow ['DEL_DELEGATE_DATE'] = $row ['DEL_DELEGATE_DATE']; + $aRow ['DEL_DURATION'] = $row ['DEL_DURATION']; + $aRow ['DEL_FINISHED'] = (isset ($row ['DEL_FINISH_DATE']) && $row ['DEL_FINISH_DATE'] != '') ? 1 : 0; + $aRow ['DEL_FINISH_DATE'] = $row ['DEL_FINISH_DATE']; + $aRow ['DEL_INDEX'] = $row ['DEL_INDEX']; + $aRow ['DEL_INIT_DATE'] = $row ['DEL_INIT_DATE']; + $aRow ['DEL_QUEUE_DURATION'] = $row ['DEL_QUEUE_DURATION']; + $aRow ['DEL_STARTED'] = (isset ($row ['DEL_INIT_DATE']) && $row ['DEL_INIT_DATE'] != '') ? 1 : 0; + $aRow ['DEL_TASK_DUE_DATE'] = $row ['DEL_TASK_DUE_DATE']; + $aRow ['DEL_THREAD_STATUS'] = $row ['DEL_THREAD_STATUS']; + $aRow ['PREVIOUS_USR_UID'] = $row ['PREVIOUS_USR_UID']; + $aRow ['TAS_UID'] = $row ['TAS_UID']; + $aRow ['USR_UID'] = $userUid; + $aRow ['DEL_PRIORITY'] = G::LoadTranslation("ID_PRIORITY_{$aPriorities[$aRow['DEL_PRIORITY']]}"); + + $rows [] = $aRow; + } - return $xmlDoc; + } + $result ['data'] = $rows; + $result ['success'] = true; + $result ['result'] = true; + $result ['message'] = ""; + + //var_dump($result); + + /*********************************************/ + if($this->debug) + { + $this->afterPrepareResultTime = microtime (true); + + $fh = fopen("SolrSearchTime.txt", 'a') or die("can't open file to store Solr search time."); + //fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s \n", gmdate ('H:i:s:u', ($this->afterSolrQueryTime - $this->initTimeAll)), gmdate ('H:i:s:u', ($this->afterDbQueryTime - $this->afterSolrQueryTime)), gmdate ('H:i:s:u', ($this->afterPrepareResultTime - $this->afterDbQueryTime)) )); + fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s Total:%s \r\n", ($this->afterSolrQueryTime - $this->initTimeAll), ($this->afterDbQueryTime - $this->afterSolrQueryTime), ($this->afterPrepareResultTime - $this->afterDbQueryTime), ($this->afterPrepareResultTime - $this->initTimeAll) )); + fclose($fh); + } + /***************************************/ + + return $result; + + } // end try + catch ( InvalidIndexSearchTextException $ex ) { + // return empty result with description of error + $result = array (); + $result ['totalCount'] = 0; + $result ['data'] = array (); + $result ['success'] = true; + $result ['result'] = false; + $result ['message'] = $ex->getMessage (); + return $result; + } + } + + /** + * Get the array of counters of cases + * + * @param string $userUid + * the current logged user uid identifier + */ + public function getCasesCount($userUid) + { + $casesCount = array (); + + // get number of records in todo list + $data = $this->getAppGridData ($userUid, 0, 0, 'todo', null, null, null, null, null, + null, null, null, null, null, null, true); + $casesCount ['to_do'] = $data ['totalCount']; + // get number of records in participated list + $data = $this->getAppGridData ($userUid, 0, 0, 'sent', null, null, null, null, null, + null, null, null, null, null, null, true); + $casesCount ['sent'] = $data ['totalCount']; + // get number of records in draft list + $data = $this->getAppGridData ($userUid, 0, 0, 'draft', null, null, null, null, null, + null, null, null, null, null, null, true); + $casesCount ['draft'] = $data ['totalCount']; + // get number of records in unassigned list + $data = $this->getAppGridData ($userUid, 0, 0, 'unassigned', null, null, null, null, + null, null, null, null, null, null, null, true); + $casesCount ['selfservice'] = $data ['totalCount']; + + return $casesCount; + } + + /** + * Get the user groups + * @param string $usrUID the user identifier + * @return array of user groups + */ + public function getUserGroups($usrUID) + { + $gu = new GroupUser (); + $rows = $gu->getAllUserGroups ($usrUID); + return $rows; + } + + /** + * Get the application delegation record from database + * + * @param string $aappUIDs + * array of Application identifiers + * @return array of arrays with delegation information. + */ + public function getListApplicationDelegationData($aappUIDs) + { + + $c = new Criteria (); + + $c->addSelectColumn (ApplicationPeer::APP_CREATE_DATE); + $c->addSelectColumn (ApplicationPeer::APP_NUMBER); + $c->addSelectColumn (ApplicationPeer::APP_STATUS); + $c->addSelectColumn (ApplicationPeer::APP_UPDATE_DATE); + $c->addSelectColumn (ApplicationPeer::PRO_UID); + + $c->addSelectColumn (AppDelegationPeer::APP_UID); + $c->addSelectColumn (AppDelegationPeer::DEL_INDEX); + + $c->addAsColumn ('USR_NAME', 'u.USR_FIRSTNAME'); + $c->addAsColumn ('USR_LAST', 'u.USR_LASTNAME'); + + $c->addAsColumn ('USR_PREV_NAME', 'uprev.USR_FIRSTNAME'); + $c->addAsColumn ('USR_PREV_LAST', 'uprev.USR_LASTNAME'); + $c->addAsColumn ('PREVIOUS_USR_UID', 'uprev.USR_UID'); + + $c->addAsColumn ('APP_TAS_TITLE', 'ctastitle.CON_VALUE'); + $c->addAsColumn ('APP_THREAD_STATUS', 'at.APP_THREAD_STATUS'); + + $c->addSelectColumn (AppDelegationPeer::APP_OVERDUE_PERCENTAGE); + + $c->addSelectColumn (AppDelegationPeer::DEL_DELAYED); + $c->addSelectColumn (AppDelegationPeer::DEL_DELAY_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_DELEGATE_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_FINISH_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_INIT_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_QUEUE_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_TASK_DUE_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_THREAD_STATUS); + $c->addSelectColumn (AppDelegationPeer::TAS_UID); + + $c->addAlias ('u', 'USERS'); + $c->addAlias ('uprev', 'USERS'); + $c->addAlias ('adprev', 'APP_DELEGATION'); + $c->addAlias ('ctastitle', 'CONTENT'); + $c->addAlias ('at', 'APP_THREAD'); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::APP_UID, + ApplicationPeer::APP_UID + ); + $c->addJoinMC ($aConditions, Criteria::JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::USR_UID, + 'u.USR_UID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::APP_UID, + 'adprev.APP_UID' + ); + $aConditions [] = array ( + AppDelegationPeer::DEL_PREVIOUS, + 'adprev.DEL_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::TAS_UID, + 'ctastitle.CON_ID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + 'adprev.USR_UID', + 'uprev.USR_UID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::APP_UID, + 'at.APP_UID' + ); + $aConditions [] = array ( + AppDelegationPeer::DEL_THREAD, + 'at.APP_THREAD_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $c->add (AppDelegationPeer::APP_UID, $aappUIDs, Criteria::IN ); + //$c->add (AppDelegationPeer::DEL_INDEX, $delIndex); + + $c->add ('ctastitle.CON_CATEGORY', 'TAS_TITLE'); + $c->add ('ctastitle.CON_LANG', 'en'); + + $rs = AppDelegationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + // echo $c->toString(); + $rs->next (); + $row = $rs->getRow (); + + $appDataRows = array (); + while (is_array ($row)) { + $appDataRows [] = $row; + $rs->next (); + $row = $rs->getRow (); + } + + //Propel::close(); + + return $appDataRows; + } + + /** + * Get the application delegation record from database + * + * @param string $appUID + * Application identifier + * @param string $delIndex + * delegation index + * @return array with delegation record. + */ + public function getAppDelegationData($appUID, $delIndex) + { + + $c = new Criteria (); + + $c->addSelectColumn (AppDelegationPeer::APP_UID); + $c->addSelectColumn (AppDelegationPeer::DEL_INDEX); + + $c->addAsColumn ('USR_NAME', 'u.USR_FIRSTNAME'); + $c->addAsColumn ('USR_LAST', 'u.USR_LASTNAME'); + + $c->addAsColumn ('USR_PREV_NAME', 'uprev.USR_FIRSTNAME'); + $c->addAsColumn ('USR_PREV_LAST', 'uprev.USR_LASTNAME'); + $c->addAsColumn ('PREVIOUS_USR_UID', 'uprev.USR_UID'); + + $c->addAsColumn ('APP_TAS_TITLE', 'ctastitle.CON_VALUE'); + $c->addAsColumn ('APP_THREAD_STATUS', 'at.APP_THREAD_STATUS'); + + $c->addSelectColumn (AppDelegationPeer::APP_OVERDUE_PERCENTAGE); + + $c->addSelectColumn (AppDelegationPeer::DEL_DELAYED); + $c->addSelectColumn (AppDelegationPeer::DEL_DELAY_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_DELEGATE_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_FINISH_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_INIT_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_QUEUE_DURATION); + $c->addSelectColumn (AppDelegationPeer::DEL_TASK_DUE_DATE); + $c->addSelectColumn (AppDelegationPeer::DEL_THREAD_STATUS); + $c->addSelectColumn (AppDelegationPeer::TAS_UID); + + $c->addAlias ('u', 'USERS'); + $c->addAlias ('uprev', 'USERS'); + $c->addAlias ('adprev', 'APP_DELEGATION'); + $c->addAlias ('ctastitle', 'CONTENT'); + $c->addAlias ('at', 'APP_THREAD'); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::USR_UID, + 'u.USR_UID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::APP_UID, + 'adprev.APP_UID' + ); + $aConditions [] = array ( + AppDelegationPeer::DEL_PREVIOUS, + 'adprev.DEL_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::TAS_UID, + 'ctastitle.CON_ID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + 'adprev.USR_UID', + 'uprev.USR_UID' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + AppDelegationPeer::APP_UID, + 'at.APP_UID' + ); + $aConditions [] = array ( + AppDelegationPeer::DEL_THREAD, + 'at.APP_THREAD_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $c->add (AppDelegationPeer::APP_UID, $appUID); + $c->add (AppDelegationPeer::DEL_INDEX, $delIndex); + + $c->add ('ctastitle.CON_CATEGORY', 'TAS_TITLE'); + $c->add ('ctastitle.CON_LANG', 'en'); + + $rs = AppDelegationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + // echo $c->toString(); + $rs->next (); + $row = $rs->getRow (); + + //Propel::close(); + + return $row; + } + + /** + * return the correct search text for solr. + * if a field is included only search in this field. + * + * @param string $plainSearchText + * @return string formated Solr search string. + */ + public function getSearchText($plainSearchText) + { + $formattedSearchText = ""; + // if an error is found in string null is returned + $includeToken = true; + + // prepare string to separate and join parentesis + // " " => " " + $count = 1; + while ($count > 0) { + $plainSearchText = preg_replace ('/\s\s+/', ' ', $plainSearchText, - 1, $count); + } + // "text0( text1" => "text0 (text1"; "text0 )text1" => "text0) text1"; + $plainSearchText = preg_replace ('/\s\[\s/', '[', $plainSearchText); + $plainSearchText = preg_replace ('/\s\]\s/', '] ', $plainSearchText); + $plainSearchText = preg_replace ('/\s"\s/', '" ', $plainSearchText); + + // print "format search string: " . $plainSearchText . "\n"; + // format + // 1: plain text that is used to search in text field: concat field + // 2: a field is specified [field_name]:["phrase search"] + // [field_name]:["phrase search"] [field_name]:[word_search] word_search + // "phrase search" + // to scape a reserved character use a double value: "::", """" + // ex: (APP_ASSIGNED_USERS:7091676694d9269da75c254003021135) AND + // (contrato_t:76* AND Causal_t:1021 AND Materiales AND 143073) + // ex: date search => APP_CREATE_DATE:[2012-03-12T00:00:00Z TO + // 2012-04-12T00:00:00Z] + // ex: phrase => TEXT:"This is a lazy dog" + + // search the first + + // cache the index fields + //G::LoadClass ('PMmemcached'); + //$oMemcache = PMmemcached::getSingleton ($this->_solrInstance); + //$ListFieldsInfo = $oMemcache->get ('Solr_Index_Fields'); + //if (! $ListFieldsInfo) { + G::LoadClass ('searchIndex'); + + $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + // execute query + $ListFieldsInfo = $searchIndex->getIndexFields ($this->_solrInstance); + + //var_dump($ListFieldsInfo); + // cache + //$oMemcache->set ('Solr_Index_Fields', $ListFieldsInfo); + + //} + + $tok = strtok ($plainSearchText, " "); + + while ($tok !== false) { + $fieldName = substr ($tok, 0, strpos ($tok, ":")); // strstr ( $tok, + // ":", + // true ); php 5.3 + $searchText = strstr ($tok, ":"); + + // verify if there's a field definition + if ($fieldName === false || $fieldName == "") { + // it's not a field + // the token is not a field + // add it completelly + $includeToken = true; + // no field found + $formattedSearchText .= $tok; // used to search in the general default + // text field + } + else { + // it's a field + // verify if is complete + if ($fieldName == "" || $searchText == ":") { + $includeToken = false; + throw new InvalidIndexSearchTextException (" Invalid search text, verify the syntax. Expected format = {variable_name}:{search_text}"); + } + + // field name found + // search index field name + $indexFieldName = ""; + if (array_key_exists ($fieldName, $ListFieldsInfo)) { + $indexFieldName = $ListFieldsInfo [$fieldName]; + } + else { + // no field name found + // don't include field search + // return message about it + $includeToken = false; + throw new InvalidIndexSearchTextException (" Invalid search text, variable not found."); + } + + // The token is part of a phrase, date or a word? + if ($searchText [1] == "[" || $searchText [1] == "\"") { // + // expecting + // date + // interval + // we must + // search + // the end of + // the + // phrase + + // the phrase is complete? + if ($searchText [1] == "[" && $searchText [strlen ($searchText) - 1] == "]") { + // complete phrase ok, the date must be validated + // throw new InvalidIndexSearchTextException("Invalid search text. + // Expected date interval format => + // {variable_name}:[YYYY-MM-DDThh:mm:ssZ TO YYYY-MM-DDThh:mm:ssZ]"); + } + elseif ($searchText [1] == "\"" && $searchText [strlen ($searchText) - 1] == "\"") { + // the phrase is complete and is ok. + } + else { + // search end of phrase + $tok = strtok (" "); + $found = false; + while ($tok !== false) { + if ((($searchText [1] == "[") && ($tok [strlen ($tok) - 1] == "]")) || (($searchText [1] == "\"") && ($tok [strlen ($tok) - 1] == "\""))) { + // end of phrase found + $found = true; + $searchText .= " " . $tok; + break; + } + else { + // continue adding text + $searchText .= " " . $tok; + } + $tok = strtok (" "); + } + if (! $found) { + // error invalid text + // Expected date interval format => {variable_name}:[YYYY-MM-DDThh:mm:ssZ TO YYYY-MM-DDThh:mm:ssZ] + throw new InvalidIndexSearchTextException ("Invalid search text. The date or phase is not completed"); + } + } + } + + // validate phrase in case of date + if (($searchText [1] == "[")) { + // validate date range format + // use regular expresion to validate it [yyyy-mm-dd TO yyyy-mm-dd] + $reg = "/:\[(\d\d\d\d-\d\d-\d\d|\*)\sTO\s(\d\d\d\d-\d\d-\d\d|\*)\]/"; + // convert date to utc + $matched = preg_match ($reg, $searchText, $matches); + if ($matched == 1) { + // the date interval is valid + // convert to SOlr format + $fromDateOriginal = $matches [1]; + $fromDate = $matches [1]; + + $toDateOriginal = $matches [2]; + $toDate = $matches [2]; + + if ($fromDateOriginal != '*') { + // TODO complete date creation + // list($year, $month, $day) = sscanf($fromDateOriginal, + // '%04d/%02d/%02d'); + // $fromDateDatetime = new DateTime($fromDateOriginal); + // $fromDateDatetime = date_create_from_format ( 'Y-m-d', + // $fromDateOriginal ); + // $fromDateDatetime->getTimestamp () + $fromDate = gmdate ("Y-m-d\T00:00:00\Z", strtotime ($fromDateOriginal)); + } + if ($toDateOriginal != '*') { + // list($year, $month, $day) = sscanf($fromDateOriginal, + // '%04d/%02d/%02d'); + // $toDateDatetime = new DateTime($toDateOriginal); + // $toDateDatetime = date_create_from_format ( 'Y-m-d', + // $toDateOriginal ); + $toDate = gmdate ("Y-m-d\T23:59:59.999\Z", strtotime ($toDateOriginal)); + } + $searchText = ":[" . $fromDate . " TO " . $toDate . "]"; + } + else { + throw new InvalidIndexSearchTextException ("Invalid search text. Expected date interval format => {variable_name}:[YYYY-MM-DD TO YYYY-MM-DD]"); + } + } + + $formattedSearchText .= $indexFieldName . $searchText; + $includeToken = true; + } + + if ($includeToken) + $formattedSearchText .= " AND "; + + // next token + $tok = strtok (" "); + } + // remove last AND + $formattedSearchText = substr_replace ($formattedSearchText, "", - 5); + return $formattedSearchText; + } + + /** + * Get all the application delegation records from database + * + * @param string $appUID + * Application identifier + * @return array delegation records + */ + public function getApplicationDelegationsIndex($appUID) + { + $delIndexes = array (); + + $c = new Criteria (); + + $c->addSelectColumn (AppDelegationPeer::DEL_INDEX); + $c->add (AppDelegationPeer::APP_UID, $appUID); + + $rs = AppDelegationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + + $rs->next (); + $row = $rs->getRow (); + + while (is_array ($row)) { + $delIndexes [] = $row ['DEL_INDEX']; + $rs->next (); + $row = $rs->getRow (); } - /** - * build Solr index document xml for an application - * @gearman = false - * @rest = false - * @background = false - * - * @param [in] array $documentData array of data for the xml document of - * application - * @param [in] array $dynaformFieldTypes array of dynaform field types, used - * to store the info of APP_DATA with types - * @param [in] array $appTitles array of array of application titles in all - * languages - * @param [in] array $proTitles array of array of process titles in all - * languages - * @param [in] array $assignedUsers array of array of uids of assigned users - * to Application UIDs - * @param [in] array $draftUsers array of array of uids of draft users to - * Application UIDs - * @param [in] array $participatedUsers array of array of participated users - * UIDs in application - * @param [in] array $unassignedUsers array of unassigned users UIDs - * @param [in] array $unassignedGroups array of unassigned groups UIDs - * @param [in] array $pausedUser array of array of uids of paused users to Application UIDs - * @param [in] array $cancelledUser array of array of uids of cancelled users to Application UIDs - * @param [out] xml xml document - * - * $xmlDoc .= buildSearchIndexDocumentPMOS2($documentInformation, - * $dynaformFieldTypes, - * $lastUpdateDate, $maxPriority, - * $assignedUsers, $assignedUsersRead, $assignedUsersUnread, - * $draftUser, - * $participatedUsers, $participatedUsersStartedByUser, - * $participatedUsersCompletedByUser, - * $unassignedUsers, $unassignedGroups, $pausedUser, $cancelledUser); - */ - public function buildSearchIndexDocumentPMOS2( - $documentData, + //Propel::close(); + + return $delIndexes; + + } + + + /** + * Update the information of the specified applications in Solr + * + * @param array $aaAPPUIDs + * Array of arrays of App_UID that must be updated, + * APP_UID is permitted also + */ + public function updateApplicationSearchIndex($aaAPPUIDs, $saveDBRecord = false) + { + + if (empty ($aaAPPUIDs)) + return; + + if($this->debug) + { + //show app to reindex + var_dump($aaAPPUIDs); + } + + if (! is_array ($aaAPPUIDs)) { + // convert to array + $APPUID = $aaAPPUIDs; + $aaAPPUIDs = array (); + $aaAPPUIDs [] = array ( + 'APP_UID' => $APPUID + ); + } + + if($this->debug) + { + //show app to reindex + var_dump($aaAPPUIDs); + } + + try{ + + // check if index server is available + /* + if ($saveDBRecord) { + if($this->isSolrEnabled()){ + //store update in table but with status updated + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 0); + } + } + else{ + // store update in table and return + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], true); + } + return; + } + + }*/ + + + if($this->debug) + { + $this->getApplicationDataDBTime = 0; + $this->getPreparedApplicationDataDBTime = 0; + $this->getBuilXMLDocTime = 0; + $this->afterUpdateSolrXMLDocTime = 0; + + $this->beforeCreateSolrXMLDocTime = microtime (true); + + } + // create XML document + $xmlDoc = $this->createSolrXMLDocument ($aaAPPUIDs); + + if($this->debug ) + { + $this->afterCreateSolrXMLDocTime = microtime (true); + } + // update document + $data = array ( + 'workspace' => $this->_solrInstance, + 'document' => $xmlDoc + ); + + $oSolrUpdateDocument = Entity_SolrUpdateDocument::createForRequest ($data); + + G::LoadClass ('searchIndex'); + + $oSearchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + + $oSearchIndex->updateIndexDocument ($oSolrUpdateDocument); + + + if($this->debug) + { + $this->afterUpdateSolrXMLDocTime = microtime (true); + } + // commit changes no required because of the commitwithin option + //$oSearchIndex->commitIndexChanges ($this->_solrInstance); + //change status in db to indexed + if ($saveDBRecord) { + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 0); + } + } + + } + catch(Exception $ex) { + //echo $ex->getMessage(); + //echo $ex->getTraceAsString(); + $appuidsString = " "; + //register all the appuids that can't be indexed + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], true); + $appuidsString .= $aAPPUID ['APP_UID'] . ", "; + } + //print "Excepcion indexing data: " . $ex->getMessage() . "\n"; die; + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . ":" . $appuidsString . $ex->getMessage() . "\r\n"); + fclose($fh); + } + if($this->debug) + { + + //$this->afterCommitSolrDocTime = microtime (true); + + $fh = fopen("SolrIndexTime.txt", 'a') or die("can't open file to store Solr index time."); + //fwrite($fh, sprintf("Solr Query time: %s DB Query time: %s Prepare result time: %s \n", gmdate ('H:i:s:u', ($this->afterSolrQueryTime - $this->initTimeAll)), gmdate ('H:i:s:u', ($this->afterDbQueryTime - $this->afterSolrQueryTime)), gmdate ('H:i:s:u', ($this->afterPrepareResultTime - $this->afterDbQueryTime)) )); + $trunkSize = count($aaAPPUIDs); + $this->trunkSizeAcumulated += $trunkSize; + $this->totalTimeAcumulated += ($this->afterUpdateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime); + + //Solr App trunk size| Get Data from DB (s)| Prepare DB data (s) | Create XML file (s)| Create XML Document total (s)| Update Solr Document (s) + fwrite($fh, sprintf("%s|%s|%s|%s|%s|%s|%s|%s\r\n", + $this->trunkSizeAcumulated, + $this->totalTimeAcumulated, + $this->getApplicationDataDBTime, + $this->getPreparedApplicationDataDBTime, + $this->getBuilXMLDocTime, + ($this->afterCreateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime), + ($this->afterUpdateSolrXMLDocTime - $this->afterCreateSolrXMLDocTime), + ($this->afterUpdateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime) + )); + + fclose($fh); + + /* + fwrite($fh, sprintf("Solr App trunk size: %s => Create XML Document total (s): %s, Update Solr Document (s): %s, Total (s):%s \r\n", + $trunkSize, ($this->afterCreateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime), ($this->afterUpdateSolrXMLDocTime - $this->afterCreateSolrXMLDocTime), + ($this->afterUpdateSolrXMLDocTime - $this->beforeCreateSolrXMLDocTime))); + fclose($fh); + $fh = fopen("SolrIndexTime.txt", 'a') or die("can't open file to store Solr index time."); + fwrite($fh, sprintf("APP range => Get Data from DB (s): %s, Prepare DB data (s): %s, Create XML file(s): %s \r\n", + $this->getApplicationDataDBTime, $this->getPreparedApplicationDataDBTime, $this->getBuilXMLDocTime )); + fclose($fh);*/ + + } + } + + /** + * Delete the specified application record from Solr + * + * @param string $aaAPPUIDs + * array of arrays of Application identifiers format:$aaAPPUIDs [] = array ('APP_UID' => '...') + */ + public function deleteApplicationSearchIndex($aaAPPUIDs, $saveDBRecord = false) + { + if (empty ($aaAPPUIDs)) + return; + + + if (! is_array ($aaAPPUIDs)) { + // convert to array + $APPUID = $aaAPPUIDs; + $aaAPPUIDs = array (); + $aaAPPUIDs [] = array ( + 'APP_UID' => $APPUID + ); + } + + /* + if ($saveDBRecord) { + if($this->isSolrEnabled()){ + //store update in table but with status updated + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 0); + } + } + else{ + // store update in table and return + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 2); + } + return; + } + }*/ + + try{ + + G::LoadClass ('searchIndex'); + + $oSearchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + + foreach ($aaAPPUIDs as $aAPPUID) { + $idQuery = "APP_UID:" . $aAPPUID ['APP_UID']; + + $oSearchIndex->deleteDocumentFromIndex ($this->_solrInstance, $idQuery); + + } + + if ($saveDBRecord) { + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 0); + } + } + } + catch(Exception $ex) { + //register all the appuids that can't be indexed + $appuidsString = " "; + foreach ($aaAPPUIDs as $aAPPUID) { + $this->applicationChangedUpdateSolrQueue ($aAPPUID ['APP_UID'], 2); + $appuidsString .= $aAPPUID ['APP_UID'] . ", "; + } + //print "Excepcion indexing data: " . $ex->getMessage() . "\n"; die; + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . ":" . $appuidsString . $ex->getMessage() . "\r\n"); + fclose($fh); + } + + // commit changes + //$oSearchIndex->commitIndexChanges ($this->_solrInstance); + } + + /** + * Create XML data in Solr format of the specified applications + * this function uses the buildSearchIndexDocumentPMOS2 function to create + * each record + * + * @param array $aaAPPUIDs + * array of arrays of application identifiers + * @return string The resulting XML document in Solr format + */ + public function createSolrXMLDocument($aaAPPUIDs) + { + if($this->debug) + { + $this->getApplicationDataDBTime = 0; + $this->getPreparedApplicationDataDBTime = 0; + $this->getBuilXMLDocTime = 0; + } + // search data from DB + $xmlDoc = "\n"; + $xmlDoc .= "\n"; + + //get all application data from DB of all applications and delegations + $aAPPUIDs = array(); + foreach($aaAPPUIDs as $aAPPUID) { + $aAPPUIDs[] =$aAPPUID ['APP_UID']; + } + if($this->debug) + { + $this->beforeGetApplicationDataDBTime = microtime (true); + } + $aaAllAppDelData = $this->getListApplicationUpdateDelegationData($aAPPUIDs); + if($this->debug) + { + $this->afterGetApplicationDataDBTime = microtime (true); + + $this->getApplicationDataDBTime = $this->afterGetApplicationDataDBTime - $this->beforeGetApplicationDataDBTime; + } + foreach ($aaAPPUIDs as $aAPPUID) { + try { + + if($this->debug) + { + $this->beforePrepareApplicationDataDBTime = microtime (true); + } + //filter data, include all the rows of the application + // get delegation data from DB + $aaAppData = array(); + //filter data from db + $indexes = $this->aaSearchRecords ($aaAllAppDelData, array ( + 'APP_UID' => $aAPPUID ['APP_UID'] + )); + + foreach ($indexes as $index) { + $aaAppData[] = $aaAllAppDelData [$index]; + } + + $result = $this->getApplicationIndexData ($aAPPUID ['APP_UID'], $aaAppData); + + if($this->debug) + { + $this->afterPrepareApplicationDataDBTime = microtime (true); + + $this->getPreparedApplicationDataDBTime += $this->afterPrepareApplicationDataDBTime - $this->beforePrepareApplicationDataDBTime; + } + + } + catch ( ApplicationWithoutDelegationRecordsException $ex ) { + // exception trying to get application information + // skip and continue with the next application + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . " " . $ex->getMessage()); + fclose($fh); + continue; + } + catch( ApplicationWithCorruptDynaformException $ex) { + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . " " . $ex->getMessage()); + fclose($fh); + continue; + } + catch (Exception $ex) { + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . " " . "getApplicationIndexData " . $aAPPUID['APP_UID'] . ":" . $ex->getMessage() . "\n"); + fclose($fh); + continue; + } + /*$documentInformation, + * $dynaformFieldTypes, + * $lastUpdateDate, + * $maxPriority, + * $delLastIndex, + * $assignedUsers, + * $assignedUsersRead, + * $assignedUsersUnread, + * $draftUser, + * $participatedUsers, + * $participatedUsersStartedByUser, + * $participatedUsersCompletedByUser, + * $unassignedUsers, + * $unassignedGroups */ + $documentInformation = $result [0]; + $dynaformFieldTypes = $result [1]; + $lastUpdateDate = $result [2]; + $maxPriority = $result [3]; + $delLastIndex = $result [4]; + $assignedUsers = $result [5]; + $assignedUsersRead = $result [6]; + $assignedUsersUnread = $result [7]; + $draftUser = $result [8]; + $participatedUsers = $result [9]; + $participatedUsersStartedByUser = $result [10]; + $participatedUsersCompletedByUser = $result [11]; + $unassignedUsers = $result [12]; + $unassignedGroups = $result [13]; + + try { + + // create document + $xmlCurrentDoc = $this->buildSearchIndexDocumentPMOS2 ($documentInformation, $dynaformFieldTypes, + $lastUpdateDate, $maxPriority, $delLastIndex, $assignedUsers, $assignedUsersRead, $assignedUsersUnread, + $draftUser, $participatedUsers, $participatedUsersStartedByUser, $participatedUsersCompletedByUser, + $unassignedUsers, $unassignedGroups); + + //concat doc to the list of docs + $xmlDoc .= $xmlCurrentDoc; + + if($this->debug) + { + $this->afterBuilXMLDocTime = microtime (true); + + $this->getBuilXMLDocTime += $this->afterBuilXMLDocTime - $this->afterPrepareApplicationDataDBTime; + } + } + catch ( ApplicationAPP_DATAUnserializeException $ex ) { + // exception trying to get application information + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . " " . $ex->getMessage()); + fclose($fh); + // skip and continue with the next application + continue; + } + catch (Exception $ex) { + $fh = fopen("./SolrIndexErrors.txt", 'a') or die("can't open file to store Solr index errors."); + fwrite($fh, date('Y-m-d H:i:s:u') . " " . "buildSearchIndexDocumentPMOS2 " . $aAPPUID['APP_UID'] . ":" . $ex->getMessage() . "\n"); + fclose($fh); + continue; + } + + if($this->debugAppInfo) + { + $fh = fopen("SolrAPPUIDIndexSize.txt", 'a') or die("can't open file to store Solr index time."); + //fwrite($fh, sprintf("APP UID %s => doc size: %s\r\n", + // $aAPPUID['APP_UID'], strlen($xmlCurrentDoc))); + fwrite($fh, sprintf("%s|%s|%s\r\n", + $documentInformation ['APP_NUMBER'], $aAPPUID['APP_UID'], strlen($xmlCurrentDoc))); + fclose($fh); + } + + + }//End foreach APPUID + + $xmlDoc .= "\n"; + + /* + if($this->debug) + { + $fh = fopen("SolrIndexTime.txt", 'a') or die("can't open file to store Solr index time."); + fwrite($fh, sprintf("APP range => Get Data from DB (s): %s, Prepare DB data (s): %s, Create XML file(s): %s \r\n", + $this->getApplicationDataDBTime, $this->getPreparedApplicationDataDBTime, $this->getBuilXMLDocTime )); + fclose($fh); + }*/ + + return $xmlDoc; + } + + /** + * build Solr index document xml for an application + * @gearman = false + * @rest = false + * @background = false + * + * @param + * [in] array $documentData array of data for the xml document of + * application + * @param + * [in] array $dynaformFieldTypes array of dynaform field types, used + * to store the info of APP_DATA with types + * @param + * [in] array $appTitles array of array of application titles in all + * languages + * @param + * [in] array $proTitles array of array of process titles in all + * languages + * @param + * [in] array $assignedUsers array of array of uids of assigned users + * to Application UIDs + * @param + * [in] array $draftUsers array of array of uids of draft users to + * Application UIDs + * @param + * [in] array $participatedUsers array of array of participated users + * UIDs in application + * @param + * [in] array $unassignedUsers array of unassigned users UIDs + * @param + * [in] array $unassignedGroups array of unassigned groups UIDs + * @param + * [out] xml xml document + * + * $xmlDoc .= buildSearchIndexDocumentPMOS2($documentInformation, + * $dynaformFieldTypes, + * $lastUpdateDate, $maxPriority, + * $assignedUsers, $assignedUsersRead, $assignedUsersUnread, + * $draftUser, + * $participatedUsers, $participatedUsersStartedByUser, + * $participatedUsersCompletedByUser, + * $unassignedUsers, $unassignedGroups);* + */ + public function buildSearchIndexDocumentPMOS2($documentData, $dynaformFieldTypes, $lastUpdateDate, + $maxPriority, $delLastIndex, $assignedUsers, $assignedUsersRead, $assignedUsersUnread, $draftUser, + $participatedUsers, $participatedUsersStartedByUser, $participatedUsersCompletedByUser, + $unassignedUsers, $unassignedGroups) + { + // build xml document + + $writer = new XMLWriter (); + $writer->openMemory (); + $writer->setIndent (4); + + $writer->startElement ("doc"); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_UID'); + $writer->text ($documentData ['APP_UID']); + $writer->endElement (); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_NUMBER'); + $writer->text ($documentData ['APP_NUMBER']); + $writer->endElement (); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_STATUS'); + $writer->text ($documentData ['APP_STATUS']); + $writer->endElement (); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'PRO_UID'); + $writer->text ($documentData ['PRO_UID']); + $writer->endElement (); + + if (! empty ($documentData ['APP_TITLE'])) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_TITLE'); + $writer->text ($documentData ['APP_TITLE']); + $writer->endElement (); + } + else { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_TITLE'); + $writer->text (""); + $writer->endElement (); + } + + if (! empty ($documentData ['PRO_TITLE'])) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PRO_TITLE'); + $writer->text ($documentData ['PRO_TITLE']); + $writer->endElement (); + + } + else { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PRO_TITLE'); + $writer->text (""); + $writer->endElement (); + } + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_CREATE_DATE'); + // convert date to UTC with gmdate + $writer->text (gmdate ("Y-m-d\TH:i:s\Z", strtotime ($documentData ['APP_CREATE_DATE']))); + $writer->endElement (); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'DEL_LAST_UPDATE_DATE'); + // convert date to UTC with gmdate + $writer->text (gmdate ("Y-m-d\TH:i:s\Z", strtotime ($lastUpdateDate))); + $writer->endElement (); + + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'DEL_MAX_PRIORITY'); + $writer->text ($maxPriority); + $writer->endElement (); + + if (!empty($documentData["PRO_CATEGORY_UID"])) { + $writer->startElement("field"); + $writer->writeAttribute("name", "PRO_CATEGORY_UID_s"); + $writer->text($documentData["PRO_CATEGORY_UID"]); + $writer->endElement(); + } + + foreach ($delLastIndex as $lastIndex) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'DEL_LAST_INDEX'); + $writer->text ($lastIndex); + $writer->endElement (); + } + + if (is_array ($assignedUsers) && ! empty ($assignedUsers)) { + foreach ($assignedUsers as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USERS'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USER_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + + } + } + + if (is_array ($assignedUsersRead) && ! empty ($assignedUsersRead)) { + foreach ($assignedUsersRead as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USERS_READ'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USER_READ_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (is_array ($assignedUsersUnread) && ! empty ($assignedUsersUnread)) { + foreach ($assignedUsersUnread as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USERS_UNREAD'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_ASSIGNED_USER_UNREAD_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (! empty ($draftUser)) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_DRAFT_USER'); + $writer->text ($draftUser ['USR_UID']); + $writer->endElement (); + } + + if (is_array ($participatedUsers) && ! empty ($participatedUsers)) { + foreach ($participatedUsers as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USERS'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USER_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (is_array ($participatedUsersStartedByUser) && ! empty ($participatedUsersStartedByUser)) { + foreach ($participatedUsersStartedByUser as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USERS_STARTED'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USER_STARTED_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (is_array ($participatedUsersCompletedByUser) && ! empty ($participatedUsersCompletedByUser)) { + foreach ($participatedUsersCompletedByUser as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USERS_COMPLETED'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (is_array ($unassignedUsers) && ! empty ($unassignedUsers)) { + foreach ($unassignedUsers as $userUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_UNASSIGNED_USERS'); + $writer->text ($userUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_UNASSIGNED_USER_GROUP_DEL_INDEX_' . trim ($userUID ['USR_UID']) . '_txt'); + $writer->text ($userUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + if (is_array ($unassignedGroups) && ! empty ($unassignedGroups)) { + foreach ($unassignedGroups as $groupUID) { + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_UNASSIGNED_GROUPS'); + $writer->text ($groupUID ['USR_UID']); + $writer->endElement (); + + // add dynamic field for del_index information + $writer->startElement ("field"); + $writer->writeAttribute ('name', 'APP_UNASSIGNED_USER_GROUP_DEL_INDEX_' . trim ($groupUID ['USR_UID']) . '_txt'); + $writer->text ($groupUID ['DEL_INDEX']); + $writer->endElement (); + } + } + + // get the serialized fields + if (! empty ($documentData ['APP_DATA']) && $documentData ['APP_DATA'] != "N;" ) { + + $UnSerializedCaseData = unserialize ($documentData ['APP_DATA']); + + if ($UnSerializedCaseData === false) { + $UnSerializedCaseData = preg_replace ('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $documentData ['APP_DATA']); // utf8_encode + $UnSerializedCaseData = unserialize ($UnSerializedCaseData); + } + + if (! $UnSerializedCaseData) { + // error unserializing + throw new ApplicationAPP_DATAUnserializeException (date('Y-m-d H:i:s:u') . " Could not unserialize APP_DATA of APP_UID: " . $documentData ['APP_UID'] . "\n"); + } + else { + foreach ($UnSerializedCaseData as $k => $value) { + if (! is_array ($value) && ! is_object ($value) && $value != '' && $k != 'SYS_LANG' && $k != 'SYS_SKIN' && $k != 'SYS_SYS') { + // search the field type in array of dynaform fields + if (! empty ($dynaformFieldTypes) && array_key_exists (trim ($k), $dynaformFieldTypes)) { + $type = $dynaformFieldTypes [trim ($k)]; + $typeSufix = '_t'; + switch ($type) { + case 'text' : + $typeSufix = '_t'; + break; + case 'Int' : + if(intval ($value) > 2147483647) { + $typeSufix = '_tl'; //for long values + $value = intval ($value); + } + else { + $typeSufix = '_ti'; + $value = intval ($value); + } + break; + case 'Real' : + $typeSufix = '_td'; + $value = floatval ($value); + break; + case 'date' : + $newdate = false; + $withHour = true; + // try to convert string to date + // TODO convert to php 5.2 format + /* + * $newdate = date_create_from_format ( 'Y-m-d H:i:s', $value + * ); if (! $newdate) { $newdate = date_create_from_format ( + * 'Y-m-d', $value ); $withHour = false; } if (! $newdate) { + * $newdate = date_create_from_format ( 'd/m/Y', $value ); + * $withHour = false; } if (! $newdate) { $newdate = + * date_create_from_format ( 'j/m/Y', $value ); $withHour = + * false; } + */ + $newdate = strtotime ($value); + if (! $newdate) { + $typeSufix = '*'; // not store field + } + else { + $typeSufix = '_tdt'; + /* + * if ($withHour) //$value = gmdate ( "Y-m-d\TH:i:s\Z", + * $newdate->getTimestamp () ); $value = gmdate ( + * "Y-m-d\TH:i:s\Z", $newdate ); else { $value = gmdate ( + * "Y-m-d\T00:00:00\Z", $newdate ); } + */ + $value = gmdate ("Y-m-d\T00:00:00\Z", $newdate); + } + break; + case 'dropdown' : + $typeSufix = '_t'; + break; + case 'textarea' : + $typeSufix = '_t'; + break; + case 'currency' : + $typeSufix = '_td'; + $value = floatval ($value); + break; + case 'percentage' : + $typeSufix = '_t'; + break; + case 'password' : + $typeSufix = '_t'; + break; + case 'suggest' : + $typeSufix = '_t'; + break; + case 'yesno' : + $typeSufix = '_t'; + break; + case 'listbox' : + $typeSufix = '_t'; + break; + case 'checkbox' : + $typeSufix = '_t'; + break; + case 'checkgroup' : + $typeSufix = '_t'; + break; + case 'radiogroup' : + $typeSufix = '_t'; + break; + case 'hidden' : + $typeSufix = '_t'; + break; + } + if ($typeSufix != '*') { + $writer->startElement ("field"); + $writer->writeAttribute ('name', trim ($k) . $typeSufix); + $writer->text ($value); + $writer->endElement (); + } + } + else { + $writer->startElement ("field"); + $writer->writeAttribute ('name', trim ($k) . '_t'); + $writer->text ($value); + $writer->endElement (); + } + } + } // foreach unserialized data + }// else unserialize APP_DATA + } // empty APP_DATA + + $writer->endElement (); // end /doc + + return $writer->outputMemory (true); + } + + /** + * Search records in specified application delegation data + * + * @param string $AppUID + * application identifier + * @param string $allAppDbData + * array of rows (array) with application data + * @throws ApplicationWithoutDelegationRecordsException + * @return array array of arrays with the following information( + * $documentInformation, + * $dynaformFieldTypes, + * $lastUpdateDate, + * $maxPriority, + * $delLastIndex, + * $assignedUsers, + * $assignedUsersRead, + * $assignedUsersUnread, + * $draftUser, + * $participatedUsers, + * $participatedUsersStartedByUser, + * $participatedUsersCompletedByUser, + * $unassignedUsers, + * $unassignedGroups + */ + public function getApplicationIndexData($AppUID, $allAppDbData) + { + //G::LoadClass ('memcached'); + + // get all the application data + //$allAppDbData = $this->getApplicationDelegationData ($AppUID); + // check if the application record was found + // this case occurs when the application doesn't have related delegation + // records. + if (empty ($allAppDbData) || ! isset ($allAppDbData [0])) { + throw new ApplicationWithoutDelegationRecordsException ( date('Y-m-d H:i:s:u') . " Application without delegation records. APP_UID: " . $AppUID . "\n"); + } + + // copy the application information + $documentInformation = $allAppDbData [0]; + + // get the last delegate date using the del_delegate_date + $index = $this->aaGetMaximun ($allAppDbData, 'DEL_DELEGATE_DATE', 'DATE'); + + $lastUpdateDate = $allAppDbData [$index] ['DEL_DELEGATE_DATE']; + + // get the delegate with max priority => minimun value + $index2 = $this->aaGetMinimun ($allAppDbData, 'DEL_PRIORITY', 'NUMBER', 'DEL_THREAD_STATUS', 'OPEN'); + + if ($index2 == null) { + // get the last priority + $maxPriority = $allAppDbData [$index] ['DEL_PRIORITY']; + } + else { + $maxPriority = $allAppDbData [$index2] ['DEL_PRIORITY']; + } + + //get last delegation + //in the case of parallel cases see the open cases + $delLastIndex = array(); + $appStatus = $allAppDbData [0]['APP_STATUS']; + if($appStatus == 'COMPLETED' || $appStatus == 'CANCELLED' || $appStatus == 'PAUSED'){ + //case closed + //get the last delegation + //The correct would be to get all the cases paused in parallel cases + $index = $this->aaGetMaximun ($allAppDbData, 'DEL_INDEX', 'NUMBER'); + $delLastIndex[] = $allAppDbData [$index] ['DEL_INDEX']; + }else{ + //case is vigent + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_THREAD_STATUS' => 'OPEN', + 'DEL_FINISH_DATE' => 'NULL' + )); + foreach ($indexes as $index) { + $delLastIndex[] = $allAppDbData [$index] ['DEL_INDEX']; + } + if(count($indexes) == 0){ + //verify if is a paused case + //show the last delegation + //the correct would be to identify multiple cases if paused + $index = $this->aaGetMaximun ($allAppDbData, 'DEL_INDEX', 'NUMBER'); + $delLastIndex[] = $allAppDbData [$index] ['DEL_INDEX']; + } + } + + $assignedUsers = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_THREAD_STATUS' => 'OPEN', + 'DEL_FINISH_DATE' => 'NULL', + 'APP_STATUS' => 'TO_DO' //, 'APP_THREAD_STATUS' => 'OPEN' + )); + foreach ($indexes as $index) { + $assignedUsers [] = array ( + 'USR_UID' => $allAppDbData [$index] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] + ); + } + + $assignedUsersRead = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_THREAD_STATUS' => 'OPEN', + 'DEL_FINISH_DATE' => 'NULL', + 'APP_STATUS' => 'TO_DO', //, 'APP_THREAD_STATUS' => 'OPEN', + 'DEL_INIT_DATE' => 'NOTNULL' + )); + foreach ($indexes as $index) { + $assignedUsersRead [] = array ( + 'USR_UID' => $allAppDbData [$index] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] + ); + } + + $assignedUsersUnread = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_THREAD_STATUS' => 'OPEN', + 'DEL_FINISH_DATE' => 'NULL', + 'APP_STATUS' => 'TO_DO', //, 'APP_THREAD_STATUS' => 'OPEN', + 'DEL_INIT_DATE' => 'NULL' + )); + foreach ($indexes as $index) { + $assignedUsersUnread [] = array ( + 'USR_UID' => $allAppDbData [$index] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] + ); + } + + $draftUser = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_THREAD_STATUS' => 'OPEN', + 'DEL_FINISH_DATE' => 'NULL', + 'APP_STATUS' => 'DRAFT'//, 'APP_THREAD_STATUS' => 'OPEN' + )); + if (! empty ($indexes)) { + $draftUser = array ( + 'USR_UID' => $allAppDbData [$indexes [0]] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$indexes [0]] ['DEL_INDEX'] + ); + } + + $participatedUsers = array (); + foreach ($allAppDbData as $row) { + $participatedUsers [] = array ( + 'USR_UID' => $row ['USR_UID'], + 'DEL_INDEX' => $row ['DEL_INDEX'] + ); + } + + $participatedUsersStartedByUser = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'DEL_INDEX' => '1' + )); + foreach ($indexes as $index) { + $participatedUsersStartedByUser [] = array ( + 'USR_UID' => $allAppDbData [$index] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] + ); + } + + $participatedUsersCompletedByUser = array (); + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'APP_STATUS' => 'COMPLETED' + )); + foreach ($indexes as $index) { + $participatedUsersCompletedByUser [] = array ( + 'USR_UID' => $allAppDbData [$index] ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] + ); + } + // search information of unassigned users + // the unassigned users are the self service users and groups. + // the self service users are defined in the TASKs of the PROCESS. + $unassignedUsers = array (); + $unassignedGroups = array (); + //filter only the delegations that are in selfservice status + // `USR_UID` = '' AND `DEL_FINISH_DATE` IS NULL + $indexes = $this->aaSearchRecords ($allAppDbData, array ( + 'USR_UID' => 'NULL', + 'DEL_FINISH_DATE' => 'NULL' //, 'APP_THREAD_STATUS' => 'OPEN' + )); + foreach ($indexes as $index) { + $unassignedUsersGroups = array (); + // use cache + //$oMemcache = PMmemcached::getSingleton ($this->_solrInstance); + //$unassignedUsersGroups = $oMemcache->get ("SOLR_UNASSIGNED_USERS_GROUPS_" . $allAppDbData [$index] ['PRO_UID'] . "_" . $allAppDbData [$index] ['TAS_UID']); + //if (! $unassignedUsersGroups) { + + $unassignedUsersGroups = $this->getTaskUnassignedUsersGroupsData ($allAppDbData [$index] ['PRO_UID'], $allAppDbData [$index] ['TAS_UID']); + + // if the task has unassigned users or groups add del_index of delegation + //foreach ($unassignedUsersGroups as $i => $newRow) { + // $unassignedUsersGroups [$i] ['DEL_INDEX'] = $allAppDbData [$index] ['DEL_INDEX']; + //} + // store in cache + //$oMemcache->set ("SOLR_UNASSIGNED_USERS_GROUPS_" . $allAppDbData [$index] ['PRO_UID'] . "_" . $allAppDbData [$index] ['TAS_UID'], $unassignedUsersGroups); + //} + + // copy list of unassigned users and groups + foreach ($unassignedUsersGroups as $unassignedUserGroup) { + //unassigned users + if ($unassignedUserGroup ['TU_RELATION'] == 1) { + $unassignedUsers [] = array ( + 'USR_UID' => $unassignedUserGroup ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] //$unassignedUserGroup ['DEL_INDEX'] + ); + } + //unassigned groups + elseif ($unassignedUserGroup ['TU_RELATION'] == 2) { + $unassignedGroups [] = array ( + 'USR_UID' => $unassignedUserGroup ['USR_UID'], + 'DEL_INDEX' => $allAppDbData [$index] ['DEL_INDEX'] //$unassignedUserGroup ['DEL_INDEX'] + ); + } + } + + } + + // Get DataTypes of dynaforms + // use cache array to store the dynaform variables per process + // use memory array to store information of Datatypes of Dynaforms + // All the datatypes of the process => all variables in all dynaforms in the + // process + $dynaformFieldTypes = array (); + + // get cache instance + //$oMemcache = PMmemcached::getSingleton ($this->_solrInstance); + //$dynaformFieldTypes = $oMemcache->get ("SOLR_DYNAFORM_FIELD_TYPES_" . $documentInformation ['PRO_UID']); + //if (! $dynaformFieldTypes) { + G::LoadClass ('dynaformhandler'); + $dynaformFileNames = $this->getProcessDynaformFileNames ($documentInformation ['PRO_UID']); + $dynaformFields = array (); + foreach ($dynaformFileNames as $dynaformFileName) { + if (is_file(PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName ['DYN_FILENAME'] . '.xml') && + filesize(PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName ['DYN_FILENAME'] . '.xml') >0 ) { + $dyn = new dynaFormHandler (PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName ['DYN_FILENAME'] . '.xml'); + $dynaformFields [] = $dyn->getFields (); + } + if (is_file(PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName ['DYN_FILENAME'] . '.xml') && + filesize(PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName ['DYN_FILENAME'] . '.xml') == 0 ) { + + throw new ApplicationWithCorruptDynaformException(date('Y-m-d H:i:s:u') . "Application with corrupt dynaform. APP_UID: " . $AppUID . "\n"); + } + } + + foreach ($dynaformFields as $aDynFormFields) { + foreach ($aDynFormFields as $field) { + // create array of fields and types + if ($field->getAttribute ('validate') == 'Int') { + $dynaformFieldTypes [$field->nodeName] = 'Int'; + } + elseif ($field->getAttribute ('validate') == 'Real') { + $dynaformFieldTypes [$field->nodeName] = 'Real'; + } + else { + $dynaformFieldTypes [$field->nodeName] = $field->getAttribute ('type'); + } + } + } + // create cache of dynaformfields + //$oMemcache->set ("SOLR_DYNAFORM_FIELD_TYPES_" . $documentInformation ['PRO_UID'], $dynaformFieldTypes); + //} + // return result values + $result = array ( + $documentInformation, $dynaformFieldTypes, $lastUpdateDate, $maxPriority, + $delLastIndex, $assignedUsers, $assignedUsersRead, $assignedUsersUnread, @@ -1801,1181 +2329,703 @@ class AppSolr $participatedUsersStartedByUser, $participatedUsersCompletedByUser, $unassignedUsers, - $unassignedGroups, - $pausedUser, - $cancelledUser - ) { - // build xml document - - - $writer = new XMLWriter(); - $writer->openMemory(); - $writer->setIndent( 4 ); - - $writer->startElement( "doc" ); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_UID' ); - $writer->text( $documentData['APP_UID'] ); - $writer->endElement(); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_NUMBER' ); - $writer->text( $documentData['APP_NUMBER'] ); - $writer->endElement(); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_STATUS' ); - $writer->text( $documentData['APP_STATUS'] ); - $writer->endElement(); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'PRO_UID' ); - $writer->text( $documentData['PRO_UID'] ); - $writer->endElement(); - - if (! empty( $documentData['APP_TITLE'] )) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_TITLE' ); - $writer->text( $documentData['APP_TITLE'] ); - $writer->endElement(); - } else { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_TITLE' ); - $writer->text( "" ); - $writer->endElement(); - } - - if (! empty( $documentData['PRO_TITLE'] )) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PRO_TITLE' ); - $writer->text( $documentData['PRO_TITLE'] ); - $writer->endElement(); - - } else { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PRO_TITLE' ); - $writer->text( "" ); - $writer->endElement(); - } - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_CREATE_DATE' ); - // convert date to UTC with gmdate - $writer->text( gmdate( "Y-m-d\TH:i:s\Z", strtotime( $documentData['APP_CREATE_DATE'] ) ) ); - $writer->endElement(); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'DEL_LAST_UPDATE_DATE' ); - // convert date to UTC with gmdate - $writer->text( gmdate( "Y-m-d\TH:i:s\Z", strtotime( $lastUpdateDate ) ) ); - $writer->endElement(); - - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'DEL_MAX_PRIORITY' ); - $writer->text( $maxPriority ); - $writer->endElement(); - - if (!empty($documentData["PRO_CATEGORY_UID"])) { - $writer->startElement("field"); - $writer->writeAttribute("name", "PRO_CATEGORY_UID_s"); - $writer->text($documentData["PRO_CATEGORY_UID"]); - $writer->endElement(); - } - - if (is_array( $assignedUsers ) && ! empty( $assignedUsers )) { - foreach ($assignedUsers as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USERS' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USER_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - - } - } - - if (is_array( $assignedUsersRead ) && ! empty( $assignedUsersRead )) { - foreach ($assignedUsersRead as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USERS_READ' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USER_READ_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (is_array( $assignedUsersUnread ) && ! empty( $assignedUsersUnread )) { - foreach ($assignedUsersUnread as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USERS_UNREAD' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_ASSIGNED_USER_UNREAD_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (count($draftUser) > 0) { - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_DRAFT_USER"); - $writer->text($draftUser["USR_UID"]); - $writer->endElement(); - - //Add field for DEL_INDEX information - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_DRAFT_USER_DEL_INDEX_" . trim($draftUser["USR_UID"]) . "_txt"); - $writer->text($draftUser["DEL_INDEX"]); - $writer->endElement(); - } - - if (count($pausedUser) > 0) { - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_PAUSED_USERS"); - $writer->text($pausedUser["USR_UID"]); - $writer->endElement(); - - //Add field for DEL_INDEX information - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_PAUSED_USERS_DEL_INDEX_" . trim($pausedUser["USR_UID"]) . "_txt"); - $writer->text($pausedUser["DEL_INDEX"]); - $writer->endElement(); - } - - if (count($cancelledUser) > 0) { - foreach ($cancelledUser as $userUid) { - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_CANCELLED_USER_txt"); - $writer->text($userUid["USR_UID"]); - $writer->endElement(); - - //Add field for DEL_INDEX information - $writer->startElement("field"); - $writer->writeAttribute("name", "APP_CANCELLED_USER_DEL_INDEX_" . trim($userUid["USR_UID"]) . "_txt"); - $writer->text($userUid["DEL_INDEX"]); - $writer->endElement(); - } - } - - if (is_array( $participatedUsers ) && ! empty( $participatedUsers )) { - foreach ($participatedUsers as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USERS' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USER_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (is_array( $participatedUsersStartedByUser ) && ! empty( $participatedUsersStartedByUser )) { - foreach ($participatedUsersStartedByUser as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USERS_STARTED' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USER_STARTED_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (is_array( $participatedUsersCompletedByUser ) && ! empty( $participatedUsersCompletedByUser )) { - foreach ($participatedUsersCompletedByUser as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USERS_COMPLETED' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_PARTICIPATED_USER_COMPLETED_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (is_array( $unassignedUsers ) && ! empty( $unassignedUsers )) { - foreach ($unassignedUsers as $userUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_UNASSIGNED_USERS' ); - $writer->text( $userUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_UNASSIGNED_USER_GROUP_DEL_INDEX_' . trim( $userUID['USR_UID'] ) . '_txt' ); - $writer->text( $userUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - if (is_array( $unassignedGroups ) && ! empty( $unassignedGroups )) { - foreach ($unassignedGroups as $groupUID) { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_UNASSIGNED_GROUPS' ); - $writer->text( $groupUID['USR_UID'] ); - $writer->endElement(); - - // add dynamic field for del_index information - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', 'APP_UNASSIGNED_USER_GROUP_DEL_INDEX_' . trim( $groupUID['USR_UID'] ) . '_txt' ); - $writer->text( $groupUID['DEL_INDEX'] ); - $writer->endElement(); - } - } - - // get the serialized fields - if (! empty( $documentData['APP_DATA'] ) && $documentData['APP_DATA'] != "N;") { - - $UnSerializedCaseData = unserialize( $documentData['APP_DATA'] ); - - if ($UnSerializedCaseData === false) { - $UnSerializedCaseData = preg_replace( '!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $documentData['APP_DATA'] ); // utf8_encode - $UnSerializedCaseData = unserialize( $UnSerializedCaseData ); - } - - if (! $UnSerializedCaseData) { - // error unserializing - throw new ApplicationAPP_DATAUnserializeException( "Could not unserialize APP_DATA of APP_UID: " . $documentData['APP_UID'] . "\n" ); - } else { - foreach ($UnSerializedCaseData as $k => $value) { - if (! is_array( $value ) && ! is_object( $value ) && $value != '' && $k != 'SYS_LANG' && $k != 'SYS_SKIN' && $k != 'SYS_SYS') { - // search the field type in array of dynaform fields - if (! empty( $dynaformFieldTypes ) && array_key_exists( trim( $k ), $dynaformFieldTypes )) { - $type = $dynaformFieldTypes[trim( $k )]; - $typeSufix = '_t'; - switch ($type) { - case 'text': - $typeSufix = '_t'; - break; - case 'Int': - if (intval( $value ) > 2147483647) { - $typeSufix = '_tl'; //for long values - $value = intval( $value ); - } else { - $typeSufix = '_ti'; - $value = intval( $value ); - } - break; - case 'Real': - $typeSufix = '_td'; - $value = floatval( $value ); - break; - case 'date': - $newdate = false; - $withHour = true; - // try to convert string to date - // TODO convert to php 5.2 format - /* - * $newdate = date_create_from_format ( 'Y-m-d H:i:s', $value ); if (! $newdate) { $newdate = date_create_from_format ( 'Y-m-d', $value ); $withHour = false; } if (! $newdate) { $newdate = date_create_from_format ( 'd/m/Y', $value ); $withHour = false; } if (! - * $newdate) { $newdate = date_create_from_format ( 'j/m/Y', $value ); $withHour = false; } - */ - $newdate = strtotime( $value ); - if (! $newdate) { - $typeSufix = '*'; // not store field - } else { - $typeSufix = '_tdt'; - /* - * if ($withHour) //$value = gmdate ( "Y-m-d\TH:i:s\Z", $newdate->getTimestamp () ); $value = gmdate ( "Y-m-d\TH:i:s\Z", $newdate ); else { $value = gmdate ( "Y-m-d\T00:00:00\Z", $newdate ); } - */ - $value = gmdate( "Y-m-d\T00:00:00\Z", $newdate ); - } - break; - case 'dropdown': - $typeSufix = '_t'; - break; - case 'textarea': - $typeSufix = '_t'; - break; - case 'currency': - $typeSufix = '_td'; - $value = floatval( $value ); - break; - case 'percentage': - $typeSufix = '_t'; - break; - case 'password': - $typeSufix = '_t'; - break; - case 'suggest': - $typeSufix = '_t'; - break; - case 'yesno': - $typeSufix = '_t'; - break; - case 'listbox': - $typeSufix = '_t'; - break; - case 'checkbox': - $typeSufix = '_t'; - break; - case 'checkgroup': - $typeSufix = '_t'; - break; - case 'radiogroup': - $typeSufix = '_t'; - break; - case 'hidden': - $typeSufix = '_t'; - break; - } - if ($typeSufix != '*') { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', trim( $k ) . $typeSufix ); - $writer->text( $value ); - $writer->endElement(); - } - } else { - $writer->startElement( "field" ); - $writer->writeAttribute( 'name', trim( $k ) . '_t' ); - $writer->text( $value ); - $writer->endElement(); - } - } - } // foreach unserialized data - } // else unserialize APP_DATA - } // empty APP_DATA - - - $writer->endElement(); // end /doc - - - return $writer->outputMemory( true ); + $unassignedGroups + ); + + return $result; + } + + /** + * Find the maximun value of the specified column in the array and return the + * row index + * + * @param array $arr + * array of arrays with the data + * @param string $column + * column name to search in + * @param string $columnType + * column type STRING, NUMBER, DATE + * @param string $columnCondition + * column condition + * @param string $condition + * the condition + * @return integer The index of the maximun record in array + */ + public function aaGetMaximun($arr, $column, $columnType = 'STRING', + $columnCondition = "", $condition = "") + { + // get first value + $auxValue = $arr [0] [$column]; + $index = null; + foreach ($arr as $i => $row) { + switch ($columnType) { + case 'STRING' : + if ((strnatcmp ($row [$column], $auxValue) >= 0) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + } + break; + case 'NUMBER' : + if (($row [$column] >= $auxValue) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + } + break; + case 'DATE' : + if ((strtotime ($row [$column]) >= strtotime ($auxValue)) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + } + break; + } } - - /** - * Search records in specified application delegation data - * - * @param string $AppUID application identifier - * @param string $allAppDbData array of rows (array) with application data - * @throws ApplicationWithoutDelegationRecordsException - * @return array array of arrays with the following information( - * $documentInformation, - * $dynaformFieldTypes, - * $lastUpdateDate, - * $maxPriority, - * $assignedUsers, - * $assignedUsersRead, - * $assignedUsersUnread, - * $draftUser, - * $participatedUsers, - * $participatedUsersStartedByUser, - * $participatedUsersCompletedByUser, - * $unassignedUsers, - * $unassignedGroups, - * $pausedUser, - * $cancelledUser - */ - public function getApplicationIndexData ($AppUID, $allAppDbData) - { - G::LoadClass( 'memcached' ); - - // get all the application data - //$allAppDbData = $this->getApplicationDelegationData ($AppUID); - // check if the application record was found - // this case occurs when the application doesn't have related delegation - // records. - if (empty( $allAppDbData ) || ! isset( $allAppDbData[0] )) { - throw new ApplicationWithoutDelegationRecordsException( "Application without delegation records. APP_UID: " . $AppUID . "\n" ); - } - - // copy the application information - $documentInformation = $allAppDbData[0]; - - // get the last delegate date using the del_delegate_date - $index = $this->aaGetMaximun( $allAppDbData, 'DEL_DELEGATE_DATE', 'DATE' ); - - $lastUpdateDate = $allAppDbData[$index]['DEL_DELEGATE_DATE']; - - // get the delegate with max priority => minimun value - $index2 = $this->aaGetMinimun( $allAppDbData, 'DEL_PRIORITY', 'NUMBER', 'DEL_THREAD_STATUS', 'OPEN' ); - - if ($index2 == null) { - // get the last priority - $maxPriority = $allAppDbData[$index]['DEL_PRIORITY']; - } else { - $maxPriority = $allAppDbData[$index2]['DEL_PRIORITY']; - } - - $assignedUsers = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('DEL_THREAD_STATUS' => 'OPEN','DEL_FINISH_DATE' => 'NULL','APP_STATUS' => 'TO_DO','APP_THREAD_STATUS' => 'OPEN' - ) ); - foreach ($indexes as $index) { - $assignedUsers[] = array ('USR_UID' => $allAppDbData[$index]['USR_UID'],'DEL_INDEX' => $allAppDbData[$index]['DEL_INDEX'] - ); - } - - $assignedUsersRead = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('DEL_THREAD_STATUS' => 'OPEN','DEL_FINISH_DATE' => 'NULL','APP_STATUS' => 'TO_DO','APP_THREAD_STATUS' => 'OPEN','DEL_INIT_DATE' => 'NOTNULL' - ) ); - foreach ($indexes as $index) { - $assignedUsersRead[] = array ('USR_UID' => $allAppDbData[$index]['USR_UID'],'DEL_INDEX' => $allAppDbData[$index]['DEL_INDEX'] - ); - } - - $assignedUsersUnread = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('DEL_THREAD_STATUS' => 'OPEN','DEL_FINISH_DATE' => 'NULL','APP_STATUS' => 'TO_DO','APP_THREAD_STATUS' => 'OPEN','DEL_INIT_DATE' => 'NULL' - ) ); - foreach ($indexes as $index) { - $assignedUsersUnread[] = array ('USR_UID' => $allAppDbData[$index]['USR_UID'],'DEL_INDEX' => $allAppDbData[$index]['DEL_INDEX'] - ); - } - - $draftUser = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('DEL_THREAD_STATUS' => 'OPEN','DEL_FINISH_DATE' => 'NULL','APP_STATUS' => 'DRAFT','APP_THREAD_STATUS' => 'OPEN' - ) ); - if (! empty( $indexes )) { - $draftUser = array ('USR_UID' => $allAppDbData[$indexes[0]]['USR_UID'],'DEL_INDEX' => $allAppDbData[$indexes[0]]['DEL_INDEX'] - ); - } - - //Paused - $pausedUser = array(); - - foreach ($allAppDbData as $row) { - if ((empty($row["APPDELY_APP_DISABLE_ACTION_USER"]) || $row["APPDELY_APP_DISABLE_ACTION_USER"] == "0") && - !empty($row["APPDELY_APP_DELAY_UID"]) && $row["APPDELY_APP_TYPE"] == "PAUSE" - ) { - $pausedUser = array("USR_UID" => $row["USR_UID"], "DEL_INDEX" => $row["DEL_INDEX"]); - break; - } - } - - //Cancelled - $cancelledUser = array(); - - $arrayIndex = $this->aaSearchRecords( - $allAppDbData, - array("APP_STATUS" => "CANCELLED", "DEL_THREAD_STATUS" => "CLOSED") - ); - - foreach ($arrayIndex as $index) { - $cancelledUser[] = array( - "USR_UID" => $allAppDbData[$index]["USR_UID"], - "DEL_INDEX" => $allAppDbData[$index]["DEL_INDEX"] - ); - } - - //Participated - $participatedUsers = array (); - foreach ($allAppDbData as $row) { - $participatedUsers[] = array ('USR_UID' => $row['USR_UID'],'DEL_INDEX' => $row['DEL_INDEX'] - ); - } - - $participatedUsersStartedByUser = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('DEL_INDEX' => '1' - ) ); - foreach ($indexes as $index) { - $participatedUsersStartedByUser[] = array ('USR_UID' => $allAppDbData[$index]['USR_UID'],'DEL_INDEX' => $allAppDbData[$index]['DEL_INDEX'] - ); - } - - $participatedUsersCompletedByUser = array (); - $indexes = $this->aaSearchRecords( $allAppDbData, array ('APP_STATUS' => 'COMPLETED' - ) ); - foreach ($indexes as $index) { - $participatedUsersCompletedByUser[] = array ('USR_UID' => $allAppDbData[$index]['USR_UID'],'DEL_INDEX' => $allAppDbData[$index]['DEL_INDEX'] - ); - } - // search information of unassigned users - // the unassigned users are the self service users and groups. - // the self service users are defined in the TASKs of the PROCESS. - $unassignedUsers = array (); - $unassignedGroups = array (); - //filter only the delegations that are in selfservice status - // `USR_UID` = '' AND `DEL_FINISH_DATE` IS NULL - $indexes = $this->aaSearchRecords( $allAppDbData, array ('USR_UID' => 'NULL','DEL_FINISH_DATE' => 'NULL','APP_THREAD_STATUS' => 'OPEN' - ) ); - foreach ($indexes as $index) { - $unassignedUsersGroups = array (); - // use cache - $oMemcache = PMmemcached::getSingleton( $this->_solrInstance ); - $unassignedUsersGroups = $oMemcache->get( $allAppDbData[$index]['PRO_UID'] . "_" . $allAppDbData[$index]['TAS_UID'] ); - if (! $unassignedUsersGroups) { - - $unassignedUsersGroups = $this->getTaskUnassignedUsersGroupsData( $allAppDbData[$index]['PRO_UID'], $allAppDbData[$index]['TAS_UID'] ); - - // if the task has unassigned users or groups add del_index of delegation - foreach ($unassignedUsersGroups as $i => $newRow) { - $unassignedUsersGroups[$i]['DEL_INDEX'] = $allAppDbData[$index]['DEL_INDEX']; - } - // store in cache - $oMemcache->set( $allAppDbData[$index]['PRO_UID'] . "_" . $allAppDbData[$index]['TAS_UID'], $unassignedUsersGroups ); - } - - // copy list of unassigned users and groups - foreach ($unassignedUsersGroups as $unassignedUserGroup) { - //unassigned users - if ($unassignedUserGroup['TU_RELATION'] == 1) { - $unassignedUsers[] = array ('USR_UID' => $unassignedUserGroup['USR_UID'],'DEL_INDEX' => $unassignedUserGroup['DEL_INDEX'] - ); - } //unassigned groups - elseif ($unassignedUserGroup['TU_RELATION'] == 2) { - $unassignedGroups[] = array ('USR_UID' => $unassignedUserGroup['USR_UID'],'DEL_INDEX' => $unassignedUserGroup['DEL_INDEX'] - ); - } - } - - } - // Get DataTypes of dynaforms - // use cache array to store the dynaform variables per process - // use memory array to store information of Datatypes of Dynaforms - // All the datatypes of the process => all variables in all dynaforms in the - // process - $dynaformFieldTypes = array (); - - // get cache instance - $oMemcache = PMmemcached::getSingleton( $this->_solrInstance ); - $dynaformFieldTypes = $oMemcache->get( $documentInformation['PRO_UID'] ); - if (! $dynaformFieldTypes) { - G::LoadClass( 'dynaformhandler' ); - $dynaformFileNames = $this->getProcessDynaformFileNames( $documentInformation['PRO_UID'] ); - $dynaformFields = array (); - foreach ($dynaformFileNames as $dynaformFileName) { - if (is_file( PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName['DYN_FILENAME'] . '.xml' ) && filesize( PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName['DYN_FILENAME'] . '.xml' ) > 0) { - $dyn = new dynaFormHandler( PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName['DYN_FILENAME'] . '.xml' ); - $dynaformFields[] = $dyn->getFields(); - } - if (is_file( PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName['DYN_FILENAME'] . '.xml' ) && filesize( PATH_DATA . '/sites/workflow/xmlForms/' . $dynaformFileName['DYN_FILENAME'] . '.xml' ) == 0) { - - throw new ApplicationWithCorruptDynaformException( "Application with corrupt dynaform. APP_UID: " . $AppUID . "\n" ); - } - } - - foreach ($dynaformFields as $aDynFormFields) { - foreach ($aDynFormFields as $field) { - // create array of fields and types - if ($field->getAttribute( 'validate' ) == 'Int') { - $dynaformFieldTypes[$field->nodeName] = 'Int'; - } elseif ($field->getAttribute( 'validate' ) == 'Real') { - $dynaformFieldTypes[$field->nodeName] = 'Real'; - } else { - $dynaformFieldTypes[$field->nodeName] = $field->getAttribute( 'type' ); - } - } - } - // create cache of dynaformfields - $oMemcache->set( $documentInformation['PRO_UID'], $dynaformFieldTypes ); - } - - //Return result values - $result = array( - $documentInformation, - $dynaformFieldTypes, - $lastUpdateDate, - $maxPriority, - $assignedUsers, - $assignedUsersRead, - $assignedUsersUnread, - $draftUser, - $participatedUsers, - $participatedUsersStartedByUser, - $participatedUsersCompletedByUser, - $unassignedUsers, - $unassignedGroups, - $pausedUser, - $cancelledUser - ); - - return $result; + return $index; + } + + /** + * Get minimum of array of arrays + * + * @param array $arr + * array of arrays with the data + * @param string $column + * the name of the column to search in + * @param string $columnType + * the column type STRING, NUMBER, DATE + * @param string $columnCondition + * the column condition + * @param string $condition + * the condition + * @return Ambigous Index of the minimun value found + */ + public function aaGetMinimun($arr, $column, $columnType = 'STRING', + $columnCondition = "", $condition = "") + { + // get first value + $auxValue = $arr [0] [$column]; + $index = null; + foreach ($arr as $i => $row) { + switch ($columnType) { + case 'STRING' : + if ((strnatcmp ($row [$column], $auxValue) <= 0) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + } + break; + case 'NUMBER' : + if (($row [$column] <= $auxValue) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + } + break; + case 'DATE' : + if ((strtotime ($row [$column]) <= strtotime ($auxValue)) && (($columnCondition == "") || ($row [$columnCondition] == $condition))) { + $auxValue = $row [$column]; + $index = $i; + + } + break; + } } - - /** - * Find the maximun value of the specified column in the array and return the - * row index - * - * @param array $arr array of arrays with the data - * @param string $column column name to search in - * @param string $columnType column type STRING, NUMBER, DATE - * @param string $columnCondition column condition - * @param string $condition the condition - * @return integer The index of the maximun record in array - */ - public function aaGetMaximun ($arr, $column, $columnType = 'STRING', $columnCondition = "", $condition = "") - { - // get first value - $auxValue = $arr[0][$column]; - $index = null; - foreach ($arr as $i => $row) { - switch ($columnType) { - case 'STRING': - if ((strnatcmp( $row[$column], $auxValue ) >= 0) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - } - break; - case 'NUMBER': - if (($row[$column] >= $auxValue) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - } - break; - case 'DATE': - if ((strtotime( $row[$column] ) >= strtotime( $auxValue )) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - } - break; - } - } - return $index; - } - - /** - * Get minimum of array of arrays - * - * @param array $arr array of arrays with the data - * @param string $column the name of the column to search in - * @param string $columnType the column type STRING, NUMBER, DATE - * @param string $columnCondition the column condition - * @param string $condition the condition - * @return Ambigous Index of the minimun value found - */ - public function aaGetMinimun ($arr, $column, $columnType = 'STRING', $columnCondition = "", $condition = "") - { - // get first value - $auxValue = $arr[0][$column]; - $index = null; - foreach ($arr as $i => $row) { - switch ($columnType) { - case 'STRING': - if ((strnatcmp( $row[$column], $auxValue ) <= 0) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - } - break; - case 'NUMBER': - if (($row[$column] <= $auxValue) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - } - break; - case 'DATE': - if ((strtotime( $row[$column] ) <= strtotime( $auxValue )) && (($columnCondition == "") || ($row[$columnCondition] == $condition))) { - $auxValue = $row[$column]; - $index = $i; - - } - break; - } - } - return $index; - } - - /** - * Search array of indexes that fullfill the conditions - * - * @param array of arrays $arr contains the arrays that are searched - * @param array $andColumnsConditions contain the conditions that must fullfill 'Column'=>'Condition' - * @return array of indexes with the found records - */ - public function aaSearchRecords ($arr, $andColumnsConditions) - { - $indexes = array (); + return $index; + } + + /** + * Search array of indexes that fullfill the conditions + * + * @param + * array of arrays $arr contains the arrays that are searched + * @param array $andColumnsConditions + * contain the conditions that must fullfill 'Column'=>'Condition' + * @return array of indexes with the found records + */ + public function aaSearchRecords($arr, $andColumnsConditions) + { + $indexes = array (); + $isEqual = true; + foreach ($arr as $i => $row) { + $evaluateRow = false; + // evaluate each row + foreach ($andColumnsConditions as $column => $valueCondition) { + $condition = $valueCondition; $isEqual = true; - foreach ($arr as $i => $row) { + if ($valueCondition == 'NULL') { + $isEqual = true; + $condition = ''; + } + if ($valueCondition == 'NOTNULL') { + $isEqual = false; + $condition = ''; + } + if ($isEqual) { + if ($row [$column] == $condition) { + $evaluateRow = true; + } + else { $evaluateRow = false; - // evaluate each row - foreach ($andColumnsConditions as $column => $valueCondition) { - $condition = $valueCondition; - $isEqual = true; - if ($valueCondition == 'NULL') { - $isEqual = true; - $condition = ''; - } - if ($valueCondition == 'NOTNULL') { - $isEqual = false; - $condition = ''; - } - if ($isEqual) { - if ($row[$column] == $condition) { - $evaluateRow = true; - } else { - $evaluateRow = false; - break; - } - } else { - if ($row[$column] != $condition) { - $evaluateRow = true; - } else { - $evaluateRow = false; - break; - } - } - } - // add row to indexes - if ($evaluateRow) { - $indexes[] = $i; - } + breaK; + } } - return $indexes; - } - - /** - * Get application and delegation data from database - * - * @param string $AppUID the application identifier - * @return array of records from database - */ - public function getApplicationDelegationData ($AppUID) - { - - $allAppDbData = array (); - - $c = new Criteria(); - - $c->addSelectColumn( ApplicationPeer::APP_UID ); - $c->addSelectColumn( ApplicationPeer::APP_NUMBER ); - $c->addSelectColumn( ApplicationPeer::APP_STATUS ); - $c->addSelectColumn( ApplicationPeer::PRO_UID ); - $c->addSelectColumn( ApplicationPeer::APP_CREATE_DATE ); - $c->addSelectColumn( ApplicationPeer::APP_FINISH_DATE ); - $c->addSelectColumn( ApplicationPeer::APP_UPDATE_DATE ); - $c->addSelectColumn( ApplicationPeer::APP_DATA ); - - $c->addAsColumn( 'APP_TITLE', 'capp.CON_VALUE' ); - $c->addAsColumn( 'PRO_TITLE', 'cpro.CON_VALUE' ); - - $c->addSelectColumn( 'ad.DEL_INDEX' ); - $c->addSelectColumn( 'ad.DEL_PREVIOUS' ); - $c->addSelectColumn( 'ad.TAS_UID' ); - $c->addSelectColumn( 'ad.USR_UID' ); - $c->addSelectColumn( 'ad.DEL_TYPE' ); - $c->addSelectColumn( 'ad.DEL_THREAD' ); - $c->addSelectColumn( 'ad.DEL_THREAD_STATUS' ); - $c->addSelectColumn( 'ad.DEL_PRIORITY' ); - $c->addSelectColumn( 'ad.DEL_DELEGATE_DATE' ); - $c->addSelectColumn( 'ad.DEL_INIT_DATE' ); - $c->addSelectColumn( 'ad.DEL_TASK_DUE_DATE' ); - $c->addSelectColumn( 'ad.DEL_FINISH_DATE' ); - $c->addSelectColumn( 'ad.DEL_DURATION' ); - $c->addSelectColumn( 'ad.DEL_QUEUE_DURATION' ); - $c->addSelectColumn( 'ad.DEL_DELAY_DURATION' ); - $c->addSelectColumn( 'ad.DEL_STARTED' ); - $c->addSelectColumn( 'ad.DEL_FINISHED' ); - $c->addSelectColumn( 'ad.DEL_DELAYED' ); - $c->addSelectColumn( 'ad.APP_OVERDUE_PERCENTAGE' ); - - $c->addSelectColumn( 'at.APP_THREAD_INDEX' ); - $c->addSelectColumn( 'at.APP_THREAD_PARENT' ); - $c->addSelectColumn( 'at.APP_THREAD_STATUS' ); - - $c->addAlias("capp", ContentPeer::TABLE_NAME); - $c->addAlias("cpro", ContentPeer::TABLE_NAME); - $c->addAlias("ad", AppDelegationPeer::TABLE_NAME); - $c->addAlias("at", AppThreadPeer::TABLE_NAME); - - $aConditions = array (); - $aConditions[] = array (ApplicationPeer::APP_UID,'capp.CON_ID' - ); - $aConditions[] = array ('capp.CON_CATEGORY',DBAdapter::getStringDelimiter() . 'APP_TITLE' . DBAdapter::getStringDelimiter() - ); - $aConditions[] = array ('capp.CON_LANG',DBAdapter::getStringDelimiter() . 'en' . DBAdapter::getStringDelimiter() - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $aConditions = array (); - $aConditions[] = array (ApplicationPeer::PRO_UID,'cpro.CON_ID' - ); - $aConditions[] = array ('cpro.CON_CATEGORY',DBAdapter::getStringDelimiter() . 'PRO_TITLE' . DBAdapter::getStringDelimiter() - ); - $aConditions[] = array ('cpro.CON_LANG',DBAdapter::getStringDelimiter() . 'en' . DBAdapter::getStringDelimiter() - ); - $c->addJoinMC( $aConditions, Criteria::LEFT_JOIN ); - - $c->addJoin( ApplicationPeer::APP_UID, 'ad.APP_UID', Criteria::JOIN ); - - $aConditions = array (); - $aConditions[] = array ('ad.APP_UID','at.APP_UID' - ); - $aConditions[] = array ('ad.DEL_THREAD','at.APP_THREAD_INDEX' - ); - $c->addJoinMC( $aConditions, Criteria::JOIN ); - - $c->add( ApplicationPeer::APP_UID, $AppUID ); - - $rs = ApplicationPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - - $rs->next(); - $row = $rs->getRow(); - - while (is_array( $row )) { - $allAppDbData[] = $row; - $rs->next(); - $row = $rs->getRow(); + else { + if ($row [$column] != $condition) { + $evaluateRow = true; + } + else { + $evaluateRow = false; + breaK; + } } - return $allAppDbData; + } + // add row to indexes + if ($evaluateRow) { + $indexes [] = $i; + } + } + return $indexes; + } + + /** + * Get application and delegation data from database + * + * @param string $AppUID + * the application identifier + * @return array of records from database + */ + public function getApplicationDelegationData($AppUID) + { + + $allAppDbData = array (); + + $c = new Criteria (); + + $c->addSelectColumn (ApplicationPeer::APP_UID); + $c->addSelectColumn (ApplicationPeer::APP_NUMBER); + $c->addSelectColumn (ApplicationPeer::APP_STATUS); + $c->addSelectColumn (ApplicationPeer::PRO_UID); + $c->addSelectColumn (ApplicationPeer::APP_CREATE_DATE); + $c->addSelectColumn (ApplicationPeer::APP_FINISH_DATE); + $c->addSelectColumn (ApplicationPeer::APP_UPDATE_DATE); + $c->addSelectColumn (ApplicationPeer::APP_DATA); + + $c->addAsColumn ('APP_TITLE', 'capp.CON_VALUE'); + $c->addAsColumn ('PRO_TITLE', 'cpro.CON_VALUE'); + + $c->addSelectColumn ('ad.DEL_INDEX'); + $c->addSelectColumn ('ad.DEL_PREVIOUS'); + $c->addSelectColumn ('ad.TAS_UID'); + $c->addSelectColumn ('ad.USR_UID'); + $c->addSelectColumn ('ad.DEL_TYPE'); + $c->addSelectColumn ('ad.DEL_THREAD'); + $c->addSelectColumn ('ad.DEL_THREAD_STATUS'); + $c->addSelectColumn ('ad.DEL_PRIORITY'); + $c->addSelectColumn ('ad.DEL_DELEGATE_DATE'); + $c->addSelectColumn ('ad.DEL_INIT_DATE'); + $c->addSelectColumn ('ad.DEL_TASK_DUE_DATE'); + $c->addSelectColumn ('ad.DEL_FINISH_DATE'); + $c->addSelectColumn ('ad.DEL_DURATION'); + $c->addSelectColumn ('ad.DEL_QUEUE_DURATION'); + $c->addSelectColumn ('ad.DEL_DELAY_DURATION'); + $c->addSelectColumn ('ad.DEL_STARTED'); + $c->addSelectColumn ('ad.DEL_FINISHED'); + $c->addSelectColumn ('ad.DEL_DELAYED'); + $c->addSelectColumn ('ad.APP_OVERDUE_PERCENTAGE'); + + $c->addSelectColumn ('at.APP_THREAD_INDEX'); + $c->addSelectColumn ('at.APP_THREAD_PARENT'); + $c->addSelectColumn ('at.APP_THREAD_STATUS'); + + $c->addAlias ('capp', 'CONTENT'); + $c->addAlias ('cpro', 'CONTENT'); + $c->addAlias ('ad', 'APP_DELEGATION'); + $c->addAlias ('at', 'APP_THREAD'); + + $aConditions = array (); + $aConditions [] = array ( + ApplicationPeer::APP_UID, + 'capp.CON_ID' + ); + $aConditions [] = array ( + 'capp.CON_CATEGORY', + DBAdapter::getStringDelimiter () . 'APP_TITLE' . DBAdapter::getStringDelimiter () + ); + $aConditions [] = array ( + 'capp.CON_LANG', + DBAdapter::getStringDelimiter () . 'en' . DBAdapter::getStringDelimiter () + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + ApplicationPeer::PRO_UID, + 'cpro.CON_ID' + ); + $aConditions [] = array ( + 'cpro.CON_CATEGORY', + DBAdapter::getStringDelimiter () . 'PRO_TITLE' . DBAdapter::getStringDelimiter () + ); + $aConditions [] = array ( + 'cpro.CON_LANG', + DBAdapter::getStringDelimiter () . 'en' . DBAdapter::getStringDelimiter () + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $c->addJoin (ApplicationPeer::APP_UID, 'ad.APP_UID', Criteria::JOIN); + + $aConditions = array (); + $aConditions [] = array ( + 'ad.APP_UID', + 'at.APP_UID' + ); + $aConditions [] = array ( + 'ad.DEL_THREAD', + 'at.APP_THREAD_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::JOIN); + + $c->add (ApplicationPeer::APP_UID, $AppUID); + + $rs = ApplicationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + + $rs->next (); + $row = $rs->getRow (); + + while (is_array ($row)) { + $allAppDbData [] = $row; + $rs->next (); + $row = $rs->getRow (); } - /** - * Get application and delegation data from database - * - * @param string $aAppUID array of application identifiers - * @return array of array of records from database - */ - public function getListApplicationUpdateDelegationData($aaAppUIDs) - { - $allAppDbData = array(); + //Propel::close(); - $c = new Criteria(); + return $allAppDbData; + } + + /** + * Get application and delegation data from database + * + * @param string $aAppUID + * array of application identifiers + * @return array of array of records from database + */ + public function getListApplicationUpdateDelegationData($aaAppUIDs) + { + + $allAppDbData = array (); + + $c = new Criteria (); + + $c->addSelectColumn (ApplicationPeer::APP_UID); + $c->addSelectColumn (ApplicationPeer::APP_NUMBER); + $c->addSelectColumn (ApplicationPeer::APP_STATUS); + $c->addSelectColumn (ApplicationPeer::PRO_UID); + $c->addSelectColumn (ApplicationPeer::APP_CREATE_DATE); + $c->addSelectColumn (ApplicationPeer::APP_FINISH_DATE); + $c->addSelectColumn (ApplicationPeer::APP_UPDATE_DATE); + $c->addSelectColumn (ApplicationPeer::APP_DATA); + + $c->addAsColumn ('APP_TITLE', 'capp.CON_VALUE'); + $c->addAsColumn ('PRO_TITLE', 'cpro.CON_VALUE'); + + $c->addSelectColumn ('ad.DEL_INDEX'); + $c->addSelectColumn ('ad.DEL_PREVIOUS'); + $c->addSelectColumn ('ad.TAS_UID'); + $c->addSelectColumn ('ad.USR_UID'); + $c->addSelectColumn ('ad.DEL_TYPE'); + $c->addSelectColumn ('ad.DEL_THREAD'); + $c->addSelectColumn ('ad.DEL_THREAD_STATUS'); + $c->addSelectColumn ('ad.DEL_PRIORITY'); + $c->addSelectColumn ('ad.DEL_DELEGATE_DATE'); + $c->addSelectColumn ('ad.DEL_INIT_DATE'); + $c->addSelectColumn ('ad.DEL_TASK_DUE_DATE'); + $c->addSelectColumn ('ad.DEL_FINISH_DATE'); + $c->addSelectColumn ('ad.DEL_DURATION'); + $c->addSelectColumn ('ad.DEL_QUEUE_DURATION'); + $c->addSelectColumn ('ad.DEL_DELAY_DURATION'); + $c->addSelectColumn ('ad.DEL_STARTED'); + $c->addSelectColumn ('ad.DEL_FINISHED'); + $c->addSelectColumn ('ad.DEL_DELAYED'); + $c->addSelectColumn ('ad.APP_OVERDUE_PERCENTAGE'); + + $c->addSelectColumn ('at.APP_THREAD_INDEX'); + $c->addSelectColumn ('at.APP_THREAD_PARENT'); + $c->addSelectColumn ('at.APP_THREAD_STATUS'); - $c->addSelectColumn(ApplicationPeer::APP_UID); - $c->addSelectColumn(ApplicationPeer::APP_NUMBER); - $c->addSelectColumn(ApplicationPeer::APP_STATUS); - $c->addSelectColumn(ApplicationPeer::PRO_UID); - $c->addSelectColumn(ApplicationPeer::APP_CREATE_DATE); - $c->addSelectColumn(ApplicationPeer::APP_FINISH_DATE); - $c->addSelectColumn(ApplicationPeer::APP_UPDATE_DATE); - $c->addSelectColumn(ApplicationPeer::APP_DATA); + $c->addAsColumn("PRO_CATEGORY_UID", "pro.PRO_CATEGORY"); + + $c->addAlias ('capp', 'CONTENT'); + $c->addAlias ('cpro', 'CONTENT'); + $c->addAlias ('ad', 'APP_DELEGATION'); + $c->addAlias ('at', 'APP_THREAD'); + $c->addAlias ("pro", ProcessPeer::TABLE_NAME); + + $aConditions = array (); + $aConditions [] = array ( + ApplicationPeer::APP_UID, + 'capp.CON_ID' + ); + $aConditions [] = array ( + 'capp.CON_CATEGORY', + DBAdapter::getStringDelimiter () . 'APP_TITLE' . DBAdapter::getStringDelimiter () + ); + $aConditions [] = array ( + 'capp.CON_LANG', + DBAdapter::getStringDelimiter () . 'en' . DBAdapter::getStringDelimiter () + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $aConditions = array (); + $aConditions [] = array ( + ApplicationPeer::PRO_UID, + 'cpro.CON_ID' + ); + $aConditions [] = array ( + 'cpro.CON_CATEGORY', + DBAdapter::getStringDelimiter () . 'PRO_TITLE' . DBAdapter::getStringDelimiter () + ); + $aConditions [] = array ( + 'cpro.CON_LANG', + DBAdapter::getStringDelimiter () . 'en' . DBAdapter::getStringDelimiter () + ); + $c->addJoinMC ($aConditions, Criteria::LEFT_JOIN); + + $c->addJoin (ApplicationPeer::APP_UID, 'ad.APP_UID', Criteria::JOIN); + + $aConditions = array (); + $aConditions [] = array ( + 'ad.APP_UID', + 'at.APP_UID' + ); + $aConditions [] = array ( + 'ad.DEL_THREAD', + 'at.APP_THREAD_INDEX' + ); + $c->addJoinMC ($aConditions, Criteria::JOIN); - $c->addAsColumn("APP_TITLE", "capp.CON_VALUE"); - $c->addAsColumn("PRO_TITLE", "cpro.CON_VALUE"); - - $c->addSelectColumn("ad.DEL_INDEX"); - $c->addSelectColumn("ad.DEL_PREVIOUS"); - $c->addSelectColumn("ad.TAS_UID"); - $c->addSelectColumn("ad.USR_UID"); - $c->addSelectColumn("ad.DEL_TYPE"); - $c->addSelectColumn("ad.DEL_THREAD"); - $c->addSelectColumn("ad.DEL_THREAD_STATUS"); - $c->addSelectColumn("ad.DEL_PRIORITY"); - $c->addSelectColumn("ad.DEL_DELEGATE_DATE"); - $c->addSelectColumn("ad.DEL_INIT_DATE"); - $c->addSelectColumn("ad.DEL_TASK_DUE_DATE"); - $c->addSelectColumn("ad.DEL_FINISH_DATE"); - $c->addSelectColumn("ad.DEL_DURATION"); - $c->addSelectColumn("ad.DEL_QUEUE_DURATION"); - $c->addSelectColumn("ad.DEL_DELAY_DURATION"); - $c->addSelectColumn("ad.DEL_STARTED"); - $c->addSelectColumn("ad.DEL_FINISHED"); - $c->addSelectColumn("ad.DEL_DELAYED"); - $c->addSelectColumn("ad.APP_OVERDUE_PERCENTAGE"); - - $c->addSelectColumn("at.APP_THREAD_INDEX"); - $c->addSelectColumn("at.APP_THREAD_PARENT"); - $c->addSelectColumn("at.APP_THREAD_STATUS"); - - $c->addAsColumn("APPDELY_APP_DELAY_UID", "appDely.APP_DELAY_UID"); - $c->addAsColumn("APPDELY_APP_TYPE", "appDely.APP_TYPE"); - $c->addAsColumn("APPDELY_APP_DISABLE_ACTION_USER", "appDely.APP_DISABLE_ACTION_USER"); - - $c->addAsColumn("PRO_CATEGORY_UID", "pro.PRO_CATEGORY"); - - $c->addAlias("capp", ContentPeer::TABLE_NAME); - $c->addAlias("cpro", ContentPeer::TABLE_NAME); - $c->addAlias("ad", AppDelegationPeer::TABLE_NAME); - $c->addAlias("at", AppThreadPeer::TABLE_NAME); - $c->addAlias("appDely", AppDelayPeer::TABLE_NAME); - $c->addAlias("pro", ProcessPeer::TABLE_NAME); - - $arrayCondition = array(); - $arrayCondition[] = array(ApplicationPeer::APP_UID, "capp.CON_ID"); - $arrayCondition[] = array("capp.CON_CATEGORY", DBAdapter::getStringDelimiter() . "APP_TITLE" . DBAdapter::getStringDelimiter()); - $arrayCondition[] = array("capp.CON_LANG", DBAdapter::getStringDelimiter() . "en" . DBAdapter::getStringDelimiter()); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(ApplicationPeer::PRO_UID, "cpro.CON_ID"); - $arrayCondition[] = array("cpro.CON_CATEGORY", DBAdapter::getStringDelimiter() . "PRO_TITLE" . DBAdapter::getStringDelimiter()); - $arrayCondition[] = array("cpro.CON_LANG", DBAdapter::getStringDelimiter() . "en" . DBAdapter::getStringDelimiter()); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $c->addJoin(ApplicationPeer::APP_UID, "ad.APP_UID", Criteria::JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array("ad.APP_UID", "at.APP_UID"); - $arrayCondition[] = array("ad.DEL_THREAD", "at.APP_THREAD_INDEX"); - $c->addJoinMC($arrayCondition, Criteria::JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array("ad.APP_UID", "appDely.APP_UID"); - $arrayCondition[] = array("ad.DEL_INDEX", "appDely.APP_DEL_INDEX"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $arrayCondition = array(); - $arrayCondition[] = array(ApplicationPeer::PRO_UID, "pro.PRO_UID"); - $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); - - $c->add(ApplicationPeer::APP_UID, $aaAppUIDs, Criteria::IN); - - $rs = ApplicationPeer::doSelectRS($c); - $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); - - while ($rs->next()) { - $row = $rs->getRow(); - - $allAppDbData[] = $row; - } - - return $allAppDbData; + $arrayCondition = array(); + $arrayCondition[] = array(ApplicationPeer::PRO_UID, "pro.PRO_UID"); + $c->addJoinMC($arrayCondition, Criteria::LEFT_JOIN); + + $c->add (ApplicationPeer::APP_UID, $aaAppUIDs, Criteria::IN); + + $rs = ApplicationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + + $rs->next (); + $row = $rs->getRow (); + + while (is_array ($row)) { + $allAppDbData [] = $row; + $rs->next (); + $row = $rs->getRow (); } - /** - * Get the list of groups of unassigned users of the specified task from - * database - * - * @param string $ProUID Process identifier - * @param string $TaskUID task identifier - * @return array of unassigned user groups - */ - public function getTaskUnassignedUsersGroupsData ($ProUID, $TaskUID) - { - $unassignedUsersGroups = array (); + //Propel::close(); - $c = new Criteria(); + return $allAppDbData; + } + + /** + * Get the list of groups of unassigned users of the specified task from + * database + * + * @param string $ProUID + * Process identifier + * @param string $TaskUID + * task identifier + * @return array of unassigned user groups + */ + public function getTaskUnassignedUsersGroupsData($ProUID, $TaskUID) + { + $unassignedUsersGroups = array (); + + $c = new Criteria (); + + $c->addSelectColumn (TaskUserPeer::USR_UID); + $c->addSelectColumn (TaskUserPeer::TU_RELATION); + + $aConditions = array (); + $aConditions [] = array ( + TaskPeer::TAS_UID, + TaskUserPeer::TAS_UID + ); + $aConditions [] = array ( + TaskPeer::TAS_ASSIGN_TYPE, + DBAdapter::getStringDelimiter () . 'SELF_SERVICE' . DBAdapter::getStringDelimiter () + ); + $c->addJoinMC ($aConditions, Criteria::JOIN); + + $c->add (TaskPeer::PRO_UID, $ProUID); + $c->add (TaskPeer::TAS_UID, $TaskUID); + + $rs = TaskPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + // echo $c->toString(); + $rs->next (); + $row = $rs->getRow (); + + while (is_array ($row)) { + $unassignedUsersGroups [] = $row; + $rs->next (); + $row = $rs->getRow (); + } + + //Propel::close(); - $c->addSelectColumn( TaskUserPeer::USR_UID ); - $c->addSelectColumn( TaskUserPeer::TU_RELATION ); + return $unassignedUsersGroups; + } + + /** + * Get the list of dynaform file names associated with the specified process + * from database + * + * @param string $ProUID + * process identifier + * @return array of dynaform file names + */ + public function getProcessDynaformFileNames($ProUID) + { + $dynaformFileNames = array (); + + $c = new Criteria (); + + $c->addSelectColumn (DynaformPeer::DYN_FILENAME); + + $c->add (DynaformPeer::PRO_UID, $ProUID); + + $rs = DynaformPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + $rs->next (); + $row = $rs->getRow (); + + while (is_array ($row)) { + $dynaformFileNames [] = $row; + $rs->next (); + $row = $rs->getRow (); + } + + //Propel::close(); - $aConditions = array (); - $aConditions[] = array (TaskPeer::TAS_UID,TaskUserPeer::TAS_UID - ); - $aConditions[] = array (TaskPeer::TAS_ASSIGN_TYPE,DBAdapter::getStringDelimiter() . 'SELF_SERVICE' . DBAdapter::getStringDelimiter() - ); - $c->addJoinMC( $aConditions, Criteria::JOIN ); + return $dynaformFileNames; + } + + /** + * Store a flag indicating if the application was updated in database + * table APP_SOLR_QUEUE + * + * @param string $AppUid + * applicatiom identifier + * @param integer $updated + * 0:false, not updated, 1: updated, 2:deleted + */ + public function applicationChangedUpdateSolrQueue($AppUid, $updated) + { + $traceData = $this->getCurrentTraceInfo(); + //var_dump($traceData); - $c->add( TaskPeer::PRO_UID, $ProUID ); - $c->add( TaskPeer::TAS_UID, $TaskUID ); + $oAppSolrQueue = new AppSolrQueue (); + + $oAppSolrQueue->createUpdate ($AppUid, $traceData, $updated); + } - $rs = TaskPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - // echo $c->toString(); - $rs->next(); - $row = $rs->getRow(); + private function getCurrentTraceInfo() + { + $resultTraceString = ""; - while (is_array( $row )) { - $unassignedUsersGroups[] = $row; - $rs->next(); - $row = $rs->getRow(); - } + // + $traceData = debug_backtrace(); + foreach ($traceData as $key => $value) { + if($value['function'] != 'getCurrentTraceInfo' && $value['function'] != 'require_once') + $resultTraceString .= $value['file'] . " (" . $value['line'] . ") " . $value['function'] . "\n"; + } + return $resultTraceString; + } + + /** + * Update application records in Solr that are stored in APP_SOLR_QUEUE table + */ + public function synchronizePendingApplications() + { + if(!$this->isSolrEnabled()) + throw new Exception(date('Y-m-d H:i:s:u') . " Error connecting to solr server."); + + // check table of pending updates + $oAppSolrQueue = new AppSolrQueue (); + + $aAppSolrQueue = $oAppSolrQueue->getListUpdatedApplications (); - return $unassignedUsersGroups; + $trunkSize = 100; + //filter updated cases + $aUpdatedApplications = array(); + $aDeletedApplications = array(); + foreach ($aAppSolrQueue as $oAppSolrQueueEntity) { + // call the syncronization function + if($oAppSolrQueueEntity->appUpdated == 1){ + $aUpdatedApplications[] = array ('APP_UID' => $oAppSolrQueueEntity->appUid ); + } + if($oAppSolrQueueEntity->appUpdated == 2){ + $aDeletedApplications[] = array ('APP_UID' => $oAppSolrQueueEntity->appUid ); + } } - /** - * Get the list of dynaform file names associated with the specified process - * from database - * - * @param string $ProUID process identifier - * @return array of dynaform file names - */ - public function getProcessDynaformFileNames ($ProUID) - { - $dynaformFileNames = array (); + $totalCasesUpdated = count($aUpdatedApplications); + $loops = ((($totalCasesUpdated % $trunkSize) > 0 )? ($totalCasesUpdated / $trunkSize)+1: ($totalCasesUpdated / $trunkSize)); + for ($i = 0; $i < $loops; $i++) { + //prepare trunk of appuids + $trunkUpdatedApplications = array_slice($aUpdatedApplications, $i * $trunkSize, $trunkSize); - $c = new Criteria(); + $this->updateApplicationSearchIndex ($trunkUpdatedApplications, true); - $c->addSelectColumn( DynaformPeer::DYN_FILENAME ); - - $c->add( DynaformPeer::PRO_UID, $ProUID ); - - $rs = DynaformPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $rs->next(); - $row = $rs->getRow(); - - while (is_array( $row )) { - $dynaformFileNames[] = $row; - $rs->next(); - $row = $rs->getRow(); - } - - return $dynaformFileNames; + /*foreach($trunkUpdatedApplications as $appUid){ + $this->applicationChangedUpdateSolrQueue ($appUid, 0); + }*/ } - /** - * Store a flag indicating if the application was updated in database - * table APP_SOLR_QUEUE - * - * @param string $AppUid applicatiom identifier - * @param integer $updated 0:false, not updated, 1: updated, 2:deleted - */ - public function applicationChangedUpdateSolrQueue ($AppUid, $updated) - { - $traceData = $this->getCurrentTraceInfo(); + $totalCasesDeleted = count($aDeletedApplications); + $loops = ((($totalCasesDeleted % $trunkSize) > 0 )? ($totalCasesDeleted / $trunkSize)+1: ($totalCasesDeleted / $trunkSize)); + for ($i = 0; $i < $loops; $i++) { + //prepare trunk of appuids + $trunkDeleteddApplications = array_slice($aDeletedApplications, $i * $trunkSize, $trunkSize); - $oAppSolrQueue = new AppSolrQueue(); + $this->deleteApplicationSearchIndex ($trunkDeleteddApplications, true); - $oAppSolrQueue->createUpdate($AppUid, $traceData, $updated); + /*foreach($trunkDeleteddApplications as $appUid){ + $this->applicationChangedUpdateSolrQueue ($appUid, 0); + }*/ + } + + /* + foreach ($aAppSolrQueue as $oAppSolrQueueEntity) { + // call the syncronization function + if($oAppSolrQueueEntity->appUpdated == 1){ + $this->updateApplicationSearchIndex ($oAppSolrQueueEntity->appUid, false); + } + if($oAppSolrQueueEntity->appUpdated == 2){ + $this->deleteApplicationSearchIndex ($oAppSolrQueueEntity->appUid, false); + } + $this->applicationChangedUpdateSolrQueue ($oAppSolrQueueEntity->appUid, 0); + }*/ + } + + /** + * Get the total number of application records in database + * + * @return integer application counter + */ + public function getCountApplicationsPMOS2() + { + $c = new Criteria (); + + $c->addSelectColumn (ApplicationPeer::APP_UID); + + $count = ApplicationPeer::doCount ($c); + + //Propel::close(); + + return $count; + } + + /** + * Get the total number of application records in search index + * + * @return integer application counter + */ + public function getCountApplicationsSearchIndex() + { + G::LoadClass ('searchIndex'); + + $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + // execute query + $count = $searchIndex->getNumberDocuments ($this->_solrInstance); + + return $count; + } + + /** + * Optimize the records in search index + * + * @return + */ + public function optimizeSearchIndex() + { + G::LoadClass ('searchIndex'); + + $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); + // execute query + $searchIndex->optimizeIndexChanges ($this->_solrInstance); + + } + + /** + * Get a paginated list of application uids from database. + * + * @param integer $skip + * the offset from where to return the application records + * @param integer $pagesize + * the size of the page + * @return array of application id's in the specified page. + */ + public function getPagedApplicationUids($skip, $pagesize) + { + + $c = new Criteria (); + + $c->addSelectColumn (ApplicationPeer::APP_UID); + $c->setOffset ($skip); + $c->setLimit ($pagesize); + + $rs = ApplicationPeer::doSelectRS ($c); + $rs->setFetchmode (ResultSet::FETCHMODE_ASSOC); + + $rs->next (); + $row = $rs->getRow (); + $appUIds = array (); + while (is_array ($row)) { + $appUIds [] = $row; + $rs->next (); + $row = $rs->getRow (); } - private function getCurrentTraceInfo() - { - $traceData = debug_backtrace(); - $resultTraceString = ""; + //Propel::close(); - foreach ($traceData as $key => $value) { - if ($value["function"] != "getCurrentTraceInfo" && $value["function"] != "require_once") { - $resultTraceString .= $value["file"] . " (" . $value["line"] . ") " . $value["function"] . "\n"; - } - } + return $appUIds; + } + + /** + * Reindex all the application records in Solr server + * update applications in groups of 1000 + */ + public function reindexAllApplications($SkipRecords = 0, $indexTrunkSize = 1000) + { + $trunk = $indexTrunkSize; - return $resultTraceString; + if(!$this->isSolrEnabled()) + throw new Exception(date('Y-m-d H:i:s:u') . " Error connecting to solr server."); + + // delete all documents to begin reindex + // deleteAllDocuments(); + // commitChanges(); + // print "Deleted all documents \n"; + // search trunks of id's to regenerate index + $numRows = $this->getCountApplicationsPMOS2 (); + print "Total number of records: " . $numRows . "\n"; + // + $initTimeAll = microtime (true); + + for ($skip = $SkipRecords; $skip <= $numRows;) { + $aaAPPUIds = $this->getPagedApplicationUids ($skip, $trunk); + + printf ("Indexing %d to %d \n", $skip, $skip + $trunk); + $initTimeDoc = microtime (true); + $this->updateApplicationSearchIndex ($aaAPPUIds, false); + + $curTimeDoc = gmdate ('H:i:s', (microtime (true) - $initTimeDoc)); + printf ("Indexing document time: %s \n", $curTimeDoc); + $skip += $trunk; } + + $curTimeDoc = gmdate ('H:i:s', (microtime (true) - $initTimeAll)); + printf ("Total reindex time: %s \n", $curTimeDoc); + printf ("Reindex completed successfully!!.\n"); + } - /** - * Update application records in Solr that are stored in APP_SOLR_QUEUE table - */ - public function synchronizePendingApplications () - { - if (!$this->isSolrEnabled()) { - throw new Exception("Error connecting to solr server."); - } - - // check table of pending updates - $oAppSolrQueue = new AppSolrQueue(); - - $aAppSolrQueue = $oAppSolrQueue->getListUpdatedApplications(); - - foreach ($aAppSolrQueue as $oAppSolrQueueEntity) { - // call the syncronization function - if ($oAppSolrQueueEntity->appUpdated == 1) { - $this->updateApplicationSearchIndex($oAppSolrQueueEntity->appUid, false); - } - if ($oAppSolrQueueEntity->appUpdated == 2) { - $this->deleteApplicationSearchIndex($oAppSolrQueueEntity->appUid, false); - } - $this->applicationChangedUpdateSolrQueue( $oAppSolrQueueEntity->appUid, 0 ); - } - } - - /** - * Get the total number of application records in database - * - * @return integer application counter - */ - public function getCountApplicationsPMOS2 () - { - $c = new Criteria(); - - $c->addSelectColumn( ApplicationPeer::APP_UID ); - - $count = ApplicationPeer::doCount( $c ); - - return $count; - } - - /** - * Get the total number of application records in search index - * - * @return integer application counter - */ - public function getCountApplicationsSearchIndex () - { - G::LoadClass( 'searchIndex' ); - - $searchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - // execute query - $count = $searchIndex->getNumberDocuments( $this->_solrInstance ); - - return $count; - } - - /** - * Optimize the records in search index - * - * @return - * - */ - public function optimizeSearchIndex () - { - G::LoadClass( 'searchIndex' ); - - $searchIndex = new BpmnEngine_Services_SearchIndex( $this->_solrIsEnabled, $this->_solrHost ); - // execute query - $searchIndex->optimizeIndexChanges( $this->_solrInstance ); - - } - - /** - * Get a paginated list of application uids from database. - * - * @param integer $skip the offset from where to return the application records - * @param integer $pagesize the size of the page - * @return array of application id's in the specified page. - */ - public function getPagedApplicationUids ($skip, $pagesize) - { - - $c = new Criteria(); - - $c->addSelectColumn( ApplicationPeer::APP_UID ); - $c->setOffset( $skip ); - $c->setLimit( $pagesize ); - - $rs = ApplicationPeer::doSelectRS( $c ); - $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - - $rs->next(); - $row = $rs->getRow(); - $appUIds = array (); - while (is_array( $row )) { - $appUIds[] = $row; - $rs->next(); - $row = $rs->getRow(); - } - return $appUIds; - } - - /** - * Reindex all the application records in Solr server - * update applications in groups of 1000 - */ - public function reindexAllApplications ($SkipRecords = 0, $indexTrunkSize = 1000) - { - if (!$this->isSolrEnabled()) { - throw new Exception("Error connecting to solr server."); - } - - $trunk = $indexTrunkSize; - - // delete all documents to begin reindex - // deleteAllDocuments(); - // commitChanges(); - // print "Deleted all documents \n"; - // search trunks of id's to regenerate index - $numRows = $this->getCountApplicationsPMOS2(); - print "Total number of records: " . $numRows . "\n"; - $initTimeAll = microtime( true ); - - for ($skip = $SkipRecords; $skip <= $numRows; true) { - $aaAPPUIds = $this->getPagedApplicationUids( $skip, $trunk ); - - printf( "Indexing %d to %d \n", $skip, $skip + $trunk ); - $initTimeDoc = microtime( true ); - $this->updateApplicationSearchIndex($aaAPPUIds, false); - - $curTimeDoc = gmdate( 'H:i:s', (microtime( true ) - $initTimeDoc) ); - printf( "Indexing document time: %s \n", $curTimeDoc ); - $skip += $trunk; - } - - $curTimeDoc = gmdate( 'H:i:s', (microtime( true ) - $initTimeAll) ); - printf( "Total reindex time: %s \n", $curTimeDoc ); - printf( "Reindex completed successfully!!.\n" ); - } } - diff --git a/workflow/engine/classes/class.memcached.php b/workflow/engine/classes/class.memcached.php index 49cfa3266..f0c20f2dc 100644 --- a/workflow/engine/classes/class.memcached.php +++ b/workflow/engine/classes/class.memcached.php @@ -153,7 +153,7 @@ class PMmemcached public function delete($key) { - if (!$this->connected) { + if (! $this->connected || $this->class == 'filecache') { return false; } @@ -162,7 +162,7 @@ class PMmemcached public function flush() { - if (!$this->connected) { + if (! $this->connected || $this->class == 'filecache') { return false; } @@ -171,7 +171,7 @@ class PMmemcached public function getStats() { - if (!$this->connected) { + if (! $this->connected || $this->class == 'filecache') { return false; } @@ -180,13 +180,13 @@ class PMmemcached public function printDetails() { - if (!$this->connected) { + if (! $this->connected || $this->class == 'filecache') { return false; } $status = $this->mem->getStats(); - if (!is_array($status)) { + if (! is_array($status)) { return false; } diff --git a/workflow/engine/classes/class.searchIndex.php b/workflow/engine/classes/class.searchIndex.php index 3ea5497d0..5b00cee56 100644 --- a/workflow/engine/classes/class.searchIndex.php +++ b/workflow/engine/classes/class.searchIndex.php @@ -1,5 +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; - // } - } - + private $_solrIsEnabled = false; + private $_solrHost = ""; + + 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($workspace) + { + // 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 ($workspace); + } + + /** + * 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'); + /** - * 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($workspace) - { - // 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($workspace); + // 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); } - + /** - * 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; } - - /** - * *************************************************************** - */ - // 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]; - } + // 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; } - // 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][$columnName] = $doc->$columnName; - } else { - $data["aaData"][$i][$columnName] = ""; - } - } - } - } - - $solrQueryResponse = Entity_SolrQueryResult::createForRequest( $data ); - // - - - return $solrQueryResponse; + } } - + // TODO:convert facet queries + // ----- /** - * 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; + // 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] [$columnName] = $doc->$columnName; + } + else { + $data ['aaData'] [$i] [$columnName] = ''; + } + } + } + } + + $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; + } +} \ No newline at end of file diff --git a/workflow/engine/classes/class.solr.php b/workflow/engine/classes/class.solr.php index 3dbdfd32d..2bf840a5d 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($workspace) + { + $resultServerStatus = false; - const SOLR_VERSION = '&version=2.2'; + //if($this->_solrIsEnabled != true) + //return $resultServerStatus; - private $_solrIsEnabled = false; - private $_solrHost = ""; + // verify solr server response + try{ + $resultServerStatus = $this->ping($workspace); + }catch(Exception $ex){ + $resultServerStatus = false; + } + + return $resultServerStatus; + } + + /** + * 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); - public function __construct($solrIsEnabled = false, $solrHost = "") - { - // use the parameters to initialize class - $this->_solrIsEnabled = $solrIsEnabled; - $this->_solrHost = $solrHost; + //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:')); } - /** - * Verify if the Solr service is available - * @gearman = false - * @rest = false - * @background = false - * - * @return bool - */ - public function isEnabled($workspace) - { - $resultServerStatus = false; + $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 (date('Y-m-d H:i:s:u') . " 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); + } + + $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); - if ($this->_solrIsEnabled != true) { - return $resultServerStatus; - } - - //Verify solr server response - try { - $resultServerStatus = $this->ping($workspace); - } catch (Exception $e) { - $resultServerStatus = false; - } - - return $resultServerStatus; + //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:')); } - /** - * 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"; + $response = curl_exec ($handler); + curl_close ($handler); + + // decode + $responseSolr = G::json_decode ($response); + if ($responseSolr->responseHeader->status != 0) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error executing query to Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + + 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"; + + $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 - $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; + //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:')); } - /** - * 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; + $response = curl_exec ($handler); + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error updating document in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * 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 - // 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; + //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:')); } - /** - * 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"; + $response = curl_exec ($handler); + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error commiting changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * Rollback the changes since the last commit + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function rollbackChanges($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 - $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:')); - } - - $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"); - } + //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:')); } - /** - * 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"; + $response = curl_exec ($handler); + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error rolling back changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * Optimize Solr index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function optimizeChanges($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 - $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:')); - } - - $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"); - } + //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:')); } - /** - * Rollback the changes since the last commit - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function rollbackChanges($workspace) - { - if (!$this->_solrIsEnabled) { - return; - } + $response = curl_exec ($handler); + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error optimizing changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * 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; + + $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"; + + $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 .= "/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:')); - } - - $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"); - } + //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:')); } - /** - * Optimize Solr index - * @gearman = false - * @rest = false - * @background = false - * - * @return solr response - */ - public function optimizeChanges($workspace) - { - if (!$this->_solrIsEnabled) { - return; - } + $response = curl_exec ($handler); + curl_close ($handler); + // decode + $responseSolr = G::json_decode ($response); + if ($responseSolr->responseHeader->status != 0) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error getting index fields in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + return $responseSolr; + } + + /** + * Ping the Solr Server to check his health + * + * @param string $workspace + * Solr instance name + * @throws Exception + * @return void mixed of field names + */ + public function ping($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 .= "/admin/ping?wt=json"; + + $handler = curl_init ($solrIntruct); + curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec ($handler); + curl_close ($handler); - $solrIntruct = ''; - // get configuration information in base to workspace parameter - $solrIntruct = (substr($this->_solrHost, - 1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; - $solrIntruct .= $workspace; - $solrIntruct .= "/update"; + //there's no response + if(!$response) + return false; - $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:')); - } + // decode + $responseSolr = G::json_decode ($response); + if ($responseSolr->responseHeader->status != "OK") { + throw new Exception (date('Y-m-d H:i:s:u') . " Error pinging Solr server." . $solrIntruct . " response error: " . $response . "\n"); + } + return true; + } - $response = curl_exec($handler); - curl_close($handler); + /** + * 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"; + + $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 - $swOk = strpos($response, '0'); - if (!$swOk) { - throw new Exception("Error optimizing changes in Solr." . $solrIntruct . " response error: " . $response . "\n"); - } + //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:')); } - /** - * 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; - } + $response = curl_exec ($handler); + + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error deleting all documents in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * 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(); + + $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 - $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"; - - $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; + //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:')); } - /** - * Ping the Solr Server to check his health - * - * @param string $workspace - * Solr instance name - * @throws Exception - * @return void mixed of field names - */ - public function ping($workspace) - { - if (!$this->_solrIsEnabled) { - return; - } + $response = curl_exec ($handler); + + curl_close ($handler); + + $swOk = strpos ($response, '0'); + if (! $swOk) { + throw new Exception (date('Y-m-d H:i:s:u') . " Error deleting document in Solr." . $solrIntruct . " response error: " . $response . "\n"); + } + } + + /** + * 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);
 
-        $solrIntruct = "";
-
-        //Get configuration information in base to workspace parameter
-        $solrIntruct = (substr($this->_solrHost, -1) == "/") ? $this->_solrHost : $this->_solrHost . "/";
-        $solrIntruct .= $workspace;
-        $solrIntruct .= "/admin/ping?wt=json";
-
-        $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);
-
-        //There's no response
-        if (!$response) {
-            return false;
-        }
-
-        //Decode
-        $responseSolr = G::json_decode($response);
-
-        if ($responseSolr->responseHeader->status != "OK") {
-            throw new Exception("Error pinging Solr server." . $solrIntruct . " response error: " . $response . "\n");
-        }
-
-        return 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:'));
     }
 
-    /**
-     * 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";
-
-        $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:'));
-        }
-
-        $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");
-        }
-    }
-
-    /**
-     * 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();
-
-
-        $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:'));
-        }
-
-        $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");
-        }
-    }
-
-    /**
-     * 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;
+    $response = curl_exec ($handler);
+    curl_close ($handler);
+    
+    // decode
+    $responseSolr = G::json_decode ($response);
+    if ($responseSolr->responseHeader->status != 0) {
+      throw new Exception (date('Y-m-d H:i:s:u') . " Error getting faceted list from Solr." . $solrIntruct . " response error: " . $response . "\n");
     }
+    
+    return $responseSolr;
+  }
 }
-
diff --git a/workflow/engine/classes/entities/AppSolrQueue.php b/workflow/engine/classes/entities/AppSolrQueue.php
index 6c3ef1290..8df7933fa 100644
--- a/workflow/engine/classes/entities/AppSolrQueue.php
+++ b/workflow/engine/classes/entities/AppSolrQueue.php
@@ -1,43 +1,43 @@
 initializeObject ($data);
+    
+    $requiredFields = array (
+        "appUid",
+        "appChangeDate",
+        "appChangeTrace",
+        "appUpdated" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
-    private function __construct ()
-    {
-
-    }
-
-    static function createEmpty ()
-    {
-        $obj = new Entity_AppSolrQueue();
-        return $obj;
-    }
-
-    static function createForRequest ($data)
-    {
-        $obj = new Entity_AppSolrQueue();
-
-        $obj->initializeObject( $data );
-
-        $requiredFields = array(
-            "appUid",
-            "appChangeDate",
-            "appChangeTrace",
-            "appUpdated"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
 }
-
diff --git a/workflow/engine/classes/entities/Base.php b/workflow/engine/classes/entities/Base.php
index b8134c007..5aa927469 100644
--- a/workflow/engine/classes/entities/Base.php
+++ b/workflow/engine/classes/entities/Base.php
@@ -2,154 +2,156 @@
 
 class Entity_Base
 {
-
-    /**
-     * this function check if a field is in the data sent in the constructor
-     * you can specify an array, and this function will use like alias
-     */
-    protected function validateField ($field, $default = false)
-    {
-        $fieldIsEmpty = true;
-
-        // this is a trick, if $fields is a string, $fields will be an array with
-        // one element
-        if (is_array( $field )) {
-            $fields = $field;
-        } else {
-            $fields = array ();
-            $fields[] = $field;
-        }
-
-        // if there are aliases for this field, evaluate all aliases and take the
-        // first occurence
-        foreach ($fields as $k => $f) {
-            if (isset( $this->temp[$f] )) {
-                $fieldIsEmpty = false;
-                return $this->temp[$f];
-            }
-        }
-
-        // field empty means the user has not sent a value for this Field, so we are
-        // using the default value
-        if ($fieldIsEmpty) {
-            if ($default !== false) {
-                return $default;
-            }
+  
+  /**
+   * this function check if a field is in the data sent in the constructor
+   * you can specify an array, and this function will use like alias
+   */
+  protected function validateField($field, $default = false)
+  {
+    $fieldIsEmpty = true;
+    
+    // this is a trick, if $fields is a string, $fields will be an array with
+    // one element
+    if (is_array ($field)) {
+      $fields = $field;
+    }
+    else {
+      $fields = array ();
+      $fields [] = $field;
+    }
+    
+    // if there are aliases for this field, evaluate all aliases and take the
+    // first occurence
+    foreach ($fields as $k => $f) {
+      if (isset ($this->temp [$f])) {
+        $fieldIsEmpty = false;
+        return $this->temp [$f];
+      }
+    }
+    
+    // field empty means the user has not sent a value for this Field, so we are
+    // using the default value
+    if ($fieldIsEmpty) {
+      if ($default !== false) {
+        return $default;
+      }
+    }
+  }
+  
+  protected function validateRequiredFields($requiredFields = array())
+  {
+    foreach ($requiredFields as $k => $field) {
+      if ($this->{$field} === NULL) {
+        throw (new Exception ("Field $field is required in " . get_class ($this)));
+        die ();
+      }
+    }
+  }
+  
+  /**
+   *
+   *
+   *
+   * Copy the values of the Entity to the array of aliases
+   * The array of aliases must be defined.
+   *
+   * @return Array of alias with the Entity values
+   */
+  public function getAliasDataArray()
+  {
+    $aAlias = array ();
+    // get aliases from class
+    $className = get_class ($this);
+    if (method_exists ($className, 'GetAliases')) {
+      $aliases = call_user_func (array (
+          $className,
+          'GetAliases' 
+      ));
+      // $aliases = $className::GetAliases ();
+      foreach ($this as $field => $value)
+        if (isset ($aliases [$field])) {
+          // echo "Field exists in Aliases: " . $field . "\n";
+          // echo "Alias Name:" . $aliases[$field] . "\n";
+          // echo "Alias value:" . $value . "\n";
+          $aAlias [$aliases [$field]] = $value;
         }
     }
-
-    protected function validateRequiredFields ($requiredFields = array())
-    {
-        foreach ($requiredFields as $k => $field) {
-            if ($this->{$field} === null) {
-                throw (new Exception( "Field $field is required in " . get_class( $this ) ));
-                die();
-            }
-        }
+    
+    return $aAlias;
+  }
+  
+  /**
+   *
+   *
+   *
+   * Set the data from array of alias to Entity
+   *
+   * @param $aAliasData array
+   *          of data of aliases
+   */
+  public function setAliasDataArray($aAliasData)
+  {
+    // get aliases from class
+    $className = get_class ($this);
+    if (method_exists ($className, 'GetAliases')) {
+      $aliases = call_user_func (array (
+          $className,
+          'GetAliases' 
+      ));
+      // $aliases = $className::GetAliases ();
+      foreach ($this as $field => $value)
+        if (isset ($aliases [$field]))
+          $this->{$field} = $aAliasData [$aliases [$field]];
     }
-
-    /**
-     *
-     *
-     *
-     *
-     * Copy the values of the Entity to the array of aliases
-     * The array of aliases must be defined.
-     *
-     * @return Array of alias with the Entity values
-     */
-    public function getAliasDataArray ()
-    {
-        $aAlias = array ();
-        // get aliases from class
-        $className = get_class( $this );
-        if (method_exists( $className, 'GetAliases' )) {
-            $aliases = call_user_func( array ($className,'GetAliases'
-            ) );
-            // $aliases = $className::GetAliases ();
-            foreach ($this as $field => $value) {
-                if (isset( $aliases[$field] )) {
-                    // echo "Field exists in Aliases: " . $field . "\n";
-                    // echo "Alias Name:" . $aliases[$field] . "\n";
-                    // echo "Alias value:" . $value . "\n";
-                    $aAlias[$aliases[$field]] = $value;
-                }
-            }
-        }
-
-        return $aAlias;
+  }
+  
+  /**
+   *
+   *
+   *
+   * Initialize object with values from $data.
+   * The values from data use properties or alias array.
+   *
+   * @param
+   *          $data
+   */
+  protected function initializeObject($data)
+  {
+    // get aliases from class
+    $className = get_class ($this);
+    $aliases = array ();
+    $swAliases = false;
+    if (method_exists ($className, 'GetAliases')) {
+      $aliases = call_user_func (array (
+          $className,
+          'GetAliases' 
+      ));
+      // $aliases = $className::GetAliases ();
+      $swAliases = true;
     }
+    // use object properties or aliases to initialize
+    foreach ($this as $field => $value)
+      if (isset ($data [$field])) {
+        $this->$field = $data [$field];
+      }
+      elseif ($swAliases && isset ($aliases [$field]) && isset ($data [$aliases [$field]])) {
+        $this->$field = $data [$aliases [$field]];
+      }
+  }
+  
+  public function serialize()
+  {
+    if (isset ($this->temp))
+      unset ($this->temp);
+    return serialize ($this);
+  }
+  
+  public function unserialize($str)
+  {
+    $className = get_class ($this);
+    $data = unserialize ($str);
+    return new $className ($data);
+  }
 
-    /**
-     *
-     *
-     *
-     *
-     * Set the data from array of alias to Entity
-     *
-     * @param $aAliasData array of data of aliases
-     */
-    public function setAliasDataArray ($aAliasData)
-    {
-        // get aliases from class
-        $className = get_class( $this );
-        if (method_exists( $className, 'GetAliases' )) {
-            $aliases = call_user_func( array ($className,'GetAliases'
-            ) );
-            // $aliases = $className::GetAliases ();
-            foreach ($this as $field => $value) {
-                if (isset( $aliases[$field] )) {
-                    $this->{$field} = $aAliasData[$aliases[$field]];
-                }
-            }
-        }
-    }
-
-    /**
-     *
-     *
-     *
-     *
-     * Initialize object with values from $data.
-     * The values from data use properties or alias array.
-     *
-     * @param $data
-     */
-    protected function initializeObject ($data)
-    {
-        // get aliases from class
-        $className = get_class( $this );
-        $aliases = array ();
-        $swAliases = false;
-        if (method_exists( $className, 'GetAliases' )) {
-            $aliases = call_user_func( array ($className,'GetAliases'
-            ) );
-            // $aliases = $className::GetAliases ();
-            $swAliases = true;
-        }
-        // use object properties or aliases to initialize
-        foreach ($this as $field => $value) {
-            if (isset( $data[$field] )) {
-                $this->$field = $data[$field];
-            } elseif ($swAliases && isset( $aliases[$field] ) && isset( $data[$aliases[$field]] )) {
-                $this->$field = $data[$aliases[$field]];
-            }
-        }
-    }
-
-    public function serialize ()
-    {
-        if (isset( $this->temp )) {
-            unset( $this->temp );
-        }
-        return serialize( $this );
-    }
-
-    public function unserialize ($str)
-    {
-        $className = get_class( $this );
-        $data = unserialize( $str );
-        return new $className( $data );
-    }
-}
-
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/FacetGroup.php b/workflow/engine/classes/entities/FacetGroup.php
index 5e48822ab..4e3302d8d 100644
--- a/workflow/engine/classes/entities/FacetGroup.php
+++ b/workflow/engine/classes/entities/FacetGroup.php
@@ -1,49 +1,51 @@
 initializeObject( $data );
-
-        $requiredFields = array ("facetGroupName","facetItems"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $facetGroupName = '';
+  public $facetGroupPrintName = '';
+  public $facetGroupType = ''; // field, daterange, query
+  public $facetGroupId = '';
+  public $facetItems = array ();
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_FacetGroup ();
+    return $obj;
+  }
+  
+  static function createForInsert($data)
+  {
+    $obj = new Entity_FacetGroup ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "facetGroupName",
+        "facetItems" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/FacetInterfaceRequest.php b/workflow/engine/classes/entities/FacetInterfaceRequest.php
index d23b773b8..2b074a2a5 100644
--- a/workflow/engine/classes/entities/FacetInterfaceRequest.php
+++ b/workflow/engine/classes/entities/FacetInterfaceRequest.php
@@ -1,40 +1,40 @@
 initializeObject( $data );
-
-        $requiredFields = array ("searchText","selectedFacetsString"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $searchText = '';
+  public $selectedFacetsString = ''; // string of selected facet groups and
+                                     // items in format:
+                                     // groupkey1::groupdesc1:::itemkey1::itemdesc1,groupkey2::groupdesc2:::itemkey2::itemdesc2,
+                                     // groupkey3::groupdesc3:::itemkey3::itemdesc3
+                                     // var $selectedFacetFields = array();
+                                     // var $selectedFacetTypes = array();
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_FacetInterfaceRequest ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_FacetInterfaceRequest ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "searchText",
+        "selectedFacetsString" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
diff --git a/workflow/engine/classes/entities/FacetInterfaceResult.php b/workflow/engine/classes/entities/FacetInterfaceResult.php
index 39ecdfa1b..600581321 100644
--- a/workflow/engine/classes/entities/FacetInterfaceResult.php
+++ b/workflow/engine/classes/entities/FacetInterfaceResult.php
@@ -1,37 +1,39 @@
 initializeObject( $data );
-
-        $requiredFields = array ("aFacetGroup","aSelectedFacetGroupItem","sFilterText"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  // array of facetsgroups, array of Entity_SelectedFacetGroupItem, filter text
+  
+  public $aFacetGroup = array ();
+  public $aSelectedFacetGroupItem = array ();
+  public $sFilterText = '';
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_FacetInterfaceResult ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_FacetInterfaceResult ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "aFacetGroup",
+        "aSelectedFacetGroupItem",
+        "sFilterText" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/FacetItem.php b/workflow/engine/classes/entities/FacetItem.php
index 070ba3420..f710af459 100644
--- a/workflow/engine/classes/entities/FacetItem.php
+++ b/workflow/engine/classes/entities/FacetItem.php
@@ -1,48 +1,47 @@
 initializeObject( $data );
-
-        $requiredFields = array ("facetName","facetCount"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $facetName = '';
+  public $facetPrintName = '';
+  public $facetCount = '';
+  public $facetSelectCondition = ''; // selected condition used to select
+                                     // this facet
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_FacetItem ();
+    return $obj;
+  }
+  
+  static function createForInsert($data)
+  {
+    $obj = new Entity_FacetItem ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "facetName",
+        "facetCount" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/FacetRequest.php b/workflow/engine/classes/entities/FacetRequest.php
index 5c0fbeeb1..cfd82ed40 100644
--- a/workflow/engine/classes/entities/FacetRequest.php
+++ b/workflow/engine/classes/entities/FacetRequest.php
@@ -1,45 +1,43 @@
 initializeObject ($data);
+    
+    $requiredFields = array (
+        "workspace" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
-    public $workspace = '';
-    public $searchText = '';
-    public $facetFields = array();
-    public $facetQueries = array();
-    public $facetDates = array();
-    public $facetDatesStart = '';
-    public $facetDatesEnd = '';
-    public $facetDateGap = '';
-    public $facetRanges = array();
-    public $filters = array();
-    public $selectedFacetsString = '';
-
-    private function __construct()
-    {
-    }
-
-    public static function createEmpty()
-    {
-        $obj = new Entity_FacetRequest ();
-        return $obj;
-    }
-
-    public static function createForRequest($data)
-    {
-        $obj = new Entity_FacetRequest ();
-
-        $obj->initializeObject($data);
-
-        $requiredFields = array(
-            "workspace"
-        );
-
-        $obj->validateRequiredFields($requiredFields);
-
-        return $obj;
-    }
-}
- 
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/FacetResult.php b/workflow/engine/classes/entities/FacetResult.php
index 8fd97da4a..c115a6220 100644
--- a/workflow/engine/classes/entities/FacetResult.php
+++ b/workflow/engine/classes/entities/FacetResult.php
@@ -1,34 +1,37 @@
 initializeObject( $data );
-
-        $requiredFields = array ("aFacetGroups","aSelectedFacetGroups","sFilterText"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $aFacetGroups = array ();
+  public $aSelectedFacetGroups = array ();
+  public $sFilterText = '';
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_FacetResult ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_FacetResult ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "aFacetGroups",
+        "aSelectedFacetGroups",
+        "sFilterText" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/SelectedFacetGroupItem.php b/workflow/engine/classes/entities/SelectedFacetGroupItem.php
index 2fbf7109d..364ca2d74 100644
--- a/workflow/engine/classes/entities/SelectedFacetGroupItem.php
+++ b/workflow/engine/classes/entities/SelectedFacetGroupItem.php
@@ -1,40 +1,40 @@
 initializeObject( $data );
-
-        $requiredFields = array ("selectedFacetGroupName","selectedFacetItemName"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $selectedFacetGroupName = '';
+  public $selectedFacetGroupPrintName = '';
+  public $selectedFacetItemName = '';
+  public $selectedFacetItemPrintName = '';
+  public $selectedFacetRemoveCondition = ''; // remove condition, string of
+                                             // selected facets without this
+                                             // facet
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_SelectedFacetGroupItem ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_SelectedFacetGroupItem ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "selectedFacetGroupName",
+        "selectedFacetItemName" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/SolrQueryResult.php b/workflow/engine/classes/entities/SolrQueryResult.php
index 98e00abd1..7be7246b5 100644
--- a/workflow/engine/classes/entities/SolrQueryResult.php
+++ b/workflow/engine/classes/entities/SolrQueryResult.php
@@ -1,38 +1,40 @@
 initializeObject( $data );
-
-        $requiredFields = array ('sEcho','iTotalRecords','iTotalDisplayRecords','aaData'
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  public $sEcho = '';
+  public $iTotalRecords = 0;
+  public $iTotalDisplayRecords = 10;
+  public $aaData = array (); // array of arrays of records to
+                             // display
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_SolrQueryResult ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_SolrQueryResult ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        'sEcho',
+        'iTotalRecords',
+        'iTotalDisplayRecords',
+        'aaData' 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/SolrRequestData.php b/workflow/engine/classes/entities/SolrRequestData.php
index 4bd43f4be..931afbea4 100644
--- a/workflow/engine/classes/entities/SolrRequestData.php
+++ b/workflow/engine/classes/entities/SolrRequestData.php
@@ -1,48 +1,46 @@
 initializeObject ($data);
+    
+    $requiredFields = array (
+        'workspace' 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
-    public $workspace = '';
-    public $startAfter = 0;
-    public $pageSize = 10;
-    public $searchText = '*:*';
-    public $filterText = ''; // comma separated list of filters field:value
-    public $numSortingCols = 0; // number of columns that are sorted
-    public $sortableCols = array(); // array of booleans indicating if column is
-    // sortable (true, false)
-    public $sortCols = array(); // array of indices of sorted columns index
-    // based in the total number of sorting cols
-    public $sortDir = array(); // array of direction of sorting for each
-    // column (desc, asc)
-    public $includeCols = array();
-    public $resultFormat = 'xml'; // json, xml, php
-
-    private function __construct()
-    {
-    }
-
-    public static function createEmpty()
-    {
-        $obj = new Entity_SolrRequestData ();
-        return $obj;
-    }
-
-    public static function createForRequestPagination($data)
-    {
-        $obj = new Entity_SolrRequestData ();
-
-        $obj->initializeObject($data);
-
-        $requiredFields = array(
-            'workspace'
-        );
-
-        $obj->validateRequiredFields($requiredFields);
-
-        return $obj;
-    }
-}
- 
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/entities/SolrUpdateDocument.php b/workflow/engine/classes/entities/SolrUpdateDocument.php
index 713ce9dc3..6ce732516 100644
--- a/workflow/engine/classes/entities/SolrUpdateDocument.php
+++ b/workflow/engine/classes/entities/SolrUpdateDocument.php
@@ -1,33 +1,35 @@
 initializeObject( $data );
-
-        $requiredFields = array ("workspace","document"
-        );
-
-        $obj->validateRequiredFields( $requiredFields );
-
-        return $obj;
-    }
-}
+  var $workspace = '';
+  var $document = '';
+  
+  private function __construct()
+  {
+  }
+  
+  static function createEmpty()
+  {
+    $obj = new Entity_SolrUpdateDocument ();
+    return $obj;
+  }
+  
+  static function createForRequest($data)
+  {
+    $obj = new Entity_SolrUpdateDocument ();
+    
+    $obj->initializeObject ($data);
+    
+    $requiredFields = array (
+        "workspace",
+        "document" 
+    );
+    
+    $obj->validateRequiredFields ($requiredFields);
+    
+    return $obj;
+  }
 
+}
\ No newline at end of file
diff --git a/workflow/engine/classes/model/AppSolrQueue.php b/workflow/engine/classes/model/AppSolrQueue.php
index fbe3fffa4..680481646 100644
--- a/workflow/engine/classes/model/AppSolrQueue.php
+++ b/workflow/engine/classes/model/AppSolrQueue.php
@@ -81,22 +81,30 @@ class AppSolrQueue extends BaseAppSolrQueue
      * Returns the list of updated applications
      * array of Entity_AppSolrQueue
      */
-    public function getListUpdatedApplications ()
+    public function getListUpdatedApplications($updated = true, $deleted = true)
     {
         $updatedApplications = array ();
         try {
             $c = new Criteria();
-
+            
             $c->addSelectColumn(AppSolrQueuePeer::APP_UID);
             $c->addSelectColumn(AppSolrQueuePeer::APP_CHANGE_DATE);
             $c->addSelectColumn(AppSolrQueuePeer::APP_CHANGE_TRACE);
             $c->addSelectColumn(AppSolrQueuePeer::APP_UPDATED);
-
-            //"WHERE
-            $c->add( AppSolrQueuePeer::APP_UPDATED, 0, Criteria::NOT_EQUAL );
-
-            $rs = AppSolrQueuePeer::doSelectRS( $c );
-            $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC );
+            
+            //"WHERE 
+            if($updated == true && $deleted == true){
+                $c->add(AppSolrQueuePeer::APP_UPDATED, 0, Criteria::NOT_EQUAL);    
+            }
+            if($updated == true && $deleted == false){
+                $c->add(AppSolrQueuePeer::APP_UPDATED, 1, Criteria::EQUAL);    
+            }
+            if($updated == false && $deleted == true){
+                $c->add(AppSolrQueuePeer::APP_UPDATED, 2, Criteria::EQUAL);    
+            }
+            
+            $rs = AppSolrQueuePeer::doSelectRS($c);
+            $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
             //echo $c->toString();
             $rs->next();
             $row = $rs->getRow();
@@ -111,11 +119,11 @@ class AppSolrQueue extends BaseAppSolrQueue
                 $rs->next();
                 $row = $rs->getRow();
             }
+            
             return $updatedApplications;
         } catch (Exception $e) {
             $con->rollback();
             throw ($e);
         }
     }
-}
-
+} // AppSolrQueue
diff --git a/workflow/engine/methods/cases/casesMenuLoader.php b/workflow/engine/methods/cases/casesMenuLoader.php
index bb206131f..4bf88641e 100755
--- a/workflow/engine/methods/cases/casesMenuLoader.php
+++ b/workflow/engine/methods/cases/casesMenuLoader.php
@@ -181,10 +181,8 @@ function getAllCounters ()
         G::LoadClass( 'AppSolr' );
         $ApplicationSolrIndex = new AppSolr( $solrConf['solr_enabled'], $solrConf['solr_host'], $solrConf['solr_instance'] );
 
-        if ($ApplicationSolrIndex->isSolrEnabled()) {
+        if ($ApplicationSolrIndex->isSolrEnabled() && $solrConf['solr_enabled'] == true) {
             $solrEnabled = true;
-        } else {
-            $solrEnabled = false;
         }
     }
 
diff --git a/workflow/engine/methods/cases/proxyCasesList.php b/workflow/engine/methods/cases/proxyCasesList.php
index e8985ed61..d78f4a33d 100755
--- a/workflow/engine/methods/cases/proxyCasesList.php
+++ b/workflow/engine/methods/cases/proxyCasesList.php
@@ -62,7 +62,7 @@ try {
             $solrConf["solr_instance"]
         );
 
-        if ($ApplicationSolrIndex->isSolrEnabled()) {
+        if ($ApplicationSolrIndex->isSolrEnabled() && $solrConf['solr_enabled'] == true) {
             //Check if there are missing records to reindex and reindex them
             $ApplicationSolrIndex->synchronizePendingApplications();
             $solrEnabled = true;