diff --git a/composer.json b/composer.json index 33e36f4aa..0ac6c5d6f 100644 --- a/composer.json +++ b/composer.json @@ -68,7 +68,6 @@ "workflow/engine/includes/", "thirdparty/smarty/libs/Smarty.class.php", "thirdparty/jsmin/jsmin.php", - "thirdparty/libchart/classes/", "thirdparty/pear", "thirdparty/html2ps_pdf", "thirdparty/phing", @@ -80,7 +79,8 @@ "gulliver/includes/smarty_plugins/function.pmos.php", "thirdparty/pear/PEAR.php", "thirdparty/HTMLPurifier/HTMLPurifier.auto.php", - "workflow/engine/classes/class.pmFunctions.php" + "workflow/engine/classes/class.pmFunctions.php", + "workflow/engine/src/ProcessMaker/Util/helpers.php" ] }, "autoload-dev": { diff --git a/framework/src/Maveriks/WebApplication.php b/framework/src/Maveriks/WebApplication.php index 2c85b2d08..faf88a941 100644 --- a/framework/src/Maveriks/WebApplication.php +++ b/framework/src/Maveriks/WebApplication.php @@ -2,11 +2,13 @@ namespace Maveriks; use Maveriks\Util; +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Services; use ProcessMaker\Services\Api; use Luracast\Restler\RestException; use Illuminate\Foundation\Http\Kernel; +use G; /** * Web application bootstrap @@ -287,7 +289,7 @@ class WebApplication Services\Api::setWorkspace(SYS_SYS); $cacheDir = defined("PATH_WORKSPACE") ? PATH_WORKSPACE : (defined("PATH_C")? PATH_C: sys_get_temp_dir()); - $sysConfig = \PmSystem::getSystemConfiguration(); + $sysConfig = System::getSystemConfiguration(); \Luracast\Restler\Defaults::$cacheDirectory = $cacheDir; $productionMode = (bool) !(isset($sysConfig["service_api_debug"]) && $sysConfig["service_api_debug"]); @@ -448,7 +450,8 @@ class WebApplication define("PATH_CONTROLLERS", PATH_CORE . "controllers" . PATH_SEP); define("PATH_SERVICES_REST", PATH_CORE . "services" . PATH_SEP . "rest" . PATH_SEP); - $arraySystemConfiguration = \PmSystem::getSystemConfiguration(); + G::defineConstants(); + $arraySystemConfiguration = System::getSystemConfiguration(); ini_set('date.timezone', $arraySystemConfiguration['time_zone']); //Set Time Zone @@ -500,7 +503,7 @@ class WebApplication exit(0); } - $arraySystemConfiguration = \PmSystem::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); //Do not change any of these settings directly, use env.ini instead ini_set('display_errors', $arraySystemConfiguration['display_errors']); diff --git a/gulliver/bin/tasks/pakeGulliver.php b/gulliver/bin/tasks/pakeGulliver.php index f624f959e..804529e07 100644 --- a/gulliver/bin/tasks/pakeGulliver.php +++ b/gulliver/bin/tasks/pakeGulliver.php @@ -1505,7 +1505,7 @@ function get_infoOnPM($workspace) { if( defined("DB_HOST") ) { - $dbNetView = new NET(DB_HOST); + $dbNetView = new Net(DB_HOST); $dbNetView->loginDbServer(DB_USER, DB_PASS); $dbConns = new DbConnections(''); diff --git a/gulliver/methods/defaultAjax.php b/gulliver/methods/defaultAjax.php index 1daa72eea..645cf34b6 100644 --- a/gulliver/methods/defaultAjax.php +++ b/gulliver/methods/defaultAjax.php @@ -54,7 +54,7 @@ if (! is_file( XMLFORM_AJAX_PATH . $xmlFile )) { } } -$G_FORM = new form( $xmlFile, $sPath ); +$G_FORM = new Form( $xmlFile, $sPath ); $G_FORM->id = urlDecode( $_POST['form'] ); $G_FORM->values = isset( $_SESSION[$G_FORM->id] ) ? $_SESSION[$G_FORM->id] : array (); diff --git a/gulliver/system/class.bootstrap.php b/gulliver/system/class.bootstrap.php index a4faf6502..33c3ec4f3 100644 --- a/gulliver/system/class.bootstrap.php +++ b/gulliver/system/class.bootstrap.php @@ -1,4 +1,7 @@ workspaceExists()) { - $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', $workspace->name); + $arraySystemConfiguration = System::getSystemConfiguration('', '', $workspace->name); $flag = (int)($arraySystemConfiguration['enable_blacklist']) == 1; } break; diff --git a/gulliver/system/class.filterForm.php b/gulliver/system/class.filterForm.php index ef8dda3dd..8b88de924 100644 --- a/gulliver/system/class.filterForm.php +++ b/gulliver/system/class.filterForm.php @@ -32,7 +32,7 @@ * */ -class filterForm extends form +class filterForm extends Form { public $cols = 3; public $type = 'filterform'; diff --git a/gulliver/system/class.form.php b/gulliver/system/class.form.php index 63e3fd5bf..9814d8e5f 100644 --- a/gulliver/system/class.form.php +++ b/gulliver/system/class.form.php @@ -1,34 +1,8 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ /** * Class Form * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ @@ -57,7 +31,6 @@ class Form extends XmlForm /** * Function setDefaultValues * - * @author David S. Callizaya S. * @access public * @return string */ @@ -109,7 +82,6 @@ class Form extends XmlForm /** * Function Form * - * @author David S. Callizaya S. * @access public * @param string filename * @param string home @@ -118,7 +90,7 @@ class Form extends XmlForm * @param string $visual_frontend * @return string */ - public function Form ($filename, $home = '', $language = '', $forceParse = false, $visual_frontend = null) + public function __construct ($filename, $home = '', $language = '', $forceParse = false, $visual_frontend = null) { $this->visual_frontend = $visual_frontend; if ($language === '') { @@ -218,7 +190,7 @@ class Form extends XmlForm $values = $this->values; $aValuekeys = array_keys( $values ); if (isset( $aValuekeys[0] ) && ((int) $aValuekeys[0] == 1)) { - $values = XmlForm_Field_Grid::flipValues( $values ); + $values = XmlFormFieldGrid::flipValues( $values ); } //TODO: Review when $values of a grid has only one row it is converted as a $values for a list (when template="grid" at addContent()) if (is_array( reset( $values ) )) { diff --git a/gulliver/system/class.g.php b/gulliver/system/class.g.php index 174749f9f..0f88ab4b4 100644 --- a/gulliver/system/class.g.php +++ b/gulliver/system/class.g.php @@ -24,6 +24,7 @@ * */ +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; /** @@ -865,7 +866,7 @@ class G /* Fix to prevent use uxs skin outside siplified interface, because that skin is not compatible with others interfaces*/ if ($args['SYS_SKIN'] == 'uxs' && $args['SYS_COLLECTION'] != 'home' && $args['SYS_COLLECTION'] != 'cases') { - $config = PmSystem::getSystemConfiguration(); + $config = System::getSystemConfiguration(); $args['SYS_SKIN'] = $config['default_skin']; } @@ -1011,7 +1012,7 @@ class G if (((in_array($browserName, $enabledBrowsers)) || (in_array('ALL', $enabledBrowsers)))&&(!(in_array($browserName, $disabledBrowsers)))) { if ($cssFileInfo['__ATTRIBUTES__']['file'] == 'rtl.css') { - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); if (!(defined('SYS_LANG'))) { if (isset($_SERVER['HTTP_REFERER'])) { $syss = explode('://', $_SERVER['HTTP_REFERER']); @@ -4649,7 +4650,7 @@ class G */ public function getCheckSum ($files) { - $key = PmSystem::getVersion(); + $key = System::getVersion(); if (! is_array( $files )) { $tmp = $files; @@ -5280,7 +5281,7 @@ class G public static function browserCacheFilesGetUid() { - $sysConf = PmSystem::getSystemConfiguration(PATH_CONFIG . "env.ini"); + $sysConf = System::getSystemConfiguration(PATH_CONFIG . "env.ini"); return (isset($sysConf["browser_cache_files_uid"]))? $sysConf["browser_cache_files_uid"] : null; } @@ -5405,7 +5406,7 @@ class G */ public static function log($message, $pathData = PATH_DATA, $file = 'cron.log') { - $config = PmSystem::getSystemConfiguration(); + $config = System::getSystemConfiguration(); $oLogger = Logger::getSingleton($pathData, PATH_SEP, $file); @@ -5823,6 +5824,19 @@ class G $_SESSION['_DATA_TRIGGER_']['_TRI_LOG_'] = true; } } + + /** + * Define the Processmaker constants. + * + */ + public static function defineConstants() + { + //Moved from Enterprise class. + if (file_exists(PATH_METHODS . "login/version-pmos.php")) { + include (PATH_METHODS . "login/version-pmos.php"); + } + //Removed default version from code. + } } /** @@ -5913,8 +5927,3 @@ function eprintln ($s = "", $c = null) print "$s\n"; } } - -function __ ($msgID, $lang = SYS_LANG, $data = null) -{ - return G::LoadTranslation( $msgID, $lang, $data ); -} diff --git a/gulliver/system/class.headPublisher.php b/gulliver/system/class.headPublisher.php index 5cc0e0861..85b6dc60b 100644 --- a/gulliver/system/class.headPublisher.php +++ b/gulliver/system/class.headPublisher.php @@ -360,7 +360,7 @@ class headPublisher //$head .= $this->getExtJsStylesheets(); $head .= $this->getExtJsScripts(); $head .= $this->getExtJsVariablesScript(); - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); if ($oServerConf->isRtl(SYS_LANG)) { $head = $head . " \n"; } @@ -751,7 +751,7 @@ class headPublisher $views = array(); $keyState = "extJsViewState"; $prefixExtJs = "ys-"; - $oServerConf = &serverConf::getSingleton(); + $oServerConf = &ServerConf::getSingleton(); $deleteCache = true; $sjson = $oServerConf->getProperty($keyState); diff --git a/gulliver/system/class.htmlArea.php b/gulliver/system/class.htmlArea.php index e9a4bace8..b5e5e32ed 100644 --- a/gulliver/system/class.htmlArea.php +++ b/gulliver/system/class.htmlArea.php @@ -1,59 +1,33 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - /** * * @package gulliver.system * */ -class XmlForm_Field_HTML extends XmlForm_Field_Textarea +class XmlFormFieldHTML extends XmlFormFieldTextarea { - /* //'default','office2003','silver' - var $skin = 'default'; - //'Default','Basic' - var $toolbarSet = 'Default'; - var $width = '90%'; - var $height = '200' ; - var $cols = 40; - var $rows = 6; - function render( $value , $owner=NULL ) { - if ($this->mode==='edit') { - if ($this->readOnly) - $html=''; - else - $html=''; - } elseif ($this->mode==='view') { - $html=''; - } else { - $html=''; - } - return $html; + /* //'default','office2003','silver' + var $skin = 'default'; + //'Default','Basic' + var $toolbarSet = 'Default'; + var $width = '90%'; + var $height = '200' ; + var $cols = 40; + var $rows = 6; + function render( $value , $owner=NULL ) { + if ($this->mode==='edit') { + if ($this->readOnly) + $html=''; + else + $html=''; + } elseif ($this->mode==='view') { + $html=''; + } else { + $html=''; + } + return $html; }*/ /** * attachEvents function is putting its events diff --git a/gulliver/system/class.pagedTable.php b/gulliver/system/class.pagedTable.php index 670659643..ce030655d 100644 --- a/gulliver/system/class.pagedTable.php +++ b/gulliver/system/class.pagedTable.php @@ -90,7 +90,7 @@ class pagedTable public $name = 'pagedTable'; public $id = 'A1'; public $disableFooter = false; - //This attribute is used to set STYLES to groups of TD, using the field type "cellMark" (see XmlForm_Field_cellMark) + //This attribute is used to set STYLES to groups of TD, using the field type "cellMark" (see XmlFormFieldCellMark) public $tdStyle = ''; public $tdClass = ''; //Config Save definition diff --git a/gulliver/system/class.publisher.php b/gulliver/system/class.publisher.php index a9010fff2..0d0904c98 100644 --- a/gulliver/system/class.publisher.php +++ b/gulliver/system/class.publisher.php @@ -192,7 +192,7 @@ class Publisher if (($this->publishType == 'dynaform') && (($Part['Template'] == 'xmlform') || ($Part['Template'] == 'xmlform_preview'))) { $dynaformShow = (isset( $G_FORM->printdynaform ) && ($G_FORM->printdynaform)) ? 'gulliver/dynaforms_OptionsPrint' : 'gulliver/dynaforms_Options'; - $G_FORM->fields = G::array_merges( array ('__DYNAFORM_OPTIONS' => new XmlForm_Field_XmlMenu( new Xml_Node( '__DYNAFORM_OPTIONS', 'complete', '', array ('type' => 'xmlmenu','xmlfile' => $dynaformShow, 'parentFormId' => $G_FORM->id + $G_FORM->fields = G::array_merges( array ('__DYNAFORM_OPTIONS' => new XmlFormFieldXmlMenu( new Xml_Node( '__DYNAFORM_OPTIONS', 'complete', '', array ('type' => 'xmlmenu','xmlfile' => $dynaformShow, 'parentFormId' => $G_FORM->id ) ), SYS_LANG, PATH_XMLFORM, $G_FORM ) ), $G_FORM->fields ); } @@ -355,7 +355,7 @@ class Publisher /* End Block */ /* Start Block: PagedTable Right Click */ - $pm = new popupMenu( 'gulliver/pagedTable_PopupMenu' ); + $pm = new PopupMenu( 'gulliver/pagedTable_PopupMenu' ); $pm->name = $oTable->id; $fields = array_keys( $oTable->fields ); foreach ($fields as $f) { @@ -369,7 +369,7 @@ class Publisher default: $label = ($oTable->fields[$f]['Label'] != '') ? $oTable->fields[$f]['Label'] : $f; $label = str_replace( "\n", ' ', $label ); - $pm->fields[$f] = new XmlForm_Field_popupOption( new Xml_Node( $f, 'complete', '', array ('label' => $label,'type' => 'popupOption','launch' => $oTable->id . '.showHideField("' . $f . '")' ) ) ); + $pm->fields[$f] = new XmlFormFieldPopupOption( new Xml_Node( $f, 'complete', '', array ('label' => $label,'type' => 'popupOption','launch' => $oTable->id . '.showHideField("' . $f . '")' ) ) ); $pm->values[$f] = ''; } } @@ -430,7 +430,7 @@ class Publisher $_SESSION[$G_FORM->id] = $G_FORM->values; } - $oTable = new propelTable(); + $oTable = new PropelTable(); $oTable->template = $Part['Template']; $oTable->criteria = $Part['Content']; if (isset( $Part['ajaxServer'] ) && ($Part['ajaxServer'] !== '')) { @@ -461,7 +461,7 @@ class Publisher /* End Block */ /* Start Block: PagedTable Right Click */ - $pm = new popupMenu( 'gulliver/pagedTable_PopupMenu' ); + $pm = new PopupMenu( 'gulliver/pagedTable_PopupMenu' ); $sc = $pm->renderPopup( $oTable->id, $oTable->fields ); /* End Block */ //krumo ( $Part ); diff --git a/gulliver/system/class.rbac.php b/gulliver/system/class.rbac.php index 65c4754be..5bb5d5713 100644 --- a/gulliver/system/class.rbac.php +++ b/gulliver/system/class.rbac.php @@ -532,7 +532,7 @@ class RBAC { /*----------------------------------********---------------------------------*/ - $licenseManager =& pmLicenseManager::getSingleton(); + $licenseManager =& PmLicenseManager::getSingleton(); if (in_array(G::encryptOld($licenseManager->result), array('38afd7ae34bd5e3e6fc170d8b09178a3', 'ba2b45bdc11e2a4a6e86aab2ac693cbb'))) { return -7; } diff --git a/gulliver/system/class.soapNtlm.php b/gulliver/system/class.soapNtlm.php index fc5e04aa3..89ab4651b 100644 --- a/gulliver/system/class.soapNtlm.php +++ b/gulliver/system/class.soapNtlm.php @@ -30,6 +30,8 @@ * to allow NTLM authentication throw soap connection */ +use ProcessMaker\Core\System; + /** * * @package gulliver.system @@ -200,7 +202,7 @@ class soapNtlm curl_setopt( $this->ch, CURLOPT_USERPWD, $this->getuser() . ':' . $this->getpassword() ); // Ankit's code //Apply proxy settings if (class_exists( 'System' )) { - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); $sysConf = $filter->xssFilterHard($sysConf); if ($sysConf['proxy_host'] != '') { curl_setopt( $this->ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); @@ -243,7 +245,7 @@ class NTLMSoapClient extends SoapClient //Apply proxy settings if (class_exists( 'System' )) { - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt( $ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); if ($sysConf['proxy_port'] != '') { diff --git a/gulliver/system/class.wysiwygEditor.php b/gulliver/system/class.wysiwygEditor.php index fd4952b8b..15e6a6782 100644 --- a/gulliver/system/class.wysiwygEditor.php +++ b/gulliver/system/class.wysiwygEditor.php @@ -26,7 +26,7 @@ */ /** - * XmlForm_Field_HTML class definition + * XmlFormFieldWYSIWYGEditor class definition * It is useful to see dynaforms how are built * * @package gulliver.system @@ -36,7 +36,7 @@ * */ -class XmlForm_Field_WYSIWYG_EDITOR extends XmlForm_Field +class XmlFormFieldWYSIWYGEditor extends XmlFormField { public $width = '100%'; public $height = '300'; @@ -76,7 +76,7 @@ class XmlForm_Field_WYSIWYG_EDITOR extends XmlForm_Field { $editorDefinition = 'tinyMCE.baseURL = "/js/tinymce/jscripts/tiny_mce"; '; $editorDefinition .= 'var domainURL = "/sys'.SYS_SYS.'/'.SYS_LANG.'/'.SYS_SKIN.'/"'; - $serverConf =& serverConf::getSingleton(); + $serverConf =& ServerConf::getSingleton(); switch ($this->editorType){ case 'EMAIL_TEMPLATE': diff --git a/gulliver/system/class.xmlMenu.php b/gulliver/system/class.xmlMenu.php index c6745e98a..2bba1b6e7 100644 --- a/gulliver/system/class.xmlMenu.php +++ b/gulliver/system/class.xmlMenu.php @@ -30,21 +30,21 @@ * * @package gulliver.system */ -class xmlMenu extends form +class xmlMenu extends Form { public $type = 'xmlmenu'; public $parentFormId; } /** - * XmlForm_Field_XmlMenu + * XmlFormFieldXmlMenu * - * extends XmlForm_Field + * extends XmlFormField * * @package gulliver.system * */ -class XmlForm_Field_XmlMenu extends XmlForm_Field +class XmlFormFieldXmlMenu extends XmlFormField { public $xmlfile = ''; public $type = 'xmlmenuDyn'; @@ -54,7 +54,7 @@ class XmlForm_Field_XmlMenu extends XmlForm_Field public $parentFormId; /** - * XmlForm_Field_XmlMenu + * XmlFormFieldXmlMenu * * @param string $xmlNode * @param string $lang default value 'en' @@ -63,9 +63,9 @@ class XmlForm_Field_XmlMenu extends XmlForm_Field * * @return none */ - public function XmlForm_Field_XmlMenu ($xmlNode, $lang = 'en', $home = '', $owner = null) + public function XmlFormFieldXmlMenu ($xmlNode, $lang = 'en', $home = '', $owner = null) { - parent::XmlForm_Field( $xmlNode, $lang, $home, $owner ); + parent::__construct( $xmlNode, $lang, $home, $owner ); $this->home = $home; } diff --git a/gulliver/system/class.xmlform.php b/gulliver/system/class.xmlform.php index 8c8e71236..1418fbc38 100644 --- a/gulliver/system/class.xmlform.php +++ b/gulliver/system/class.xmlform.php @@ -1,40 +1,14 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ use ProcessMaker\Plugins\PluginRegistry; /** - * Class XmlForm_Field + * Class XmlFormField * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field +class XmlFormField { public $name = ''; public $type = 'field'; @@ -82,16 +56,15 @@ class XmlForm_Field public $modeForGrid = ''; /** - * Function XmlForm_Field + * Function XmlFormField * - * @author David S. Callizaya S. * @access public * @param string xmlNode * @param string lang * @param string home * @return string */ - public function XmlForm_Field ($xmlNode, $lang = 'en', $home = '', $owner = null) + public function __construct ($xmlNode, $lang = 'en', $home = '', $owner = null) { //Loads any attribute that were defined in the xmlNode //except name and label. @@ -141,7 +114,6 @@ class XmlForm_Field } $this->options = (isset( $this->option )) ? $this->option : array (); //Sql Options : cause warning because values are not setted yet. - //if ($this->sql!=='') $this->executeSQL(); if (isset( $owner )) { if (isset( $owner->mode )) { $ownerMode = $owner->mode; @@ -315,7 +287,6 @@ class XmlForm_Field /** * Function executeSQL * - * @author David S. Callizaya S. * @access public * @param string owner * @return string @@ -398,7 +369,6 @@ class XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -412,7 +382,6 @@ class XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @return string @@ -446,7 +415,6 @@ class XmlForm_Field /** * Function dependentOf * - * @author David S. Callizaya S. * @access public * @return array */ @@ -472,7 +440,6 @@ class XmlForm_Field /** * Function mask * - * @author David S. Callizaya S. * @access public * @param string format * @param string value @@ -534,7 +501,6 @@ class XmlForm_Field /** * Function getAttributes * - * @author David S. Callizaya S. * @access public * @return string */ @@ -566,7 +532,6 @@ class XmlForm_Field /** * Function getEvents * - * @author David S. Callizaya S. * @access public * @return string */ @@ -590,7 +555,6 @@ class XmlForm_Field * Function attachEvents: Attaches events to a control using * leimnud.event.add * - * @author David S. Callizaya S. * @param $elementRef * @access public */ @@ -608,7 +572,6 @@ class XmlForm_Field * Function createXmlNode: Creates an Xml_Node object storing * the data of $this Xml_Field. * - * @author David S. Callizaya S. * @access public * @return Xml_Node */ @@ -639,7 +602,6 @@ class XmlForm_Field * Function updateXmlNode: Updates and existing Xml_Node * with the data of $this Xml_Field. * - * @author David S. Callizaya S. * @access public * @param string value * @return Xml_Node @@ -672,7 +634,6 @@ class XmlForm_Field * Function getXmlAttributes: Returns an associative array * with the attributes of $this Xml_field (only the modified ones). * - * @author David S. Callizaya S. * @access public * @param boolean includeDefaultValues Includes attributes * with default values. @@ -925,19 +886,17 @@ class XmlForm_Field } /** - * Class XmlForm_Field_Title + * Class XmlFormFieldTitle * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Title extends XmlForm_Field +class XmlFormFieldTitle extends XmlFormField { /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -961,19 +920,17 @@ class XmlForm_Field_Title extends XmlForm_Field } /** - * Class XmlForm_Field_Subtitle + * Class XmlFormFieldSubtitle * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Subtitle extends XmlForm_Field +class XmlFormFieldSubtitle extends XmlFormField { /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -996,13 +953,12 @@ class XmlForm_Field_Subtitle extends XmlForm_Field } /** - * Class XmlForm_Field_SimpleText + * Class XmlFormFieldSimpleText * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_SimpleText extends XmlForm_Field +class XmlFormFieldSimpleText extends XmlFormField { public $size = 15; public $maxLength = ''; @@ -1015,7 +971,6 @@ class XmlForm_Field_SimpleText extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -1042,7 +997,6 @@ class XmlForm_Field_SimpleText extends XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @param string owner @@ -1088,13 +1042,12 @@ class XmlForm_Field_SimpleText extends XmlForm_Field } /** - * Class XmlForm_Field_Text + * Class XmlFormFieldText * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Text extends XmlForm_Field_SimpleText +class XmlFormFieldText extends XmlFormFieldSimpleText { public $size = 15; public $maxLength = 64; @@ -1122,7 +1075,6 @@ class XmlForm_Field_Text extends XmlForm_Field_SimpleText /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -1215,7 +1167,6 @@ class XmlForm_Field_Text extends XmlForm_Field_SimpleText /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @param string owner @@ -1282,13 +1233,12 @@ class XmlForm_Field_Text extends XmlForm_Field_SimpleText } /** - * Class XmlForm_Field_Suggest + * Class XmlFormFieldSuggest * - * @author Erik Amaru Ortiz * @package gulliver.system * @access public */ -class XmlForm_Field_Suggest extends XmlForm_Field_SimpleText //by neyek +class XmlFormFieldSuggest extends XmlFormFieldSimpleText { public $size = 15; public $maxLength = 64; @@ -1734,7 +1684,6 @@ class XmlForm_Field_Suggest extends XmlForm_Field_SimpleText //by neyek /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @param string owner @@ -1771,7 +1720,7 @@ class XmlForm_Field_Suggest extends XmlForm_Field_SimpleText //by neyek * * @package gulliver.system */ -class XmlForm_Field_Print extends XmlForm_Field_SimpleText //by neyek +class XmlFormFieldPrint extends XmlFormFieldSimpleText //by neyek { //Instead of public --> link public $link = ''; @@ -1815,7 +1764,7 @@ class XmlForm_Field_Print extends XmlForm_Field_SimpleText //by neyek * * @package gulliver.system */ -class XmlForm_Field_Caption extends XmlForm_Field +class XmlFormFieldCaption extends XmlFormField { public $defaultValue = ''; @@ -1844,7 +1793,6 @@ class XmlForm_Field_Caption extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string modified @@ -1897,13 +1845,12 @@ class XmlForm_Field_Caption extends XmlForm_Field } /** - * Class XmlForm_Field_Password + * Class XmlFormFieldPassword * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Password extends XmlForm_Field +class XmlFormFieldPassword extends XmlFormField { public $size = 15; public $maxLength = 15; @@ -1914,7 +1861,6 @@ class XmlForm_Field_Password extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -1948,13 +1894,12 @@ class XmlForm_Field_Password extends XmlForm_Field } /** - * Class XmlForm_Field_Textarea + * Class XmlFormFieldTextarea * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Textarea extends XmlForm_Field +class XmlFormFieldTextarea extends XmlFormField { public $rows = 12; public $cols = 40; @@ -1968,7 +1913,6 @@ class XmlForm_Field_Textarea extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -2029,7 +1973,6 @@ class XmlForm_Field_Textarea extends XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -2100,13 +2043,12 @@ class XmlForm_Field_Textarea extends XmlForm_Field } /** - * Class XmlForm_Field_Currency + * Class XmlFormFieldCurrency * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Currency extends XmlForm_Field_SimpleText +class XmlFormFieldCurrency extends XmlFormFieldSimpleText { public $group = 0; public $size = 15; @@ -2253,13 +2195,12 @@ class XmlForm_Field_Currency extends XmlForm_Field_SimpleText * * @package gulliver.system */ -class XmlForm_Field_CaptionCurrency extends XmlForm_Field +class XmlFormFieldCaptionCurrency extends XmlFormField { /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -2271,13 +2212,12 @@ class XmlForm_Field_CaptionCurrency extends XmlForm_Field } /** - * Class XmlForm_Field_Percentage + * Class XmlFormFieldPercentage * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Percentage extends XmlForm_Field_SimpleText +class XmlFormFieldPercentage extends XmlFormFieldSimpleText { public $size = 15; public $required = false; @@ -2400,7 +2340,7 @@ class XmlForm_Field_Percentage extends XmlForm_Field_SimpleText * * @package gulliver.system */ -class XmlForm_Field_CaptionPercentage extends XmlForm_Field +class XmlFormFieldCaptionPercentage extends XmlFormField { public function render($value = null, $paramDummy2 = null) @@ -2410,13 +2350,12 @@ class XmlForm_Field_CaptionPercentage extends XmlForm_Field } /** - * Class XmlForm_Field_Date + * Class XmlFormFieldDate * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Date2 extends XmlForm_Field_SimpleText +class XmlFormFieldDate2 extends XmlFormFieldSimpleText { //Instead of size --> startDate public $startDate = ''; @@ -2677,7 +2616,7 @@ class XmlForm_Field_Date2 extends XmlForm_Field_SimpleText * * @package gulliver.system */ -class XmlForm_Field_DateView extends XmlForm_Field +class XmlFormFieldDateView extends XmlFormField { public function render($value = null, $paramDummy2 = null) @@ -2687,13 +2626,12 @@ class XmlForm_Field_DateView extends XmlForm_Field } /** - * Class XmlForm_Field_YesNo + * Class XmlFormFieldYesNo * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_YesNo extends XmlForm_Field +class XmlFormFieldYesNo extends XmlFormField { public $required = false; public $readonly = false; @@ -2702,7 +2640,6 @@ class XmlForm_Field_YesNo extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -2816,13 +2753,12 @@ class XmlForm_Field_YesNo extends XmlForm_Field } /** - * Class XmlForm_Field_Link + * Class XmlFormFieldLink * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Link extends XmlForm_Field +class XmlFormFieldLink extends XmlFormField { //Instead of var --> link public $link = ''; @@ -2835,7 +2771,6 @@ class XmlForm_Field_Link extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -2953,13 +2888,12 @@ class XmlForm_Field_Link extends XmlForm_Field } /** - * Class XmlForm_Field_File + * Class XmlFormFieldFile * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_File extends XmlForm_Field +class XmlFormFieldFile extends XmlFormField { public $required = false; public $input = null; @@ -2968,7 +2902,6 @@ class XmlForm_Field_File extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -3090,14 +3023,13 @@ class XmlForm_Field_File extends XmlForm_Field } /** - * Class XmlForm_Field_Dropdownpt + * Class XmlFormFieldDropdownpt * hook, dropdown field for Propel table * - * @author Erik Amaru * @package gulliver.system * @access public */ -class XmlForm_Field_Dropdownpt extends XmlForm_Field +class XmlFormFieldDropdownpt extends XmlFormField { public $value; @@ -3126,14 +3058,13 @@ class XmlForm_Field_Dropdownpt extends XmlForm_Field } /** - * Class XmlForm_Field_Checkboxpt + * Class XmlFormFieldCheckboxpt * checkbox field for Propel table * - * @author Erik Amaru * @package gulliver.system * @access public */ -class XmlForm_Field_Checkboxpt extends XmlForm_Field +class XmlFormFieldCheckboxpt extends XmlFormField { public $required = false; public $value = 'on'; @@ -3192,13 +3123,12 @@ class XmlForm_Field_Checkboxpt extends XmlForm_Field } /** - * Class XmlForm_Field_Checkbox + * Class XmlFormFieldCheckbox * - * @author Erik Amaru * @package gulliver.system * @access public */ -class XmlForm_Field_Checkbox extends XmlForm_Field +class XmlFormFieldCheckbox extends XmlFormField { public $required = false; public $value = 'on'; @@ -3209,7 +3139,6 @@ class XmlForm_Field_Checkbox extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -3304,7 +3233,7 @@ class XmlForm_Field_Checkbox extends XmlForm_Field * * @package gulliver.system */ -class XmlForm_Field_Checkbox2 extends XmlForm_Field +class XmlFormFieldCheckbox2 extends XmlFormField { public $required = false; @@ -3315,13 +3244,12 @@ class XmlForm_Field_Checkbox2 extends XmlForm_Field } /** - * Class XmlForm_Field_Button + * Class XmlFormFieldButton * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Button extends XmlForm_Field +class XmlFormFieldButton extends XmlFormField { public $onclick = ''; public $align = 'center'; @@ -3330,7 +3258,6 @@ class XmlForm_Field_Button extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -3351,19 +3278,17 @@ class XmlForm_Field_Button extends XmlForm_Field } /** - * Class XmlForm_Field_Reset + * Class XmlFormFieldReset * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Reset extends XmlForm_Field +class XmlFormFieldReset extends XmlFormField { /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -3386,20 +3311,18 @@ class XmlForm_Field_Reset extends XmlForm_Field } /** - * Class XmlForm_Field_Submit + * Class XmlFormFieldSubmit * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Submit extends XmlForm_Field +class XmlFormFieldSubmit extends XmlFormField { public $onclick = ''; /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -3428,13 +3351,12 @@ class XmlForm_Field_Submit extends XmlForm_Field } /** - * Class XmlForm_Field_Hidden + * Class XmlFormFieldHidden * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Hidden extends XmlForm_Field +class XmlFormFieldHidden extends XmlFormField { public $sqlConnection = 0; public $sql = ''; @@ -3444,7 +3366,6 @@ class XmlForm_Field_Hidden extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -3509,13 +3430,12 @@ class XmlForm_Field_Hidden extends XmlForm_Field } /** - * Class XmlForm_Field_Dropdown + * Class XmlFormFieldDropdown * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Dropdown extends XmlForm_Field +class XmlFormFieldDropdown extends XmlFormField { public $defaultValue = ''; public $required = false; @@ -3539,7 +3459,6 @@ class XmlForm_Field_Dropdown extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -3713,7 +3632,6 @@ class XmlForm_Field_Dropdown extends XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @return string @@ -3736,13 +3654,12 @@ class XmlForm_Field_Dropdown extends XmlForm_Field } /** - * Class XmlForm_Field_Listbox + * Class XmlFormFieldListbox * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Listbox extends XmlForm_Field +class XmlFormFieldListbox extends XmlFormField { public $defaultValue = ''; public $required = false; @@ -3756,7 +3673,6 @@ class XmlForm_Field_Listbox extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -3854,13 +3770,12 @@ class XmlForm_Field_Listbox extends XmlForm_Field } /** - * Class XmlForm_Field_RadioGroup + * Class XmlFormFieldRadioGroup * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_RadioGroup extends XmlForm_Field +class XmlFormFieldRadioGroup extends XmlFormField { public $defaultValue = ''; public $required = false; @@ -3874,7 +3789,6 @@ class XmlForm_Field_RadioGroup extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -3933,7 +3847,7 @@ class XmlForm_Field_RadioGroup extends XmlForm_Field * @package gulliver.system * */ -class XmlForm_Field_RadioGroupView extends XmlForm_Field +class XmlFormFieldRadioGroupView extends XmlFormField { public $defaultValue = ''; public $required = false; @@ -3945,7 +3859,6 @@ class XmlForm_Field_RadioGroupView extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -3963,13 +3876,12 @@ class XmlForm_Field_RadioGroupView extends XmlForm_Field } /** - * Class XmlForm_Field_CheckGroup + * Class XmlFormFieldCheckGroup * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_CheckGroup extends XmlForm_Field +class XmlFormFieldCheckGroup extends XmlFormField { public $required = false; public $option = array (); @@ -3984,7 +3896,6 @@ class XmlForm_Field_CheckGroup extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -4087,7 +3998,7 @@ class XmlForm_Field_CheckGroup extends XmlForm_Field * @package gulliver.system * */ -class XmlForm_Field_CheckGroupView extends XmlForm_Field +class XmlFormFieldCheckGroupView extends XmlFormField { public $option = array (); public $sqlConnection = 0; @@ -4097,7 +4008,6 @@ class XmlForm_Field_CheckGroupView extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -4113,13 +4023,12 @@ class XmlForm_Field_CheckGroupView extends XmlForm_Field } /** - * Class XmlForm_Field_Grid + * Class XmlFormFieldGrid * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_Grid extends XmlForm_Field +class XmlFormFieldGrid extends XmlFormField { public $xmlGrid = ''; public $initRows = 1; @@ -4135,25 +4044,23 @@ class XmlForm_Field_Grid extends XmlForm_Field public $id = ''; /** - * Function XmlForm_Field_Grid + * Function XmlFormFieldGrid * - * @author David S. Callizaya S. * @access public * @param string xmlnode * @param string language * @param string home * @return string */ - public function XmlForm_Field_Grid ($xmlnode, $language, $home) + public function __construct ($xmlnode, $language, $home) { - parent::XmlForm_Field( $xmlnode, $language ); + parent::__construct( $xmlnode, $language ); $this->parseFile( $home, $language ); } /** * Function parseFile * - * @author David S. Callizaya S. * @access public * @param string home * @param string language @@ -4191,7 +4098,6 @@ class XmlForm_Field_Grid extends XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string values * @return string @@ -4387,28 +4293,26 @@ class XmlForm_Field_Grid extends XmlForm_Field } /** - * Class XmlForm_Field_JavaScript + * Class XmlFormFieldJavaScript * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ -class XmlForm_Field_JavaScript extends XmlForm_Field +class XmlFormFieldJavaScript extends XmlFormField { public $code = ''; public $replaceTags = true; /** - * Function XmlForm_Field_JavaScript + * Function XmlFormFieldJavaScript * - * @author David S. Callizaya S. * @access public * @param string xmlNode * @param string lang * @param string home * @return string */ - public function XmlForm_Field_JavaScript ($xmlNode, $lang = 'en', $home = '') + public function __construct ($xmlNode, $lang = 'en', $home = '') { //Loads any attribute that were defined in the xmlNode //except name and label. @@ -4432,7 +4336,6 @@ class XmlForm_Field_JavaScript extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string value * @return string @@ -4446,7 +4349,6 @@ class XmlForm_Field_JavaScript extends XmlForm_Field /** * Function renderGrid * - * @author David S. Callizaya S. * @access public * @param string value * @param string owner @@ -4470,12 +4372,11 @@ class XmlForm_Field_JavaScript extends XmlForm_Field } /** - * - * @author Erik amaru Ortiz * Comment Working for after and before date attributes + * * @package gulliver.system */ -class XmlForm_Field_Date extends XmlForm_Field_SimpleText +class XmlFormFieldDate extends XmlFormFieldSimpleText { public $required = false; public $readOnly = false; @@ -4932,10 +4833,9 @@ class XmlForm_Field_Date extends XmlForm_Field_SimpleText /** * Calendar Widget with Javascript Routines * - * @author Erik amaru Ortiz * @package gulliver.system */ -class XmlForm_Field_Date5 extends XmlForm_Field_SimpleText +class XmlFormFieldDate5 extends XmlFormFieldSimpleText { public $required = false; public $readOnly = false; @@ -5345,11 +5245,8 @@ class XmlForm_Field_Date5 extends XmlForm_Field_SimpleText /** * * @package gulliver.system - * AVOID TO ENTER HERE : EXPERIMENTAL !!! - * by Caleeli. - * */ -class XmlForm_Field_Xmlform extends XmlForm_Field +class XmlFormFieldXmlform extends XmlFormField { public $xmlfile = ''; public $initRows = 1; @@ -5365,25 +5262,23 @@ class XmlForm_Field_Xmlform extends XmlForm_Field public $id = ''; /** - * Function XmlForm_Field_Xmlform + * Function XmlFormFieldXmlform * - * @author David S. Callizaya S. * @access public * @param string xmlnode * @param string language * @param string home * @return string */ - public function XmlForm_Field_Xmlform ($xmlnode, $language, $home) + public function __construct ($xmlnode, $language, $home) { - parent::XmlForm_Field( $xmlnode, $language ); + parent::__construct( $xmlnode, $language ); $this->parseFile( $home, $language ); } /** * Function parseFile * - * @author David S. Callizaya S. * @access public * @param string home * @param string language @@ -5403,7 +5298,6 @@ class XmlForm_Field_Xmlform extends XmlForm_Field /** * Function render * - * @author David S. Callizaya S. * @access public * @param string values * @return string @@ -5431,7 +5325,6 @@ class XmlForm_Field_Xmlform extends XmlForm_Field * Class XmlForm * Main Class * - * @author David S. Callizaya S. * @package gulliver.system * @access public */ @@ -5467,10 +5360,89 @@ class XmlForm public $requiredFields = array (); public $fieldContentWidth = 450; + /** + * List of xmlform controls and its classes. + * + * @var string[] + */ + private static $controls = [ + 'button' => XmlFormFieldButton::class, + 'caption' => XmlFormFieldCaption::class, + 'captioncurrency' => XmlFormFieldCaptionCurrency::class, + 'captionpercentage' => XmlFormFieldCaptionPercentage::class, + 'cellmark' => XmlFormFieldCellMark::class, + 'checkbox2' => XmlFormFieldCheckbox2::class, + 'checkbox' => XmlFormFieldCheckbox::class, + 'checkboxpt' => XmlFormFieldCheckboxpt::class, + 'checkboxtable' => XmlFormFieldCheckBoxTable::class, + 'checkgroup' => XmlFormFieldCheckGroup::class, + 'checkgroupview' => XmlFormFieldCheckGroupView::class, + 'currency' => XmlFormFieldCurrency::class, + 'date2' => XmlFormFieldDate2::class, + 'date5' => XmlFormFieldDate5::class, + 'date' => XmlFormFieldDate::class, + 'dateview' => XmlFormFieldDateView::class, + 'dropdown' => XmlFormFieldDropdown::class, + 'dropdownpt' => XmlFormFieldDropdownpt::class, + 'dveditor' => XmlFormFieldDVEditor::class, + 'fastsearch' => XmlFormFieldFastSearch::class, + 'file' => XmlFormFieldFile::class, + 'grid' => XmlFormFieldGrid::class, + 'hidden' => XmlFormFieldHidden::class, + 'hours' => XmlFormFieldHours::class, + 'html' => XmlFormFieldHTML::class, + 'image' => XmlFormFieldImage::class, + 'javascript' => XmlFormFieldJavaScript::class, + 'label' => XmlFormFieldLabel::class, + 'link' => XmlFormFieldLink::class, + 'listbox' => XmlFormFieldListbox::class, + 'password' => XmlFormFieldPassword::class, + 'percentage' => XmlFormFieldPercentage::class, + 'popupoption' => XmlFormFieldPopupOption::class, + 'print' => XmlFormFieldPrint::class, + 'radiogroup' => XmlFormFieldRadioGroup::class, + 'radiogroupview' => XmlFormFieldRadioGroupView::class, + 'reset' => XmlFormFieldReset::class, + 'simpletext' => XmlFormFieldSimpleText::class, + 'submit' => XmlFormFieldSubmit::class, + 'subtitle' => XmlFormFieldSubtitle::class, + 'suggest' => XmlFormFieldSuggest::class, + 'text' => XmlFormFieldText::class, + 'textarea' => XmlFormFieldTextarea::class, + 'textareapm' => XmlFormFieldTextareaPM::class, + 'textpm' => XmlFormFieldTextPM::class, + 'title' => XmlFormFieldTitle::class, + 'toolbar' => XmlFormFieldToolBar::class, + 'toolbutton' => XmlFormFieldToolButton::class, + 'wysiwyg_editor' => XmlFormFieldWYSIWYGEditor::class, + 'xmlform' => XmlFormFieldXmlform::class, + 'xmlmenu' => XmlFormFieldXmlMenu::class, + 'yesno' => XmlFormFieldYesNo::class, + ]; + + /** + * Get xmlform control class by type. + * + * @param string $type + * @return string + */ + private function getClassByControlType($type) + { + $key = strtolower($type); + if (isset(self::$controls[$key])) { + return self::$controls[$key]; + } elseif (class_exists('XmlForm_Field_' . $type)) { + return 'XmlForm_Field_' . $type; + } elseif (class_exists('XmlForm_Field_' . $key)) { + return 'XmlForm_Field_' . $key; + } else { + return XmlFormField::class; + } + } + /** * Function xmlformTemplate * - * @author David S. Callizaya S. * @access public * @param string form * @param string templateFile @@ -5567,14 +5539,8 @@ class XmlForm foreach ($xmlNode as $k => $v) { if (($xmlNode[$k]->type !== 'cdata') && isset( $xmlNode[$k]->attributes['type'] )) { - if (class_exists( 'XmlForm_Field_' . $xmlNode[$k]->attributes['type'] )) { - $x = '$field = new XmlForm_Field_' . $xmlNode[$k]->attributes['type'] . '( $xmlNode[$k], $language, $this->home, $this);'; - - eval( $x ); - } else { - $field = new XmlForm_Field( $xmlNode[$k], $language, $this->home, $this ); - } - + $class = $this->getClassByControlType($xmlNode[$k]->attributes['type']); + $field = new $class( $xmlNode[$k], $language, $this->home, $this ); $field->language = $this->language; $this->fields[$field->name] = $field; } @@ -5730,9 +5696,9 @@ class XmlForm } /** -* @package gulliver.system -*/ -class XmlForm_Field_Image extends XmlForm_Field + * @package gulliver.system + */ +class XmlFormFieldImage extends XmlFormField { public $file = ''; public $home = 'public_html'; @@ -5740,7 +5706,6 @@ class XmlForm_Field_Image extends XmlForm_Field /** * Function render - * @author David S. Callizaya S. * @access public * @param string values * @return string diff --git a/gulliver/system/class.xmlformExtension.php b/gulliver/system/class.xmlformExtension.php index f369f65a4..b990e9752 100644 --- a/gulliver/system/class.xmlformExtension.php +++ b/gulliver/system/class.xmlformExtension.php @@ -1,36 +1,10 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - /** * * @package gulliver.system */ -class XmlForm_Field_Label extends XmlForm_Field +class XmlFormFieldLabel extends XmlFormField { public $withoutValue = true; public $align = 'left'; @@ -43,7 +17,7 @@ class XmlForm_Field_Label extends XmlForm_Field * * @package gulliver.system */ -class XmlForm_Field_cellMark extends XmlForm_Field +class XmlFormFieldCellMark extends XmlFormField { /* Defines the style of the next tds of the pagedTable. @@ -91,14 +65,14 @@ class XmlForm_Field_cellMark extends XmlForm_Field } /** - * XmlForm_Field_DVEditor + * XmlFormFieldDVEditor * - * extends XmlForm_Field + * extends XmlFormField * * @package gulliver.system * */ -class XmlForm_Field_DVEditor extends XmlForm_Field +class XmlFormFieldDVEditor extends XmlFormField { public $toolbarSet = 'toolbar2lines.html'; public $width = '90%'; @@ -150,7 +124,7 @@ class XmlForm_Field_DVEditor extends XmlForm_Field * * @package gulliver.system */ -class XmlForm_Field_FastSearch extends XmlForm_Field_Text +class XmlFormFieldFastSearch extends XmlFormFieldText { public $onkeypress = "if (event.keyCode===13)@#PAGED_TABLE_ID.doFastSearch(this.value);if (event.keyCode===13)return false;"; public $colAlign = "right"; diff --git a/rbac/engine/config/paths.php b/rbac/engine/config/paths.php index 38c3c4015..db7867be6 100644 --- a/rbac/engine/config/paths.php +++ b/rbac/engine/config/paths.php @@ -81,4 +81,4 @@ if (!is_dir(PATH_SMARTY_C)) G::mk_dir(PATH_SMARTY_C); if (!is_dir(PATH_SMARTY_CACHE)) G::mk_dir(PATH_SMARTY_CACHE); -?> +G::defineConstants(); diff --git a/tests/WorkflowTestCase.php b/tests/WorkflowTestCase.php index 56df31b9c..ccef158c9 100644 --- a/tests/WorkflowTestCase.php +++ b/tests/WorkflowTestCase.php @@ -170,7 +170,7 @@ class WorkflowTestCase extends TestCase throw new \Exception('To continue please put a valid license at features/resources'); } G::LoadClass('pmLicenseManager'); - $licenseManager = new pmLicenseManager(); + $licenseManager = new PmLicenseManager(); $licenseManager->installLicense($licenseFile[0]); } diff --git a/thirdparty/pear/Archive/Tar.php b/thirdparty/pear/Archive/Tar.php deleted file mode 100644 index 2dd69cf98..000000000 --- a/thirdparty/pear/Archive/Tar.php +++ /dev/null @@ -1,1991 +0,0 @@ - - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * @category File_Formats - * @package Archive_Tar - * @author Vincent Blavet - * @copyright 1997-2010 The Authors - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version CVS: $Id$ - * @link http://pear.php.net/package/Archive_Tar - */ - -define('ARCHIVE_TAR_ATT_SEPARATOR', 90001); -define('ARCHIVE_TAR_END_BLOCK', pack("a512", '')); - -/** - * Creates a (compressed) Tar archive - * - * @package Archive_Tar - * @author Vincent Blavet - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version $Revision$ - */ -class Archive_Tar extends PEAR -{ - /** - * @var string Name of the Tar - */ - var $_tarname=''; - - /** - * @var boolean if true, the Tar file will be gzipped - */ - var $_compress=false; - - /** - * @var string Type of compression : 'none', 'gz' or 'bz2' - */ - var $_compress_type='none'; - - /** - * @var string Explode separator - */ - var $_separator=' '; - - /** - * @var file descriptor - */ - var $_file=0; - - /** - * @var string Local Tar name of a remote Tar (http:// or ftp://) - */ - var $_temp_tarname=''; - - /** - * @var string regular expression for ignoring files or directories - */ - var $_ignore_regexp=''; - - /** - * @var object PEAR_Error object - */ - var $error_object=null; - - // {{{ constructor - /** - * Archive_Tar Class constructor. This flavour of the constructor only - * declare a new Archive_Tar object, identifying it by the name of the - * tar file. - * If the compress argument is set the tar will be read or created as a - * gzip or bz2 compressed TAR file. - * - * @param string $p_tarname The name of the tar archive to create - * @param string $p_compress can be null, 'gz' or 'bz2'. This - * parameter indicates if gzip or bz2 compression - * is required. For compatibility reason the - * boolean value 'true' means 'gz'. - * - * @access public - */ - function Archive_Tar($p_tarname, $p_compress = null) - { - $this->PEAR(); - $this->_compress = false; - $this->_compress_type = 'none'; - if (($p_compress === null) || ($p_compress == '')) { - if (@file_exists($p_tarname)) { - if ($fp = @fopen($p_tarname, "rb")) { - // look for gzip magic cookie - $data = fread($fp, 2); - fclose($fp); - if ($data == "\37\213") { - $this->_compress = true; - $this->_compress_type = 'gz'; - // No sure it's enought for a magic code .... - } elseif ($data == "BZ") { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } - } - } else { - // probably a remote file or some file accessible - // through a stream interface - if (substr($p_tarname, -2) == 'gz') { - $this->_compress = true; - $this->_compress_type = 'gz'; - } elseif ((substr($p_tarname, -3) == 'bz2') || - (substr($p_tarname, -2) == 'bz')) { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } - } - } else { - if (($p_compress === true) || ($p_compress == 'gz')) { - $this->_compress = true; - $this->_compress_type = 'gz'; - } else if ($p_compress == 'bz2') { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } else { - $this->_error("Unsupported compression type '$p_compress'\n". - "Supported types are 'gz' and 'bz2'.\n"); - return false; - } - } - $this->_tarname = $p_tarname; - if ($this->_compress) { // assert zlib or bz2 extension support - if ($this->_compress_type == 'gz') - $extname = 'zlib'; - else if ($this->_compress_type == 'bz2') - $extname = 'bz2'; - - if (!extension_loaded($extname)) { - PEAR::loadExtension($extname); - } - if (!extension_loaded($extname)) { - $this->_error("The extension '$extname' couldn't be found.\n". - "Please make sure your version of PHP was built ". - "with '$extname' support.\n"); - return false; - } - } - } - // }}} - - // {{{ destructor - function _Archive_Tar() - { - $this->_close(); - // ----- Look for a local copy to delete - if ($this->_temp_tarname != '') - @unlink($this->_temp_tarname); - $this->_PEAR(); - } - // }}} - - // {{{ create() - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If a file with the same name exist and is writable, it is replaced - * by the new tar. - * The method return false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * For each directory added in the archive, the files and - * sub-directories are also added. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - * @access public - */ - function create($p_filelist) - { - return $this->createModify($p_filelist, '', ''); - } - // }}} - - // {{{ add() - /** - * This method add the files / directories that are listed in $p_filelist in - * the archive. If the archive does not exist it is created. - * The method return false and a PEAR error text. - * The files and directories listed are only added at the end of the archive, - * even if a file with the same name is already archived. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - * @access public - */ - function add($p_filelist) - { - return $this->addModify($p_filelist, '', ''); - } - // }}} - - // {{{ extract() - function extract($p_path='', $p_preserve=false) - { - return $this->extractModify($p_path, '', $p_preserve); - } - // }}} - - // {{{ listContent() - function listContent() - { - $v_list_detail = array(); - - if ($this->_openRead()) { - if (!$this->_extractList('', $v_list_detail, "list", '', '')) { - unset($v_list_detail); - $v_list_detail = 0; - } - $this->_close(); - } - - return $v_list_detail; - } - // }}} - - // {{{ createModify() - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If the file already exists and is writable, it is replaced by the - * new tar. It is a create and not an add. If the file exists and is - * read-only or is a directory it is not replaced. The method return - * false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * See also addModify() method for file adding properties. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated by - * a single blank space. - * @param string $p_add_dir A string which contains a path to be added - * to the memorized path of each element in - * the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of each - * element in the list, when relevant. - * - * @return boolean true on success, false on error. - * @access public - * @see addModify() - */ - function createModify($p_filelist, $p_add_dir, $p_remove_dir='') - { - $v_result = true; - - if (!$this->_openWrite()) - return false; - - if ($p_filelist != '') { - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_cleanFile(); - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir); - } - - if ($v_result) { - $this->_writeFooter(); - $this->_close(); - } else - $this->_cleanFile(); - - return $v_result; - } - // }}} - - // {{{ addModify() - /** - * This method add the files / directories listed in $p_filelist at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * If a file/dir is already in the archive it will only be added at the - * end of the archive. There is no update of the existing archived - * file/dir. However while extracting the archive, the last file will - * replace the first one. This results in a none optimization of the - * archive size. - * If a file/dir does not exist the file/dir is ignored. However an - * error text is send to PEAR error. - * If a file/dir is not readable the file/dir is ignored. However an - * error text is send to PEAR error. - * - * @param array $p_filelist An array of filenames and directory - * names, or a single string with names - * separated by a single blank space. - * @param string $p_add_dir A string which contains a path to be - * added to the memorized path of each - * element in the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of - * each element in the list, when - * relevant. - * - * @return true on success, false on error. - * @access public - */ - function addModify($p_filelist, $p_add_dir, $p_remove_dir='') - { - $v_result = true; - - if (!$this->_isArchive()) - $v_result = $this->createModify($p_filelist, $p_add_dir, - $p_remove_dir); - else { - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir); - } - - return $v_result; - } - // }}} - - // {{{ addString() - /** - * This method add a single string as a file at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * - * @param string $p_filename A string which contains the full - * filename path that will be associated - * with the string. - * @param string $p_string The content of the file added in - * the archive. - * @param int $p_datetime A custom date/time (unix timestamp) - * for the file (optional). - * - * @return true on success, false on error. - * @access public - */ - function addString($p_filename, $p_string, $p_datetime = false) - { - $v_result = true; - - if (!$this->_isArchive()) { - if (!$this->_openWrite()) { - return false; - } - $this->_close(); - } - - if (!$this->_openAppend()) - return false; - - // Need to check the get back to the temporary file ? .... - $v_result = $this->_addString($p_filename, $p_string, $p_datetime); - - $this->_writeFooter(); - - $this->_close(); - - return $v_result; - } - // }}} - - // {{{ extractModify() - /** - * This method extract all the content of the archive in the directory - * indicated by $p_path. When relevant the memorized path of the - * files/dir can be modified by removing the $p_remove_path path at the - * beginning of the file/dir path. - * While extracting a file, if the directory path does not exists it is - * created. - * While extracting a file, if the file already exists it is replaced - * without looking for last modification date. - * While extracting a file, if the file already exists and is write - * protected, the extraction is aborted. - * While extracting a file, if a directory with the same name already - * exists, the extraction is aborted. - * While extracting a directory, if a file with the same name already - * exists, the extraction is aborted. - * While extracting a file/directory if the destination directory exist - * and is write protected, or does not exist but can not be created, - * the extraction is aborted. - * If after extraction an extracted file does not show the correct - * stored file size, the extraction is aborted. - * When the extraction is aborted, a PEAR error text is set and false - * is returned. However the result can be a partial extraction that may - * need to be manually cleaned. - * - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return boolean true on success, false on error. - * @access public - * @see extractList() - */ - function extractModify($p_path, $p_remove_path, $p_preserve=false) - { - $v_result = true; - $v_list_detail = array(); - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList($p_path, $v_list_detail, - "complete", 0, $p_remove_path, $p_preserve); - $this->_close(); - } - - return $v_result; - } - // }}} - - // {{{ extractInString() - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or NULL on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or NULL. - * @access public - */ - function extractInString($p_filename) - { - if ($this->_openRead()) { - $v_result = $this->_extractInString($p_filename); - $this->_close(); - } else { - $v_result = null; - } - - return $v_result; - } - // }}} - - // {{{ extractList() - /** - * This method extract from the archive only the files indicated in the - * $p_filelist. These files are extracted in the current directory or - * in the directory indicated by the optional $p_path parameter. - * If indicated the $p_remove_path can be used in the same way as it is - * used in extractModify() method. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated - * by a single blank space. - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return true on success, false on error. - * @access public - * @see extractModify() - */ - function extractList($p_filelist, $p_path='', $p_remove_path='', $p_preserve=false) - { - $v_result = true; - $v_list_detail = array(); - - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_error('Invalid string list'); - return false; - } - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList($p_path, $v_list_detail, "partial", - $v_list, $p_remove_path, $p_preserve); - $this->_close(); - } - - return $v_result; - } - // }}} - - // {{{ setAttribute() - /** - * This method set specific attributes of the archive. It uses a variable - * list of parameters, in the format attribute code + attribute values : - * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ','); - * - * @param mixed $argv variable list of attributes and values - * - * @return true on success, false on error. - * @access public - */ - function setAttribute() - { - $v_result = true; - - // ----- Get the number of variable list of arguments - if (($v_size = func_num_args()) == 0) { - return true; - } - - // ----- Get the arguments - $v_att_list = &func_get_args(); - - // ----- Read the attributes - $i=0; - while ($i<$v_size) { - - // ----- Look for next option - switch ($v_att_list[$i]) { - // ----- Look for options that request a string value - case ARCHIVE_TAR_ATT_SEPARATOR : - // ----- Check the number of parameters - if (($i+1) >= $v_size) { - $this->_error('Invalid number of parameters for ' - .'attribute ARCHIVE_TAR_ATT_SEPARATOR'); - return false; - } - - // ----- Get the value - $this->_separator = $v_att_list[$i+1]; - $i++; - break; - - default : - $this->_error('Unknow attribute code '.$v_att_list[$i].''); - return false; - } - - // ----- Next attribute - $i++; - } - - return $v_result; - } - // }}} - - // {{{ setIgnoreRegexp() - /** - * This method sets the regular expression for ignoring files and directories - * at import, for example: - * $arch->setIgnoreRegexp("#CVS|\.svn#"); - * - * @param string $regexp regular expression defining which files or directories to ignore - * - * @access public - */ - function setIgnoreRegexp($regexp) - { - $this->_ignore_regexp = $regexp; - } - // }}} - - // {{{ setIgnoreList() - /** - * This method sets the regular expression for ignoring all files and directories - * matching the filenames in the array list at import, for example: - * $arch->setIgnoreList(array('CVS', '.svn', 'bin/tool')); - * - * @param array $list a list of file or directory names to ignore - * - * @access public - */ - function setIgnoreList($list) - { - $regexp = str_replace(array('#', '.', '^', '$'), array('\#', '\.', '\^', '\$'), $list); - $regexp = '#/'.join('$|/', $list).'#'; - $this->setIgnoreRegexp($regexp); - } - // }}} - - // {{{ _error() - function _error($p_message) - { - $this->error_object = &$this->raiseError($p_message); - } - // }}} - - // {{{ _warning() - function _warning($p_message) - { - $this->error_object = &$this->raiseError($p_message); - } - // }}} - - // {{{ _isArchive() - function _isArchive($p_filename=null) - { - if ($p_filename == null) { - $p_filename = $this->_tarname; - } - clearstatcache(); - return @is_file($p_filename) && !@is_link($p_filename); - } - // }}} - - // {{{ _openWrite() - function _openWrite() - { - if ($this->_compress_type == 'gz' && function_exists('gzopen')) - $this->_file = @gzopen($this->_tarname, "wb9"); - else if ($this->_compress_type == 'bz2' && function_exists('bzopen')) - $this->_file = @bzopen($this->_tarname, "w"); - else if ($this->_compress_type == 'none') - $this->_file = @fopen($this->_tarname, "wb"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in write mode \'' - .$this->_tarname.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _openRead() - function _openRead() - { - if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') { - - // ----- Look if a local copy need to be done - if ($this->_temp_tarname == '') { - $this->_temp_tarname = uniqid('tar').'.tmp'; - if (!$v_file_from = @fopen($this->_tarname, 'rb')) { - $this->_error('Unable to open in read mode \'' - .$this->_tarname.'\''); - $this->_temp_tarname = ''; - return false; - } - if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) { - $this->_error('Unable to open in write mode \'' - .$this->_temp_tarname.'\''); - $this->_temp_tarname = ''; - return false; - } - while ($v_data = @fread($v_file_from, 1024)) - @fwrite($v_file_to, $v_data); - @fclose($v_file_from); - @fclose($v_file_to); - } - - // ----- File to open if the local copy - $v_filename = $this->_temp_tarname; - - } else - // ----- File to open if the normal Tar file - $v_filename = $this->_tarname; - - if ($this->_compress_type == 'gz' && function_exists('gzopen')) - $this->_file = @gzopen($v_filename, "rb"); - else if ($this->_compress_type == 'bz2' && function_exists('bzopen')) - $this->_file = @bzopen($v_filename, "r"); - else if ($this->_compress_type == 'none') - $this->_file = @fopen($v_filename, "rb"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in read mode \''.$v_filename.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _openReadWrite() - function _openReadWrite() - { - if ($this->_compress_type == 'gz') - $this->_file = @gzopen($this->_tarname, "r+b"); - else if ($this->_compress_type == 'bz2') { - $this->_error('Unable to open bz2 in read/write mode \'' - .$this->_tarname.'\' (limitation of bz2 extension)'); - return false; - } else if ($this->_compress_type == 'none') - $this->_file = @fopen($this->_tarname, "r+b"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in read/write mode \'' - .$this->_tarname.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _close() - function _close() - { - //if (isset($this->_file)) { - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') - @gzclose($this->_file); - else if ($this->_compress_type == 'bz2') - @bzclose($this->_file); - else if ($this->_compress_type == 'none') - @fclose($this->_file); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - $this->_file = 0; - } - - // ----- Look if a local copy need to be erase - // Note that it might be interesting to keep the url for a time : ToDo - if ($this->_temp_tarname != '') { - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } - - return true; - } - // }}} - - // {{{ _cleanFile() - function _cleanFile() - { - $this->_close(); - - // ----- Look for a local copy - if ($this->_temp_tarname != '') { - // ----- Remove the local copy but not the remote tarname - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } else { - // ----- Remove the local tarname file - @unlink($this->_tarname); - } - $this->_tarname = ''; - - return true; - } - // }}} - - // {{{ _writeBlock() - function _writeBlock($p_binary_data, $p_len=null) - { - if (is_resource($this->_file)) { - if ($p_len === null) { - if ($this->_compress_type == 'gz') - @gzputs($this->_file, $p_binary_data); - else if ($this->_compress_type == 'bz2') - @bzwrite($this->_file, $p_binary_data); - else if ($this->_compress_type == 'none') - @fputs($this->_file, $p_binary_data); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - } else { - if ($this->_compress_type == 'gz') - @gzputs($this->_file, $p_binary_data, $p_len); - else if ($this->_compress_type == 'bz2') - @bzwrite($this->_file, $p_binary_data, $p_len); - else if ($this->_compress_type == 'none') - @fputs($this->_file, $p_binary_data, $p_len); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - } - } - return true; - } - // }}} - - // {{{ _readBlock() - function _readBlock() - { - $v_block = null; - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') - $v_block = @gzread($this->_file, 512); - else if ($this->_compress_type == 'bz2') - $v_block = @bzread($this->_file, 512); - else if ($this->_compress_type == 'none') - $v_block = @fread($this->_file, 512); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - } - return $v_block; - } - // }}} - - // {{{ _jumpBlock() - function _jumpBlock($p_len=null) - { - if (is_resource($this->_file)) { - if ($p_len === null) - $p_len = 1; - - if ($this->_compress_type == 'gz') { - @gzseek($this->_file, gztell($this->_file)+($p_len*512)); - } - else if ($this->_compress_type == 'bz2') { - // ----- Replace missing bztell() and bzseek() - for ($i=0; $i<$p_len; $i++) - $this->_readBlock(); - } else if ($this->_compress_type == 'none') - @fseek($this->_file, $p_len*512, SEEK_CUR); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - } - return true; - } - // }}} - - // {{{ _writeFooter() - function _writeFooter() - { - if (is_resource($this->_file)) { - // ----- Write the last 0 filled block for end of archive - $v_binary_data = pack('a1024', ''); - $this->_writeBlock($v_binary_data); - } - return true; - } - // }}} - - // {{{ _addList() - function _addList($p_list, $p_add_dir, $p_remove_dir) - { - $v_result=true; - $v_header = array(); - - // ----- Remove potential windows directory separator - $p_add_dir = $this->_translateWinPath($p_add_dir); - $p_remove_dir = $this->_translateWinPath($p_remove_dir, false); - - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if (sizeof($p_list) == 0) - return true; - - foreach ($p_list as $v_filename) { - if (!$v_result) { - break; - } - - // ----- Skip the current tar name - if ($v_filename == $this->_tarname) - continue; - - if ($v_filename == '') - continue; - - // ----- ignore files and directories matching the ignore regular expression - if ($this->_ignore_regexp && preg_match($this->_ignore_regexp, '/'.$v_filename)) { - $this->_warning("File '$v_filename' ignored"); - continue; - } - - if (!file_exists($v_filename) && !is_link($v_filename)) { - $this->_warning("File '$v_filename' does not exist"); - continue; - } - - // ----- Add the file or directory header - if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir)) - return false; - - if (@is_dir($v_filename) && !@is_link($v_filename)) { - if (!($p_hdir = opendir($v_filename))) { - $this->_warning("Directory '$v_filename' can not be read"); - continue; - } - while (false !== ($p_hitem = readdir($p_hdir))) { - if (($p_hitem != '.') && ($p_hitem != '..')) { - if ($v_filename != ".") - $p_temp_list[0] = $v_filename.'/'.$p_hitem; - else - $p_temp_list[0] = $p_hitem; - - $v_result = $this->_addList($p_temp_list, - $p_add_dir, - $p_remove_dir); - } - } - - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - // }}} - - // {{{ _addFile() - function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir) - { - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false);; - $v_stored_filename = $p_filename; - if (strcmp($p_filename, $p_remove_dir) == 0) { - return true; - } - if ($p_remove_dir != '') { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= '/'; - - if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - $v_stored_filename = $this->_translateWinPath($v_stored_filename); - if ($p_add_dir != '') { - if (substr($p_add_dir, -1) == '/') - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir.'/'.$v_stored_filename; - } - - $v_stored_filename = $this->_pathReduction($v_stored_filename); - - if ($this->_isArchive($p_filename)) { - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_warning("Unable to open file '".$p_filename - ."' in binary read mode"); - return true; - } - - if (!$this->_writeHeader($p_filename, $v_stored_filename)) - return false; - - while (($v_buffer = fread($v_file, 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - fclose($v_file); - - } else { - // ----- Only header for dir - if (!$this->_writeHeader($p_filename, $v_stored_filename)) - return false; - } - - return true; - } - // }}} - - // {{{ _addString() - function _addString($p_filename, $p_string, $p_datetime = false) - { - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false);; - - // ----- If datetime is not specified, set current time - if ($p_datetime === false) { - $p_datetime = time(); - } - - if (!$this->_writeHeaderBlock($p_filename, strlen($p_string), - $p_datetime, 384, "", 0, 0)) - return false; - - $i=0; - while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') { - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - return true; - } - // }}} - - // {{{ _writeHeader() - function _writeHeader($p_filename, $p_stored_filename) - { - if ($p_stored_filename == '') - $p_stored_filename = $p_filename; - $v_reduce_filename = $this->_pathReduction($p_stored_filename); - - if (strlen($v_reduce_filename) > 99) { - if (!$this->_writeLongHeader($v_reduce_filename)) - return false; - } - - $v_info = lstat($p_filename); - $v_uid = sprintf("%07s", DecOct($v_info[4])); - $v_gid = sprintf("%07s", DecOct($v_info[5])); - $v_perms = sprintf("%07s", DecOct($v_info['mode'] & 000777)); - - $v_mtime = sprintf("%011s", DecOct($v_info['mtime'])); - - $v_linkname = ''; - - if (@is_link($p_filename)) { - $v_typeflag = '2'; - $v_linkname = readlink($p_filename); - $v_size = sprintf("%011s", DecOct(0)); - } elseif (@is_dir($p_filename)) { - $v_typeflag = "5"; - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_typeflag = '0'; - clearstatcache(); - $v_size = sprintf("%011s", DecOct($v_info['size'])); - } - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) - { - $userinfo = posix_getpwuid($v_info[4]); - $groupinfo = posix_getgrgid($v_info[5]); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } - else - { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12a12", - $v_reduce_filename, $v_perms, $v_uid, - $v_gid, $v_size, $v_mtime); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - // }}} - - // {{{ _writeHeaderBlock() - function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0, - $p_type='', $p_uid=0, $p_gid=0) - { - $p_filename = $this->_pathReduction($p_filename); - - if (strlen($p_filename) > 99) { - if (!$this->_writeLongHeader($p_filename)) - return false; - } - - if ($p_type == "5") { - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_size = sprintf("%011s", DecOct($p_size)); - } - - $v_uid = sprintf("%07s", DecOct($p_uid)); - $v_gid = sprintf("%07s", DecOct($p_gid)); - $v_perms = sprintf("%07s", DecOct($p_perms & 000777)); - - $v_mtime = sprintf("%11s", DecOct($p_mtime)); - - $v_linkname = ''; - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) - { - $userinfo = posix_getpwuid($p_uid); - $groupinfo = posix_getgrgid($p_gid); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } - else - { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12A12", - $p_filename, $v_perms, $v_uid, $v_gid, - $v_size, $v_mtime); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $p_type, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - // }}} - - // {{{ _writeLongHeader() - function _writeLongHeader($p_filename) - { - $v_size = sprintf("%11s ", DecOct(strlen($p_filename))); - - $v_typeflag = 'L'; - - $v_linkname = ''; - - $v_magic = ''; - - $v_version = ''; - - $v_uname = ''; - - $v_gname = ''; - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12a12", - '././@LongLink', 0, 0, 0, $v_size, 0); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - // ----- Write the filename as content of the block - $i=0; - while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - return true; - } - // }}} - - // {{{ _readHeader() - function _readHeader($v_binary_data, &$v_header) - { - if (strlen($v_binary_data)==0) { - $v_header['filename'] = ''; - return true; - } - - if (strlen($v_binary_data) != 512) { - $v_header['filename'] = ''; - $this->_error('Invalid block size : '.strlen($v_binary_data)); - return false; - } - - if (!is_array($v_header)) { - $v_header = array(); - } - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum+=ord(substr($v_binary_data,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156; $i<512; $i++) - $v_checksum+=ord(substr($v_binary_data,$i,1)); - - if (version_compare(PHP_VERSION,"5.5.0-dev")<0) { - $fmt = "a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/" . - "a8checksum/a1typeflag/a100link/a6magic/a2version/" . - "a32uname/a32gname/a8devmajor/a8devminor/a131prefix"; - } else { - $fmt = "Z100filename/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/" . - "Z8checksum/Z1typeflag/Z100link/Z6magic/Z2version/" . - "Z32uname/Z32gname/Z8devmajor/Z8devminor/Z131prefix"; - } - $v_data = unpack($fmt, $v_binary_data); - - if (strlen($v_data["prefix"]) > 0) { - $v_data["filename"] = "$v_data[prefix]/$v_data[filename]"; - } - - // ----- Extract the checksum - $v_header['checksum'] = OctDec(trim($v_data['checksum'])); - if ($v_header['checksum'] != $v_checksum) { - $v_header['filename'] = ''; - - // ----- Look for last block (empty block) - if (($v_checksum == 256) && ($v_header['checksum'] == 0)) - return true; - - $this->_error('Invalid checksum for file "'.$v_data['filename'] - .'" : '.$v_checksum.' calculated, ' - .$v_header['checksum'].' expected'); - return false; - } - - // ----- Extract the properties - $v_header['filename'] = $v_data['filename']; - if ($this->_maliciousFilename($v_header['filename'])) { - $this->_error('Malicious .tar detected, file "' . $v_header['filename'] . - '" will not install in desired directory tree'); - return false; - } - $v_header['mode'] = OctDec(trim($v_data['mode'])); - $v_header['uid'] = OctDec(trim($v_data['uid'])); - $v_header['gid'] = OctDec(trim($v_data['gid'])); - $v_header['size'] = OctDec(trim($v_data['size'])); - $v_header['mtime'] = OctDec(trim($v_data['mtime'])); - if (($v_header['typeflag'] = $v_data['typeflag']) == "5") { - $v_header['size'] = 0; - } - $v_header['link'] = trim($v_data['link']); - /* ----- All these fields are removed form the header because - they do not carry interesting info - $v_header[magic] = trim($v_data[magic]); - $v_header[version] = trim($v_data[version]); - $v_header[uname] = trim($v_data[uname]); - $v_header[gname] = trim($v_data[gname]); - $v_header[devmajor] = trim($v_data[devmajor]); - $v_header[devminor] = trim($v_data[devminor]); - */ - - return true; - } - // }}} - - // {{{ _maliciousFilename() - /** - * Detect and report a malicious file name - * - * @param string $file - * - * @return bool - * @access private - */ - function _maliciousFilename($file) - { - if (strpos($file, '/../') !== false) { - return true; - } - if (strpos($file, '../') === 0) { - return true; - } - return false; - } - // }}} - - // {{{ _readLongHeader() - function _readLongHeader(&$v_header) - { - $v_filename = ''; - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_content = $this->_readBlock(); - $v_filename .= $v_content; - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_filename .= trim($v_content); - } - - // ----- Read the next header - $v_binary_data = $this->_readBlock(); - - if (!$this->_readHeader($v_binary_data, $v_header)) - return false; - - $v_filename = trim($v_filename); - $v_header['filename'] = $v_filename; - if ($this->_maliciousFilename($v_filename)) { - $this->_error('Malicious .tar detected, file "' . $v_filename . - '" will not install in desired directory tree'); - return false; - } - - return true; - } - // }}} - - // {{{ _extractInString() - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or null on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or null. - * @access private - */ - function _extractInString($p_filename) - { - $v_result_str = ""; - - While (strlen($v_binary_data = $this->_readBlock()) != 0) - { - if (!$this->_readHeader($v_binary_data, $v_header)) - return null; - - if ($v_header['filename'] == '') - continue; - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) - return null; - } - - if ($v_header['filename'] == $p_filename) { - if ($v_header['typeflag'] == "5") { - $this->_error('Unable to extract in string a directory ' - .'entry {'.$v_header['filename'].'}'); - return null; - } else { - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_result_str .= $this->_readBlock(); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_result_str .= substr($v_content, 0, - ($v_header['size'] % 512)); - } - return $v_result_str; - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - } - - return null; - } - // }}} - - // {{{ _extractList() - function _extractList($p_path, &$p_list_detail, $p_mode, - $p_file_list, $p_remove_path, $p_preserve=false) - { - $v_result=true; - $v_nb = 0; - $v_extract_all = true; - $v_listing = false; - - $p_path = $this->_translateWinPath($p_path, false); - if ($p_path == '' || (substr($p_path, 0, 1) != '/' - && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) { - $p_path = "./".$p_path; - } - $p_remove_path = $this->_translateWinPath($p_remove_path); - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/')) - $p_remove_path .= '/'; - $p_remove_path_size = strlen($p_remove_path); - - switch ($p_mode) { - case "complete" : - $v_extract_all = true; - $v_listing = false; - break; - case "partial" : - $v_extract_all = false; - $v_listing = false; - break; - case "list" : - $v_extract_all = false; - $v_listing = true; - break; - default : - $this->_error('Invalid extract mode ('.$p_mode.')'); - return false; - } - - clearstatcache(); - - while (strlen($v_binary_data = $this->_readBlock()) != 0) - { - $v_extract_file = FALSE; - $v_extraction_stopped = 0; - - if (!$this->_readHeader($v_binary_data, $v_header)) - return false; - - if ($v_header['filename'] == '') { - continue; - } - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) - return false; - } - - if ((!$v_extract_all) && (is_array($p_file_list))) { - // ----- By default no unzip if the file is not found - $v_extract_file = false; - - for ($i=0; $i strlen($p_file_list[$i])) - && (substr($v_header['filename'], 0, strlen($p_file_list[$i])) - == $p_file_list[$i])) { - $v_extract_file = true; - break; - } - } - - // ----- It is a file, so compare the file names - elseif ($p_file_list[$i] == $v_header['filename']) { - $v_extract_file = true; - break; - } - } - } else { - $v_extract_file = true; - } - - // ----- Look if this file need to be extracted - if (($v_extract_file) && (!$v_listing)) - { - if (($p_remove_path != '') - && (substr($v_header['filename'].'/', 0, $p_remove_path_size) - == $p_remove_path)) { - $v_header['filename'] = substr($v_header['filename'], - $p_remove_path_size); - if( $v_header['filename'] == '' ){ - continue; - } - } - if (($p_path != './') && ($p_path != '/')) { - while (substr($p_path, -1) == '/') - $p_path = substr($p_path, 0, strlen($p_path)-1); - - if (substr($v_header['filename'], 0, 1) == '/') - $v_header['filename'] = $p_path.$v_header['filename']; - else - $v_header['filename'] = $p_path.'/'.$v_header['filename']; - } - if (file_exists($v_header['filename'])) { - if ( (@is_dir($v_header['filename'])) - && ($v_header['typeflag'] == '')) { - $this->_error('File '.$v_header['filename'] - .' already exists as a directory'); - return false; - } - if ( ($this->_isArchive($v_header['filename'])) - && ($v_header['typeflag'] == "5")) { - $this->_error('Directory '.$v_header['filename'] - .' already exists as a file'); - return false; - } - if (!is_writeable($v_header['filename'])) { - $this->_error('File '.$v_header['filename'] - .' already exists and is write protected'); - return false; - } - if (filemtime($v_header['filename']) > $v_header['mtime']) { - // To be completed : An error or silent no replace ? - } - } - - // ----- Check the directory availability and create it if necessary - elseif (($v_result - = $this->_dirCheck(($v_header['typeflag'] == "5" - ?$v_header['filename'] - :dirname($v_header['filename'])))) != 1) { - $this->_error('Unable to create path for '.$v_header['filename']); - return false; - } - - if ($v_extract_file) { - if ($v_header['typeflag'] == "5") { - if (!@file_exists($v_header['filename'])) { - if (!@mkdir($v_header['filename'], 0777)) { - $this->_error('Unable to create directory {' - .$v_header['filename'].'}'); - return false; - } - } - } elseif ($v_header['typeflag'] == "2") { - if (@file_exists($v_header['filename'])) { - @unlink($v_header['filename']); - } - if (!@symlink($v_header['link'], $v_header['filename'])) { - $this->_error('Unable to extract symbolic link {' - .$v_header['filename'].'}'); - return false; - } - } else { - if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) { - $this->_error('Error while opening {'.$v_header['filename'] - .'} in write binary mode'); - return false; - } else { - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, 512); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, ($v_header['size'] % 512)); - } - - @fclose($v_dest_file); - - if ($p_preserve) { - @chown($v_header['filename'], $v_header['uid']); - @chgrp($v_header['filename'], $v_header['gid']); - } - - // ----- Change the file mode, mtime - @touch($v_header['filename'], $v_header['mtime']); - if ($v_header['mode'] & 0111) { - // make file executable, obey umask - $mode = fileperms($v_header['filename']) | (~umask() & 0111); - @chmod($v_header['filename'], $mode); - } - } - - // ----- Check the file size - clearstatcache(); - if (!is_file($v_header['filename'])) { - $this->_error('Extracted file '.$v_header['filename'] - .'does not exist. Archive may be corrupted.'); - return false; - } - - $filesize = filesize($v_header['filename']); - if ($filesize != $v_header['size']) { - $this->_error('Extracted file '.$v_header['filename'] - .' does not have the correct file size \'' - .$filesize - .'\' ('.$v_header['size'] - .' expected). Archive may be corrupted.'); - return false; - } - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - - /* TBC : Seems to be unused ... - if ($this->_compress) - $v_end_of_file = @gzeof($this->_file); - else - $v_end_of_file = @feof($this->_file); - */ - - if ($v_listing || $v_extract_file || $v_extraction_stopped) { - // ----- Log extracted files - if (($v_file_dir = dirname($v_header['filename'])) - == $v_header['filename']) - $v_file_dir = ''; - if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == '')) - $v_file_dir = '/'; - - $p_list_detail[$v_nb++] = $v_header; - if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) { - return true; - } - } - } - - return true; - } - // }}} - - // {{{ _openAppend() - function _openAppend() - { - if (filesize($this->_tarname) == 0) - return $this->_openWrite(); - - if ($this->_compress) { - $this->_close(); - - if (!@rename($this->_tarname, $this->_tarname.".tmp")) { - $this->_error('Error while renaming \''.$this->_tarname - .'\' to temporary file \''.$this->_tarname - .'.tmp\''); - return false; - } - - if ($this->_compress_type == 'gz') - $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb"); - elseif ($this->_compress_type == 'bz2') - $v_temp_tar = @bzopen($this->_tarname.".tmp", "r"); - - if ($v_temp_tar == 0) { - $this->_error('Unable to open file \''.$this->_tarname - .'.tmp\' in binary read mode'); - @rename($this->_tarname.".tmp", $this->_tarname); - return false; - } - - if (!$this->_openWrite()) { - @rename($this->_tarname.".tmp", $this->_tarname); - return false; - } - - if ($this->_compress_type == 'gz') { - $end_blocks = 0; - - while (!@gzeof($v_temp_tar)) { - $v_buffer = @gzread($v_temp_tar, 512); - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @gzclose($v_temp_tar); - } - elseif ($this->_compress_type == 'bz2') { - $end_blocks = 0; - - while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) { - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @bzclose($v_temp_tar); - } - - if (!@unlink($this->_tarname.".tmp")) { - $this->_error('Error while deleting temporary file \'' - .$this->_tarname.'.tmp\''); - } - - } else { - // ----- For not compressed tar, just add files before the last - // one or two 512 bytes block - if (!$this->_openReadWrite()) - return false; - - clearstatcache(); - $v_size = filesize($this->_tarname); - - // We might have zero, one or two end blocks. - // The standard is two, but we should try to handle - // other cases. - fseek($this->_file, $v_size - 1024); - if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 1024); - } - elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 512); - } - } - - return true; - } - // }}} - - // {{{ _append() - function _append($p_filelist, $p_add_dir='', $p_remove_dir='') - { - if (!$this->_openAppend()) - return false; - - if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir)) - $this->_writeFooter(); - - $this->_close(); - - return true; - } - // }}} - - // {{{ _dirCheck() - - /** - * Check if a directory exists and create it (including parent - * dirs) if not. - * - * @param string $p_dir directory to check - * - * @return bool true if the directory exists or was created - */ - function _dirCheck($p_dir) - { - clearstatcache(); - if ((@is_dir($p_dir)) || ($p_dir == '')) - return true; - - $p_parent_dir = dirname($p_dir); - - if (($p_parent_dir != $p_dir) && - ($p_parent_dir != '') && - (!$this->_dirCheck($p_parent_dir))) - return false; - - if (!@mkdir($p_dir, 0777)) { - $this->_error("Unable to create directory '$p_dir'"); - return false; - } - - return true; - } - - // }}} - - // {{{ _pathReduction() - - /** - * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar", - * rand emove double slashes. - * - * @param string $p_dir path to reduce - * - * @return string reduced path - * - * @access private - * - */ - function _pathReduction($p_dir) - { - $v_result = ''; - - // ----- Look for not empty path - if ($p_dir != '') { - // ----- Explode path by directory names - $v_list = explode('/', $p_dir); - - // ----- Study directories from last to first - for ($i=sizeof($v_list)-1; $i>=0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") { - // ----- Ignore it and ignore the $i-1 - $i--; - } - else if ( ($v_list[$i] == '') - && ($i!=(sizeof($v_list)-1)) - && ($i!=0)) { - // ----- Ignore only the double '//' in path, - // but not the first and last / - } else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/' - .$v_result:''); - } - } - } - - if (defined('OS_WINDOWS') && OS_WINDOWS) { - $v_result = strtr($v_result, '\\', '/'); - } - - return $v_result; - } - - // }}} - - // {{{ _translateWinPath() - function _translateWinPath($p_path, $p_remove_disk_letter=true) - { - if (defined('OS_WINDOWS') && OS_WINDOWS) { - // ----- Look for potential disk letter - if ( ($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } - // }}} - -} -?> \ No newline at end of file diff --git a/thirdparty/pear/Archive/Zip.php b/thirdparty/pear/Archive/Zip.php deleted file mode 100644 index 941b0d655..000000000 --- a/thirdparty/pear/Archive/Zip.php +++ /dev/null @@ -1,3620 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Zip.php,v 1.2 2005/11/21 06:51:57 vblavet Exp $ - - require_once 'PEAR.php'; - - // ----- Constants - define( 'ARCHIVE_ZIP_READ_BLOCK_SIZE', 2048 ); - - // ----- File list separator - define( 'ARCHIVE_ZIP_SEPARATOR', ',' ); - - // ----- Optional static temporary directory - // By default temporary files are generated in the script current - // path. - // If defined : - // - MUST BE terminated by a '/'. - // - MUST be a valid, already created directory - // Samples : - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '/temp/' ); - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', 'C:/Temp/' ); - define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '' ); - - // ----- Error codes - define( 'ARCHIVE_ZIP_ERR_NO_ERROR', 0 ); - define( 'ARCHIVE_ZIP_ERR_WRITE_OPEN_FAIL', -1 ); - define( 'ARCHIVE_ZIP_ERR_READ_OPEN_FAIL', -2 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAMETER', -3 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_FILE', -4 ); - define( 'ARCHIVE_ZIP_ERR_FILENAME_TOO_LONG', -5 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ZIP', -6 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTRACTED_FILE', -7 ); - define( 'ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL', -8 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTENSION', -9 ); - define( 'ARCHIVE_ZIP_ERR_BAD_FORMAT', -10 ); - define( 'ARCHIVE_ZIP_ERR_DELETE_FILE_FAIL', -11 ); - define( 'ARCHIVE_ZIP_ERR_RENAME_FILE_FAIL', -12 ); - define( 'ARCHIVE_ZIP_ERR_BAD_CHECKSUM', -13 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_OPTION_VALUE', -15 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE', -16 ); - - // ----- Warning codes - define( 'ARCHIVE_ZIP_WARN_NO_WARNING', 0 ); - define( 'ARCHIVE_ZIP_WARN_FILE_EXIST', 1 ); - - // ----- Methods parameters - define( 'ARCHIVE_ZIP_PARAM_PATH', 'path' ); - define( 'ARCHIVE_ZIP_PARAM_ADD_PATH', 'add_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_PATH', 'remove_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_ALL_PATH', 'remove_all_path' ); - define( 'ARCHIVE_ZIP_PARAM_SET_CHMOD', 'set_chmod' ); - define( 'ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING', 'extract_as_string' ); - define( 'ARCHIVE_ZIP_PARAM_NO_COMPRESSION', 'no_compression' ); - define( 'ARCHIVE_ZIP_PARAM_BY_NAME', 'by_name' ); - define( 'ARCHIVE_ZIP_PARAM_BY_INDEX', 'by_index' ); - define( 'ARCHIVE_ZIP_PARAM_BY_EREG', 'by_ereg' ); - define( 'ARCHIVE_ZIP_PARAM_BY_PREG', 'by_preg' ); - - define( 'ARCHIVE_ZIP_PARAM_PRE_EXTRACT', 'callback_pre_extract' ); - define( 'ARCHIVE_ZIP_PARAM_POST_EXTRACT', 'callback_post_extract' ); - define( 'ARCHIVE_ZIP_PARAM_PRE_ADD', 'callback_pre_add' ); - define( 'ARCHIVE_ZIP_PARAM_POST_ADD', 'callback_post_add' ); - - - -/** -* Class for manipulating zip archive files -* -* A class which provided common methods to manipulate ZIP formatted -* archive files. -* It provides creation, extraction, deletion and add features. -* -* @author Vincent Blavet -* @version $Revision: 1.2 $ -* @package Archive_Zip -* @category Archive -*/ -class Archive_Zip -{ - /** - * The filename of the zip archive. - * - * @var string Name of the Zip file - */ - var $_zipname=''; - - /** - * File descriptor of the opened Zip file. - * - * @var int Internal zip file descriptor - */ - var $_zip_fd=0; - - /** - * @var int last error code - */ - var $_error_code=1; - - /** - * @var string Last error description - */ - var $_error_string=''; - - // {{{ constructor - /** - * Archive_Zip Class constructor. This flavour of the constructor only - * declare a new Archive_Zip object, identifying it by the name of the - * zip file. - * - * @param string $p_zipname The name of the zip archive to create - * @access public - */ - function Archive_Zip($p_zipname) - { - - // ----- Check the zlib - if (!extension_loaded('zlib')) { - PEAR::loadExtension('zlib'); - } - if (!extension_loaded('zlib')) { - die("The extension 'zlib' couldn't be found.\n". - "Please make sure your version of PHP was built ". - "with 'zlib' support.\n"); - return false; - } - - // ----- Set the attributes - $this->_zipname = $p_zipname; - $this->_zip_fd = 0; - - return; - } - // }}} - - // {{{ create() - /** - * This method creates a Zip Archive with the filename set with - * the constructor. - * The files and directories indicated in $p_filelist - * are added in the archive. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * an error code on error - */ - function create($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array('no_compression' => false, - 'add_path' => "", - 'remove_path' => "", - 'remove_all_path' => false)) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - $v_result = $this->_create($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - $v_result = $this->_create($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Invalid variable type p_filelist'); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - return $p_result_list; - } - // }}} - - // {{{ add() - /** - * This method add files or directory in an existing Zip Archive. - * If the Zip Archive does not exist it is created. - * The files and directories to add are indicated in $p_filelist. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * 'callback_pre_add' : A callback function that will be called before - * each entry archiving. - * 'callback_post_add' : A callback function that will be called after - * each entry archiving. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function add($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('no_compression' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_add' => '', - 'callback_post_add' => '')) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - // ----- Call the create fct - $v_result = $this->_add($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - // ----- Call the create fct - $v_result = $this->_add($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "add() : Invalid variable type p_filelist"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - // ----- Return the result list - return $p_result_list; - } - // }}} - - // {{{ listContent() - /** - * This method gives the names and properties of the files and directories - * which are present in the zip archive. - * The properties of each entries in the list are : - * filename : Name of the file. - * For create() or add() it's the filename given by the user. - * For an extract() it's the filename of the extracted file. - * stored_filename : Name of the file / directory stored in the archive. - * size : Size of the stored file. - * compressed_size : Size of the file's data compressed in the archive - * (without the zip headers overhead) - * mtime : Last known modification date of the file (UNIX timestamp) - * comment : Comment associated with the file - * folder : true | false (indicates if the entry is a folder) - * index : index of the file in the archive (-1 when not available) - * status : status of the action on the entry (depending of the action) : - * Values are : - * ok : OK ! - * filtered : the file/dir was not extracted (filtered by user) - * already_a_directory : the file can't be extracted because a - * directory with the same name already - * exists - * write_protected : the file can't be extracted because a file - * with the same name already exists and is - * write protected - * newer_exist : the file was not extracted because a newer - * file already exists - * path_creation_fail : the file is not extracted because the - * folder does not exists and can't be - * created - * write_error : the file was not extracted because there was a - * error while writing the file - * read_error : the file was not extracted because there was a - * error while reading the file - * invalid_header : the file was not extracted because of an - * archive format error (bad file header) - * Note that each time a method can continue operating when there - * is an error on a single file, the error is only logged in the file status. - * - * @access public - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function listContent() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - $v_list = array(); - if ($this->_list($v_list) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ extract() - /** - * This method extract the files and folders which are in the zip archive. - * It can extract all the archive or a part of the archive by using filter - * feature (extract by name, by index, by ereg, by preg). The extraction - * can occur in the current path or an other path. - * All the advanced features are activated by the use of variable - * parameters. - * The return value is an array of entry descriptions which gives - * information on extracted files (See listContent()). - * The method may return a success value (an array) even if some files - * are not correctly extracted (see the file status in listContent()). - * The supported variable parameters for this method are : - * 'add_path' : Path where the files and directories are to be extracted - * 'remove_path' : First part ('root' part) of the memorized path - * (if similar) to remove while extracting. - * 'remove_all_path' : Remove all the memorized path while extracting. - * 'extract_as_string' : - * 'set_chmod' : After the extraction of the file the indicated mode - * will be set. - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to extract from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * 'callback_pre_extract' : A callback function that will be called before - * each entry extraction. - * 'callback_post_extract' : A callback function that will be called after - * each entry extraction. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function extract($p_params=0) - { - - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('extract_as_string' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_extract' => '', - 'callback_post_extract' => '', - 'set_chmod' => 0, - 'by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Call the extracting fct - $v_list = array(); - if ($this->_extractByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - - // {{{ delete() - /** - * This methods delete archive entries in the zip archive. - * Notice that at least one filtering rule (set by the variable parameter - * list) must be set. - * Also notice that if you delete a folder entry, only the folder entry - * is deleted, not all the files bellonging to this folder. - * The supported variable parameters for this method are : - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to delete from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function delete($p_params) - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($this->_check_parameters($p_params, - array ('by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Check that at least one rule is set - if ( ($p_params['by_name'] == '') - && ($p_params['by_index'] == '') - && ($p_params['by_ereg'] == '') - && ($p_params['by_preg'] == '')) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'At least one filtering rule must' - .' be set as parameter'); - return 0; - } - - // ----- Call the delete fct - $v_list = array(); - if ($this->_deleteByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ properties() - /** - * This method gives the global properties of the archive. - * The properties are : - * nb : Number of files in the archive - * comment : Comment associated with the archive file - * status : not_exist, ok - * - * @access public - * @param mixed $p_params {Description} - * @return mixed An array with the global properties or 0 on error. - */ - function properties() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Default properties - $v_prop = array(); - $v_prop['comment'] = ''; - $v_prop['nb'] = 0; - $v_prop['status'] = 'not_exist'; - - // ----- Look if file exists - if (@is_file($this->_zipname)) { - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in binary read mode'); - return 0; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - return 0; - } - - $this->_closeFd(); - - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; - } - - return $v_prop; - } - // }}} - - - // {{{ duplicate() - /** - * This method creates an archive by copying the content of an other one. - * If the archive already exist, it is replaced by the new one without - * any warning. - * - * @access public - * @param mixed $p_archive It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function duplicate($p_archive) - { - $this->_errorReset(); - - // ----- Look if the $p_archive is a Archive_Zip object - if ( (is_object($p_archive)) - && (strtolower(get_class($p_archive)) == 'archive_zip')) { - $v_result = $this->_duplicate($p_archive->_zipname); - } - - // ----- Look if the $p_archive is a string (so a filename) - else if (is_string($p_archive)) { - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "No file with filename '".$p_archive."'"); - $v_result = ARCHIVE_ZIP_ERR_MISSING_FILE; - } - else { - $v_result = $this->_duplicate($p_archive); - } - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ merge() - /** - * This method merge a valid zip archive at the end of the - * archive identified by the Archive_Zip object. - * If the archive ($this) does not exist, the merge becomes a duplicate. - * If the archive to add does not exist, the merge is a success. - * - * @access public - * @param mixed $p_archive_to_add It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function merge($p_archive_to_add) - { - $v_result = 1; - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Look if the $p_archive_to_add is a Archive_Zip object - if ( (is_object($p_archive_to_add)) - && (strtolower(get_class($p_archive_to_add)) == 'archive_zip')) { - $v_result = $this->_merge($p_archive_to_add); - } - - // ----- Look if the $p_archive_to_add is a string (so a filename) - else if (is_string($p_archive_to_add)) { - // ----- Create a temporary archive - $v_object_archive = new Archive_Zip($p_archive_to_add); - - // ----- Merge the archive - $v_result = $this->_merge($v_object_archive); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ errorCode() - /** - * Method that gives the lastest error code. - * - * @access public - * @return integer The error code value. - */ - function errorCode() - { - return($this->_error_code); - } - // }}} - - // {{{ errorName() - /** - * This method gives the latest error code name. - * - * @access public - * @param boolean $p_with_code If true, gives the name and the int value. - * @return string The error name. - */ - function errorName($p_with_code=false) - { - $v_const_list = get_defined_constants(); - - // ----- Extract error constants from all const. - for (reset($v_const_list); - list($v_key, $v_value) = each($v_const_list);) { - if (substr($v_key, 0, strlen('ARCHIVE_ZIP_ERR_')) - =='ARCHIVE_ZIP_ERR_') { - $v_error_list[$v_key] = $v_value; - } - } - - // ----- Search the name form the code value - $v_key=array_search($this->_error_code, $v_error_list, true); - if ($v_key!=false) { - $v_value = $v_key; - } - else { - $v_value = 'NoName'; - } - - if ($p_with_code) { - return($v_value.' ('.$this->_error_code.')'); - } - else { - return($v_value); - } - } - // }}} - - // {{{ errorInfo() - /** - * This method returns the description associated with the latest error. - * - * @access public - * @param boolean $p_full If set to true gives the description with the - * error code, the name and the description. - * If set to false gives only the description - * and the error code. - * @return string The error description. - */ - function errorInfo($p_full=false) - { - if ($p_full) { - return($this->errorName(true)." : ".$this->_error_string); - } - else { - return($this->_error_string." [code ".$this->_error_code."]"); - } - } - // }}} - - -// ----------------------------------------------------------------------------- -// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** -// ***** ***** -// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** -// ----------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _checkFormat() - // Description : - // This method check that the archive exists and is a valid zip archive. - // Several level of check exists. (futur) - // Parameters : - // $p_level : Level of check. Default 0. - // 0 : Check the first bytes (magic codes) (default value)) - // 1 : 0 + Check the central directory (futur) - // 2 : 1 + Check each file header (futur) - // Return Values : - // true on success, - // false on error, the error code is set. - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_checkFormat() - * - * { Description } - * - * @param integer $p_level - */ - function _checkFormat($p_level=0) - { - $v_result = true; - - // ----- Reset the error handler - $this->_errorReset(); - - // ----- Look if the file exits - if (!is_file($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "Missing archive file '".$this->_zipname."'"); - return(false); - } - - // ----- Check that the file is readeable - if (!is_readable($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - "Unable to read archive '".$this->_zipname."'"); - return(false); - } - - // ----- Check the magic code - // TBC - - // ----- Check the central header - // TBC - - // ----- Check each file header - // TBC - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _create() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_create() - * - * { Description } - * - */ - function _create($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Open the file in write mode - if (($v_result = $this->_openFd('wb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Add the list of files - $v_result = $this->_addList($p_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Close - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _add() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_add() - * - * { Description } - * - */ - function _add($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Look if the archive exists or is empty and need to be created - if ((!is_file($this->_zipname)) || (filesize($this->_zipname) == 0)) { - $v_result = $this->_create($p_list, $p_result_list, $p_params); - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to - // use the following methods on the temporary fil and not the real archive - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) - { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $i_writeCentralFileHeader($v_header_list[$i]))!=1) { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count - +$v_central_dir['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _openFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_openFd() - * - * { Description } - * - */ - function _openFd($p_mode) - { - $v_result=1; - - // ----- Look if already open - if ($this->_zip_fd != 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Zip file \''.$this->_zipname.'\' already open'); - return Archive_Zip::errorCode(); - } - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, $p_mode)) == 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in '.$p_mode.' mode'); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _closeFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_closeFd() - * - * { Description } - * - */ - function _closeFd() - { - $v_result=1; - - if ($this->_zip_fd != 0) - @fclose($this->_zip_fd); - $this->_zip_fd = 0; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to have PclTar - // running in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addList() - * - * { Description } - * - */ - function _addList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) { - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Create the Central Dir files header - for ($i=0,$v_count=0; $i_writeCentralFileHeader($v_header_list[$i])) != 1) { - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count, $v_size, $v_offset, - $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFileList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to - // run the lib in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFileList() - * - * { Description } - * - */ - function _addFileList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, - &$p_params) - { - $v_result=1; - $v_header = array(); - - // ----- Recuperate the current number of elt in list - $v_nb = sizeof($p_result_list); - - // ----- Loop on the files - for ($j=0; ($j_tool_TranslateWinPath($p_list[$j], false); - - // ----- Skip empty file names - if ($p_filename == "") - { - continue; - } - - // ----- Check the filename - if (!file_exists($p_filename)) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "File '$p_filename' does not exists"); - return Archive_Zip::errorCode(); - } - - // ----- Look if it is a file or a dir with no all pathnre move - if ((is_file($p_filename)) || ((is_dir($p_filename)) && !$p_remove_all_dir)) { - // ----- Add the file - if (($v_result = $this->_addFile($p_filename, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Look for directory - if (is_dir($p_filename)) - { - - // ----- Look for path - if ($p_filename != ".") - $v_path = $p_filename."/"; - else - $v_path = ""; - - // ----- Read the directory for files and sub-directories - $p_hdir = opendir($p_filename); - $p_hitem = readdir($p_hdir); // '.' directory - $p_hitem = readdir($p_hdir); // '..' directory - while ($p_hitem = readdir($p_hdir)) - { - - // ----- Look for a file - if (is_file($v_path.$p_hitem)) - { - - // ----- Add the file - if (($v_result = $this->_addFile($v_path.$p_hitem, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Recursive call to _addFileList() - else - { - - // ----- Need an array as parameter - $p_temp_list[0] = $v_path.$p_hitem; - $v_result = $this->_addFileList($p_temp_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Update the number of elements of the list - $v_nb = sizeof($p_result_list); - } - } - - // ----- Free memory for the recursive loop - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFile() - * - * { Description } - * - */ - function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - if ($p_filename == "") - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") - { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) - { - if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) - $p_remove_dir = "./".$p_remove_dir; - if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) - $p_remove_dir = substr($p_remove_dir, 2); - } - - $v_compare = $this->_tool_PathInclusion($p_remove_dir, $p_filename); - if ($v_compare > 0) -// if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) - { - - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - } - } - // ----- Look for path to add - if ($p_add_dir != "") - { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } - - // ----- Filename (reduce the path of stored name) - $v_stored_filename = $this->_tool_PathReduction($v_stored_filename); - - - /* filename length moved after call-back in release 1.3 - // ----- Check the path length - if (strlen($v_stored_filename) > 0xFF) - { - // ----- Error log - $this->_errorLog(-5, "Stored file name is too long (max. 255) : '$v_stored_filename'"); - - // ----- Return - return Archive_Zip::errorCode(); - } - */ - - // ----- Set the file properties - clearstatcache(); - $p_header['version'] = 20; - $p_header['version_extracted'] = 10; - $p_header['flag'] = 0; - $p_header['compression'] = 0; - $p_header['mtime'] = filemtime($p_filename); - $p_header['crc'] = 0; - $p_header['compressed_size'] = 0; - $p_header['size'] = filesize($p_filename); - $p_header['filename_len'] = strlen($p_filename); - $p_header['extra_len'] = 0; - $p_header['comment_len'] = 0; - $p_header['disk'] = 0; - $p_header['internal'] = 0; - $p_header['external'] = (is_file($p_filename)?0xFE49FFE0:0x41FF0010); - $p_header['offset'] = 0; - $p_header['filename'] = $p_filename; - $p_header['stored_filename'] = $v_stored_filename; - $p_header['extra'] = ''; - $p_header['comment'] = ''; - $p_header['status'] = 'ok'; - $p_header['index'] = -1; - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_ADD].'(ARCHIVE_ZIP_PARAM_PRE_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_header['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { - $p_header['stored_filename'] = $this->_tool_PathReduction($v_local_header['stored_filename']); - } - } - - // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; - } - - // ----- Check the path length - if (strlen($p_header['stored_filename']) > 0xFF) { - $p_header['status'] = 'filename_too_long'; - } - - // ----- Look if no error, or file not skipped - if ($p_header['status'] == 'ok') { - - // ----- Look for a file - if (is_file($p_filename)) - { - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return Archive_Zip::errorCode(); - } - - if ($p_params['no_compression']) { - // ----- Read the file content - $v_content_compressed = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content_compressed); - } - else { - // ----- Read the file content - $v_content = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content); - - // ----- Compress the file - $v_content_compressed = gzdeflate($v_content); - } - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content_compressed); - $p_header['compression'] = 8; - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } - - // ----- Write the compressed content - $v_binary_data = pack('a'.$p_header['compressed_size'], $v_content_compressed); - @fwrite($this->_zip_fd, $v_binary_data, $p_header['compressed_size']); - - // ----- Close the file - @fclose($v_file); - } - - // ----- Look for a directory - else - { - // ----- Set the file properties - $p_header['filename'] .= '/'; - $p_header['filename_len']++; - $p_header['size'] = 0; - $p_header['external'] = 0x41FF0010; // Value for a folder : to be checked - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) - { - return $v_result; - } - } - } - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_ADD].'(ARCHIVE_ZIP_PARAM_POST_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Ignored - $v_result = 1; - } - - // ----- Update the informations - // Nothing can be modified - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeFileHeader() - * - * { Description } - * - */ - function _writeFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Store the offset position of the file - $p_header['offset'] = ftell($this->_zip_fd); - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len']); - - // ----- Write the first 148 bytes of the header in the archive - fputs($this->_zip_fd, $v_binary_data, 30); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralFileHeader() - * - * { Description } - * - */ - function _writeCentralFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); - - // ----- Write the 42 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 46); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - if ($p_header['comment_len'] != 0) - { - fputs($this->_zip_fd, $p_header['comment'], $p_header['comment_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralHeader() - * - * { Description } - * - */ - function _writeCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) - { - $v_result=1; - - // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); - - // ----- Write the 22 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 22); - - // ----- Write the variable fields - if (strlen($p_comment) != 0) - { - fputs($this->_zip_fd, $p_comment, strlen($p_comment)); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _list() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_list() - * - * { Description } - * - */ - function _list(&$p_list) - { - $v_result=1; - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->_zipname.'\' in binary read mode'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - return $v_result; - } - - // ----- Go to beginning of Central Dir - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_central_dir['offset'])) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) - { - // ----- Read the file header - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) - { - return $v_result; - } - $v_header['index'] = $i; - - // ----- Get the only interesting attributes - $this->_convertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _convertHeader2FileInfo() - // Description : - // This function takes the file informations from the central directory - // entries and extract the interesting parameters that will be given back. - // The resulting file infos are set in the array $p_info - // $p_info['filename'] : Filename with full path. Given by user (add), - // extracted in the filesystem (extract). - // $p_info['stored_filename'] : Stored filename in the archive. - // $p_info['size'] = Size of the file. - // $p_info['compressed_size'] = Compressed size of the file. - // $p_info['mtime'] = Last modification date of the file. - // $p_info['comment'] = Comment associated with the file. - // $p_info['folder'] = true/false : indicates if the entry is a folder or not. - // $p_info['status'] = status of the action on the file. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_convertHeader2FileInfo() - * - * { Description } - * - */ - function _convertHeader2FileInfo($p_header, &$p_info) - { - $v_result=1; - - // ----- Get the interesting attributes - $p_info['filename'] = $p_header['filename']; - $p_info['stored_filename'] = $p_header['stored_filename']; - $p_info['size'] = $p_header['size']; - $p_info['compressed_size'] = $p_header['compressed_size']; - $p_info['mtime'] = $p_header['mtime']; - $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); - $p_info['index'] = $p_header['index']; - $p_info['status'] = $p_header['status']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractByRule() - // Description : - // Extract a file or directory depending of rules (by index, by name, ...) - // Parameters : - // $p_file_list : An array where will be placed the properties of each - // extracted file - // $p_path : Path to add while writing the extracted files - // $p_remove_path : Path to remove (from the file memorized path) while writing the - // extracted files. If the path does not match the file path, - // the file is extracted with its memorized path. - // $p_remove_path does not apply to 'list' mode. - // $p_path and $p_remove_path are commulative. - // Return Values : - // 1 on success,0 or less on error (see error code list) - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractByRule() - * - * { Description } - * - */ - function _extractByRule(&$p_file_list, &$p_params) - { - $v_result=1; - - $p_path = $p_params['add_path']; - $p_remove_path = $p_params['remove_path']; - $p_remove_all_path = $p_params['remove_all_path']; - - // ----- Check the path - if (($p_path == "") - || ((substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - - // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) { - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } - } - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); - - // ----- Open the zip file - if (($v_result = $this->_openFd('rb')) != 1) - { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - - // ----- Read each entry - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - // ----- Read next Central dir entry - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) { - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->_zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_extract = true; - } - } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_extract = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } - - - // ----- Look for real extraction - if ($v_extract) - { - - // ----- Go to the file position - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_header['offset'])) - { - // ----- Close the zip file - $this->_closeFd(); - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Look for extraction as string - if ($p_params[ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING]) { - - // ----- Extracting the file - if (($v_result = $this->_extractFileAsString($v_header, $v_string)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; - - // ----- Next extracted file - $v_nb_extracted++; - } - else { - // ----- Extracting the file - if (($v_result = $this->_extractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_params)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - } - } - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFile() - * - * { Description } - * - */ - function _extractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_params) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Look for all path to remove - if ($p_remove_all_path == true) { - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); - } - - // ----- Look for path to remove - else if ($p_remove_path != "") - { - //if (strcmp($p_remove_path, $p_entry['filename'])==0) - if ($this->_tool_PathInclusion($p_remove_path, $p_entry['filename']) == 2) - { - - // ----- Change the file status - $p_entry['status'] = "filtered"; - - // ----- Return - return $v_result; - } - - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { - - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - - } - } - - // ----- Add the path - if ($p_path != '') - { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; - } - - // ----- Look for pre-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT].'(ARCHIVE_ZIP_PARAM_PRE_EXTRACT, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - // ----- Trace - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Look for specific actions while the file exist - if (file_exists($p_entry['filename'])) - { - - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Return - //return $v_result; - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "write_protected"; - - // ----- Return - //return $v_result; - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - - // ----- Change the file status - $p_entry['status'] = "newer_exist"; - - // ----- Return - //return $v_result; - } - } - - // ----- Check the directory availability and create it if necessary - else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->_dirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; - - // ----- Return - //return $v_result; - $v_result = 1; - } - } - } - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - // ----- Return - return $v_result; - } - - - // ----- Read the file by ARCHIVE_ZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Closing the destination file - fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - else - { - // ----- Trace - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - return $v_result; - } - - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); - - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); - - // ----- Closing the destination file - @fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - - // ----- Look for chmod option - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD])) - && ($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD] != 0)) { - - // ----- Change the mode of the file - chmod($p_entry['filename'], $p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD]); - } - - } - } - - // ----- Look for post-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT].'(ARCHIVE_ZIP_PARAM_POST_EXTRACT, $v_local_header);'); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFileAsString() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFileAsString() - * - * { Description } - * - */ - function _extractFileAsString(&$p_entry, &$p_string) - { - $v_result=1; - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Trace - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - // ----- Trace - - // ----- Reading the file - $p_string = fread($this->_zip_fd, $p_entry['compressed_size']); - } - else - { - // ----- Trace - - // ----- Reading the file - $v_data = fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $p_string = gzinflate($v_data); - } - - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readFileHeader() - * - * { Description } - * - */ - function _readFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x04034b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 26); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 26) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - - // ----- Get filename - $p_header['filename'] = fread($this->_zip_fd, $v_data['filename_len']); - - // ----- Get extra_fields - if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->_zip_fd, $v_data['extra_len']); - } - else { - $p_header['extra'] = ''; - } - - // ----- Extract properties - $p_header['compression'] = $v_data['compression']; - $p_header['size'] = $v_data['size']; - $p_header['compressed_size'] = $v_data['compressed_size']; - $p_header['crc'] = $v_data['crc']; - $p_header['flag'] = $v_data['flag']; - - // ----- Recuperate date in UNIX format - $p_header['mdate'] = $v_data['mdate']; - $p_header['mtime'] = $v_data['mtime']; - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Other informations - - // TBC - //for(reset($v_data); $key = key($v_data); next($v_data)) { - //} - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set the status field - $p_header['status'] = "ok"; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readCentralFileHeader() - * - * { Description } - * - */ - function _readCentralFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x02014b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 42); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 42) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - - // ----- Get filename - if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->_zip_fd, $p_header['filename_len']); - else - $p_header['filename'] = ''; - - // ----- Get extra - if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->_zip_fd, $p_header['extra_len']); - else - $p_header['extra'] = ''; - - // ----- Get comment - if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->_zip_fd, $p_header['comment_len']); - else - $p_header['comment'] = ''; - - // ----- Extract properties - - // ----- Recuperate date in UNIX format - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set default status to ok - $p_header['status'] = 'ok'; - - // ----- Look if it is a directory - if (substr($p_header['filename'], -1) == '/') - { - $p_header['external'] = 0x41FF0010; - } - - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readEndCentralDir() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readEndCentralDir() - * - * { Description } - * - */ - function _readEndCentralDir(&$p_central_dir) - { - $v_result=1; - - // ----- Go to the end of the zip file - $v_size = filesize($this->_zipname); - @fseek($this->_zip_fd, $v_size); - if (@ftell($this->_zip_fd) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to go to the end of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- First try : look if this is an archive with no commentaries - // (most of the time) - // in this case the end of central dir is at 22 bytes of the file end - $v_found = 0; - if ($v_size > 26) { - @fseek($this->_zip_fd, $v_size-22); - if (($v_pos = @ftell($this->_zip_fd)) != ($v_size-22)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read for bytes - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } - - $v_pos = ftell($this->_zip_fd); - } - - // ----- Go back to the maximum possible size of the Central Dir End Record - if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->_zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->_zip_fd) != ($v_size-$v_maximum_size)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->_zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) { - // ----- Read a byte - $v_byte = @fread($this->_zip_fd, 1); - - // ----- Add the byte - $v_bytes = ($v_bytes << 8) | Ord($v_byte); - - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) { - $v_pos++; - break; - } - - $v_pos++; - } - - // ----- Look if not found end of central dir - if ($v_pos == $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Unable to find End of Central Dir Record signature"); - return Archive_Zip::errorCode(); - } - } - - // ----- Read the first 18 bytes of the header - $v_binary_data = fread($this->_zip_fd, 18); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 18) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Invalid End of Central Dir Record size : " - .strlen($v_binary_data)); - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - - // ----- Check the global size - if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Fail to find the right signature"); - return Archive_Zip::errorCode(); - } - - // ----- Get comment - if ($v_data['comment_size'] != 0) - $p_central_dir['comment'] = fread($this->_zip_fd, $v_data['comment_size']); - else - $p_central_dir['comment'] = ''; - - $p_central_dir['entries'] = $v_data['entries']; - $p_central_dir['disk_entries'] = $v_data['disk_entries']; - $p_central_dir['offset'] = $v_data['offset']; - $p_central_dir['size'] = $v_data['size']; - $p_central_dir['disk'] = $v_data['disk']; - $p_central_dir['disk_start'] = $v_data['disk_start']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _deleteByRule() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_deleteByRule() - * - * { Description } - * - */ - function _deleteByRule(&$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Scan all the files - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - // ----- Clean - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - $v_header_list = array(); - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - $v_result - = $this->_readCentralFileHeader($v_header_list[$v_nb_extracted]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] - == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; - ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) - && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for deletion - if ($v_found) { - unset($v_header_list[$v_nb_extracted]); - } - else { - $v_nb_extracted++; - } - } - - // ----- Look if something need to be deleted - if ($v_nb_extracted > 0) { - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-') - .'.tmp'; - - // ----- Creates a temporary zip archive - $v_temp_zip = new Archive_Zip($v_zip_temp_name); - - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->_openFd('wb')) != 1) { - $this->_closeFd(); - - // ----- Return - return $v_result; - } - - // ----- Look which file need to be kept - for ($i=0; $i_zip_fd); - if (@fseek($this->_zip_fd, $v_header_list[$i]['offset'])) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header_list[$i])) != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Write the file header - $v_result = $v_temp_zip->_writeFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Read/write the data block - $v_result = $this->_tool_CopyBlock($this->_zip_fd, - $v_temp_zip->_zip_fd, - $v_header_list[$i]['compressed_size']); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->_zip_fd); - - // ----- Re-Create the Central Dir files header - for ($i=0; $i_writeCentralFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Transform the header to a 'usable' info - $v_temp_zip->_convertHeader2FileInfo($v_header_list[$i], - $p_result_list[$i]); - } - - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - $v_result = $v_temp_zip->_writeCentralHeader(sizeof($v_header_list), - $v_size, $v_offset, - $v_comment); - if ($v_result != 1) { - // ----- Clean - unset($v_header_list); - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Close - $v_temp_zip->_closeFd(); - $this->_closeFd(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Destroy the temporary archive - unset($v_temp_zip); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _dirCheck() - // Description : - // Check if a directory exists, if not it creates it and all the parents directory - // which may be useful. - // Parameters : - // $p_dir : Directory path to check. - // Return Values : - // 1 : OK - // -1 : Unable to create directory - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_dirCheck() - * - * { Description } - * - * @param [type] $p_is_dir - */ - function _dirCheck($p_dir, $p_is_dir=false) - { - $v_result = 1; - - // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); - } - - // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) { - return 1; - } - - // ----- Extract parent directory - $p_parent_dir = dirname($p_dir); - - // ----- Just a check - if ($p_parent_dir != $p_dir) { - // ----- Look for parent directory - if ($p_parent_dir != "") { - if (($v_result = $this->_dirCheck($p_parent_dir)) != 1) { - return $v_result; - } - } - } - - // ----- Create the directory - if (!@mkdir($p_dir, 0777)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL, - "Unable to create directory '$p_dir'"); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _merge() - // Description : - // If $p_archive_to_add does not exist, the function exit with a success result. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_merge() - * - * { Description } - * - */ - function _merge(&$p_archive_to_add) - { - $v_result=1; - - // ----- Look if the archive_to_add exists - if (!is_file($p_archive_to_add->_zipname)) { - // ----- Nothing to merge, so merge is a success - return 1; - } - - // ----- Look if the archive exists - if (!is_file($this->_zipname)) { - // ----- Do a duplicate - $v_result = $this->_duplicate($p_archive_to_add->_zipname); - - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->_openFd('rb')) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir_to_add = array(); - $v_result = $p_archive_to_add->_readEndCentralDir($v_central_dir_to_add); - if ($v_result != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($p_archive_to_add->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the files from the archive_to_add into the temporary file - $v_size = $v_central_dir_to_add['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_zip_temp_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the block of file headers from the archive_to_add - $v_size = $v_central_dir_to_add['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Zip file comment - // TBC : I should merge the two comments - $v_comment = ''; - - // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive fd - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_central_dir['entries'] - +$v_central_dir_to_add['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - @fclose($v_zip_temp_fd); - $this->_zip_fd = null; - - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _duplicate() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_duplicate() - * - * { Description } - * - */ - function _duplicate($p_archive_filename) - { - $v_result=1; - - // ----- Look if the $p_archive_filename exists - if (!is_file($p_archive_filename)) { - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('wb')) != 1) { - // ----- Return - return $v_result; - } - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { - $this->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive file \'' - .$p_archive_filename.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = filesize($p_archive_filename); - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - return $v_result; - } - // --------------------------------------------------------------------------- - - /** - * Archive_Zip::_check_parameters() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _check_parameters(&$p_params, $p_default) - { - - // ----- Check that param is an array - if (!is_array($p_params)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter, waiting for an array'); - return Archive_Zip::errorCode(); - } - - // ----- Check that all the params are valid - for (reset($p_params); list($v_key, $v_value) = each($p_params); ) { - if (!isset($p_default[$v_key])) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter with key \''.$v_key.'\''); - - return Archive_Zip::errorCode(); - } - } - - // ----- Set the default values - for (reset($p_default); list($v_key, $v_value) = each($p_default); ) { - if (!isset($p_params[$v_key])) { - $p_params[$v_key] = $p_default[$v_key]; - } - } - - // ----- Check specific parameters - $v_callback_list = array ('callback_pre_add','callback_post_add', - 'callback_pre_extract','callback_post_extract'); - for ($i=0; $i_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE, - "Callback '".$p_params[$v_key] - ."()' is not an existing function for " - ."parameter '".$v_key."'"); - return Archive_Zip::errorCode(); - } - } - } - - return(1); - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorLog() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorLog() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _errorLog($p_error_code=0, $p_error_string='') - { - $this->_error_code = $p_error_code; - $this->_error_string = $p_error_string; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorReset() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorReset() - * - * { Description } - * - */ - function _errorReset() - { - $this->_error_code = 1; - $this->_error_string = ''; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathReduction() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_PathReduction() - * - * { Description } - * - */ - function _tool_PathReduction($p_dir) - { - $v_result = ""; - - // ----- Look for not empty path - if ($p_dir != "") - { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); - - // ----- Study directories from last to first - for ($i=sizeof($v_list)-1; $i>=0; $i--) - { - // ----- Look for current path - if ($v_list[$i] == ".") - { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") - { - // ----- Ignore it and ignore the $i-1 - $i--; - } - else if (($v_list[$i] == "") && ($i!=(sizeof($v_list)-1)) && ($i!=0)) - { - // ----- Ignore only the double '//' in path, - // but not the first and last '/' - } - else - { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); - } - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathInclusion() - // Description : - // This function indicates if the path $p_path is under the $p_dir tree. Or, - // said in an other way, if the file or sub-dir $p_path is inside the dir - // $p_dir. - // The function indicates also if the path is exactly the same as the dir. - // This function supports path with duplicated '/' like '//', but does not - // support '.' or '..' statements. - // Parameters : - // Return Values : - // 0 if $p_path is not inside directory $p_dir - // 1 if $p_path is inside directory $p_dir - // 2 if $p_path is exactly the same as $p_dir - // --------------------------------------------------------------------------- - /** - * _tool_PathInclusion() - * - * { Description } - * - */ - function _tool_PathInclusion($p_dir, $p_path) - { - $v_result = 1; - - // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); - $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); - $v_list_path_size = sizeof($v_list_path); - - // ----- Study directories paths - $i = 0; - $j = 0; - while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } - - // ----- Compare the items - if ( ($v_list_dir[$i] != $v_list_path[$j]) - && ($v_list_dir[$i] != '') - && ( $v_list_path[$j] != '')) { - $v_result = 0; - } - - // ----- Next items - $i++; - $j++; - } - - // ----- Look if everything seems to be the same - if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_CopyBlock() - // Description : - // Parameters : - // $p_mode : read/write compression mode - // 0 : src & dest normal - // 1 : src gzip, dest normal - // 2 : src normal, dest gzip - // 3 : src & dest gzip - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_CopyBlock() - * - * { Description } - * - * @param integer $p_mode - */ - function _tool_CopyBlock($p_src, $p_dest, $p_size, $p_mode=0) - { - $v_result = 1; - - if ($p_mode==0) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==1) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==2) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==3) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_Rename() - // Description : - // This function tries to do a simple rename() function. If it fails, it - // tries to copy the $p_src file in a new $p_dest file and then unlink the - // first one. - // Parameters : - // $p_src : Old filename - // $p_dest : New filename - // Return Values : - // 1 on success, 0 on failure. - // --------------------------------------------------------------------------- - /** - * _tool_Rename() - * - * { Description } - * - */ - function _tool_Rename($p_src, $p_dest) - { - $v_result = 1; - - // ----- Try to rename the files - if (!@rename($p_src, $p_dest)) { - - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_TranslateWinPath() - // Description : - // Translate windows path by replacing '\' by '/' and optionally removing - // drive letter. - // Parameters : - // $p_path : path to translate. - // $p_remove_disk_letter : true | false - // Return Values : - // The path translated. - // --------------------------------------------------------------------------- - /** - * _tool_TranslateWinPath() - * - * { Description } - * - * @param [type] $p_remove_disk_letter - */ - function _tool_TranslateWinPath($p_path, $p_remove_disk_letter=true) - { - if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if ( ($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } - // --------------------------------------------------------------------------- - - public function encryptCrc32($string) - { - if (!class_exists('G')) { - $realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] ); - $docuroot = explode( '/', $realdocuroot ); - array_pop( $docuroot ); - $pathhome = implode( '/', $docuroot ) . '/'; - array_pop( $docuroot ); - $pathTrunk = implode( '/', $docuroot ) . '/'; - require_once($pathTrunk.'gulliver/system/class.g.php'); - } - return G::encryptCrc32($string); - } - - } - // End of class - -?> diff --git a/thirdparty/pear/class.nusoap_base.php b/thirdparty/pear/class.nusoap_base.php deleted file mode 100644 index 8e8e88e9c..000000000 --- a/thirdparty/pear/class.nusoap_base.php +++ /dev/null @@ -1,905 +0,0 @@ -globalDebugLevel = 9; - -/** -* -* nusoap_base -* -* @author Dietrich Ayala -* @version $Id: class.nusoap_base.php,v 1.43 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class nusoap_base { - /** - * Identification for HTTP headers. - * - * @var string - * @access private - */ - var $title = 'NuSOAP'; - /** - * Version for HTTP headers. - * - * @var string - * @access private - */ - var $version = '0.7.2'; - /** - * CVS revision for HTTP headers. - * - * @var string - * @access private - */ - var $revision = '$Revision: 1.43 $'; - /** - * Current error string (manipulated by getError/setError) - * - * @var string - * @access private - */ - var $error_str = ''; - /** - * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) - * - * @var string - * @access private - */ - var $debug_str = ''; - /** - * toggles automatic encoding of special characters as entities - * (should always be true, I think) - * - * @var boolean - * @access private - */ - var $charencoding = true; - /** - * the debug level for this instance - * - * @var integer - * @access private - */ - var $debugLevel; - - /** - * set schema version - * - * @var string - * @access public - */ - var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; - - /** - * charset encoding for outgoing messages - * - * @var string - * @access public - */ - var $soap_defencoding = 'ISO-8859-1'; - //var $soap_defencoding = 'UTF-8'; - - /** - * namespaces in an array of prefix => uri - * - * this is "seeded" by a set of constants, but it may be altered by code - * - * @var array - * @access public - */ - var $namespaces = array( - 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', - 'xsd' => 'http://www.w3.org/2001/XMLSchema', - 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' - ); - - /** - * namespaces used in the current context, e.g. during serialization - * - * @var array - * @access private - */ - var $usedNamespaces = array(); - - /** - * XML Schema types in an array of uri => (array of xml type => php type) - * is this legacy yet? - * no, this is used by the xmlschema class to verify type => namespace mappings. - * @var array - * @access public - */ - var $typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', - 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', - 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', - // abstract "any" types - 'anyType'=>'string','anySimpleType'=>'string', - // derived datatypes - 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', - 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', - 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', - 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), - 'http://www.w3.org/2000/10/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), - 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), - 'http://xml.apache.org/xml-soap' => array('Map') - ); - - /** - * XML entities to convert - * - * @var array - * @access public - * @deprecated - * @see expandEntities - */ - var $xmlEntities = array('quot' => '"','amp' => '&', - 'lt' => '<','gt' => '>','apos' => "'"); - - /** - * constructor - * - * @access public - */ - function nusoap_base() { - $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * gets the global debug level, which applies to future instances - * - * @return integer Debug level 0-9, where 0 turns off - * @access public - */ - function getGlobalDebugLevel() { - return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * sets the global debug level, which applies to future instances - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setGlobalDebugLevel($level) { - $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level; - } - - /** - * gets the debug level for this instance - * - * @return int Debug level 0-9, where 0 turns off - * @access public - */ - function getDebugLevel() { - return $this->debugLevel; - } - - /** - * sets the debug level for this instance - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setDebugLevel($level) { - $this->debugLevel = $level; - } - - /** - * adds debug data to the instance debug string with formatting - * - * @param string $string debug data - * @access private - */ - function debug($string){ - if ($this->debugLevel > 0) { - $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); - } - } - - /** - * adds debug data to the instance debug string without formatting - * - * @param string $string debug data - * @access public - */ - function appendDebug($string){ - if ($this->debugLevel > 0) { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str .= $string; - } - } - - /** - * clears the current debug data for this instance - * - * @access public - */ - function clearDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str = ''; - } - - /** - * gets the current debug data for this instance - * - * @return debug data - * @access public - */ - function &getDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - return $this->debug_str; - } - - /** - * gets the current debug data for this instance as an XML comment - * this may change the contents of the debug data - * - * @return debug data as an XML comment - * @access public - */ - function &getDebugAsXMLComment() { - // it would be nice to use a memory stream here to use - // memory more efficiently - while (strpos($this->debug_str, '--')) { - $this->debug_str = str_replace('--', '- -', $this->debug_str); - } - return ""; - } - - /** - * expands entities, e.g. changes '<' to '<'. - * - * @param string $val The string in which to expand entities. - * @access private - */ - function expandEntities($val) { - if ($this->charencoding) { - $val = str_replace('&', '&', $val); - $val = str_replace("'", ''', $val); - $val = str_replace('"', '"', $val); - $val = str_replace('<', '<', $val); - $val = str_replace('>', '>', $val); - } - return $val; - } - - /** - * returns error string if present - * - * @return mixed error string or false - * @access public - */ - function getError(){ - if($this->error_str != ''){ - return $this->error_str; - } - return false; - } - - /** - * sets error string - * - * @return boolean $string error string - * @access private - */ - function setError($str){ - $this->error_str = $str; - } - - /** - * detect if array is a simple array or a struct (associative array) - * - * @param mixed $val The PHP array - * @return string (arraySimple|arrayStruct) - * @access private - */ - function isArraySimpleOrStruct($val) { - $keyList = array_keys($val); - foreach ($keyList as $keyListValue) { - if (!is_int($keyListValue)) { - return 'arrayStruct'; - } - } - return 'arraySimple'; - } - - /** - * serializes PHP values in accordance w/ section 5. Type information is - * not serialized if $use == 'literal'. - * - * @param mixed $val The value to serialize - * @param string $name The name (local part) of the XML element - * @param string $type The XML schema type (local part) for the element - * @param string $name_ns The namespace for the name of the XML element - * @param string $type_ns The namespace for the type of the element - * @param array $attributes The attributes to serialize as name=>value pairs - * @param string $use The WSDL "use" (encoded|literal) - * @return string The serialized element, possibly with child elements - * @access public - */ - function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){ - $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use"); - $this->appendDebug('value=' . $this->varDump($val)); - $this->appendDebug('attributes=' . $this->varDump($attributes)); - - if(is_object($val) && get_class($val) == 'soapval'){ - return $val->serialize($use); - } - // force valid name if necessary - if (is_numeric($name)) { - $name = '__numeric_' . $name; - } elseif (! $name) { - $name = 'noname'; - } - // if name has ns, add ns prefix to name - $xmlns = ''; - if($name_ns){ - $prefix = 'nu'.rand(1000,9999); - $name = $prefix.':'.$name; - $xmlns .= " xmlns:$prefix=\"$name_ns\""; - } - // if type is prefixed, create type prefix - if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ - // need to fix this. shouldn't default to xsd if no ns specified - // w/o checking against typemap - $type_prefix = 'xsd'; - } elseif($type_ns){ - $type_prefix = 'ns'.rand(1000,9999); - $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; - } - // serialize attributes if present - $atts = ''; - if($attributes){ - foreach($attributes as $k => $v){ - $atts .= " $k=\"".$this->expandEntities($v).'"'; - } - } - // serialize null value - if (is_null($val)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - return "<$name$xmlns $atts/>"; - } else { - if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; - } - } - // serialize if an xsd built-in primitive type - if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ - if (is_bool($val)) { - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - } else if (is_string($val)) { - $val = $this->expandEntities($val); - } - if ($use == 'literal') { - return "<$name$xmlns $atts>$val"; - } else { - return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val"; - } - } - // detect type and serialize - $xml = ''; - switch(true) { - case (is_bool($val) || $type == 'boolean'): - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; - } - break; - case (is_int($val) || is_long($val) || $type == 'int'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; - } - break; - case (is_float($val)|| is_double($val) || $type == 'float'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; - } - break; - case (is_string($val) || $type == 'string'): - $val = $this->expandEntities($val); - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; - } - break; - case is_object($val): - if (! $name) { - $name = get_class($val); - $this->debug("In serialize_val, used class name $name as element name"); - } else { - $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); - } - foreach(get_object_vars($val) as $k => $v){ - $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); - } - $xml .= '<'.$name.'>'.$pXml.''; - break; - break; - case (is_array($val) || $type): - // detect if struct or array - $valueType = $this->isArraySimpleOrStruct($val); - if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){ - $i = 0; - if(is_array($val) && count($val)> 0){ - foreach($val as $v){ - if(is_object($v) && get_class($v) == 'soapval'){ - $tt_ns = $v->type_ns; - $tt = $v->type; - } elseif (is_array($v)) { - $tt = $this->isArraySimpleOrStruct($v); - } else { - $tt = gettype($v); - } - $array_types[$tt] = 1; - // TODO: for literal, the name should be $name - $xml .= $this->serialize_val($v,'item',false,false,false,false,$use); - ++$i; - } - if(count($array_types) > 1){ - $array_typename = 'xsd:anyType'; - } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { - if ($tt == 'integer') { - $tt = 'int'; - } - $array_typename = 'xsd:'.$tt; - } elseif(isset($tt) && $tt == 'arraySimple'){ - $array_typename = 'SOAP-ENC:Array'; - } elseif(isset($tt) && $tt == 'arrayStruct'){ - $array_typename = 'unnamed_struct_use_soapval'; - } else { - // if type is prefixed, create type prefix - if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ - $array_typename = 'xsd:' . $tt; - } elseif ($tt_ns) { - $tt_prefix = 'ns' . rand(1000, 9999); - $array_typename = "$tt_prefix:$tt"; - $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; - } else { - $array_typename = $tt; - } - } - $array_type = $i; - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; - } - // empty array - } else { - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; - } - } - // TODO: for array in literal, there is no wrapper here - $xml = "<$name$xmlns$type_str$atts>".$xml.""; - } else { - // got a struct - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>"; - } else { - $xml .= "<$name$xmlns$type_str$atts>"; - } - foreach($val as $k => $v){ - // Apache Map - if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { - $xml .= ''; - $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); - $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); - $xml .= ''; - } else { - $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - $xml .= ""; - } - break; - default: - $xml .= 'not detected, got '.gettype($val).' for '.$val; - break; - } - return $xml; - } - - /** - * serializes a message - * - * @param string $body the XML of the SOAP body - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param array $namespaces optional the namespaces used in generating the body and headers - * @param string $style optional (rpc|document) - * @param string $use optional (encoded|literal) - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @return string the message - * @access public - */ - function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ - // TODO: add an option to automatically run utf8_encode on $body and $headers - // if $this->soap_defencoding is UTF-8. Not doing this automatically allows - // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 - - $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); - $this->debug("headers:"); - $this->appendDebug($this->varDump($headers)); - $this->debug("namespaces:"); - $this->appendDebug($this->varDump($namespaces)); - - // serialize namespaces - $ns_string = ''; - foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ - $ns_string .= " xmlns:$k=\"$v\""; - } - if($encodingStyle) { - $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; - } - - // serialize headers - if($headers){ - if (is_array($headers)) { - $xml = ''; - foreach ($headers as $header) { - $xml .= $this->serialize_val($header, false, false, false, false, false, $use); - } - $headers = $xml; - $this->debug("In serializeEnvelope, serialzied array of headers to $headers"); - } - $headers = "".$headers.""; - } - // serialize envelope - return - 'soap_defencoding .'"?'.">". - '". - $headers. - "". - $body. - "". - ""; - } - - /** - * formats a string to be inserted into an HTML stream - * - * @param string $str The string to format - * @return string The formatted string - * @access public - * @deprecated - */ - function formatDump($str){ - $str = htmlspecialchars($str); - return nl2br($str); - } - - /** - * contracts (changes namespace to prefix) a qualified name - * - * @param string $qname qname - * @return string contracted qname - * @access private - */ - function contractQname($qname){ - // get element namespace - //$this->xdebug("Contract $qname"); - if (strrpos($qname, ':')) { - // get unqualified name - $name = substr($qname, strrpos($qname, ':') + 1); - // get ns - $ns = substr($qname, 0, strrpos($qname, ':')); - $p = $this->getPrefixFromNamespace($ns); - if ($p) { - return $p . ':' . $name; - } - return $qname; - } else { - return $qname; - } - } - - /** - * expands (changes prefix to namespace) a qualified name - * - * @param string $string qname - * @return string expanded qname - * @access private - */ - function expandQname($qname){ - // get element prefix - if(strpos($qname,':') && !ereg('^http://',$qname)){ - // get unqualified name - $name = substr(strstr($qname,':'),1); - // get ns prefix - $prefix = substr($qname,0,strpos($qname,':')); - if(isset($this->namespaces[$prefix])){ - return $this->namespaces[$prefix].':'.$name; - } else { - return $qname; - } - } else { - return $qname; - } - } - - /** - * returns the local part of a prefixed string - * returns the original string, if not prefixed - * - * @param string $str The prefixed string - * @return string The local part - * @access public - */ - function getLocalPart($str){ - if($sstr = strrchr($str,':')){ - // get unqualified name - return substr( $sstr, 1 ); - } else { - return $str; - } - } - - /** - * returns the prefix part of a prefixed string - * returns false, if not prefixed - * - * @param string $str The prefixed string - * @return mixed The prefix or false if there is no prefix - * @access public - */ - function getPrefix($str){ - if($pos = strrpos($str,':')){ - // get prefix - return substr($str,0,$pos); - } - return false; - } - - /** - * pass it a prefix, it returns a namespace - * - * @param string $prefix The prefix - * @return mixed The namespace, false if no namespace has the specified prefix - * @access public - */ - function getNamespaceFromPrefix($prefix){ - if (isset($this->namespaces[$prefix])) { - return $this->namespaces[$prefix]; - } - //$this->setError("No namespace registered for prefix '$prefix'"); - return false; - } - - /** - * returns the prefix for a given namespace (or prefix) - * or false if no prefixes registered for the given namespace - * - * @param string $ns The namespace - * @return mixed The prefix, false if the namespace has no prefixes - * @access public - */ - function getPrefixFromNamespace($ns) { - foreach ($this->namespaces as $p => $n) { - if ($ns == $n || $ns == $p) { - $this->usedNamespaces[$p] = $n; - return $p; - } - } - return false; - } - - /** - * returns the time in ODBC canonical form with microseconds - * - * @return string The time in ODBC canonical form with microseconds - * @access public - */ - function getmicrotime() { - if (function_exists('gettimeofday')) { - $tod = gettimeofday(); - $sec = $tod['sec']; - $usec = $tod['usec']; - } else { - $sec = time(); - $usec = 0; - } - return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); - } - - /** - * Returns a string with the output of var_dump - * - * @param mixed $data The variable to var_dump - * @return string The output of var_dump - * @access public - */ - function varDump($data) { - ob_start(); - var_dump($data); - $ret_val = ob_get_contents(); - ob_end_clean(); - return $ret_val; - } -} - -// XML Schema Datatype Helper Functions - -//xsd:dateTime helpers - -/** -* convert unix timestamp to ISO 8601 compliant date string -* -* @param string $timestamp Unix time stamp -* @access public -*/ -function timestamp_to_iso8601($timestamp,$utc=true){ - $datestr = date('Y-m-d\TH:i:sO',$timestamp); - if($utc){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - - if(ereg($eregStr,$datestr,$regs)){ - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); - } - return false; - } else { - return $datestr; - } -} - -/** -* convert ISO 8601 compliant date string to unix timestamp -* -* @param string $datestr ISO 8601 compliant date string -* @access public -*/ -function iso8601_to_timestamp($datestr){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - if(ereg($eregStr,$datestr,$regs)){ - // not utc - if($regs[8] != 'Z'){ - $op = substr($regs[8],0,1); - $h = substr($regs[8],1,2); - $m = substr($regs[8],strlen($regs[8])-2,2); - if($op == '-'){ - $regs[4] = $regs[4] + $h; - $regs[5] = $regs[5] + $m; - } elseif($op == '+'){ - $regs[4] = $regs[4] - $h; - $regs[5] = $regs[5] - $m; - } - } - return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); - } else { - return false; - } -} - -/** -* sleeps some number of microseconds -* -* @param string $usec the number of microseconds to sleep -* @access public -* @deprecated -*/ -function usleepWindows($usec) -{ - $start = gettimeofday(); - - do - { - $stop = gettimeofday(); - $timePassed = 1000000 * ($stop['sec'] - $start['sec']) - + $stop['usec'] - $start['usec']; - } - while ($timePassed < $usec); -} - - -?> \ No newline at end of file diff --git a/thirdparty/pear/class.soapclient.php b/thirdparty/pear/class.soapclient.php deleted file mode 100644 index 0d32067a7..000000000 --- a/thirdparty/pear/class.soapclient.php +++ /dev/null @@ -1,859 +0,0 @@ -call( string methodname [ ,array parameters] ); -* -* // bye bye client -* unset($soapclient); -* -* @author Dietrich Ayala -* @version $Id: class.soapclient.php,v 1.52 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soapclient extends nusoap_base { - - var $username = ''; - var $password = ''; - var $authtype = ''; - var $certRequest = array(); - var $requestHeaders = false; // SOAP headers in request (text) - var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text) - var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text) - var $endpoint; - var $forceEndpoint = ''; // overrides WSDL endpoint - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $xml_encoding = ''; // character set encoding of incoming (response) messages - var $http_encoding = false; - var $timeout = 0; // HTTP connection timeout - var $response_timeout = 30; // HTTP response timeout - var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error - var $persistentConnection = false; - var $defaultRpcParams = false; // This is no longer used - var $request = ''; // HTTP request - var $response = ''; // HTTP response - var $responseData = ''; // SOAP payload of response - var $cookies = array(); // Cookies from response or for request - var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode() - var $operations = array(); // WSDL operations, empty for WSDL initialization error - - /* - * fault related variables - */ - /** - * @var fault - * @access public - */ - var $fault; - /** - * @var faultcode - * @access public - */ - var $faultcode; - /** - * @var faultstring - * @access public - */ - var $faultstring; - /** - * @var faultdetail - * @access public - */ - var $faultdetail; - - /** - * constructor - * - * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object) - * @param bool $wsdl optional, set to true if using WSDL - * @param int $portName optional portName in WSDL document - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function soapclient($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){ - parent::nusoap_base(); - $this->endpoint = $endpoint; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // make values - if($wsdl){ - if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) { - $this->wsdl = $endpoint; - $this->endpoint = $this->wsdl->wsdl; - $this->wsdlFile = $this->endpoint; - $this->debug('existing wsdl instance created from ' . $this->endpoint); - } else { - $this->wsdlFile = $this->endpoint; - - // instantiate wsdl object and parse wsdl file - $this->debug('instantiating wsdl class with doc: '.$endpoint); - $this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout); - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - // catch errors - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - } elseif($this->operations = $this->wsdl->getOperations()){ - $this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile); - $this->endpointType = 'wsdl'; - } else { - $this->debug( 'getOperations returned false'); - $this->setError('no operations defined in the WSDL document!'); - } - } else { - $this->debug("instantiate SOAP with endpoint at $endpoint"); - $this->endpointType = 'soap'; - } - } - - /** - * calls method, returns PHP native type - * - * @param string $method SOAP server URL or path - * @param mixed $params An array, associative or simple, of the parameters - * for the method call, or a string that is the XML - * for the call. For rpc style, this call will - * wrap the XML in a tag named after the method, as - * well as the SOAP Envelope and Body. For document - * style, this will only wrap with the Envelope and Body. - * IMPORTANT: when using an array with document style, - * in which case there - * is really one parameter, the root of the fragment - * used in the call, which encloses what programmers - * normally think of parameters. A parameter array - * *must* include the wrapper. - * @param string $namespace optional method namespace (WSDL can override) - * @param string $soapAction optional SOAPAction value (WSDL can override) - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param boolean $rpcParams optional (no longer used) - * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override) - * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override) - * @return mixed response from SOAP call - * @access public - */ - function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){ - $this->operation = $operation; - $this->fault = false; - $this->setError(''); - $this->request = ''; - $this->response = ''; - $this->responseData = ''; - $this->faultstring = ''; - $this->faultcode = ''; - $this->opData = array(); - - $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType"); - $this->appendDebug('params=' . $this->varDump($params)); - $this->appendDebug('headers=' . $this->varDump($headers)); - if ($headers) { - $this->requestHeaders = $headers; - } - // serialize parameters - if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){ - // use WSDL for operation - $this->opData = $opData; - $this->debug("found operation"); - $this->appendDebug('opData=' . $this->varDump($opData)); - if (isset($opData['soapAction'])) { - $soapAction = $opData['soapAction']; - } - if (! $this->forceEndpoint) { - $this->endpoint = $opData['endpoint']; - } else { - $this->endpoint = $this->forceEndpoint; - } - $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace; - $style = $opData['style']; - $use = $opData['input']['use']; - // add ns to ns array - if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){ - $nsPrefix = 'ns' . rand(1000, 9999); - $this->wsdl->namespaces[$nsPrefix] = $namespace; - } - $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace); - // serialize payload - if (is_string($params)) { - $this->debug("serializing param string for WSDL operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for WSDL operation $operation"); - $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params); - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = $this->wsdl->usedNamespaces; - if (isset($opData['input']['encodingStyle'])) { - $encodingStyle = $opData['input']['encodingStyle']; - } else { - $encodingStyle = ''; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if ($errstr = $this->wsdl->getError()) { - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - return false; - } - } elseif($this->endpointType == 'wsdl') { - // operation not in WSDL - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - $this->setError( 'operation '.$operation.' not present.'); - $this->debug("operation '$operation' not present."); - return false; - } else { - // no WSDL - //$this->namespaces['ns1'] = $namespace; - $nsPrefix = 'ns' . rand(1000, 9999); - // serialize - $payload = ''; - if (is_string($params)) { - $this->debug("serializing param string for operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for operation $operation"); - foreach($params as $k => $v){ - $payload .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = array(); - if ($use == 'encoded') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } else { - $encodingStyle = ''; - } - } - // wrap RPC calls with method element - if ($style == 'rpc') { - if ($use == 'literal') { - $this->debug("wrapping RPC request with literal method element"); - if ($namespace) { - $payload = "<$operation xmlns=\"$namespace\">" . $payload . ""; - } else { - $payload = "<$operation>" . $payload . ""; - } - } else { - $this->debug("wrapping RPC request with encoded method element"); - if ($namespace) { - $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . - $payload . - ""; - } else { - $payload = "<$operation>" . - $payload . - ""; - } - } - } - // serialize envelope - $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle); - $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle"); - $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000)); - // send - $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout); - if($errstr = $this->getError()){ - $this->debug('Error: '.$errstr); - return false; - } else { - $this->return = $return; - $this->debug('sent message successfully and got a(n) '.gettype($return)); - $this->appendDebug('return=' . $this->varDump($return)); - - // fault? - if(is_array($return) && isset($return['faultcode'])){ - $this->debug('got fault'); - $this->setError($return['faultcode'].': '.$return['faultstring']); - $this->fault = true; - foreach($return as $k => $v){ - $this->$k = $v; - $this->debug("$k = $v
"); - } - return $return; - } elseif ($style == 'document') { - // NOTE: if the response is defined to have multiple parts (i.e. unwrapped), - // we are only going to return the first part here...sorry about that - return $return; - } else { - // array of return values - if(is_array($return)){ - // multiple 'out' parameters, which we return wrapped up - // in the array - if(sizeof($return) > 1){ - return $return; - } - // single 'out' parameter (normally the return value) - $return = array_shift($return); - $this->debug('return shifted value: '); - $this->appendDebug($this->varDump($return)); - return $return; - // nothing returned (ie, echoVoid) - } else { - return ""; - } - } - } - } - - /** - * get available data pertaining to an operation - * - * @param string $operation operation name - * @return array array of data pertaining to the operation - * @access public - */ - function getOperationData($operation){ - if(isset($this->operations[$operation])){ - return $this->operations[$operation]; - } - $this->debug("No data for operation: $operation"); - } - - /** - * send the SOAP message - * - * Note: if the operation has multiple return values - * the return value of this method will be an array - * of those values. - * - * @param string $msg a SOAPx4 soapmsg object - * @param string $soapaction SOAPAction value - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @return mixed native PHP types. - * @access private - */ - function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) { - $this->checkCookies(); - // detect transport - switch(true){ - // http(s) - case ereg('^http',$this->endpoint): - $this->debug('transporting via HTTP'); - if($this->persistentConnection == true && is_object($this->persistentConnection)){ - $http =& $this->persistentConnection; - } else { - $http = new soap_transport_http($this->endpoint); - if ($this->persistentConnection) { - $http->usePersistentConnection(); - } - } - $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset()); - $http->setSOAPAction($soapaction); - if($this->proxyhost && $this->proxyport){ - $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - if($this->authtype != '') { - $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); - } - if($this->http_encoding != ''){ - $http->setEncoding($this->http_encoding); - } - $this->debug('sending message, length='.strlen($msg)); - if(ereg('^http:',$this->endpoint)){ - //if(strpos($this->endpoint,'http:')){ - $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies); - } elseif(ereg('^https',$this->endpoint)){ - //} elseif(strpos($this->endpoint,'https:')){ - //if(phpversion() == '4.3.0-dev'){ - //$response = $http->send($msg,$timeout,$response_timeout); - //$this->request = $http->outgoing_payload; - //$this->response = $http->incoming_payload; - //} else - $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies); - } else { - $this->setError('no http/s in endpoint url'); - } - $this->request = $http->outgoing_payload; - $this->response = $http->incoming_payload; - $this->appendDebug($http->getDebug()); - $this->UpdateCookies($http->incoming_cookies); - - // save transport object if using persistent connections - if ($this->persistentConnection) { - $http->clearDebug(); - if (!is_object($this->persistentConnection)) { - $this->persistentConnection = $http; - } - } - - if($err = $http->getError()){ - $this->setError('HTTP Error: '.$err); - return false; - } elseif($this->getError()){ - return false; - } else { - $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']); - return $this->parseResponse($http->incoming_headers, $this->responseData); - } - break; - default: - $this->setError('no transport found, or selected transport is not yet supported!'); - return false; - break; - } - } - - /** - * processes SOAP message returned from server - * - * @param array $headers The HTTP headers - * @param string $data unprocessed response data from server - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseResponse($headers, $data) { - $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Response not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - $parser = new soap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8); - // add parser debug data to our debug - $this->appendDebug($parser->getDebug()); - // if parse errors - if($errstr = $parser->getError()){ - $this->setError( $errstr); - // destroy the parser object - unset($parser); - return false; - } else { - // get SOAP headers - $this->responseHeaders = $parser->getHeaders(); - // get decoded message - $return = $parser->get_response(); - // add document for doclit support - $this->document = $parser->document; - // destroy the parser object - unset($parser); - // return decode message - return $return; - } - } - - /** - * sets the SOAP endpoint, which can override WSDL - * - * @param $endpoint string The endpoint URL to use, or empty string or false to prevent override - * @access public - */ - function setEndpoint($endpoint) { - $this->forceEndpoint = $endpoint; - } - - /** - * set the SOAP headers - * - * @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers - * @access public - */ - function setHeaders($headers){ - $this->requestHeaders = $headers; - } - - /** - * get the SOAP response headers (namespace resolution incomplete) - * - * @return string - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->certRequest = $certRequest; - } - - /** - * use HTTP encoding - * - * @param string $enc - * @access public - */ - function setHTTPEncoding($enc='gzip, deflate'){ - $this->http_encoding = $enc; - } - - /** - * use HTTP persistent connections if possible - * - * @access public - */ - function useHTTPPersistentConnection(){ - $this->persistentConnection = true; - } - - /** - * gets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style. - * Each call() can override this value. - * - * This is no longer used. - * - * @return boolean - * @access public - * @deprecated - */ - function getDefaultRpcParams() { - return $this->defaultRpcParams; - } - - /** - * sets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style - * Each call() can override this value. - * - * This is no longer used. - * - * @param boolean $rpcParams - * @access public - * @deprecated - */ - function setDefaultRpcParams($rpcParams) { - $this->defaultRpcParams = $rpcParams; - } - - /** - * dynamically creates an instance of a proxy class, - * allowing user to directly call methods from wsdl - * - * @return object soap_proxy object - * @access public - */ - function getProxy(){ - $r = rand(); - $evalStr = $this->_getProxyClassCode($r); - //$this->debug("proxy class: $evalStr"; - // eval the class - eval($evalStr); - // instantiate proxy object - eval("\$proxy = new soap_proxy_$r('');"); - // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice - $proxy->endpointType = 'wsdl'; - $proxy->wsdlFile = $this->wsdlFile; - $proxy->wsdl = $this->wsdl; - $proxy->operations = $this->operations; - $proxy->defaultRpcParams = $this->defaultRpcParams; - // transfer other state - $proxy->username = $this->username; - $proxy->password = $this->password; - $proxy->authtype = $this->authtype; - $proxy->proxyhost = $this->proxyhost; - $proxy->proxyport = $this->proxyport; - $proxy->proxyusername = $this->proxyusername; - $proxy->proxypassword = $this->proxypassword; - $proxy->timeout = $this->timeout; - $proxy->response_timeout = $this->response_timeout; - $proxy->http_encoding = $this->http_encoding; - $proxy->persistentConnection = $this->persistentConnection; - $proxy->requestHeaders = $this->requestHeaders; - $proxy->soap_defencoding = $this->soap_defencoding; - $proxy->endpoint = $this->endpoint; - $proxy->forceEndpoint = $this->forceEndpoint; - return $proxy; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access private - */ - function _getProxyClassCode($r) { - if ($this->endpointType != 'wsdl') { - $evalStr = 'A proxy can only be created for a WSDL client'; - $this->setError($evalStr); - return $evalStr; - } - $evalStr = ''; - foreach ($this->operations as $operation => $opData) { - if ($operation != '') { - // create param string and param comment string - if (sizeof($opData['input']['parts']) > 0) { - $paramStr = ''; - $paramArrayStr = ''; - $paramCommentStr = ''; - foreach ($opData['input']['parts'] as $name => $type) { - $paramStr .= "\$$name, "; - $paramArrayStr .= "'$name' => \$$name, "; - $paramCommentStr .= "$type \$$name, "; - } - $paramStr = substr($paramStr, 0, strlen($paramStr)-2); - $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2); - $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2); - } else { - $paramStr = ''; - $paramCommentStr = 'void'; - } - $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace']; - $evalStr .= "// $paramCommentStr - function " . str_replace('.', '__', $operation) . "($paramStr) { - \$params = array($paramArrayStr); - return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."'); - } - "; - unset($paramStr); - unset($paramCommentStr); - } - } - $evalStr = 'class soap_proxy_'.$r.' extends soapclient { - '.$evalStr.' -}'; - return $evalStr; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access public - */ - function getProxyClassCode() { - $r = rand(); - return $this->_getProxyClassCode($r); - } - - /** - * gets the HTTP body for the current request. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current request. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current request. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current request. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current request. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /* - * whether or not parser should decode utf8 element content - * - * @return always returns true - * @access public - */ - function decodeUTF8($bool){ - $this->decode_utf8 = $bool; - return true; - } - - /** - * adds a new Cookie into $this->cookies array - * - * @param string $name Cookie Name - * @param string $value Cookie Value - * @return if cookie-set was successful returns true, else false - * @access public - */ - function setCookie($name, $value) { - if (strlen($name) == 0) { - return false; - } - $this->cookies[] = array('name' => $name, 'value' => $value); - return true; - } - - /** - * gets all Cookies - * - * @return array with all internal cookies - * @access public - */ - function getCookies() { - return $this->cookies; - } - - /** - * checks all Cookies and delete those which are expired - * - * @return always return true - * @access private - */ - function checkCookies() { - if (sizeof($this->cookies) == 0) { - return true; - } - $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); - $curr_cookies = $this->cookies; - $this->cookies = array(); - foreach ($curr_cookies as $cookie) { - if (! is_array($cookie)) { - $this->debug('Remove cookie that is not an array'); - continue; - } - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) > time()) { - $this->cookies[] = $cookie; - } else { - $this->debug('Remove expired cookie ' . $cookie['name']); - } - } else { - $this->cookies[] = $cookie; - } - } - $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array'); - return true; - } - - /** - * updates the current cookies with a new set - * - * @param array $cookies new cookies with which to update current ones - * @return always return true - * @access private - */ - function UpdateCookies($cookies) { - if (sizeof($this->cookies) == 0) { - // no existing cookies: take whatever is new - if (sizeof($cookies) > 0) { - $this->debug('Setting new cookie(s)'); - $this->cookies = $cookies; - } - return true; - } - if (sizeof($cookies) == 0) { - // no new cookies: keep what we've got - return true; - } - // merge - foreach ($cookies as $newCookie) { - if (!is_array($newCookie)) { - continue; - } - if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) { - continue; - } - $newName = $newCookie['name']; - - $found = false; - for ($i = 0; $i < count($this->cookies); $i++) { - $cookie = $this->cookies[$i]; - if (!is_array($cookie)) { - continue; - } - if (!isset($cookie['name'])) { - continue; - } - if ($newName != $cookie['name']) { - continue; - } - $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN'; - $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN'; - if ($newDomain != $domain) { - continue; - } - $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH'; - $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH'; - if ($newPath != $path) { - continue; - } - $this->cookies[$i] = $newCookie; - $found = true; - $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']); - break; - } - if (! $found) { - $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']); - $this->cookies[] = $newCookie; - } - } - return true; - } -} -?> diff --git a/thirdparty/pear/json/class.json.php b/thirdparty/pear/json/class.json.php deleted file mode 100644 index a6ae92da9..000000000 --- a/thirdparty/pear/json/class.json.php +++ /dev/null @@ -1,817 +0,0 @@ - - * @author Matt Knapp - * @author Brett Stimmerman - * @copyright 2005 Michal Migurski - * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ - * @license http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 - */ - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_SLICE')) { - define('SERVICES_JSON_SLICE', 1); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_STR')) { -define('SERVICES_JSON_IN_STR', 2); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_ARR')) { - define('SERVICES_JSON_IN_ARR', 3); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_OBJ')) { - define('SERVICES_JSON_IN_OBJ', 4); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_CMT')) { - define('SERVICES_JSON_IN_CMT', 5); -} -/** - * Behavior switch for Services_JSON::decode() - */ -if ( !defined('SERVICES_JSON_LOOSE_TYPE')) { - define('SERVICES_JSON_LOOSE_TYPE', 16); -} -/** - * Behavior switch for Services_JSON::decode() - */ -if ( !defined('SERVICES_JSON_SUPPRESS_ERRORS')) { - define('SERVICES_JSON_SUPPRESS_ERRORS', 32); -} -/** - * Converts to and from JSON format. - * - * Brief example of use: - * - * - * // create a new instance of Services_JSON - * $json = new Services_JSON(); - * - * // convert a complexe value to JSON notation, and send it to the browser - * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); - * $output = $json->encode($value); - * - * print($output); - * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] - * - * // accept incoming POST data, assumed to be in JSON notation - * $input = file_get_contents('php://input', 1000000); - * $value = $json->decode($input); - * - */ - -if (class_exists ('Services_JSON') ) { - return; -} -class Services_JSON -{ - /** - * constructs a new JSON instance - * - * @param int $use object behavior flags; combine with boolean-OR - * - * possible values: - * - SERVICES_JSON_LOOSE_TYPE: loose typing. - * "{...}" syntax creates associative arrays - * instead of objects in decode(). - * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. - * Values which can't be encoded (e.g. resources) - * appear as NULL instead of throwing errors. - * By default, a deeply-nested resource will - * bubble up with an error, so all return values - * from encode() should be checked with isError() - */ - function Services_JSON($use = 0) - { - $this->use = $use; - } - - /** - * convert a string from one UTF-16 char to one UTF-8 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf16 UTF-16 character - * @return string UTF-8 character - * @access private - */ - function utf162utf8($utf16) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); - } - - $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); - - switch(true) { - case ((0x7F & $bytes) == $bytes): - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x7F & $bytes); - - case (0x07FF & $bytes) == $bytes: - // return a 2-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) - . chr(0x80 | ($bytes & 0x3F)); - - case (0xFFFF & $bytes) == $bytes: - // return a 3-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) - . chr(0x80 | (($bytes >> 6) & 0x3F)) - . chr(0x80 | ($bytes & 0x3F)); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * convert a string from one UTF-8 char to one UTF-16 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf8 UTF-8 character - * @return string UTF-16 character - * @access private - */ - function utf82utf16($utf8) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); - } - - switch(strlen($utf8)) { - case 1: - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return $utf8; - - case 2: - // return a UTF-16 character from a 2-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x07 & (ord($utf8{0}) >> 2)) - . chr((0xC0 & (ord($utf8{0}) << 6)) - | (0x3F & ord($utf8{1}))); - - case 3: - // return a UTF-16 character from a 3-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr((0xF0 & (ord($utf8{0}) << 4)) - | (0x0F & (ord($utf8{1}) >> 2))) - . chr((0xC0 & (ord($utf8{1}) << 6)) - | (0x7F & ord($utf8{2}))); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * encodes an arbitrary variable into JSON format - * - * @param mixed $var any number, boolean, string, array, or object to be encoded. - * see argument 1 to Services_JSON() above for array-parsing behavior. - * if var is a strng, note that encode() always expects it - * to be in ASCII or UTF-8 format! - * - * @return mixed JSON string representation of input var or an error if a problem occurs - * @access public - */ - function encode($var) - { - switch (gettype($var)) { - case 'boolean': - return $var ? 'true' : 'false'; - - case 'NULL': - return 'null'; - - case 'integer': - return (int) $var; - - case 'double': - case 'float': - return (float) $var; - - case 'string': - // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT - $ascii = ''; - $strlen_var = strlen($var); - - /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ - for ($c = 0; $c < $strlen_var; ++$c) { - - $ord_var_c = ord($var{$c}); - - switch (true) { - case $ord_var_c == 0x08: - $ascii .= '\b'; - break; - case $ord_var_c == 0x09: - $ascii .= '\t'; - break; - case $ord_var_c == 0x0A: - $ascii .= '\n'; - break; - case $ord_var_c == 0x0C: - $ascii .= '\f'; - break; - case $ord_var_c == 0x0D: - $ascii .= '\r'; - break; - - case $ord_var_c == 0x22: - case $ord_var_c == 0x2F: - case $ord_var_c == 0x5C: - // double quote, slash, slosh - $ascii .= '\\'.$var{$c}; - break; - - case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): - // characters U-00000000 - U-0000007F (same as ASCII) - $ascii .= $var{$c}; - break; - - case (($ord_var_c & 0xE0) == 0xC0): - // characters U-00000080 - U-000007FF, mask 110XXXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, ord($var{$c + 1})); - $c += 1; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF0) == 0xE0): - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2})); - $c += 2; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF8) == 0xF0): - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3})); - $c += 3; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFC) == 0xF8): - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4})); - $c += 4; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFE) == 0xFC): - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4}), - ord($var{$c + 5})); - $c += 5; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - } - } - - return '"'.$ascii.'"'; - - case 'array': - /* - * As per JSON spec if any array key is not an integer - * we must treat the the whole array as an object. We - * also try to catch a sparsely populated associative - * array with numeric keys here because some JS engines - * will create an array with empty indexes up to - * max_index which can cause memory issues and because - * the keys, which may be relevant, will be remapped - * otherwise. - * - * As per the ECMA and JSON specification an object may - * have any string as a property. Unfortunately due to - * a hole in the ECMA specification if the key is a - * ECMA reserved word or starts with a digit the - * parameter is only accessible using ECMAScript's - * bracket notation. - */ - - // treat as a JSON object - if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { - $properties = array_map(array($this, 'name_value'), - array_keys($var), - array_values($var)); - - foreach($properties as $property) { - if(Services_JSON::isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - } - - // treat it like a regular array - $elements = array_map(array($this, 'encode'), $var); - - foreach($elements as $element) { - if(Services_JSON::isError($element)) { - return $element; - } - } - - return '[' . join(',', $elements) . ']'; - - case 'object': - $vars = get_object_vars($var); - - $properties = array_map(array($this, 'name_value'), - array_keys($vars), - array_values($vars)); - - foreach($properties as $property) { - if(Services_JSON::isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - - default: - return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) - ? 'null' - : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); - } - } - - /** - * array-walking function for use in generating JSON-formatted name-value pairs - * - * @param string $name name of key to use - * @param mixed $value reference to an array element to be encoded - * - * @return string JSON-formatted name-value pair, like '"name":value' - * @access private - */ - function name_value($name, $value) - { - $encoded_value = $this->encode($value); - - if(Services_JSON::isError($encoded_value)) { - return $encoded_value; - } - - return $this->encode(strval($name)) . ':' . $encoded_value; - } - - /** - * reduce a string by removing leading and trailing comments and whitespace - * - * @param $str string string value to strip of comments and whitespace - * - * @return string string value stripped of comments and whitespace - * @access private - */ - function reduce_string($str) - { - $str = preg_replace(array( - - // eliminate single line comments in '// ...' form - '#^\s*//(.+)$#m', - - // eliminate multi-line comments in '/* ... */' form, at start of string - '#^\s*/\*(.+)\*/#Us', - - // eliminate multi-line comments in '/* ... */' form, at end of string - '#/\*(.+)\*/\s*$#Us' - - ), '', $str); - - // eliminate extraneous space - return trim($str); - } - - /** - * decodes a JSON string into appropriate variable - * - * @param string $str JSON-formatted string - * - * @return mixed number, boolean, string, array, or object - * corresponding to given JSON input string. - * See argument 1 to Services_JSON() above for object-output behavior. - * Note that decode() always returns strings - * in ASCII or UTF-8 format! - * @access public - */ - function decode($str) - { - $str = $this->reduce_string($str); - - switch (strtolower($str)) { - case 'true': - return true; - - case 'false': - return false; - - case 'null': - return null; - - default: - $m = array(); - - if (is_numeric($str)) { - // Lookie-loo, it's a number - - // This would work on its own, but I'm trying to be - // good about returning integers where appropriate: - // return (float)$str; - - // Return float or int, as appropriate - return ((float)$str == (integer)$str) - ? (integer)$str - : (float)$str; - - } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { - // STRINGS RETURNED IN UTF-8 FORMAT - $delim = substr($str, 0, 1); - $chrs = substr($str, 1, -1); - $utf8 = ''; - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c < $strlen_chrs; ++$c) { - - $substr_chrs_c_2 = substr($chrs, $c, 2); - $ord_chrs_c = ord($chrs{$c}); - - switch (true) { - case $substr_chrs_c_2 == '\b': - $utf8 .= chr(0x08); - ++$c; - break; - case $substr_chrs_c_2 == '\t': - $utf8 .= chr(0x09); - ++$c; - break; - case $substr_chrs_c_2 == '\n': - $utf8 .= chr(0x0A); - ++$c; - break; - case $substr_chrs_c_2 == '\f': - $utf8 .= chr(0x0C); - ++$c; - break; - case $substr_chrs_c_2 == '\r': - $utf8 .= chr(0x0D); - ++$c; - break; - - case $substr_chrs_c_2 == '\\"': - case $substr_chrs_c_2 == '\\\'': - case $substr_chrs_c_2 == '\\\\': - case $substr_chrs_c_2 == '\\/': - if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || - ($delim == "'" && $substr_chrs_c_2 != '\\"')) { - $utf8 .= $chrs{++$c}; - } - break; - - case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): - // single, escaped unicode character - $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) - . chr(hexdec(substr($chrs, ($c + 4), 2))); - $utf8 .= $this->utf162utf8($utf16); - $c += 5; - break; - - case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): - $utf8 .= $chrs{$c}; - break; - - case ($ord_chrs_c & 0xE0) == 0xC0: - // characters U-00000080 - U-000007FF, mask 110XXXXX - //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 2); - ++$c; - break; - - case ($ord_chrs_c & 0xF0) == 0xE0: - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 3); - $c += 2; - break; - - case ($ord_chrs_c & 0xF8) == 0xF0: - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 4); - $c += 3; - break; - - case ($ord_chrs_c & 0xFC) == 0xF8: - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 5); - $c += 4; - break; - - case ($ord_chrs_c & 0xFE) == 0xFC: - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 6); - $c += 5; - break; - - } - - } - - return $utf8; - - } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { - // array, or object notation - - if ($str{0} == '[') { - $stk = array(SERVICES_JSON_IN_ARR); - $arr = array(); - } else { - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = array(); - } else { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = new stdClass(); - } - } - - array_push($stk, array('what' => SERVICES_JSON_SLICE, - 'where' => 0, - 'delim' => false)); - - $chrs = substr($str, 1, -1); - $chrs = $this->reduce_string($chrs); - - if ($chrs == '') { - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } else { - return $obj; - - } - } - - //print("\nparsing {$chrs}\n"); - - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c <= $strlen_chrs; ++$c) { - - $top = end($stk); - $substr_chrs_c_2 = substr($chrs, $c, 2); - - if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { - // found a comma that is not inside a string, array, etc., - // OR we've reached the end of the character list - $slice = substr($chrs, $top['where'], ($c - $top['where'])); - array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); - //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - // we are in an array, so just push an element onto the stack - array_push($arr, $this->decode($slice)); - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - // we are in an object, so figure - // out the property name and set an - // element in an associative array, - // for now - $parts = array(); - - if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // "name":value pair - $key = $this->decode($parts[1]); - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // name:value pair, where name is unquoted - $key = $parts[1]; - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } - - } - - } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { - // found a quote, and we are not inside a string - array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); - //print("Found start of string at {$c}\n"); - - } elseif (($chrs{$c} == $top['delim']) && - ($top['what'] == SERVICES_JSON_IN_STR) && - ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { - // found a quote, we're in a string, and it's not escaped - // we know that it's not escaped becase there is _not_ an - // odd number of backslashes at the end of the string so far - array_pop($stk); - //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '[') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-bracket, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); - //print("Found start of array at {$c}\n"); - - } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { - // found a right-bracket, and we're in an array - array_pop($stk); - //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '{') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-brace, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); - //print("Found start of object at {$c}\n"); - - } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { - // found a right-brace, and we're in an object - array_pop($stk); - //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($substr_chrs_c_2 == '/*') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a comment start, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); - $c++; - //print("Found start of comment at {$c}\n"); - - } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { - // found a comment end, and we're in one now - array_pop($stk); - $c++; - - for ($i = $top['where']; $i <= $c; ++$i) - $chrs = substr_replace($chrs, ' ', $i, 1); - - //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } - - } - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - return $obj; - - } - - } - } - } - - /** - * @todo Ultimately, this should just call PEAR::isError() - */ - function isError($data, $code = null) - { - if (class_exists('pear')) { - return PEAR::isError($data, $code); - } elseif (is_object($data) && (get_class($data) == 'services_json_error' || - is_subclass_of($data, 'services_json_error'))) { - return true; - } - - return false; - } -} - -if (class_exists('PEAR_Error')) { - - class Services_JSON_Error extends PEAR_Error - { - function Services_JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - parent::PEAR_Error($message, $code, $mode, $options, $userinfo); - } - } - -} else { - - /** - * @todo Ultimately, this class shall be descended from PEAR_Error - */ - class Services_JSON_Error - { - function Services_JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - - } - } - -} - -?> \ No newline at end of file diff --git a/thirdparty/phing/lib/Zip.php b/thirdparty/phing/lib/Zip.php deleted file mode 100644 index 40dfe5959..000000000 --- a/thirdparty/phing/lib/Zip.php +++ /dev/null @@ -1,3602 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Zip.php 3076 2006-12-18 08:52:12Z fabien $ - - // ----- Constants - define( 'ARCHIVE_ZIP_READ_BLOCK_SIZE', 2048 ); - - // ----- File list separator - define( 'ARCHIVE_ZIP_SEPARATOR', ',' ); - - // ----- Optional static temporary directory - // By default temporary files are generated in the script current - // path. - // If defined : - // - MUST BE terminated by a '/'. - // - MUST be a valid, already created directory - // Samples : - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '/temp/' ); - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', 'C:/Temp/' ); - define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '' ); - - // ----- Error codes - define( 'ARCHIVE_ZIP_ERR_NO_ERROR', 0 ); - define( 'ARCHIVE_ZIP_ERR_WRITE_OPEN_FAIL', -1 ); - define( 'ARCHIVE_ZIP_ERR_READ_OPEN_FAIL', -2 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAMETER', -3 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_FILE', -4 ); - define( 'ARCHIVE_ZIP_ERR_FILENAME_TOO_LONG', -5 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ZIP', -6 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTRACTED_FILE', -7 ); - define( 'ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL', -8 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTENSION', -9 ); - define( 'ARCHIVE_ZIP_ERR_BAD_FORMAT', -10 ); - define( 'ARCHIVE_ZIP_ERR_DELETE_FILE_FAIL', -11 ); - define( 'ARCHIVE_ZIP_ERR_RENAME_FILE_FAIL', -12 ); - define( 'ARCHIVE_ZIP_ERR_BAD_CHECKSUM', -13 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_OPTION_VALUE', -15 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE', -16 ); - - // ----- Warning codes - define( 'ARCHIVE_ZIP_WARN_NO_WARNING', 0 ); - define( 'ARCHIVE_ZIP_WARN_FILE_EXIST', 1 ); - - // ----- Methods parameters - define( 'ARCHIVE_ZIP_PARAM_PATH', 'path' ); - define( 'ARCHIVE_ZIP_PARAM_ADD_PATH', 'add_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_PATH', 'remove_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_ALL_PATH', 'remove_all_path' ); - define( 'ARCHIVE_ZIP_PARAM_SET_CHMOD', 'set_chmod' ); - define( 'ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING', 'extract_as_string' ); - define( 'ARCHIVE_ZIP_PARAM_NO_COMPRESSION', 'no_compression' ); - define( 'ARCHIVE_ZIP_PARAM_BY_NAME', 'by_name' ); - define( 'ARCHIVE_ZIP_PARAM_BY_INDEX', 'by_index' ); - define( 'ARCHIVE_ZIP_PARAM_BY_EREG', 'by_ereg' ); - define( 'ARCHIVE_ZIP_PARAM_BY_PREG', 'by_preg' ); - - define( 'ARCHIVE_ZIP_PARAM_PRE_EXTRACT', 'callback_pre_extract' ); - define( 'ARCHIVE_ZIP_PARAM_POST_EXTRACT', 'callback_post_extract' ); - define( 'ARCHIVE_ZIP_PARAM_PRE_ADD', 'callback_pre_add' ); - define( 'ARCHIVE_ZIP_PARAM_POST_ADD', 'callback_post_add' ); - - - -/** -* Class for manipulating zip archive files -* -* A class which provided common methods to manipulate ZIP formatted -* archive files. -* It provides creation, extraction, deletion and add features. -* -* @author Vincent Blavet -* @version $Revision: 1.3 $ -* @package phing.lib -*/ -class Archive_Zip -{ - /** - * The filename of the zip archive. - * - * @var string Name of the Zip file - */ - var $_zipname=''; - - /** - * File descriptor of the opened Zip file. - * - * @var int Internal zip file descriptor - */ - var $_zip_fd=0; - - /** - * @var int last error code - */ - var $_error_code=1; - - /** - * @var string Last error description - */ - var $_error_string=''; - - // {{{ constructor - /** - * Archive_Zip Class constructor. This flavour of the constructor only - * declare a new Archive_Zip object, identifying it by the name of the - * zip file. - * - * @param string $p_zipname The name of the zip archive to create - * @access public - */ - function __construct($p_zipname) - { - if (!extension_loaded('zlib')) { - throw new Exception("The extension 'zlib' couldn't be found.\n". - "Please make sure your version of PHP was built ". - "with 'zlib' support."); - } - - // ----- Set the attributes - $this->_zipname = $p_zipname; - $this->_zip_fd = 0; - } - // }}} - - // {{{ create() - /** - * This method creates a Zip Archive with the filename set with - * the constructor. - * The files and directories indicated in $p_filelist - * are added in the archive. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * an error code on error - */ - function create($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array('no_compression' => false, - 'add_path' => "", - 'remove_path' => "", - 'remove_all_path' => false)) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - $v_result = $this->_create($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - $v_result = $this->_create($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Invalid variable type p_filelist'); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - return $p_result_list; - } - // }}} - - // {{{ add() - /** - * This method add files or directory in an existing Zip Archive. - * If the Zip Archive does not exist it is created. - * The files and directories to add are indicated in $p_filelist. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * 'callback_pre_add' : A callback function that will be called before - * each entry archiving. - * 'callback_post_add' : A callback function that will be called after - * each entry archiving. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function add($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('no_compression' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_add' => '', - 'callback_post_add' => '')) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - // ----- Call the create fct - $v_result = $this->_add($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - // ----- Call the create fct - $v_result = $this->_add($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "add() : Invalid variable type p_filelist"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - // ----- Return the result list - return $p_result_list; - } - // }}} - - // {{{ listContent() - /** - * This method gives the names and properties of the files and directories - * which are present in the zip archive. - * The properties of each entries in the list are : - * filename : Name of the file. - * For create() or add() it's the filename given by the user. - * For an extract() it's the filename of the extracted file. - * stored_filename : Name of the file / directory stored in the archive. - * size : Size of the stored file. - * compressed_size : Size of the file's data compressed in the archive - * (without the zip headers overhead) - * mtime : Last known modification date of the file (UNIX timestamp) - * comment : Comment associated with the file - * folder : true | false (indicates if the entry is a folder) - * index : index of the file in the archive (-1 when not available) - * status : status of the action on the entry (depending of the action) : - * Values are : - * ok : OK ! - * filtered : the file/dir was not extracted (filtered by user) - * already_a_directory : the file can't be extracted because a - * directory with the same name already - * exists - * write_protected : the file can't be extracted because a file - * with the same name already exists and is - * write protected - * newer_exist : the file was not extracted because a newer - * file already exists - * path_creation_fail : the file is not extracted because the - * folder does not exists and can't be - * created - * write_error : the file was not extracted because there was a - * error while writing the file - * read_error : the file was not extracted because there was a - * error while reading the file - * invalid_header : the file was not extracted because of an - * archive format error (bad file header) - * Note that each time a method can continue operating when there - * is an error on a single file, the error is only logged in the file status. - * - * @access public - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function listContent() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - $v_list = array(); - if ($this->_list($v_list) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ extract() - /** - * This method extract the files and folders which are in the zip archive. - * It can extract all the archive or a part of the archive by using filter - * feature (extract by name, by index, by ereg, by preg). The extraction - * can occur in the current path or an other path. - * All the advanced features are activated by the use of variable - * parameters. - * The return value is an array of entry descriptions which gives - * information on extracted files (See listContent()). - * The method may return a success value (an array) even if some files - * are not correctly extracted (see the file status in listContent()). - * The supported variable parameters for this method are : - * 'add_path' : Path where the files and directories are to be extracted - * 'remove_path' : First part ('root' part) of the memorized path - * (if similar) to remove while extracting. - * 'remove_all_path' : Remove all the memorized path while extracting. - * 'extract_as_string' : - * 'set_chmod' : After the extraction of the file the indicated mode - * will be set. - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to extract from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * 'callback_pre_extract' : A callback function that will be called before - * each entry extraction. - * 'callback_post_extract' : A callback function that will be called after - * each entry extraction. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function extract($p_params=0) - { - - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('extract_as_string' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_extract' => '', - 'callback_post_extract' => '', - 'set_chmod' => 0, - 'by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Call the extracting fct - $v_list = array(); - if ($this->_extractByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - - // {{{ delete() - /** - * This methods delete archive entries in the zip archive. - * Notice that at least one filtering rule (set by the variable parameter - * list) must be set. - * Also notice that if you delete a folder entry, only the folder entry - * is deleted, not all the files bellonging to this folder. - * The supported variable parameters for this method are : - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to delete from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function delete($p_params) - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($this->_check_parameters($p_params, - array ('by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Check that at least one rule is set - if ( ($p_params['by_name'] == '') - && ($p_params['by_index'] == '') - && ($p_params['by_ereg'] == '') - && ($p_params['by_preg'] == '')) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'At least one filtering rule must' - .' be set as parameter'); - return 0; - } - - // ----- Call the delete fct - $v_list = array(); - if ($this->_deleteByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ properties() - /** - * This method gives the global properties of the archive. - * The properties are : - * nb : Number of files in the archive - * comment : Comment associated with the archive file - * status : not_exist, ok - * - * @access public - * @param mixed $p_params {Description} - * @return mixed An array with the global properties or 0 on error. - */ - function properties() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Default properties - $v_prop = array(); - $v_prop['comment'] = ''; - $v_prop['nb'] = 0; - $v_prop['status'] = 'not_exist'; - - // ----- Look if file exists - if (@is_file($this->_zipname)) { - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in binary read mode'); - return 0; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - return 0; - } - - $this->_closeFd(); - - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; - } - - return $v_prop; - } - // }}} - - - // {{{ duplicate() - /** - * This method creates an archive by copying the content of an other one. - * If the archive already exist, it is replaced by the new one without - * any warning. - * - * @access public - * @param mixed $p_archive It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function duplicate($p_archive) - { - $this->_errorReset(); - - // ----- Look if the $p_archive is a Archive_Zip object - if ( (is_object($p_archive)) - && (strtolower(get_class($p_archive)) == 'archive_zip')) { - $v_result = $this->_duplicate($p_archive->_zipname); - } - - // ----- Look if the $p_archive is a string (so a filename) - else if (is_string($p_archive)) { - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "No file with filename '".$p_archive."'"); - $v_result = ARCHIVE_ZIP_ERR_MISSING_FILE; - } - else { - $v_result = $this->_duplicate($p_archive); - } - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ merge() - /** - * This method merge a valid zip archive at the end of the - * archive identified by the Archive_Zip object. - * If the archive ($this) does not exist, the merge becomes a duplicate. - * If the archive to add does not exist, the merge is a success. - * - * @access public - * @param mixed $p_archive_to_add It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function merge($p_archive_to_add) - { - $v_result = 1; - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Look if the $p_archive_to_add is a Archive_Zip object - if ( (is_object($p_archive_to_add)) - && (strtolower(get_class($p_archive_to_add)) == 'archive_zip')) { - $v_result = $this->_merge($p_archive_to_add); - } - - // ----- Look if the $p_archive_to_add is a string (so a filename) - else if (is_string($p_archive_to_add)) { - // ----- Create a temporary archive - $v_object_archive = new Archive_Zip($p_archive_to_add); - - // ----- Merge the archive - $v_result = $this->_merge($v_object_archive); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ errorCode() - /** - * Method that gives the lastest error code. - * - * @access public - * @return integer The error code value. - */ - function errorCode() - { - return($this->_error_code); - } - // }}} - - // {{{ errorName() - /** - * This method gives the latest error code name. - * - * @access public - * @param boolean $p_with_code If true, gives the name and the int value. - * @return string The error name. - */ - function errorName($p_with_code=false) - { - $v_const_list = get_defined_constants(); - - // ----- Extract error constants from all const. - for (reset($v_const_list); - list($v_key, $v_value) = each($v_const_list);) { - if (substr($v_key, 0, strlen('ARCHIVE_ZIP_ERR_')) - =='ARCHIVE_ZIP_ERR_') { - $v_error_list[$v_key] = $v_value; - } - } - - // ----- Search the name form the code value - $v_key=array_search($this->_error_code, $v_error_list, true); - if ($v_key!=false) { - $v_value = $v_key; - } - else { - $v_value = 'NoName'; - } - - if ($p_with_code) { - return($v_value.' ('.$this->_error_code.')'); - } - else { - return($v_value); - } - } - // }}} - - // {{{ errorInfo() - /** - * This method returns the description associated with the latest error. - * - * @access public - * @param boolean $p_full If set to true gives the description with the - * error code, the name and the description. - * If set to false gives only the description - * and the error code. - * @return string The error description. - */ - function errorInfo($p_full=false) - { - if ($p_full) { - return($this->errorName(true)." : ".$this->_error_string); - } - else { - return($this->_error_string." [code ".$this->_error_code."]"); - } - } - // }}} - - -// ----------------------------------------------------------------------------- -// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** -// ***** ***** -// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** -// ----------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _checkFormat() - // Description : - // This method check that the archive exists and is a valid zip archive. - // Several level of check exists. (futur) - // Parameters : - // $p_level : Level of check. Default 0. - // 0 : Check the first bytes (magic codes) (default value)) - // 1 : 0 + Check the central directory (futur) - // 2 : 1 + Check each file header (futur) - // Return Values : - // true on success, - // false on error, the error code is set. - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_checkFormat() - * - * { Description } - * - * @param integer $p_level - */ - function _checkFormat($p_level=0) - { - $v_result = true; - - // ----- Reset the error handler - $this->_errorReset(); - - // ----- Look if the file exits - if (!is_file($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "Missing archive file '".$this->_zipname."'"); - return(false); - } - - // ----- Check that the file is readeable - if (!is_readable($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - "Unable to read archive '".$this->_zipname."'"); - return(false); - } - - // ----- Check the magic code - // TBC - - // ----- Check the central header - // TBC - - // ----- Check each file header - // TBC - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _create() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_create() - * - * { Description } - * - */ - function _create($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Open the file in write mode - if (($v_result = $this->_openFd('wb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Add the list of files - $v_result = $this->_addList($p_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Close - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _add() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_add() - * - * { Description } - * - */ - function _add($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Look if the archive exists or is empty and need to be created - if ((!is_file($this->_zipname)) || (filesize($this->_zipname) == 0)) { - $v_result = $this->_create($p_list, $p_result_list, $p_params); - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to - // use the following methods on the temporary fil and not the real archive - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) - { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $i_writeCentralFileHeader($v_header_list[$i]))!=1) { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count - +$v_central_dir['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _openFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_openFd() - * - * { Description } - * - */ - function _openFd($p_mode) - { - $v_result=1; - - // ----- Look if already open - if ($this->_zip_fd != 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Zip file \''.$this->_zipname.'\' already open'); - return Archive_Zip::errorCode(); - } - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, $p_mode)) == 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in '.$p_mode.' mode'); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _closeFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_closeFd() - * - * { Description } - * - */ - function _closeFd() - { - $v_result=1; - - if ($this->_zip_fd != 0) - @fclose($this->_zip_fd); - $this->_zip_fd = 0; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to have PclTar - // running in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addList() - * - * { Description } - * - */ - function _addList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) { - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Create the Central Dir files header - for ($i=0,$v_count=0; $i_writeCentralFileHeader($v_header_list[$i])) != 1) { - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count, $v_size, $v_offset, - $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFileList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to - // run the lib in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFileList() - * - * { Description } - * - */ - function _addFileList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, - &$p_params) - { - $v_result=1; - $v_header = array(); - - // ----- Recuperate the current number of elt in list - $v_nb = sizeof($p_result_list); - - // ----- Loop on the files - for ($j=0; ($j_tool_TranslateWinPath($p_list[$j], false); - - // ----- Skip empty file names - if ($p_filename == "") - { - continue; - } - - // ----- Check the filename - if (!file_exists($p_filename)) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "File '$p_filename' does not exists"); - return Archive_Zip::errorCode(); - } - - // ----- Look if it is a file or a dir with no all pathnre move - if ((is_file($p_filename)) || ((is_dir($p_filename)) && !$p_remove_all_dir)) { - // ----- Add the file - if (($v_result = $this->_addFile($p_filename, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Look for directory - if (is_dir($p_filename)) - { - - // ----- Look for path - if ($p_filename != ".") - $v_path = $p_filename."/"; - else - $v_path = ""; - - // ----- Read the directory for files and sub-directories - $p_hdir = opendir($p_filename); - $p_hitem = readdir($p_hdir); // '.' directory - $p_hitem = readdir($p_hdir); // '..' directory - while ($p_hitem = readdir($p_hdir)) - { - - // ----- Look for a file - if (is_file($v_path.$p_hitem)) - { - - // ----- Add the file - if (($v_result = $this->_addFile($v_path.$p_hitem, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Recursive call to _addFileList() - else - { - - // ----- Need an array as parameter - $p_temp_list[0] = $v_path.$p_hitem; - $v_result = $this->_addFileList($p_temp_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Update the number of elements of the list - $v_nb = sizeof($p_result_list); - } - } - - // ----- Free memory for the recursive loop - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFile() - * - * { Description } - * - */ - function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - if ($p_filename == "") - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") - { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) - { - if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) - $p_remove_dir = "./".$p_remove_dir; - if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) - $p_remove_dir = substr($p_remove_dir, 2); - } - - $v_compare = $this->_tool_PathInclusion($p_remove_dir, $p_filename); - if ($v_compare > 0) -// if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) - { - - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - } - } - // ----- Look for path to add - if ($p_add_dir != "") - { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } - - // ----- Filename (reduce the path of stored name) - $v_stored_filename = $this->_tool_PathReduction($v_stored_filename); - - - /* filename length moved after call-back in release 1.3 - // ----- Check the path length - if (strlen($v_stored_filename) > 0xFF) - { - // ----- Error log - $this->_errorLog(-5, "Stored file name is too long (max. 255) : '$v_stored_filename'"); - - // ----- Return - return Archive_Zip::errorCode(); - } - */ - - // ----- Set the file properties - clearstatcache(); - $p_header['version'] = 20; - $p_header['version_extracted'] = 10; - $p_header['flag'] = 0; - $p_header['compression'] = 0; - $p_header['mtime'] = filemtime($p_filename); - $p_header['crc'] = 0; - $p_header['compressed_size'] = 0; - $p_header['size'] = filesize($p_filename); - $p_header['filename_len'] = strlen($p_filename); - $p_header['extra_len'] = 0; - $p_header['comment_len'] = 0; - $p_header['disk'] = 0; - $p_header['internal'] = 0; - $p_header['external'] = (is_file($p_filename)?0xFE49FFE0:0x41FF0010); - $p_header['offset'] = 0; - $p_header['filename'] = $p_filename; - $p_header['stored_filename'] = $v_stored_filename; - $p_header['extra'] = ''; - $p_header['comment'] = ''; - $p_header['status'] = 'ok'; - $p_header['index'] = -1; - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_ADD].'(ARCHIVE_ZIP_PARAM_PRE_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_header['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { - $p_header['stored_filename'] = $this->_tool_PathReduction($v_local_header['stored_filename']); - } - } - - // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; - } - - // ----- Check the path length - if (strlen($p_header['stored_filename']) > 0xFF) { - $p_header['status'] = 'filename_too_long'; - } - - // ----- Look if no error, or file not skipped - if ($p_header['status'] == 'ok') { - - // ----- Look for a file - if (is_file($p_filename)) - { - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return Archive_Zip::errorCode(); - } - - if ($p_params['no_compression']) { - // ----- Read the file content - $v_content_compressed = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content_compressed); - } - else { - // ----- Read the file content - $v_content = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content); - - // ----- Compress the file - $v_content_compressed = gzdeflate($v_content); - } - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content_compressed); - $p_header['compression'] = 8; - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } - - // ----- Write the compressed content - $v_binary_data = pack('a'.$p_header['compressed_size'], $v_content_compressed); - @fwrite($this->_zip_fd, $v_binary_data, $p_header['compressed_size']); - - // ----- Close the file - @fclose($v_file); - } - - // ----- Look for a directory - else - { - // ----- Set the file properties - $p_header['filename'] .= '/'; - $p_header['filename_len']++; - $p_header['size'] = 0; - $p_header['external'] = 0x41FF0010; // Value for a folder : to be checked - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) - { - return $v_result; - } - } - } - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_ADD].'(ARCHIVE_ZIP_PARAM_POST_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Ignored - $v_result = 1; - } - - // ----- Update the informations - // Nothing can be modified - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeFileHeader() - * - * { Description } - * - */ - function _writeFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Store the offset position of the file - $p_header['offset'] = ftell($this->_zip_fd); - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len']); - - // ----- Write the first 148 bytes of the header in the archive - fputs($this->_zip_fd, $v_binary_data, 30); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralFileHeader() - * - * { Description } - * - */ - function _writeCentralFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); - - // ----- Write the 42 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 46); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - if ($p_header['comment_len'] != 0) - { - fputs($this->_zip_fd, $p_header['comment'], $p_header['comment_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralHeader() - * - * { Description } - * - */ - function _writeCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) - { - $v_result=1; - - // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); - - // ----- Write the 22 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 22); - - // ----- Write the variable fields - if (strlen($p_comment) != 0) - { - fputs($this->_zip_fd, $p_comment, strlen($p_comment)); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _list() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_list() - * - * { Description } - * - */ - function _list(&$p_list) - { - $v_result=1; - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->_zipname.'\' in binary read mode'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - return $v_result; - } - - // ----- Go to beginning of Central Dir - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_central_dir['offset'])) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) - { - // ----- Read the file header - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) - { - return $v_result; - } - $v_header['index'] = $i; - - // ----- Get the only interesting attributes - $this->_convertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _convertHeader2FileInfo() - // Description : - // This function takes the file informations from the central directory - // entries and extract the interesting parameters that will be given back. - // The resulting file infos are set in the array $p_info - // $p_info['filename'] : Filename with full path. Given by user (add), - // extracted in the filesystem (extract). - // $p_info['stored_filename'] : Stored filename in the archive. - // $p_info['size'] = Size of the file. - // $p_info['compressed_size'] = Compressed size of the file. - // $p_info['mtime'] = Last modification date of the file. - // $p_info['comment'] = Comment associated with the file. - // $p_info['folder'] = true/false : indicates if the entry is a folder or not. - // $p_info['status'] = status of the action on the file. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_convertHeader2FileInfo() - * - * { Description } - * - */ - function _convertHeader2FileInfo($p_header, &$p_info) - { - $v_result=1; - - // ----- Get the interesting attributes - $p_info['filename'] = $p_header['filename']; - $p_info['stored_filename'] = $p_header['stored_filename']; - $p_info['size'] = $p_header['size']; - $p_info['compressed_size'] = $p_header['compressed_size']; - $p_info['mtime'] = $p_header['mtime']; - $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); - $p_info['index'] = $p_header['index']; - $p_info['status'] = $p_header['status']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractByRule() - // Description : - // Extract a file or directory depending of rules (by index, by name, ...) - // Parameters : - // $p_file_list : An array where will be placed the properties of each - // extracted file - // $p_path : Path to add while writing the extracted files - // $p_remove_path : Path to remove (from the file memorized path) while writing the - // extracted files. If the path does not match the file path, - // the file is extracted with its memorized path. - // $p_remove_path does not apply to 'list' mode. - // $p_path and $p_remove_path are commulative. - // Return Values : - // 1 on success,0 or less on error (see error code list) - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractByRule() - * - * { Description } - * - */ - function _extractByRule(&$p_file_list, &$p_params) - { - $v_result=1; - - $p_path = $p_params['add_path']; - $p_remove_path = $p_params['remove_path']; - $p_remove_all_path = $p_params['remove_all_path']; - - // ----- Check the path - if (($p_path == "") - || ((substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - - // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) { - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } - } - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); - - // ----- Open the zip file - if (($v_result = $this->_openFd('rb')) != 1) - { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - - // ----- Read each entry - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - // ----- Read next Central dir entry - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) { - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->_zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_extract = true; - } - } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_extract = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } - - - // ----- Look for real extraction - if ($v_extract) - { - - // ----- Go to the file position - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_header['offset'])) - { - // ----- Close the zip file - $this->_closeFd(); - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Look for extraction as string - if ($p_params[ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING]) { - - // ----- Extracting the file - if (($v_result = $this->_extractFileAsString($v_header, $v_string)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; - - // ----- Next extracted file - $v_nb_extracted++; - } - else { - // ----- Extracting the file - if (($v_result = $this->_extractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_params)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - } - } - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFile() - * - * { Description } - * - */ - function _extractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_params) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Look for all path to remove - if ($p_remove_all_path == true) { - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); - } - - // ----- Look for path to remove - else if ($p_remove_path != "") - { - //if (strcmp($p_remove_path, $p_entry['filename'])==0) - if ($this->_tool_PathInclusion($p_remove_path, $p_entry['filename']) == 2) - { - - // ----- Change the file status - $p_entry['status'] = "filtered"; - - // ----- Return - return $v_result; - } - - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { - - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - - } - } - - // ----- Add the path - if ($p_path != '') - { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; - } - - // ----- Look for pre-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT].'(ARCHIVE_ZIP_PARAM_PRE_EXTRACT, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - // ----- Trace - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Look for specific actions while the file exist - if (file_exists($p_entry['filename'])) - { - - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Return - //return $v_result; - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "write_protected"; - - // ----- Return - //return $v_result; - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - - // ----- Change the file status - $p_entry['status'] = "newer_exist"; - - // ----- Return - //return $v_result; - } - } - - // ----- Check the directory availability and create it if necessary - else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->_dirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; - - // ----- Return - //return $v_result; - $v_result = 1; - } - } - } - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - // ----- Return - return $v_result; - } - - - // ----- Read the file by ARCHIVE_ZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Closing the destination file - fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - else - { - // ----- Trace - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - return $v_result; - } - - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); - - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); - - // ----- Closing the destination file - @fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - - // ----- Look for chmod option - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD])) - && ($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD] != 0)) { - - // ----- Change the mode of the file - chmod($p_entry['filename'], $p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD]); - } - - } - } - - // ----- Look for post-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT].'(ARCHIVE_ZIP_PARAM_POST_EXTRACT, $v_local_header);'); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFileAsString() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFileAsString() - * - * { Description } - * - */ - function _extractFileAsString(&$p_entry, &$p_string) - { - $v_result=1; - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Trace - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - // ----- Trace - - // ----- Reading the file - $p_string = fread($this->_zip_fd, $p_entry['compressed_size']); - } - else - { - // ----- Trace - - // ----- Reading the file - $v_data = fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $p_string = gzinflate($v_data); - } - - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readFileHeader() - * - * { Description } - * - */ - function _readFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x04034b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 26); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 26) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - - // ----- Get filename - $p_header['filename'] = fread($this->_zip_fd, $v_data['filename_len']); - - // ----- Get extra_fields - if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->_zip_fd, $v_data['extra_len']); - } - else { - $p_header['extra'] = ''; - } - - // ----- Extract properties - $p_header['compression'] = $v_data['compression']; - $p_header['size'] = $v_data['size']; - $p_header['compressed_size'] = $v_data['compressed_size']; - $p_header['crc'] = $v_data['crc']; - $p_header['flag'] = $v_data['flag']; - - // ----- Recuperate date in UNIX format - $p_header['mdate'] = $v_data['mdate']; - $p_header['mtime'] = $v_data['mtime']; - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Other informations - - // TBC - //for(reset($v_data); $key = key($v_data); next($v_data)) { - //} - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set the status field - $p_header['status'] = "ok"; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readCentralFileHeader() - * - * { Description } - * - */ - function _readCentralFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x02014b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 42); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 42) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - - // ----- Get filename - if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->_zip_fd, $p_header['filename_len']); - else - $p_header['filename'] = ''; - - // ----- Get extra - if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->_zip_fd, $p_header['extra_len']); - else - $p_header['extra'] = ''; - - // ----- Get comment - if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->_zip_fd, $p_header['comment_len']); - else - $p_header['comment'] = ''; - - // ----- Extract properties - - // ----- Recuperate date in UNIX format - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set default status to ok - $p_header['status'] = 'ok'; - - // ----- Look if it is a directory - if (substr($p_header['filename'], -1) == '/') - { - $p_header['external'] = 0x41FF0010; - } - - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readEndCentralDir() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readEndCentralDir() - * - * { Description } - * - */ - function _readEndCentralDir(&$p_central_dir) - { - $v_result=1; - - // ----- Go to the end of the zip file - $v_size = filesize($this->_zipname); - @fseek($this->_zip_fd, $v_size); - if (@ftell($this->_zip_fd) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to go to the end of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- First try : look if this is an archive with no commentaries - // (most of the time) - // in this case the end of central dir is at 22 bytes of the file end - $v_found = 0; - if ($v_size > 26) { - @fseek($this->_zip_fd, $v_size-22); - if (($v_pos = @ftell($this->_zip_fd)) != ($v_size-22)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read for bytes - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } - - $v_pos = ftell($this->_zip_fd); - } - - // ----- Go back to the maximum possible size of the Central Dir End Record - if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->_zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->_zip_fd) != ($v_size-$v_maximum_size)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->_zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) { - // ----- Read a byte - $v_byte = @fread($this->_zip_fd, 1); - - // ----- Add the byte - $v_bytes = ($v_bytes << 8) | Ord($v_byte); - - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) { - $v_pos++; - break; - } - - $v_pos++; - } - - // ----- Look if not found end of central dir - if ($v_pos == $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Unable to find End of Central Dir Record signature"); - return Archive_Zip::errorCode(); - } - } - - // ----- Read the first 18 bytes of the header - $v_binary_data = fread($this->_zip_fd, 18); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 18) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Invalid End of Central Dir Record size : " - .strlen($v_binary_data)); - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - - // ----- Check the global size - if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Fail to find the right signature"); - return Archive_Zip::errorCode(); - } - - // ----- Get comment - if ($v_data['comment_size'] != 0) - $p_central_dir['comment'] = fread($this->_zip_fd, $v_data['comment_size']); - else - $p_central_dir['comment'] = ''; - - $p_central_dir['entries'] = $v_data['entries']; - $p_central_dir['disk_entries'] = $v_data['disk_entries']; - $p_central_dir['offset'] = $v_data['offset']; - $p_central_dir['size'] = $v_data['size']; - $p_central_dir['disk'] = $v_data['disk']; - $p_central_dir['disk_start'] = $v_data['disk_start']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _deleteByRule() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_deleteByRule() - * - * { Description } - * - */ - function _deleteByRule(&$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Scan all the files - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - // ----- Clean - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - $v_header_list = array(); - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - $v_result - = $this->_readCentralFileHeader($v_header_list[$v_nb_extracted]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] - == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; - ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) - && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for deletion - if ($v_found) { - unset($v_header_list[$v_nb_extracted]); - } - else { - $v_nb_extracted++; - } - } - - // ----- Look if something need to be deleted - if ($v_nb_extracted > 0) { - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-') - .'.tmp'; - - // ----- Creates a temporary zip archive - $v_temp_zip = new Archive_Zip($v_zip_temp_name); - - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->_openFd('wb')) != 1) { - $this->_closeFd(); - - // ----- Return - return $v_result; - } - - // ----- Look which file need to be kept - for ($i=0; $i_zip_fd); - if (@fseek($this->_zip_fd, $v_header_list[$i]['offset'])) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header_list[$i])) != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Write the file header - $v_result = $v_temp_zip->_writeFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Read/write the data block - $v_result = $this->_tool_CopyBlock($this->_zip_fd, - $v_temp_zip->_zip_fd, - $v_header_list[$i]['compressed_size']); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->_zip_fd); - - // ----- Re-Create the Central Dir files header - for ($i=0; $i_writeCentralFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Transform the header to a 'usable' info - $v_temp_zip->_convertHeader2FileInfo($v_header_list[$i], - $p_result_list[$i]); - } - - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - $v_result = $v_temp_zip->_writeCentralHeader(sizeof($v_header_list), - $v_size, $v_offset, - $v_comment); - if ($v_result != 1) { - // ----- Clean - unset($v_header_list); - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Close - $v_temp_zip->_closeFd(); - $this->_closeFd(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Destroy the temporary archive - unset($v_temp_zip); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _dirCheck() - // Description : - // Check if a directory exists, if not it creates it and all the parents directory - // which may be useful. - // Parameters : - // $p_dir : Directory path to check. - // Return Values : - // 1 : OK - // -1 : Unable to create directory - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_dirCheck() - * - * { Description } - * - * @param [type] $p_is_dir - */ - function _dirCheck($p_dir, $p_is_dir=false) - { - $v_result = 1; - - // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); - } - - // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) { - return 1; - } - - // ----- Extract parent directory - $p_parent_dir = dirname($p_dir); - - // ----- Just a check - if ($p_parent_dir != $p_dir) { - // ----- Look for parent directory - if ($p_parent_dir != "") { - if (($v_result = $this->_dirCheck($p_parent_dir)) != 1) { - return $v_result; - } - } - } - - // ----- Create the directory - if (!@mkdir($p_dir, 0777)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL, - "Unable to create directory '$p_dir'"); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _merge() - // Description : - // If $p_archive_to_add does not exist, the function exit with a success result. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_merge() - * - * { Description } - * - */ - function _merge(&$p_archive_to_add) - { - $v_result=1; - - // ----- Look if the archive_to_add exists - if (!is_file($p_archive_to_add->_zipname)) { - // ----- Nothing to merge, so merge is a success - return 1; - } - - // ----- Look if the archive exists - if (!is_file($this->_zipname)) { - // ----- Do a duplicate - $v_result = $this->_duplicate($p_archive_to_add->_zipname); - - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->_openFd('rb')) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir_to_add = array(); - $v_result = $p_archive_to_add->_readEndCentralDir($v_central_dir_to_add); - if ($v_result != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($p_archive_to_add->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the files from the archive_to_add into the temporary file - $v_size = $v_central_dir_to_add['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_zip_temp_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the block of file headers from the archive_to_add - $v_size = $v_central_dir_to_add['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Zip file comment - // TBC : I should merge the two comments - $v_comment = ''; - - // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive fd - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_central_dir['entries'] - +$v_central_dir_to_add['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - @fclose($v_zip_temp_fd); - $this->_zip_fd = null; - - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _duplicate() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_duplicate() - * - * { Description } - * - */ - function _duplicate($p_archive_filename) - { - $v_result=1; - - // ----- Look if the $p_archive_filename exists - if (!is_file($p_archive_filename)) { - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('wb')) != 1) { - // ----- Return - return $v_result; - } - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { - $this->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive file \'' - .$p_archive_filename.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = filesize($p_archive_filename); - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - return $v_result; - } - // --------------------------------------------------------------------------- - - /** - * Archive_Zip::_check_parameters() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _check_parameters(&$p_params, $p_default) - { - - // ----- Check that param is an array - if (!is_array($p_params)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter, waiting for an array'); - return Archive_Zip::errorCode(); - } - - // ----- Check that all the params are valid - for (reset($p_params); list($v_key, $v_value) = each($p_params); ) { - if (!isset($p_default[$v_key])) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter with key \''.$v_key.'\''); - - return Archive_Zip::errorCode(); - } - } - - // ----- Set the default values - for (reset($p_default); list($v_key, $v_value) = each($p_default); ) { - if (!isset($p_params[$v_key])) { - $p_params[$v_key] = $p_default[$v_key]; - } - } - - // ----- Check specific parameters - $v_callback_list = array ('callback_pre_add','callback_post_add', - 'callback_pre_extract','callback_post_extract'); - for ($i=0; $i_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE, - "Callback '".$p_params[$v_key] - ."()' is not an existing function for " - ."parameter '".$v_key."'"); - return Archive_Zip::errorCode(); - } - } - } - - return(1); - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorLog() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorLog() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _errorLog($p_error_code=0, $p_error_string='') - { - $this->_error_code = $p_error_code; - $this->_error_string = $p_error_string; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorReset() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorReset() - * - * { Description } - * - */ - function _errorReset() - { - $this->_error_code = 1; - $this->_error_string = ''; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathReduction() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_PathReduction() - * - * { Description } - * - */ - function _tool_PathReduction($p_dir) - { - $v_result = ""; - - // ----- Look for not empty path - if ($p_dir != "") - { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); - - // ----- Study directories from last to first - for ($i=sizeof($v_list)-1; $i>=0; $i--) - { - // ----- Look for current path - if ($v_list[$i] == ".") - { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") - { - // ----- Ignore it and ignore the $i-1 - $i--; - } - else if (($v_list[$i] == "") && ($i!=(sizeof($v_list)-1)) && ($i!=0)) - { - // ----- Ignore only the double '//' in path, - // but not the first and last '/' - } - else - { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); - } - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathInclusion() - // Description : - // This function indicates if the path $p_path is under the $p_dir tree. Or, - // said in an other way, if the file or sub-dir $p_path is inside the dir - // $p_dir. - // The function indicates also if the path is exactly the same as the dir. - // This function supports path with duplicated '/' like '//', but does not - // support '.' or '..' statements. - // Parameters : - // Return Values : - // 0 if $p_path is not inside directory $p_dir - // 1 if $p_path is inside directory $p_dir - // 2 if $p_path is exactly the same as $p_dir - // --------------------------------------------------------------------------- - /** - * _tool_PathInclusion() - * - * { Description } - * - */ - function _tool_PathInclusion($p_dir, $p_path) - { - $v_result = 1; - - // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); - $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); - $v_list_path_size = sizeof($v_list_path); - - // ----- Study directories paths - $i = 0; - $j = 0; - while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } - - // ----- Compare the items - if ( ($v_list_dir[$i] != $v_list_path[$j]) - && ($v_list_dir[$i] != '') - && ( $v_list_path[$j] != '')) { - $v_result = 0; - } - - // ----- Next items - $i++; - $j++; - } - - // ----- Look if everything seems to be the same - if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_CopyBlock() - // Description : - // Parameters : - // $p_mode : read/write compression mode - // 0 : src & dest normal - // 1 : src gzip, dest normal - // 2 : src normal, dest gzip - // 3 : src & dest gzip - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_CopyBlock() - * - * { Description } - * - * @param integer $p_mode - */ - function _tool_CopyBlock($p_src, $p_dest, $p_size, $p_mode=0) - { - $v_result = 1; - - if ($p_mode==0) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==1) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==2) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==3) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_Rename() - // Description : - // This function tries to do a simple rename() function. If it fails, it - // tries to copy the $p_src file in a new $p_dest file and then unlink the - // first one. - // Parameters : - // $p_src : Old filename - // $p_dest : New filename - // Return Values : - // 1 on success, 0 on failure. - // --------------------------------------------------------------------------- - /** - * _tool_Rename() - * - * { Description } - * - */ - function _tool_Rename($p_src, $p_dest) - { - $v_result = 1; - - // ----- Try to rename the files - if (!@rename($p_src, $p_dest)) { - - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_TranslateWinPath() - // Description : - // Translate windows path by replacing '\' by '/' and optionally removing - // drive letter. - // Parameters : - // $p_path : path to translate. - // $p_remove_disk_letter : true | false - // Return Values : - // The path translated. - // --------------------------------------------------------------------------- - /** - * _tool_TranslateWinPath() - * - * { Description } - * - * @param [type] $p_remove_disk_letter - */ - function _tool_TranslateWinPath($p_path, $p_remove_disk_letter=true) - { - if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if ( ($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } - // --------------------------------------------------------------------------- - - public function encryptCrc32($string) - { - if (!class_exists('G')) { - $realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] ); - $docuroot = explode( '/', $realdocuroot ); - array_pop( $docuroot ); - $pathhome = implode( '/', $docuroot ) . '/'; - array_pop( $docuroot ); - $pathTrunk = implode( '/', $docuroot ) . '/'; - require_once($pathTrunk.'gulliver/system/class.g.php'); - } - return G::encryptCrc32($string); - } - - } - // End of class - -?> diff --git a/thirdparty/phing/system/io/TokenReader.php b/thirdparty/phing/system/io/TokenReader.php deleted file mode 100644 index 219d72199..000000000 --- a/thirdparty/phing/system/io/TokenReader.php +++ /dev/null @@ -1,51 +0,0 @@ -. -*/ - -include_once 'phing/system/io/Reader.php'; -include_once 'phing/filters/ReplaceTokens.php'; // for class Token - -/** - * Abstract class for reading Tokens from a resource - * - * @author Manuel Holtgewe - * @version $Revision: 1.3 $ - * @access public - * @package phing.system.io - */ -class TokenReader extends Reader { - - /** - * Constructor - */ - function __construct() { - } - - /** - * Reads a token from the resource and returns it as a - * Token object. - * - * @access public - */ - function readToken() { - } -} - -?> diff --git a/workflow/engine/PmBootstrap.php b/workflow/engine/PmBootstrap.php index ec4b5aa82..8c54c057c 100644 --- a/workflow/engine/PmBootstrap.php +++ b/workflow/engine/PmBootstrap.php @@ -1,5 +1,7 @@ pmConfig = PmSystem::getSystemConfiguration(); + $this->pmConfig = System::getSystemConfiguration(); $e_all = defined('E_DEPRECATED') ? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = defined('E_STRICT') ? $e_all & ~E_STRICT : $e_all; @@ -82,7 +84,7 @@ class PmBootstrap extends Bootstrap $this->autoloader->registerClass('publisher', PATH_GULLIVER . 'class.publisher'); $this->autoloader->registerClass('templatePower', PATH_GULLIVER . 'class.templatePower'); $this->autoloader->registerClass('xmlDocument', PATH_GULLIVER . 'class.xmlDocument'); - $this->autoloader->registerClass('XmlForm_Field_XmlMenu', PATH_GULLIVER . 'class.xmlMenu'); + $this->autoloader->registerClass('XmlFormFieldXmlMenu', PATH_GULLIVER . 'class.xmlMenu'); $this->autoloader->registerClass('xmlform', PATH_GULLIVER . 'class.xmlform'); $this->autoloader->registerClass('xmlformExtension', PATH_GULLIVER . 'class.xmlformExtension'); @@ -96,8 +98,8 @@ class PmBootstrap extends Bootstrap $this->autoloader->registerClass('headPublisher', PATH_GULLIVER . 'class.headPublisher'); $this->autoloader->registerClass('Xml_Node', PATH_GULLIVER . 'class.xmlDocument'); $this->autoloader->registerClass('Xml_document', PATH_GULLIVER . 'class.xmlDocument'); - $this->autoloader->registerClass('XmlForm_Field_*', PATH_GULLIVER . 'class.xmlform'); - $this->autoloader->registerClass('serverConf', PATH_CORE . 'classes/class.serverConfiguration'); + $this->autoloader->registerClass('XmlFormField*', PATH_GULLIVER . 'class.xmlform'); + $this->autoloader->registerClass('ServerConf', PATH_CORE . 'classes/class.serverConfiguration'); } /** diff --git a/workflow/engine/bin/cron.php b/workflow/engine/bin/cron.php index ae48cb31e..2c456ed14 100644 --- a/workflow/engine/bin/cron.php +++ b/workflow/engine/bin/cron.php @@ -1,4 +1,7 @@ addModelClassPath(PATH_TRUNK . 'workflow' . PATH_SEP . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model' . PATH_SEP); //Load classes - $arraySystemConfiguration = PmSystem::getSystemConfiguration(); + $arraySystemConfiguration = System::getSystemConfiguration(); $e_all = (defined('E_DEPRECATED'))? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = (defined('E_STRICT'))? $e_all & ~E_STRICT : $e_all; diff --git a/workflow/engine/bin/cron_single.php b/workflow/engine/bin/cron_single.php index fac05dc1a..95ff5c04a 100644 --- a/workflow/engine/bin/cron_single.php +++ b/workflow/engine/bin/cron_single.php @@ -1,6 +1,7 @@ addModelClassPath(PATH_TRUNK . 'workflow' . PATH_SEP . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model' . PATH_SEP); - $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', $workspace); + $arraySystemConfiguration = System::getSystemConfiguration('', '', $workspace); $e_all = (defined('E_DEPRECATED'))? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = (defined('E_STRICT'))? $e_all & ~E_STRICT : $e_all; @@ -333,7 +334,7 @@ function resendEmails() $dateResend = date("Y-m-d H:i:s", $mktDateSystem - (7 * 24 * 60 * 60)); } - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->resendEmails($dateResend, 1); saveLog("resendEmails", "action", "Resending Emails", "c"); @@ -980,7 +981,7 @@ function synchronizeGmailLabels() } $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); if ($pmGoogle->getServiceGmailStatus()) { setExecutionMessage("Synchronize labels in Gmail"); $labGmail = new labelsGmail(); diff --git a/workflow/engine/bin/reindex_solr.php b/workflow/engine/bin/reindex_solr.php index a277a001e..6844c0022 100644 --- a/workflow/engine/bin/reindex_solr.php +++ b/workflow/engine/bin/reindex_solr.php @@ -26,6 +26,8 @@ // php reindex_solr.php workspacename [reindexall|reindexmissing|optimizeindex] [-skip 1005] [-reindextrunksize 1000] // var_dump($argv); //(count ($argv) == 4) || ((count ($argv) == 5) && ($argv [3] != '-skip')) +use ProcessMaker\Core\System; + $commandLineSyntaxMsg = "Invalid command line arguments: \n " . "syntax: ". "php reindex_solr.php [workspace_name] [reindexall|reindexmissing|optimizeindex|reindexone|deleteindexone] [-skip {record_number}] [-reindextrunksize {trunk_size}] [-appuid {APP_UID}]\n" . @@ -143,7 +145,7 @@ if (! defined ('SYS_SYS')) { // **************************************** // read initialize file require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; - $config = PmSystem::getSystemConfiguration ('', '', SYS_SYS); + $config = System::getSystemConfiguration ('', '', SYS_SYS); define ('MEMCACHED_ENABLED', $config ['memcached']); define ('MEMCACHED_SERVER', $config ['memcached_server']); define ('TIME_ZONE', $config ['time_zone']); @@ -259,7 +261,7 @@ function processWorkspace() try { - if (($solrConf = PmSystem::solrEnv (SYS_SYS)) !== false) { + if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; print "solr_host: " . $solrConf ['solr_host'] . "\n"; diff --git a/workflow/engine/bin/tasks/cliAddons.php b/workflow/engine/bin/tasks/cliAddons.php index 3929af511..52a6fdafe 100644 --- a/workflow/engine/bin/tasks/cliAddons.php +++ b/workflow/engine/bin/tasks/cliAddons.php @@ -57,7 +57,7 @@ function run_addon_core_install($args) } /////// - $ws = new workspaceTools($workspace); + $ws = new WorkspaceTools($workspace); $ws->initPropel(false); require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php'; @@ -73,7 +73,7 @@ function run_addon_core_install($args) $addon->install(); if ($addon->isCore()) { - $ws = new workspaceTools($workspace); + $ws = new WorkspaceTools($workspace); $ws->initPropel(false); $addon->setState("install-finish"); } else { diff --git a/workflow/engine/bin/tasks/cliCommon.php b/workflow/engine/bin/tasks/cliCommon.php index dce0e93ba..eb1864f42 100644 --- a/workflow/engine/bin/tasks/cliCommon.php +++ b/workflow/engine/bin/tasks/cliCommon.php @@ -1,6 +1,9 @@ dbInfo['DB_USER'], $workspace->dbInfo['DB_PASS'] ); - foreach (workspaceTools::$populateIdsQueries as $query) { + foreach (WorkspaceTools::$populateIdsQueries as $query) { echo "."; $dbh->query($query); } diff --git a/workflow/engine/bin/tasks/cliUpgrade.php b/workflow/engine/bin/tasks/cliUpgrade.php index 934c0ff56..bfc449763 100644 --- a/workflow/engine/bin/tasks/cliUpgrade.php +++ b/workflow/engine/bin/tasks/cliUpgrade.php @@ -25,6 +25,8 @@ * @package workflow-engine-bin-tasks */ +use ProcessMaker\Core\System; + CLI::taskName('upgrade'); CLI::taskDescription("Upgrade workspaces.\n\n This command should be run after upgrading ProcessMaker to a new version so that all workspaces are also upgraded to the\n new version."); @@ -87,7 +89,7 @@ function run_upgrade($command, $args) } $flag = G::isPMUnderUpdating(1, $oneWorkspace); //start to upgrade - $checksum = PmSystem::verifyChecksum(); + $checksum = System::verifyChecksum(); if ($checksum === false) { CLI::logging(CLI::error("checksum.txt not found, integrity check is not possible") . "\n"); if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { @@ -177,7 +179,7 @@ function run_upgrade($command, $args) } } } else { - CLI::logging('ProcessMaker ' . PmSystem::getVersion(). ' installed', PATH_DATA . 'log/upgrades.log'); + CLI::logging('ProcessMaker ' . System::getVersion(). ' installed', PATH_DATA . 'log/upgrades.log'); } //Safe upgrade for JavaScript files @@ -219,10 +221,10 @@ function run_unify_database($args) if (sizeof($args) > 2) { $filename = array_pop($args); foreach ($args as $arg) { - $workspaces[] = new workspaceTools($arg); + $workspaces[] = new WorkspaceTools($arg); } } else if (sizeof($args) > 0) { - $workspace = new workspaceTools($args[0]); + $workspace = new WorkspaceTools($args[0]); $workspaces[] = $workspace; } diff --git a/workflow/engine/bin/tasks/cliWorkspaces.php b/workflow/engine/bin/tasks/cliWorkspaces.php index 9f6725af0..6b5f216c9 100644 --- a/workflow/engine/bin/tasks/cliWorkspaces.php +++ b/workflow/engine/bin/tasks/cliWorkspaces.php @@ -1,29 +1,4 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - * @author Alexandre Rosenfeld - * @package workflow-engine-bin-tasks - */ CLI::taskName('info'); CLI::taskDescription(<<printMetadata(false); - } +/** + * Function run_info + * access public + */ +function run_info($args, $opts) +{ + $workspaces = get_workspaces_from_args($args); + WorkspaceTools::printSysInfo(); + foreach ($workspaces as $workspace) { + echo "\n"; + $workspace->printMetadata(false); + } } -function run_workspace_upgrade($args, $opts) { +function run_workspace_upgrade($args, $opts) +{ + $filter = new InputFilter(); + $opts = $filter->xssFilterHard($opts); + $args = $filter->xssFilterHard($args); + $workspaces = get_workspaces_from_args($args); + $first = true; + $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; + $buildCacheView = array_key_exists('buildACV', $opts); + $flagUpdateXml = !array_key_exists('noxml', $opts); - $filter = new InputFilter(); - $opts = $filter->xssFilterHard($opts); - $args = $filter->xssFilterHard($args); - $workspaces = get_workspaces_from_args($args); - $first = true; - $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; - $buildCacheView = array_key_exists('buildACV', $opts); - $flagUpdateXml = !array_key_exists('noxml', $opts); + foreach ($workspaces as $workspace) { + try { + if (!defined("SYS_SYS")) { + define("SYS_SYS", $workspace->name); + } - foreach ($workspaces as $workspace) { - try { - if (!defined("SYS_SYS")) { - define("SYS_SYS", $workspace->name); - } + if (!defined("PATH_DATA_SITE")) { + define("PATH_DATA_SITE", PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP); + } - if (!defined("PATH_DATA_SITE")) { - define("PATH_DATA_SITE", PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP); - } - - $workspace->upgrade($buildCacheView, $workspace->name, false, $lang, ['updateXml' => $flagUpdateXml, 'updateMafe' => $first]); - $first = false; - $flagUpdateXml = false; - } catch (Exception $e) { - G::outRes( "Errors upgrading workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n" ); + $workspace->upgrade($buildCacheView, $workspace->name, false, $lang, ['updateXml' => $flagUpdateXml, 'updateMafe' => $first]); + $first = false; + $flagUpdateXml = false; + } catch (Exception $e) { + G::outRes("Errors upgrading workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); + } } - } } /** @@ -410,7 +384,8 @@ function run_workspace_upgrade($args, $opts) { * * @return void */ -function run_translation_upgrade($args, $opts) { +function run_translation_upgrade($args, $opts) +{ $noXml = array_key_exists('noxml', $opts) ? '--no-xml' : ''; $noMafe = array_key_exists('nomafe', $opts) ? '--no-mafe' : ''; if (!empty($noXml)) { @@ -459,43 +434,48 @@ function translation_upgrade($args, $opts) } } -function run_cacheview_upgrade($args, $opts) { - - $filter = new InputFilter(); - $opts = $filter->xssFilterHard($opts); - $args = $filter->xssFilterHard($args); - $workspaces = get_workspaces_from_args($args); - $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; - foreach ($workspaces as $workspace) { - try { - G::outRes( "Upgrading cache view for " . pakeColor::colorize($workspace->name, "INFO") . "\n" ); - $workspace->upgradeCacheView(true, false, $lang); - } catch (Exception $e) { - G::outRes( "Errors upgrading cache view of workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n" ); +function run_cacheview_upgrade($args, $opts) +{ + $filter = new InputFilter(); + $opts = $filter->xssFilterHard($opts); + $args = $filter->xssFilterHard($args); + $workspaces = get_workspaces_from_args($args); + $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; + foreach ($workspaces as $workspace) { + try { + G::outRes("Upgrading cache view for " . pakeColor::colorize($workspace->name, "INFO") . "\n"); + $workspace->upgradeCacheView(true, false, $lang); + } catch (Exception $e) { + G::outRes("Errors upgrading cache view of workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); + } } - } } -function run_plugins_database_upgrade($args, $opts) { - $workspaces = get_workspaces_from_args($args); - foreach ($workspaces as $workspace) { - try { - CLI::logging("Upgrading plugins database for " . CLI::info($workspace->name) . "\n"); - $workspace->upgradePluginsDatabase(); - } catch (Exception $e) { - CLI::logging("Errors upgrading plugins database: " . CLI::error($e->getMessage())); + +function run_plugins_database_upgrade($args, $opts) +{ + $workspaces = get_workspaces_from_args($args); + foreach ($workspaces as $workspace) { + try { + CLI::logging("Upgrading plugins database for " . CLI::info($workspace->name) . "\n"); + $workspace->upgradePluginsDatabase(); + } catch (Exception $e) { + CLI::logging("Errors upgrading plugins database: " . CLI::error($e->getMessage())); + } } - } } -function run_database_export($args, $opts) { - if (count($args) < 2) - throw new Exception ("Please provide a workspace name and a directory for export"); - $workspace = new workspaceTools($args[0]); - $workspace->exportDatabase($args[1]); +function run_database_export($args, $opts) +{ + if (count($args) < 2) { + throw new Exception("Please provide a workspace name and a directory for export"); + } + $workspace = new WorkspaceTools($args[0]); + $workspace->exportDatabase($args[1]); } -function run_database_import($args, $opts) { - throw new Exception("Not implemented"); +function run_database_import($args, $opts) +{ + throw new Exception("Not implemented"); } /** @@ -505,33 +485,38 @@ function run_database_import($args, $opts) { * @param string $opts * * @return void -*/ -function run_database_upgrade($args, $opts) { + */ +function run_database_upgrade($args, $opts) +{ //Check if the command is executed by a specific workspace if (count($args) === 1) { database_upgrade('upgrade', $args); } else { $workspaces = get_workspaces_from_args($args); foreach ($workspaces as $workspace) { - passthru('./processmaker database-upgrade '.$workspace->name); + passthru('./processmaker database-upgrade ' . $workspace->name); } } } -function run_database_check($args, $opts) { - database_upgrade("check", $args); +function run_database_check($args, $opts) +{ + database_upgrade("check", $args); } -function run_migrate_new_cases_lists($args, $opts) { - migrate_new_cases_lists("migrate", $args, $opts); +function run_migrate_new_cases_lists($args, $opts) +{ + migrate_new_cases_lists("migrate", $args, $opts); } -function run_migrate_counters($args, $opts) { - migrate_counters("migrate", $args); +function run_migrate_counters($args, $opts) +{ + migrate_counters("migrate", $args); } -function run_migrate_list_unassigned($args, $opts) { - migrate_list_unassigned("migrate", $args, $opts); +function run_migrate_list_unassigned($args, $opts) +{ + migrate_list_unassigned("migrate", $args, $opts); } /** @@ -540,140 +525,146 @@ function run_migrate_list_unassigned($args, $opts) { * @param array $args, workspaceName for to apply the database-upgrade * * @return void -*/ -function database_upgrade($command, $args) { + */ +function database_upgrade($command, $args) +{ + $filter = new InputFilter(); + $command = $filter->xssFilterHard($command); + $args = $filter->xssFilterHard($args); + //Load the attributes for the workspace + $workspaces = get_workspaces_from_args($args); + $checkOnly = (strcmp($command, "check") == 0); + //Loop, read all the attributes related to the one workspace + $wsName = $workspaces[key($workspaces)]->name; + Bootstrap::setConstantsRelatedWs($wsName); + if ($checkOnly) { + print_r("Checking database in " . pakeColor::colorize($wsName, "INFO") . "\n"); + } else { + print_r("Upgrading database in " . pakeColor::colorize($wsName, "INFO") . "\n"); + } - $filter = new InputFilter(); - $command = $filter->xssFilterHard($command); - $args = $filter->xssFilterHard($args); - //Load the attributes for the workspace - $workspaces = get_workspaces_from_args($args); - $checkOnly = (strcmp($command, "check") == 0); - //Loop, read all the attributes related to the one workspace - $wsName = $workspaces[key($workspaces)]->name; - Bootstrap::setConstantsRelatedWs($wsName); - if ($checkOnly) { - print_r("Checking database in ".pakeColor::colorize($wsName, "INFO")."\n"); - } else { - print_r("Upgrading database in ".pakeColor::colorize($wsName, "INFO")."\n"); - } - - foreach ($workspaces as $workspace) { - try { - $changes = $workspace->upgradeDatabase($checkOnly); - if ($changes != false) { - if ($checkOnly) { - echo "> ".pakeColor::colorize("Run upgrade", "INFO")."\n"; - echo " Tables (add = " . count($changes['tablesToAdd']); - echo ", alter = " . count($changes['tablesToAlter']) . ") "; - echo "- Indexes (add = " . count($changes['tablesWithNewIndex']).""; - echo ", alter = " . count($changes['tablesToAlterIndex']).")\n"; - } else { - echo "-> Schema fixed\n"; + foreach ($workspaces as $workspace) { + try { + $changes = $workspace->upgradeDatabase($checkOnly); + if ($changes != false) { + if ($checkOnly) { + echo "> " . pakeColor::colorize("Run upgrade", "INFO") . "\n"; + echo " Tables (add = " . count($changes['tablesToAdd']); + echo ", alter = " . count($changes['tablesToAlter']) . ") "; + echo "- Indexes (add = " . count($changes['tablesWithNewIndex']) . ""; + echo ", alter = " . count($changes['tablesToAlterIndex']) . ")\n"; + } else { + echo "-> Schema fixed\n"; + } + } else { + echo "> OK\n"; + } + } catch (Exception $e) { + G::outRes("> Error: " . CLI::error($e->getMessage()) . "\n"); } - } else { - echo "> OK\n"; - } - } catch (Exception $e) { - G::outRes( "> Error: ".CLI::error($e->getMessage()) . "\n" ); } - } } -function delete_app_from_table($con, $tableName, $appUid, $col="APP_UID") { - $stmt = $con->createStatement(); - $sql = "DELETE FROM " . $tableName . " WHERE " . $col . "='" . $appUid . "'"; - $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM); +function delete_app_from_table($con, $tableName, $appUid, $col = "APP_UID") +{ + $stmt = $con->createStatement(); + $sql = "DELETE FROM " . $tableName . " WHERE " . $col . "='" . $appUid . "'"; + $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM); } -function run_drafts_clean($args, $opts) { - echo "Cleaning drafts\n"; +function run_drafts_clean($args, $opts) +{ + echo "Cleaning drafts\n"; - if (count($args) < 1) - throw new Exception ("Please specify a workspace name"); - $workspace = $args[0]; - - if (!file_exists(PATH_DB . $workspace . '/db.php')) { - throw new Exception('Could not find workspace ' . $workspace); - } - - $allDrafts = false; - if (count($args) < 2) { - echo "Cases older them this much days will be deleted (ENTER for all): "; - $days = rtrim( fgets( STDIN ), "\n" ); - if ($days == "") { - $allDrafts = true; + if (count($args) < 1) { + throw new Exception("Please specify a workspace name"); } - } else { - $days = $args[1]; - if (strcmp($days, "all") == 0) { - $allDrafts = true; + $workspace = $args[0]; + + if (!file_exists(PATH_DB . $workspace . '/db.php')) { + throw new Exception('Could not find workspace ' . $workspace); } - } - if (!$allDrafts && (!is_numeric($days) || intval($days) <= 0)) { - throw new Exception("Days value is not valid: " . $days); - } - - if ($allDrafts) - echo "Removing all drafts\n"; - else - echo "Removing drafts older than " . $days . " days\n"; - - /* Load the configuration from the workspace */ - require_once( PATH_DB . $workspace . '/db.php' ); - require_once( PATH_THIRDPARTY . 'propel/Propel.php'); - - PROPEL::Init ( PATH_METHODS.'dbConnections/rootDbConnections.php' ); - $con = Propel::getConnection("root"); - - $stmt = $con->createStatement(); - - if (!$allDrafts) - $dateSql = "AND DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY) >= APP_CREATE_DATE"; - else - $dateSql = ""; - /* Search for all the draft cases */ - $sql = "SELECT APP_UID FROM APPLICATION WHERE APP_STATUS='DRAFT'" . $dateSql; - $appRows = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); - - /* Tables to remove the cases from */ - $tables = array( - "APPLICATION", - "APP_DELEGATION", - "APP_CACHE_VIEW", - "APP_THREAD", - "APP_DOCUMENT", - "APP_EVENT", - "APP_HISTORY", - "APP_MESSAGE" - ); - - echo "Found " . $appRows->getRecordCount() . " cases to remove"; - foreach ($appRows as $row) { - echo "."; - $appUid = $row['APP_UID']; - foreach ($tables as $table) { - delete_app_from_table($con, $table, $appUid); + $allDrafts = false; + if (count($args) < 2) { + echo "Cases older them this much days will be deleted (ENTER for all): "; + $days = rtrim(fgets(STDIN), "\n"); + if ($days == "") { + $allDrafts = true; + } + } else { + $days = $args[1]; + if (strcmp($days, "all") == 0) { + $allDrafts = true; + } } - delete_app_from_table($con, "CONTENT", $appUid, "CON_ID"); - if (file_exists(PATH_DB . $workspace . '/files/'. $appUid)) { - echo "\nRemoving files from " . $appUid . "\n"; - G::rm_dir(PATH_DB . $workspace . '/files/'. $appUid); + + if (!$allDrafts && (!is_numeric($days) || intval($days) <= 0)) { + throw new Exception("Days value is not valid: " . $days); } - } - echo "\n"; + + if ($allDrafts) { + echo "Removing all drafts\n"; + } else { + echo "Removing drafts older than " . $days . " days\n"; + } + + /* Load the configuration from the workspace */ + require_once(PATH_DB . $workspace . '/db.php'); + require_once(PATH_THIRDPARTY . 'propel/Propel.php'); + + PROPEL::Init(PATH_METHODS . 'dbConnections/rootDbConnections.php'); + $con = Propel::getConnection("root"); + + $stmt = $con->createStatement(); + + if (!$allDrafts) { + $dateSql = "AND DATE_SUB(CURDATE(),INTERVAL " . $days . " DAY) >= APP_CREATE_DATE"; + } else { + $dateSql = ""; + } + /* Search for all the draft cases */ + $sql = "SELECT APP_UID FROM APPLICATION WHERE APP_STATUS='DRAFT'" . $dateSql; + $appRows = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); + + /* Tables to remove the cases from */ + $tables = array( + "APPLICATION", + "APP_DELEGATION", + "APP_CACHE_VIEW", + "APP_THREAD", + "APP_DOCUMENT", + "APP_EVENT", + "APP_HISTORY", + "APP_MESSAGE" + ); + + echo "Found " . $appRows->getRecordCount() . " cases to remove"; + foreach ($appRows as $row) { + echo "."; + $appUid = $row['APP_UID']; + foreach ($tables as $table) { + delete_app_from_table($con, $table, $appUid); + } + delete_app_from_table($con, "CONTENT", $appUid, "CON_ID"); + if (file_exists(PATH_DB . $workspace . '/files/' . $appUid)) { + echo "\nRemoving files from " . $appUid . "\n"; + G::rm_dir(PATH_DB . $workspace . '/files/' . $appUid); + } + } + echo "\n"; } -function run_workspace_backup($args, $opts) { +function run_workspace_backup($args, $opts) +{ $workspaces = array(); if (sizeof($args) > 2) { $filename = array_pop($args); foreach ($args as $arg) { - $workspaces[] = new workspaceTools($arg); + $workspaces[] = new WorkspaceTools($arg); } - } else if (sizeof($args) > 0) { - $workspace = new workspaceTools($args[0]); + } elseif (sizeof($args) > 0) { + $workspace = new WorkspaceTools($args[0]); $workspaces[] = $workspace; if (sizeof($args) == 2) { $filename = $args[1]; @@ -692,7 +683,7 @@ function run_workspace_backup($args, $opts) { } //If this is a relative path, put the file in the backups directory - if (strpos($filename, "/") === false && strpos($filename, '\\') === false){ + if (strpos($filename, "/") === false && strpos($filename, '\\') === false) { $filename = PATH_DATA . "backups/$filename"; } CLI::logging("Backing up to $filename\n"); @@ -704,7 +695,7 @@ function run_workspace_backup($args, $opts) { CLI::error("This is not a Linux enviroment, cannot use this filesize [-s] feature.\n"); return; } - $multipleBackup = new multipleFilesBackup ($filename,$filesize);//if filesize is 0 the default size will be took + $multipleBackup = new MultipleFilesBackup($filename, $filesize); //if filesize is 0 the default size will be took //using new method foreach ($workspaces as $workspace) { $multipleBackup->addToBackup($workspace); @@ -712,76 +703,76 @@ function run_workspace_backup($args, $opts) { $multipleBackup->letsBackup(); } else { //ansient method to backup into one large file - $backup = workspaceTools::createBackup($filename); + $backup = WorkspaceTools::createBackup($filename); foreach ($workspaces as $workspace) { $workspace->backup($backup); } } CLI::logging("\n"); - workspaceTools::printSysInfo(); + WorkspaceTools::printSysInfo(); foreach ($workspaces as $workspace) { CLI::logging("\n"); $workspace->printMetadata(false); } } -function run_workspace_restore($args, $opts) { - if (sizeof($args) > 0) { +function run_workspace_restore($args, $opts) +{ + if (sizeof($args) > 0) { + $filename = $args[0]; - $filename = $args[0]; + G::verifyPath(PATH_DATA . 'upgrade', true); - G::verifyPath(PATH_DATA . 'upgrade', true); + if (isset($args[1]) && strlen($args[1]) >= 30) { + eprintln("Invalid workspace name, insert a maximum of 30 characters.", 'red'); + return; + } - if(isset($args[1]) && strlen($args[1])>=30){ - eprintln("Invalid workspace name, insert a maximum of 30 characters.", 'red'); - return; - } - - if (strpos($filename, "/") === false && strpos($filename, '\\') === false) { - $filename = PATH_DATA . "backups/$filename"; - if (!file_exists($filename) && substr_compare($filename, ".tar", -4, 4, true) != 0) - $filename .= ".tar"; - } - $info = array_key_exists("info", $opts); - $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; - $port = array_key_exists("port", $opts) ? $opts['port'] : ''; - if ($info) { - workspaceTools::getBackupInfo($filename); + if (strpos($filename, "/") === false && strpos($filename, '\\') === false) { + $filename = PATH_DATA . "backups/$filename"; + if (!file_exists($filename) && substr_compare($filename, ".tar", -4, 4, true) != 0) { + $filename .= ".tar"; + } + } + $info = array_key_exists("info", $opts); + $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; + $port = array_key_exists("port", $opts) ? $opts['port'] : ''; + if ($info) { + WorkspaceTools::getBackupInfo($filename); + } else { + CLI::logging("Restoring from $filename\n"); + $workspace = array_key_exists("workspace", $opts) ? $opts['workspace'] : null; + $overwrite = array_key_exists("overwrite", $opts); + $multiple = array_key_exists("multiple", $opts); + $dstWorkspace = isset($args[1]) ? $args[1] : null; + if (!empty($multiple)) { + if (!Bootstrap::isLinuxOs()) { + CLI::error("This is not a Linux enviroment, cannot use this multiple [-m] feature.\n"); + return; + } + MultipleFilesBackup::letsRestore($filename, $workspace, $dstWorkspace, $overwrite); + } else { + $anotherExtention = ".*"; //if there are files with and extra extention: e.g. .tar.number + $multiplefiles = glob($filename . $anotherExtention); // example: //shared/workflow_data/backups/myWorkspace.tar.* + if (count($multiplefiles) > 0) { + CLI::error("Processmaker found these files: .\n"); + foreach ($multiplefiles as $index => $value) { + CLI::logging($value . "\n"); + } + CLI::error("Please, you should use -m parameter to restore them.\n"); + return; + } + WorkspaceTools::restore($filename, $workspace, $dstWorkspace, $overwrite, $lang, $port); + } + } } else { - CLI::logging("Restoring from $filename\n"); - $workspace = array_key_exists("workspace", $opts) ? $opts['workspace'] : NULL; - $overwrite = array_key_exists("overwrite", $opts); - $multiple = array_key_exists("multiple", $opts); - $dstWorkspace = isset($args[1]) ? $args[1] : null; - if(!empty($multiple)){ - if(!Bootstrap::isLinuxOs()){ - CLI::error("This is not a Linux enviroment, cannot use this multiple [-m] feature.\n"); - return; - } - multipleFilesBackup::letsRestore ($filename,$workspace,$dstWorkspace,$overwrite); - } - else{ - $anotherExtention = ".*"; //if there are files with and extra extention: e.g. .tar.number - $multiplefiles = glob($filename . $anotherExtention);// example: //shared/workflow_data/backups/myWorkspace.tar.* - if(count($multiplefiles) > 0) - { - CLI::error("Processmaker found these files: .\n"); - foreach($multiplefiles as $index => $value){ - CLI::logging($value . "\n"); - } - CLI::error("Please, you should use -m parameter to restore them.\n"); - return; - } - workspaceTools::restore($filename, $workspace, $dstWorkspace, $overwrite, $lang, $port ); - } - } - } else { throw new Exception("No workspace specified for restore"); - } + } } -function runStructureDirectories($command, $args) { +function runStructureDirectories($command, $args) +{ $workspaces = get_workspaces_from_args($command); $count = count($workspaces); $errors = false; @@ -801,7 +792,6 @@ function runStructureDirectories($command, $args) { function run_database_generate_self_service_by_value($args, $opts) { - $filter = new InputFilter(); $opts = $filter->xssFilterHard($opts); $args = $filter->xssFilterHard($args); @@ -812,10 +802,10 @@ function run_database_generate_self_service_by_value($args, $opts) $workspace = $value; try { - G::outRes( "Generating the table \"self-service by value\" for " . pakeColor::colorize($workspace->name, "INFO") . "\n" ); + G::outRes("Generating the table \"self-service by value\" for " . pakeColor::colorize($workspace->name, "INFO") . "\n"); $workspace->appAssignSelfServiceValueTableGenerateData(); } catch (Exception $e) { - G::outRes( "Errors generating the table \"self-service by value\" of workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n" ); + G::outRes("Errors generating the table \"self-service by value\" of workspace " . CLI::info($workspace->name) . ": " . CLI::error($e->getMessage()) . "\n"); } echo "\n"; @@ -823,82 +813,82 @@ function run_database_generate_self_service_by_value($args, $opts) echo "Done!\n"; } catch (Exception $e) { - G::outRes( CLI::error($e->getMessage()) . "\n" ); + G::outRes(CLI::error($e->getMessage()) . "\n"); } } function run_database_verify_consistency($args, $opts) { - verifyAppCacheConsistency($args); + verifyAppCacheConsistency($args); } function run_database_verify_migration_consistency($args, $opts) { - verifyMigratedDataConsistency($args); + verifyMigratedDataConsistency($args); } function verifyAppCacheConsistency($args) { - $workspaces = get_workspaces_from_args($args); - foreach ($workspaces as $workspace) { - verifyWorkspaceConsistency($workspace); - } + $workspaces = get_workspaces_from_args($args); + foreach ($workspaces as $workspace) { + verifyWorkspaceConsistency($workspace); + } } function verifyWorkspaceConsistency($workspace) { - $isConsistent = true; - print_r("Verifying data in workspace " . pakeColor::colorize($workspace->name, "INFO") . "\n"); - $inconsistentUsers = $workspace->hasMissingUsers(); - $inconsistentTasks = $workspace->hasMissingTasks(); - $inconsistentProcesses = $workspace->hasMissingProcesses(); - $inconsistentDelegations = $workspace->hasMissingAppDelegations(); + $isConsistent = true; + print_r("Verifying data in workspace " . pakeColor::colorize($workspace->name, "INFO") . "\n"); + $inconsistentUsers = $workspace->hasMissingUsers(); + $inconsistentTasks = $workspace->hasMissingTasks(); + $inconsistentProcesses = $workspace->hasMissingProcesses(); + $inconsistentDelegations = $workspace->hasMissingAppDelegations(); - if ($inconsistentUsers || $inconsistentTasks || $inconsistentProcesses || $inconsistentDelegations) { - $isConsistent = false; - } - return $isConsistent; + if ($inconsistentUsers || $inconsistentTasks || $inconsistentProcesses || $inconsistentDelegations) { + $isConsistent = false; + } + return $isConsistent; } function verifyMigratedDataConsistency($args) { - $workspaces = get_workspaces_from_args($args); - $inconsistentRecords = 0; - foreach ($workspaces as $workspace) { - print_r("Verifying data in workspace " . pakeColor::colorize($workspace->name, "INFO") . "\n"); - $lists = array( - 'LIST_CANCELLED', - 'LIST_COMPLETED', - 'LIST_INBOX', - 'LIST_PARTICIPATED_HISTORY', - 'LIST_PARTICIPATED_LAST', - 'LIST_MY_INBOX', - 'LIST_UNASSIGNED', - ); - foreach ($lists as $list) { - $inconsistentRecords += $workspace->verifyListData($list); + $workspaces = get_workspaces_from_args($args); + $inconsistentRecords = 0; + foreach ($workspaces as $workspace) { + print_r("Verifying data in workspace " . pakeColor::colorize($workspace->name, "INFO") . "\n"); + $lists = array( + 'LIST_CANCELLED', + 'LIST_COMPLETED', + 'LIST_INBOX', + 'LIST_PARTICIPATED_HISTORY', + 'LIST_PARTICIPATED_LAST', + 'LIST_MY_INBOX', + 'LIST_UNASSIGNED', + ); + foreach ($lists as $list) { + $inconsistentRecords += $workspace->verifyListData($list); + } } - } - return $inconsistentRecords; + return $inconsistentRecords; } -function run_migrate_itee_to_dummytask($args, $opts){ - - $filter = new InputFilter(); - $opts = $filter->xssFilterHard($opts); - $args = $filter->xssFilterHard($args); - $arrayWorkspace = get_workspaces_from_args($args); - foreach ($arrayWorkspace as $workspace) { - try { - $ws = new workspaceTools($workspace->name); - $res = $ws->migrateIteeToDummytask($workspace->name); - } catch (Exception $e) { - G::outRes( "> Error: ".CLI::error($e->getMessage()) . "\n" ); +function run_migrate_itee_to_dummytask($args, $opts) +{ + $filter = new InputFilter(); + $opts = $filter->xssFilterHard($opts); + $args = $filter->xssFilterHard($args); + $arrayWorkspace = get_workspaces_from_args($args); + foreach ($arrayWorkspace as $workspace) { + try { + $ws = new WorkspaceTools($workspace->name); + $res = $ws->migrateIteeToDummytask($workspace->name); + } catch (Exception $e) { + G::outRes("> Error: " . CLI::error($e->getMessage()) . "\n"); + } } - } } +/* ----------------------------------********--------------------------------- */ -/*----------------------------------********---------------------------------*/ /** * Check if we need to execute an external program for each workspace * If we apply the command for all workspaces we will need to execute one by one by redefining the constants @@ -906,8 +896,9 @@ function run_migrate_itee_to_dummytask($args, $opts){ * @param string $opts * * @return void -*/ -function run_check_workspace_disabled_code($args, $opts) { + */ +function run_check_workspace_disabled_code($args, $opts) +{ //Check if the command is executed by a specific workspace if (count($args) === 1) { check_workspace_disabled_code($args, $opts); @@ -918,6 +909,7 @@ function run_check_workspace_disabled_code($args, $opts) { } } } + /** * This function is executed only by one workspace * Code Security Scanner related to the custom blacklist @@ -925,7 +917,7 @@ function run_check_workspace_disabled_code($args, $opts) { * @param array $opts, workspaceName for to apply the database-upgrade * * @return void -*/ + */ function check_workspace_disabled_code($args, $opts) { try { @@ -951,7 +943,7 @@ function check_workspace_disabled_code($args, $opts) foreach ($arrayFoundDisabledCode as $value2) { $arrayProcessData = $value2; - $strFoundDisabledCode .= ($strFoundDisabledCode != "")? "\n" : ""; + $strFoundDisabledCode .= ($strFoundDisabledCode != "") ? "\n" : ""; $strFoundDisabledCode .= " Process: " . $arrayProcessData["processTitle"] . "\n"; $strFoundDisabledCode .= " Triggers:\n"; @@ -960,7 +952,7 @@ function check_workspace_disabled_code($args, $opts) $strCodeAndLine = ""; foreach ($arrayTriggerData["disabledCode"] as $key4 => $value4) { - $strCodeAndLine .= (($strCodeAndLine != "")? ", " : "") . $key4 . " (Lines " . implode(", ", $value4) . ")"; + $strCodeAndLine .= (($strCodeAndLine != "") ? ", " : "") . $key4 . " (Lines " . implode(", ", $value4) . ")"; } $strFoundDisabledCode .= " - " . $arrayTriggerData["triggerTitle"] . ": " . $strCodeAndLine . "\n"; } @@ -970,17 +962,18 @@ function check_workspace_disabled_code($args, $opts) echo "The workspace it's OK\n\n"; } } catch (Exception $e) { - G::outRes( "Errors to check disabled code: " . CLI::error($e->getMessage()) . "\n\n" ); + G::outRes("Errors to check disabled code: " . CLI::error($e->getMessage()) . "\n\n"); } $workspace->close(); } echo "Done!\n\n"; } catch (Exception $e) { - G::outRes( CLI::error($e->getMessage()) . "\n" ); + G::outRes(CLI::error($e->getMessage()) . "\n"); } } -function migrate_new_cases_lists($command, $args, $opts) { +function migrate_new_cases_lists($command, $args, $opts) +{ $filter = new InputFilter(); $opts = $filter->xssFilterHard($opts); $args = $filter->xssFilterHard($args); @@ -992,45 +985,46 @@ function migrate_new_cases_lists($command, $args, $opts) { $workspace->migrateList($workspace->name, true, $lang); echo "> List tables are done\n"; } catch (Exception $e) { - G::outRes( "> Error: ".CLI::error($e->getMessage()) . "\n" ); + G::outRes("> Error: " . CLI::error($e->getMessage()) . "\n"); } } } -function migrate_counters($command, $args) { - $workspaces = get_workspaces_from_args($args); +function migrate_counters($command, $args) +{ + $workspaces = get_workspaces_from_args($args); - foreach ($workspaces as $workspace) { - print_r("Regenerating counters in: " . pakeColor::colorize($workspace->name, "INFO") . "\n"); + foreach ($workspaces as $workspace) { + print_r("Regenerating counters in: " . pakeColor::colorize($workspace->name, "INFO") . "\n"); - try { - $workspace->migrateCounters($workspace->name, true); + try { + $workspace->migrateCounters($workspace->name, true); - echo "> Counters are done\n"; - } catch (Exception $e) { - G::outRes( "> Error: ".CLI::error($e->getMessage()) . "\n" ); + echo "> Counters are done\n"; + } catch (Exception $e) { + G::outRes("> Error: " . CLI::error($e->getMessage()) . "\n"); + } } - } } -function migrate_list_unassigned($command, $args, $opts) { - - $filter = new InputFilter(); - $opts = $filter->xssFilterHard($opts); - $args = $filter->xssFilterHard($args); - $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; - $workspaces = get_workspaces_from_args($args); - foreach ($workspaces as $workspace) { - print_r("Upgrading Unassigned List in" . pakeColor::colorize($workspace->name, "INFO") . "\n"); - try { - $workspace->regenerateListUnassigned(); - echo "> Unassigned List is done\n"; - } catch (Exception $e) { - G::outRes( "> Error: ".CLI::error($e->getMessage()) . "\n" ); +function migrate_list_unassigned($command, $args, $opts) +{ + $filter = new InputFilter(); + $opts = $filter->xssFilterHard($opts); + $args = $filter->xssFilterHard($args); + $lang = array_key_exists("lang", $opts) ? $opts['lang'] : 'en'; + $workspaces = get_workspaces_from_args($args); + foreach ($workspaces as $workspace) { + print_r("Upgrading Unassigned List in" . pakeColor::colorize($workspace->name, "INFO") . "\n"); + try { + $workspace->regenerateListUnassigned(); + echo "> Unassigned List is done\n"; + } catch (Exception $e) { + G::outRes("> Error: " . CLI::error($e->getMessage()) . "\n"); + } } - } } -/*----------------------------------********---------------------------------*/ +/* ----------------------------------********--------------------------------- */ /** * Check if we need to execute an external program for each workspace @@ -1039,8 +1033,9 @@ function migrate_list_unassigned($command, $args, $opts) { * @param string $opts, specify the language * * @return void -*/ -function run_migrate_content($args, $opts) { + */ +function run_migrate_content($args, $opts) +{ //Check the additional parameters $lang = array_key_exists("lang", $opts) ? '--lang=' . $opts['lang'] : '--lang=' . SYS_LANG; //Check if the command is executed by a specific workspace @@ -1049,17 +1044,18 @@ function run_migrate_content($args, $opts) { } else { $workspaces = get_workspaces_from_args($args); foreach ($workspaces as $workspace) { - passthru('./processmaker migrate-content ' . $lang . ' '.$workspace->name); + passthru('./processmaker migrate-content ' . $lang . ' ' . $workspace->name); } } } + /** * This function is executed only by one workspace * @param array $args, workspaceName for to apply the migrate-content * @param array $opts, specify the language * * @return void -*/ + */ function migrate_content($args, $opts) { $filter = new InputFilter(); @@ -1081,8 +1077,8 @@ function migrate_content($args, $opts) CLI::logging("<*> Optimizing content data Process took " . ($stop - $start) . " seconds.\n"); } -function run_migrate_self_service_value($args, $opts) { - +function run_migrate_self_service_value($args, $opts) +{ $filter = new InputFilter(); $args = $filter->xssFilterHard($args); $workspaces = get_workspaces_from_args($args); @@ -1097,7 +1093,8 @@ function run_migrate_self_service_value($args, $opts) { CLI::logging("<*> Migrating Self-Service records Process took " . ($stop - $start) . " seconds.\n"); } -function run_migrate_indexing_acv($args, $opts) { +function run_migrate_indexing_acv($args, $opts) +{ $filter = new InputFilter(); $args = $filter->xssFilterHard($args); $workspaces = get_workspaces_from_args($args); @@ -1111,10 +1108,11 @@ function run_migrate_indexing_acv($args, $opts) { CLI::logging("<*> Migrating and populating indexing for avoiding the use of table APP_CACHE_VIEW process took " . ($stop - $start) . " seconds.\n"); } -function run_migrate_plugin($args, $opts) { +function run_migrate_plugin($args, $opts) +{ $workspaces = get_workspaces_from_args($args); //Check if the command is executed by a specific workspace - /** @var workspaceTools $workspace */ + /** @var WorkspaceTools $workspace */ if (count($workspaces) === 1) { $workspace = array_shift($workspaces); CLI::logging('Regenerating Singleton in: ' . pakeColor::colorize($workspace->name, 'INFO') . "\n"); @@ -1124,12 +1122,13 @@ function run_migrate_plugin($args, $opts) { CLI::logging("> Migrating and populating data...\n"); $start = microtime(true); foreach ($workspaces as $workspace) { - passthru('./processmaker migrate-plugins-singleton-information '.$workspace->name); + passthru('./processmaker migrate-plugins-singleton-information ' . $workspace->name); } $stop = microtime(true); CLI::logging("<*> Migrating and populating data Singleton took " . ($stop - $start) . " seconds.\n"); } } + /** * This method recursively finds all PHP files that reference the path PATH_DATA * incorrectly, which is caused by importing processes where the data directory @@ -1148,7 +1147,7 @@ function regenerate_pmtable_classes($args, $opts) CLI::logging("> Updating generated class files for PM Tables...\n"); Bootstrap::setConstantsRelatedWs($args[0]); - $workspaceTools = new workspaceTools($args[0]); + $workspaceTools = new WorkspaceTools($args[0]); $workspaceTools->fixReferencePathFiles(PATH_DATA_SITE . "classes", PATH_DATA); $stop = microtime(true); diff --git a/workflow/engine/bin/verify_solr.php b/workflow/engine/bin/verify_solr.php index e1debf6a2..5cb5110ac 100644 --- a/workflow/engine/bin/verify_solr.php +++ b/workflow/engine/bin/verify_solr.php @@ -26,6 +26,8 @@ // php reindex_solr.php workspacename [reindexall|reindexmissing|optimizeindex] [-skip 1005] [-reindextrunksize 1000] // var_dump($argv); //(count ($argv) == 4) || ((count ($argv) == 5) && ($argv [3] != '-skip')) +use ProcessMaker\Core\System; + $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: ". @@ -117,7 +119,7 @@ if (! defined ('SYS_SYS')) { // **************************************** // read initialize file require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; - $config = PmSystem::getSystemConfiguration ('', '', SYS_SYS); + $config = System::getSystemConfiguration ('', '', SYS_SYS); define ('MEMCACHED_ENABLED', $config ['memcached']); define ('MEMCACHED_SERVER', $config ['memcached_server']); define ('TIME_ZONE', $config ['time_zone']); @@ -335,7 +337,7 @@ function displayMissingCases($aAppUidsDB, $aAppUidsSolr) function getListUids($usrUid, $action) { - if (($solrConf = PmSystem::solrEnv (SYS_SYS)) !== false) { + if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; diff --git a/workflow/engine/classes/class.actionsByEmailCore.php b/workflow/engine/classes/ActionsByEmailCoreClass.php similarity index 98% rename from workflow/engine/classes/class.actionsByEmailCore.php rename to workflow/engine/classes/ActionsByEmailCoreClass.php index 0a1cea35f..88c11bafe 100644 --- a/workflow/engine/classes/class.actionsByEmailCore.php +++ b/workflow/engine/classes/ActionsByEmailCoreClass.php @@ -1,7 +1,8 @@ label = ''; $actionField = str_replace(array('@@', '@#', '@=', '@%', '@?', '@$'), '', $configuration['ABE_ACTION_FIELD']); - $obj = new pmDynaform($configuration['DYN_UID']); + $obj = new PmDynaform($configuration['DYN_UID']); $configuration['CURRENT_DYNAFORM'] = $configuration['DYN_UID']; $file = $obj->printPmDynaformAbe($configuration); $__ABE__ .= $file; @@ -221,7 +222,7 @@ class actionsByEmailCoreClass extends PMPlugin } } - $obj = new pmDynaform($configuration['DYN_UID']); + $obj = new PmDynaform($configuration['DYN_UID']); $configuration['CURRENT_DYNAFORM'] = $configuration['DYN_UID']; $file = $obj->printPmDynaformAbe($configuration); $__ABE__ .= $file; @@ -290,7 +291,7 @@ class actionsByEmailCoreClass extends PMPlugin } } - $wsBaseInstance = new wsBase(); + $wsBaseInstance = new WsBase(); $result = $wsBaseInstance->sendMessage( $data->APP_UID, $emailFrom, @@ -333,4 +334,3 @@ class actionsByEmailCoreClass extends PMPlugin } } } - diff --git a/workflow/engine/classes/class.AppDocumentDrive.php b/workflow/engine/classes/AppDocumentDrive.php similarity index 99% rename from workflow/engine/classes/class.AppDocumentDrive.php rename to workflow/engine/classes/AppDocumentDrive.php index 33718c428..81d62ea9e 100644 --- a/workflow/engine/classes/class.AppDocumentDrive.php +++ b/workflow/engine/classes/AppDocumentDrive.php @@ -1,13 +1,17 @@ drive = new PMDrive(); + $this->drive = new PmDrive(); $status = $this->drive->getServiceDriveStatus(); $status = !empty($status) ? ($status == 1 ? true : false): false; $this->usersEmail = ''; diff --git a/workflow/engine/classes/AppSolr.php b/workflow/engine/classes/AppSolr.php new file mode 100644 index 000000000..b45e8a4c3 --- /dev/null +++ b/workflow/engine/classes/AppSolr.php @@ -0,0 +1,2830 @@ +_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() + { + $searchIndex = new BpmnEngineServicesSearchIndex($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."; + + 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' + ); */ + + $columsToInclude = array( + 'APP_PRO_TITLE', + 'APP_TITLE', + 'APP_UID', + 'DEL_MAX_PRIORITY' + ); + + // 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_STATUS': + $sortCols [0] = 'APP_STATUS'; //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); + + $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'; + } + } + // Paused, add condition + if ($userUid != null && $action == 'paused') { + $solrSearchText .= "APP_PAUSED_USERS:" . $userUid . ' AND '; + $delegationIndexes[] = "APP_PAUSED_USER_DEL_INDEX_" . trim($userUid) . '_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 "; + } + + //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 = EntitySolrRequestData::createForRequestPagination($data); + // use search index to return list of cases + $searchIndex = new BpmnEngineServicesSearchIndex($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; + + //var_dump($solrQueryResult->aaData); die; + //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 (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 + //$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 date('Y-m-d H:i:s:u') . " Delegation not defined\n"; + } + /* + elseif ($action == 'unassigned'){ + $delIndexes = $this->getApplicationDelegationsIndex ($appUID); + } */ + } + //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 + } + + //var_dump($aRow); + + // 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 + )); + $row = ''; + foreach ($indexes as $index) { + $row = $aaappsDBData [$index]; + } + + if (empty($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']; + + $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; + } + } + $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']; + $data = $this->getAppGridData($userUid, 0, 0, 'paused', null, null, null, null, null, null, null, null, null, null, null, true); + $casesCount ['paused'] = $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', TaskPeer::TAS_TITLE); + $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('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); + + $c->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID); + + $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); + + $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', TaskPeer::TAS_TITLE); + $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('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); + + $c->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID); + + $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); + + $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 + + $searchIndex = new BpmnEngineServicesSearchIndex($this->_solrIsEnabled, $this->_solrHost); + // execute query + $ListFieldsInfo = $searchIndex->getIndexFields($this->_solrInstance); + + $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] + $result1 = strpos($searchText, '-'); + if ($result1 !== false) { + $result2 = strpos($searchText, 'TO'); + if ($result2 !== false) { + $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 != '*') { + $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 { + $searchText = str_replace("[", "", $searchText); + $searchText = str_replace("]", "", $searchText); + $searchText = str_replace(":", "", $searchText); + $searchText = ":[" . $searchText . "T00:00:00Z TO " . $searchText . "T23:59:59.999Z]"; + } + } + } + + // validate phrase in case of < and <= + $result1 = strpos($searchText, '<'); + if ($result1 !== false) { + $result = strpos($searchText, '<='); + if ($result !== false) { + $v1 = str_replace('<=', '', $searchText); + $v2 = str_replace(':', '', $v1); + $v3 = str_replace('<', '', ':[* TO ' . $v2 . ']'); + $searchText = $v3; + } else { + $v1 = str_replace('<', '', $searchText); + $v2 = str_replace(':', '', $v1); + $v3 = (int) $v2 - 1; + $v4 = str_replace('<', '', ':[* TO ' . $v3 . ']'); + $searchText = $v4; + } + } + // validate phrase in case of > and >= + $result2 = strpos($searchText, '>'); + if ($result2 !== false) { + $result = strpos($searchText, '>='); + if ($result !== false) { + $v1 = str_replace('>=', '', $searchText); + $v2 = str_replace(':', '', $v1); + $v3 = str_replace('>', '', ':[' . $v2 . ' TO *]'); + $searchText = $v3; + } else { + $v1 = str_replace('>', '', $searchText); + $v2 = str_replace(':', '', $v1); + $v3 = (int) $v2 + 1; + $v4 = str_replace('>', '', ':[' . $v3 . ' TO *]'); + $searchText = $v4; + } + } + $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(); + } + + //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 = EntitySolrUpdateDocument::createForRequest($data); + + $oSearchIndex = new BpmnEngineServicesSearchIndex($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 { + $oSearchIndex = new BpmnEngineServicesSearchIndex($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]; + $pausedtUser = $result [14]; + + try { + + // create document + $xmlCurrentDoc = $this->buildSearchIndexDocumentPMOS2($documentInformation, $dynaformFieldTypes, $lastUpdateDate, $maxPriority, $delLastIndex, $assignedUsers, $assignedUsersRead, $assignedUsersUnread, $draftUser, $participatedUsers, $participatedUsersStartedByUser, $participatedUsersCompletedByUser, $unassignedUsers, $unassignedGroups, $pausedtUser); + + //concat doc to the list of docs + $xmlDoc .= $xmlCurrentDoc; + + if ($this->debug) { + $this->afterBuilXMLDocTime = microtime(true); + + $this->getBuilXMLDocTime += $this->afterBuilXMLDocTime - $this->afterPrepareApplicationDataDBTime; + } + } catch (ApplicationAppDataUnserializeException $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, $pausedtUser) + { + // 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(); + } + } + if (!empty($pausedtUser)) { + foreach ($pausedtUser as $paused) { + $writer->startElement("field"); + $writer->writeAttribute('name', 'APP_PAUSED_USERS'); + $writer->text($paused ['USR_UID']); + $writer->endElement(); + + $writer->startElement("field"); + $writer->writeAttribute('name', 'APP_PAUSED_USER_DEL_INDEX_' . trim($paused ['USR_UID']) . '_txt'); + $writer->text($paused ['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 ApplicationAppDataUnserializeException(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) { + //This validation is only for the 'checkbox' control for the BPMN forms, + //the request is not made to the database to obtain the control + //associated with the variable so as not to decrease the performance. + if (is_array($value) && count($value) === 1 && isset($value[0]) && !is_object($value[0]) && !is_array($value[0])) { + $value = $value[0]; + } + 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 = str_replace(',', '', $value); + $value = intval($value); + } + break; + case 'Real': + $typeSufix = '_td'; + $value = str_replace(',', '', $value); + $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 != '*') { + $value = trim($value); + $pairs = array( + "\x03" => "", + "\x04" => "", + "\x05" => "", + "\x06" => "", + "\x07" => "", + "\x08" => "", + "\x0E" => "", + "\x16" => "", + "\x00-" => "", + "\x09" => "", + "\x11" => "", + "\x12" => "", + "\x14-" => "", + "\x1f" => "", + "\x7f" => "", + ); + $value = strtr($value, $pairs); + $writer->startElement("field"); + $writer->writeAttribute('name', trim($k) . $typeSufix); + $writer->startCData(); + $writer->text($value); + $writer->endCData(); + $writer->endElement(); + } + } else { + $value = trim($value); + $pairs = array( + "\x03" => "", + "\x04" => "", + "\x05" => "", + "\x06" => "", + "\x07" => "", + "\x08" => "", + "\x0E" => "", + "\x16" => "", + "\x00-" => "", + "\x09" => "", + "\x11" => "", + "\x12" => "", + "\x14-" => "", + "\x1f" => "", + "\x7f" => "", + ); + $value = strtr($value, $pairs); + $writer->startElement("field"); + $writer->writeAttribute('name', trim($k) . '_t'); + $writer->startCData(); + $writer->text($value); + $writer->endCData(); + $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) + { + // 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' + 'APP_TYPE' => '' + )); + 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'] + ); + } + + $pausedUsers = array(); + $indexes = $this->aaSearchRecords($allAppDbData, array( + 'APP_TYPE' => 'PAUSE' + )); + foreach ($indexes as $index) { + if ($allAppDbData [$index] ['APP_DISABLE_ACTION_USER'] == null || $allAppDbData [$index] ['APP_DISABLE_ACTION_USER'] == 0) { + $pausedUsers [] = 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) { + $dynaformFileNames = $this->getProcessDynaformFileNames($documentInformation ['PRO_UID']); + $dynaformFields = array(); + foreach ($dynaformFileNames as $dynaformFileName) { + if (is_file(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') && + filesize(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') > 0) { + $dyn = new DynaformHandler(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml'); + $dynaformFields [] = $dyn->getFields(); + } + if (is_file(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') && + filesize(PATH_DYNAFORM . $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'); + } + } + } + $dynaformFieldTypes = $this->getVariablesDynaform($documentInformation['PRO_UID'], $dynaformFieldTypes); + // 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, + $draftUser, + $participatedUsers, + $participatedUsersStartedByUser, + $participatedUsersCompletedByUser, + $unassignedUsers, + $unassignedGroups, + $pausedUsers + ); + + return $result; + } + + /** + * + * + * @param array $dynaformFieldTypes + * @return array + */ + public function getVariablesDynaform($processUid, $dynaformFieldTypes = array()) + { + $criteria = new Criteria(); + $criteria->add(ProcessVariablesPeer::PRJ_UID, $processUid); + $ds = ProcessVariablesPeer::doSelectRS($criteria); + $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); + while ($ds->next()) { + $row = $ds->getRow(); + $type = "text"; + if ($row["VAR_FIELD_TYPE"] === "datetime") { + $type = "date"; + } + $dynaformFieldTypes[$row["VAR_NAME"]] = $type; + } + return $dynaformFieldTypes; + } + + /** + * 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(); + $isEqual = true; + foreach ($arr as $i => $row) { + $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; + } + } + 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_TITLE); + $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->addSelectColumn(ProcessPeer::PRO_TITLE); + + $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('ad', 'APP_DELEGATION'); + $c->addAlias('at', 'APP_THREAD'); + + $c->addJoin(ApplicationPeer::PRO_UID, ProcessPeer::PRO_UID, 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(); + } + + //Propel::close(); + + 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_TITLE); + $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->addSelectColumn('pro.PRO_TITLE'); + + $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('ade.APP_DELAY_UID'); + $c->addSelectColumn('ade.APP_TYPE'); + $c->addSelectColumn('ade.APP_DISABLE_ACTION_USER'); + + $c->addAsColumn("PRO_CATEGORY_UID", "pro.PRO_CATEGORY"); + + $c->addAlias('ad', 'APP_DELEGATION'); + $c->addAlias('at', 'APP_THREAD'); + $c->addAlias('ade', 'APP_DELAY'); + $c->addAlias("pro", ProcessPeer::TABLE_NAME); + + $c->addJoin(ApplicationPeer::PRO_UID, ProcessPeer::PRO_UID, 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); + + $aConditions = array(); + $aConditions [] = array( + 'ad.APP_UID', + 'ade.APP_UID' + ); + $aConditions [] = array( + 'ad.DEL_INDEX', + 'ade.APP_DEL_INDEX' + ); + //$aConditions [] = array ( + // 'ade.APP_DISABLE_ACTION_USER', + // DBAdapter::getStringDelimiter () . 'null' . DBAdapter::getStringDelimiter () + //); + $aConditions [] = array( + 'ade.APP_DISABLE_ACTION_USER', + DBAdapter::getStringDelimiter() . '0' . DBAdapter::getStringDelimiter() + ); + $aConditions [] = array( + 'ade.APP_TYPE', + DBAdapter::getStringDelimiter() . 'PAUSE' . DBAdapter::getStringDelimiter() + ); + $c->addJoinMC($aConditions, 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); + + $rs->next(); + $row = $rs->getRow(); + + while (is_array($row)) { + $allAppDbData [] = $row; + $rs->next(); + $row = $rs->getRow(); + } + //Propel::close(); + + 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(); + + 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(); + + 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); + + $oAppSolrQueue = new AppSolrQueue(); + + $oAppSolrQueue->createUpdate($AppUid, $traceData, $updated); + } + + private function getCurrentTraceInfo() + { + $resultTraceString = ""; + $traceData = debug_backtrace(); + foreach ($traceData as $key => $value) { + if ($value['function'] != 'getCurrentTraceInfo' && $value['function'] != 'require_once') { + if (isset($value['file']) && isset($value['line']) && isset($value['function'])) { + $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(); + + $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); + } + } + + $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); + + $this->updateApplicationSearchIndex($trunkUpdatedApplications, true); + + /* foreach($trunkUpdatedApplications as $appUid){ + $this->applicationChangedUpdateSolrQueue ($appUid, 0); + } */ + } + + $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); + + $this->deleteApplicationSearchIndex($trunkDeleteddApplications, true); + + /* 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() + { + $searchIndex = new BpmnEngineServicesSearchIndex($this->_solrIsEnabled, $this->_solrHost); + // execute query + $count = $searchIndex->getNumberDocuments($this->_solrInstance); + + return $count; + } + + /** + * Optimize the records in search index + * + * @return + */ + public function optimizeSearchIndex() + { + $searchIndex = new BpmnEngineServicesSearchIndex($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(); + } + + //Propel::close(); + + 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; + + 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"); + } +} diff --git a/workflow/engine/classes/ApplicationAppDataUnserializeException.php b/workflow/engine/classes/ApplicationAppDataUnserializeException.php new file mode 100644 index 000000000..91a6a0356 --- /dev/null +++ b/workflow/engine/classes/ApplicationAppDataUnserializeException.php @@ -0,0 +1,24 @@ +code}]: {$this->message}\n"; + } +} diff --git a/workflow/engine/classes/ApplicationWithCorruptDynaformException.php b/workflow/engine/classes/ApplicationWithCorruptDynaformException.php new file mode 100644 index 000000000..886ee4dae --- /dev/null +++ b/workflow/engine/classes/ApplicationWithCorruptDynaformException.php @@ -0,0 +1,27 @@ +code}]: {$this->message}\n"; + } +} diff --git a/workflow/engine/classes/ApplicationWithoutDelegationRecordsException.php b/workflow/engine/classes/ApplicationWithoutDelegationRecordsException.php new file mode 100644 index 000000000..dfcf2b9be --- /dev/null +++ b/workflow/engine/classes/ApplicationWithoutDelegationRecordsException.php @@ -0,0 +1,21 @@ +code}]: {$this->message}\n"; + } +} diff --git a/workflow/engine/classes/class.applications.php b/workflow/engine/classes/Applications.php similarity index 100% rename from workflow/engine/classes/class.applications.php rename to workflow/engine/classes/Applications.php index 39b1e1fb5..9196779b6 100644 --- a/workflow/engine/classes/class.applications.php +++ b/workflow/engine/classes/Applications.php @@ -2,6 +2,7 @@ use ProcessMaker\Plugins\PluginRegistry; + class Applications { /** @@ -1213,4 +1214,3 @@ class Applications return $steps; } } - diff --git a/workflow/engine/classes/Archive.php b/workflow/engine/classes/Archive.php new file mode 100644 index 000000000..c73f6d248 --- /dev/null +++ b/workflow/engine/classes/Archive.php @@ -0,0 +1,365 @@ +options = array('basedir' => ".", 'name' => $name, 'prepend' => "", 'inmemory' => 0, 'overwrite' => 0, 'recurse' => 1, 'storepaths' => 1, 'followlinks' => 0, 'level' => 3, 'method' => 1, 'sfx' => "", 'type' => "", 'comment' => "" + ); + $this->files = array(); + $this->exclude = array(); + $this->storeonly = array(); + $this->error = array(); + } + + /** + * This function gives options to a archive + * + * @param array $options + * @return void + */ + public function set_options($options) + { + foreach ($options as $key => $value) { + $this->options[$key] = $value; + } + if (!empty($this->options['basedir'])) { + $this->options['basedir'] = str_replace("\\", "/", $this->options['basedir']); + $this->options['basedir'] = preg_replace("/\/+/", "/", $this->options['basedir']); + $this->options['basedir'] = preg_replace("/\/$/", "", $this->options['basedir']); + } + if (!empty($this->options['name'])) { + $this->options['name'] = str_replace("\\", "/", $this->options['name']); + $this->options['name'] = preg_replace("/\/+/", "/", $this->options['name']); + } + if (!empty($this->options['prepend'])) { + $this->options['prepend'] = str_replace("\\", "/", $this->options['prepend']); + $this->options['prepend'] = preg_replace("/^(\.*\/+)+/", "", $this->options['prepend']); + $this->options['prepend'] = preg_replace("/\/+/", "/", $this->options['prepend']); + $this->options['prepend'] = preg_replace("/\/$/", "", $this->options['prepend']) . "/"; + } + } + + /** + * This function is used to create a archive. + * + * @return boolean + */ + public function create_archive() + { + $this->make_list(); + if ($this->options['inmemory'] == 0) { + $pwd = getcwd(); + chdir($this->options['basedir']); + if ($this->options['overwrite'] == 0 && file_exists($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""))) { + $this->error[] = "File {$this->options['name']} already exist."; + chdir($pwd); + return 0; + } elseif ($this->archive = @fopen($this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""), "wb+")) { + chdir($pwd); + } else { + $this->error[] = "Could not open {$this->options['name']} for writing."; + chdir($pwd); + return 0; + } + } else { + $this->archive = ""; + } + switch ($this->options['type']) { + case "zip": + if (!$this->create_zip()) { + $this->error[] = "Could not create zip file."; + return 0; + } + break; + case "bzip": + if (!$this->create_tar()) { + $this->error[] = "Could not create tar file."; + return 0; + } + if (!$this->create_bzip()) { + $this->error[] = "Could not create bzip2 file."; + return 0; + } + break; + case "gzip": + if (!$this->create_tar()) { + $this->error[] = "Could not create tar file."; + return 0; + } + if (!$this->create_gzip()) { + $this->error[] = "Could not create gzip file."; + return 0; + } + break; + case "tar": + if (!$this->create_tar()) { + $this->error[] = "Could not create tar file."; + return 0; + } + } + if ($this->options['inmemory'] == 0) { + fclose($this->archive); + if ($this->options['type'] == "gzip" || $this->options['type'] == "bzip") { + unlink($this->options['basedir'] . "/" . $this->options['name'] . ".tmp"); + } + } + } + + /** + * This function is used for add data to a archive + * + * @param string $data + * @return void + */ + public function add_data($data) + { + if ($this->options['inmemory'] == 0) { + fwrite($this->archive, $data); + } else { + $this->archive .= $data; + } + } + + /** + * This function make a list + * + * @return void + */ + public function make_list() + { + if (!empty($this->exclude)) { + foreach ($this->files as $key => $value) { + foreach ($this->exclude as $current) { + if ($value['name'] == $current['name']) { + unset($this->files[$key]); + } + } + } + } + if (!empty($this->storeonly)) { + foreach ($this->files as $key => $value) { + foreach ($this->storeonly as $current) { + if ($value['name'] == $current['name']) { + $this->files[$key]['method'] = 0; + } + } + } + } + unset($this->exclude, $this->storeonly); + } + + /** + * Add files a list + * + * @param array $list + * @return void + */ + public function add_files($list) + { + $temp = $this->list_files($list); + foreach ($temp as $current) { + $this->files[] = $current; + } + } + + /** + * This function exclude files of a list + * + * @param array $list + * @return void + */ + public function exclude_files($list) + { + $temp = $this->list_files($list); + foreach ($temp as $current) { + $this->exclude[] = $current; + } + } + + /** + * This function store files + * + * @param array $list + */ + public function store_files($list) + { + $temp = $this->list_files($list); + foreach ($temp as $current) { + $this->storeonly[] = $current; + } + } + + /** + * List files gives a List + * + * @param array $list + * @return array + */ + public function list_files($list) + { + if (!is_array($list)) { + $temp = $list; + $list = array($temp + ); + unset($temp); + } + $files = array(); + $pwd = getcwd(); + chdir($this->options['basedir']); + foreach ($list as $current) { + $current = str_replace("\\", "/", $current); + $current = preg_replace("/\/+/", "/", $current); + $current = preg_replace("/\/$/", "", $current); + if (strstr($current, "*")) { + $regex = preg_replace("/([\\\^\$\.\[\]\|\(\)\?\+\{\}\/])/", "\\\\\\1", $current); + $regex = str_replace("*", ".*", $regex); + $dir = strstr($current, "/") ? substr($current, 0, strrpos($current, "/")) : "."; + $temp = $this->parse_dir($dir); + foreach ($temp as $current2) { + if (preg_match("/^{$regex}$/i", $current2['name'])) { + $files[] = $current2; + } + } + unset($regex, $dir, $temp, $current); + } elseif (@is_dir($current)) { + $temp = $this->parse_dir($current); + foreach ($temp as $file) { + $files[] = $file; + } + unset($temp, $file); + } elseif (@file_exists($current)) { + $files[] = array('name' => $current, 'name2' => $this->options['prepend'] . preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($current, "/")) ? substr($current, strrpos($current, "/") + 1) : $current), 'type' => @is_link($current) && $this->options['followlinks'] == 0 ? 2 : 0, 'ext' => substr($current, strrpos($current, ".")), 'stat' => stat($current) + ); + } + } + chdir($pwd); + unset($current, $pwd); + usort($files, array("archive", "sort_files" + )); + return $files; + } + + /** + * This function is for parse a directory name + * + * @param string $dirname + * @return array + */ + public function parse_dir($dirname) + { + if ($this->options['storepaths'] == 1 && !preg_match("/^(\.+\/*)+$/", $dirname)) { + $files = array(array('name' => $dirname, 'name2' => $this->options['prepend'] . preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($dirname, "/")) ? substr($dirname, strrpos($dirname, "/") + 1) : $dirname), 'type' => 5, 'stat' => stat($dirname) + ) + ); + } else { + $files = array(); + } + $dir = @opendir($dirname); + while ($file = @readdir($dir)) { + $fullname = $dirname . "/" . $file; + if ($file == "." || $file == "..") { + continue; + } elseif (@is_dir($fullname)) { + if (empty($this->options['recurse'])) { + continue; + } + $temp = $this->parse_dir($fullname); + foreach ($temp as $file2) { + $files[] = $file2; + } + } elseif (@file_exists($fullname)) { + $files[] = array('name' => $fullname, 'name2' => $this->options['prepend'] . preg_replace("/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr($fullname, "/")) ? substr($fullname, strrpos($fullname, "/") + 1) : $fullname), 'type' => @is_link($fullname) && $this->options['followlinks'] == 0 ? 2 : 0, 'ext' => substr($file, strrpos($file, ".")), 'stat' => stat($fullname) + ); + } + } + @closedir($dir); + return $files; + } + + /** + * This function sort two files + * + * @param array $a + * @param array $b + * @return boolean + */ + public function sort_files($a, $b) + { + if ($a['type'] != $b['type']) { + if ($a['type'] == 5 || $b['type'] == 2) { + return -1; + } elseif ($a['type'] == 2 || $b['type'] == 5) { + return 1; + } elseif ($a['type'] == 5) { + return strcmp(strtolower($a['name']), strtolower($b['name'])); + } elseif ($a['ext'] != $b['ext']) { + return strcmp($a['ext'], $b['ext']); + } elseif ($a['stat'][7] != $b['stat'][7]) { + return $a['stat'][7] > $b['stat'][7] ? -1 : 1; + } else { + return strcmp(strtolower($a['name']), strtolower($b['name'])); + } + } + return 0; + } + + /** + * This function download a file + * + * @return void + */ + public function download_file() + { + if ($this->options['inmemory'] == 0) { + $this->error[] = "Can only use download_file() if archive is in memory. Redirect to file otherwise, it is faster."; + return; + } + switch ($this->options['type']) { + case "zip": + header("Content-Type: application/zip"); + break; + case "bzip": + header("Content-Type: application/x-bzip2"); + break; + case "gzip": + header("Content-Type: application/x-gzip"); + break; + case "tar": + header("Content-Type: application/x-tar"); + } + $header = "Content-Disposition: attachment; filename=\""; + $header .= strstr($this->options['name'], "/") ? substr($this->options['name'], strrpos($this->options['name'], "/") + 1) : $this->options['name']; + $header .= "\""; + header($header); + header("Content-Length: " . strlen($this->archive)); + header("Content-Transfer-Encoding: binary"); + header("Cache-Control: no-cache, must-revalidate, max-age=60"); + header("Expires: Sat, 01 Jan 2000 12:00:00 GMT"); + print ($this->archive); + } +} diff --git a/workflow/engine/classes/class.ArrayPeer.php b/workflow/engine/classes/ArrayBasePeer.php similarity index 62% rename from workflow/engine/classes/class.ArrayPeer.php rename to workflow/engine/classes/ArrayBasePeer.php index d33ecf53d..e63d132eb 100644 --- a/workflow/engine/classes/class.ArrayPeer.php +++ b/workflow/engine/classes/ArrayBasePeer.php @@ -1,34 +1,6 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ require_once 'propel/util/BasePeer.php'; -// The object class -- needed for instanceof checks in this class. -// actual class may be a subclass -- as returned by ApplicationPeer::getOMClass() -include_once 'classes/model/Application.php'; /** * Base static class for performing query and update operations on the 'APPLICATION' table. @@ -37,18 +9,11 @@ include_once 'classes/model/Application.php'; */ abstract class ArrayBasePeer { - /** * The default database name for this class */ const DATABASE_NAME = 'dbarray'; - /** - * The table name for this class - */ - //const TABLE_NAME = 'APPLICATION'; - - /** * A class that can be returned by this peer. */ @@ -150,10 +115,10 @@ abstract class ArrayBasePeer * First dimension keys are the type constants * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ - private static $fieldNames = array (BasePeer::TYPE_PHPNAME => array ('AppUid','AppNumber','AppParent','AppStatus','ProUid','AppProcStatus','AppProcCode','AppParallel','AppInitUser','AppCurUser','AppCreateDate','AppInitDate','AppFinishDate','AppUpdateDate','AppData' - ),BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID,ApplicationPeer::APP_NUMBER,ApplicationPeer::APP_PARENT,ApplicationPeer::APP_STATUS,ApplicationPeer::PRO_UID,ApplicationPeer::APP_PROC_STATUS,ApplicationPeer::APP_PROC_CODE,ApplicationPeer::APP_PARALLEL,ApplicationPeer::APP_INIT_USER,ApplicationPeer::APP_CUR_USER,ApplicationPeer::APP_CREATE_DATE,ApplicationPeer::APP_INIT_DATE,ApplicationPeer::APP_FINISH_DATE,ApplicationPeer::APP_UPDATE_DATE,ApplicationPeer::APP_DATA - ),BasePeer::TYPE_FIELDNAME => array ('APP_UID','APP_NUMBER','APP_PARENT','APP_STATUS','PRO_UID','APP_PROC_STATUS','APP_PROC_CODE','APP_PARALLEL','APP_INIT_USER','APP_CUR_USER','APP_CREATE_DATE','APP_INIT_DATE','APP_FINISH_DATE','APP_UPDATE_DATE','APP_DATA' - ),BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 + private static $fieldNames = array(BasePeer::TYPE_PHPNAME => array('AppUid', 'AppNumber', 'AppParent', 'AppStatus', 'ProUid', 'AppProcStatus', 'AppProcCode', 'AppParallel', 'AppInitUser', 'AppCurUser', 'AppCreateDate', 'AppInitDate', 'AppFinishDate', 'AppUpdateDate', 'AppData' + ), BasePeer::TYPE_COLNAME => array(ApplicationPeer::APP_UID, ApplicationPeer::APP_NUMBER, ApplicationPeer::APP_PARENT, ApplicationPeer::APP_STATUS, ApplicationPeer::PRO_UID, ApplicationPeer::APP_PROC_STATUS, ApplicationPeer::APP_PROC_CODE, ApplicationPeer::APP_PARALLEL, ApplicationPeer::APP_INIT_USER, ApplicationPeer::APP_CUR_USER, ApplicationPeer::APP_CREATE_DATE, ApplicationPeer::APP_INIT_DATE, ApplicationPeer::APP_FINISH_DATE, ApplicationPeer::APP_UPDATE_DATE, ApplicationPeer::APP_DATA + ), BasePeer::TYPE_FIELDNAME => array('APP_UID', 'APP_NUMBER', 'APP_PARENT', 'APP_STATUS', 'PRO_UID', 'APP_PROC_STATUS', 'APP_PROC_CODE', 'APP_PARALLEL', 'APP_INIT_USER', 'APP_CUR_USER', 'APP_CREATE_DATE', 'APP_INIT_DATE', 'APP_FINISH_DATE', 'APP_UPDATE_DATE', 'APP_DATA' + ), BasePeer::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ) ); @@ -163,10 +128,10 @@ abstract class ArrayBasePeer * First dimension keys are the type constants * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ - private static $fieldKeys = array (BasePeer::TYPE_PHPNAME => array ('AppUid' => 0,'AppNumber' => 1,'AppParent' => 2,'AppStatus' => 3,'ProUid' => 4,'AppProcStatus' => 5,'AppProcCode' => 6,'AppParallel' => 7,'AppInitUser' => 8,'AppCurUser' => 9,'AppCreateDate' => 10,'AppInitDate' => 11,'AppFinishDate' => 12,'AppUpdateDate' => 13,'AppData' => 14 - ),BasePeer::TYPE_COLNAME => array (ApplicationPeer::APP_UID => 0,ApplicationPeer::APP_NUMBER => 1,ApplicationPeer::APP_PARENT => 2,ApplicationPeer::APP_STATUS => 3,ApplicationPeer::PRO_UID => 4,ApplicationPeer::APP_PROC_STATUS => 5,ApplicationPeer::APP_PROC_CODE => 6,ApplicationPeer::APP_PARALLEL => 7,ApplicationPeer::APP_INIT_USER => 8,ApplicationPeer::APP_CUR_USER => 9,ApplicationPeer::APP_CREATE_DATE => 10,ApplicationPeer::APP_INIT_DATE => 11,ApplicationPeer::APP_FINISH_DATE => 12,ApplicationPeer::APP_UPDATE_DATE => 13,ApplicationPeer::APP_DATA => 14 - ),BasePeer::TYPE_FIELDNAME => array ('APP_UID' => 0,'APP_NUMBER' => 1,'APP_PARENT' => 2,'APP_STATUS' => 3,'PRO_UID' => 4,'APP_PROC_STATUS' => 5,'APP_PROC_CODE' => 6,'APP_PARALLEL' => 7,'APP_INIT_USER' => 8,'APP_CUR_USER' => 9,'APP_CREATE_DATE' => 10,'APP_INIT_DATE' => 11,'APP_FINISH_DATE' => 12,'APP_UPDATE_DATE' => 13,'APP_DATA' => 14 - ),BasePeer::TYPE_NUM => array (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 + private static $fieldKeys = array(BasePeer::TYPE_PHPNAME => array('AppUid' => 0, 'AppNumber' => 1, 'AppParent' => 2, 'AppStatus' => 3, 'ProUid' => 4, 'AppProcStatus' => 5, 'AppProcCode' => 6, 'AppParallel' => 7, 'AppInitUser' => 8, 'AppCurUser' => 9, 'AppCreateDate' => 10, 'AppInitDate' => 11, 'AppFinishDate' => 12, 'AppUpdateDate' => 13, 'AppData' => 14 + ), BasePeer::TYPE_COLNAME => array(ApplicationPeer::APP_UID => 0, ApplicationPeer::APP_NUMBER => 1, ApplicationPeer::APP_PARENT => 2, ApplicationPeer::APP_STATUS => 3, ApplicationPeer::PRO_UID => 4, ApplicationPeer::APP_PROC_STATUS => 5, ApplicationPeer::APP_PROC_CODE => 6, ApplicationPeer::APP_PARALLEL => 7, ApplicationPeer::APP_INIT_USER => 8, ApplicationPeer::APP_CUR_USER => 9, ApplicationPeer::APP_CREATE_DATE => 10, ApplicationPeer::APP_INIT_DATE => 11, ApplicationPeer::APP_FINISH_DATE => 12, ApplicationPeer::APP_UPDATE_DATE => 13, ApplicationPeer::APP_DATA => 14 + ), BasePeer::TYPE_FIELDNAME => array('APP_UID' => 0, 'APP_NUMBER' => 1, 'APP_PARENT' => 2, 'APP_STATUS' => 3, 'PRO_UID' => 4, 'APP_PROC_STATUS' => 5, 'APP_PROC_CODE' => 6, 'APP_PARALLEL' => 7, 'APP_INIT_USER' => 8, 'APP_CUR_USER' => 9, 'APP_CREATE_DATE' => 10, 'APP_INIT_DATE' => 11, 'APP_FINISH_DATE' => 12, 'APP_UPDATE_DATE' => 13, 'APP_DATA' => 14 + ), BasePeer::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ) ); @@ -176,10 +141,10 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function getMapBuilder () + public static function getMapBuilder() { include_once 'classes/model/map/ApplicationMapBuilder.php'; - return BasePeer::getMapBuilder( 'classes.model.map.ApplicationMapBuilder' ); + return BasePeer::getMapBuilder('classes.model.map.ApplicationMapBuilder'); } /** @@ -190,12 +155,12 @@ abstract class ArrayBasePeer * rethrown wrapped into a PropelException. * @deprecated Use the getFieldNames() and translateFieldName() methods instead of this. */ - public static function getPhpNameMap () + public static function getPhpNameMap() { if (self::$phpNameMap === null) { $map = ApplicationPeer::getTableMap(); $columns = $map->getColumns(); - $nameMap = array (); + $nameMap = array(); foreach ($columns as $column) { $nameMap[$column->getPhpName()] = $column->getColumnName(); } @@ -213,12 +178,12 @@ abstract class ArrayBasePeer * @param string $toType One of the class type constants * @return string translated name of the field. */ - static public function translateFieldName ($name, $fromType, $toType) + static public function translateFieldName($name, $fromType, $toType) { - $toNames = self::getFieldNames( $toType ); - $key = isset( self::$fieldKeys[$fromType][$name] ) ? self::$fieldKeys[$fromType][$name] : null; + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; if ($key === null) { - throw new PropelException( "'$name' could not be found in the field names of type '$fromType'. These are: " . print_r( self::$fieldKeys[$fromType], true ) ); + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); } return $toNames[$key]; } @@ -232,10 +197,10 @@ abstract class ArrayBasePeer * @return array A list of field names */ - static public function getFieldNames ($type = BasePeer::TYPE_PHPNAME) + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) { - if (! array_key_exists( $type, self::$fieldNames )) { - throw new PropelException( 'Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.' ); + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.'); } return self::$fieldNames[$type]; } @@ -253,9 +218,9 @@ abstract class ArrayBasePeer * @param string $column The column name for current table. (i.e. ApplicationPeer::COLUMN_NAME). * @return string */ - public static function alias ($alias, $column) + public static function alias($alias, $column) { - return str_replace( ApplicationPeer::TABLE_NAME . '.', $alias . '.', $column ); + return str_replace(ApplicationPeer::TABLE_NAME . '.', $alias . '.', $column); } /** @@ -269,7 +234,7 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function addSelectColumns (Criteria $criteria) + public static function addSelectColumns(Criteria $criteria) { } @@ -286,7 +251,7 @@ abstract class ArrayBasePeer * @return int Number of matching rows. * @todo Review declarated constant d'not used COUNT, COUNT_DISTINCT */ - public static function doCount (Criteria $criteria, $distinct = false, $con = null) + public static function doCount(Criteria $criteria, $distinct = false, $con = null) { // we're going to modify criteria, so copy it first $criteria = clone $criteria; @@ -301,14 +266,14 @@ abstract class ArrayBasePeer $criteria->addSelectColumn(ApplicationPeer::COUNT); } */ - $criteria->addSelectColumn( 'COUNT(*)' ); + $criteria->addSelectColumn('COUNT(*)'); // just in case we're grouping: add those columns to the select statement foreach ($criteria->getGroupByColumns() as $column) { - $criteria->addSelectColumn( $column ); + $criteria->addSelectColumn($column); } - $rs = ArrayBasePeer::doSelectRS( $criteria, $con ); + $rs = ArrayBasePeer::doSelectRS($criteria, $con); if ($rs->next()) { $row = $rs->getRow(); return $row[1]; @@ -327,11 +292,11 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelectOne (Criteria $criteria, $con = null) + public static function doSelectOne(Criteria $criteria, $con = null) { $critcopy = clone $criteria; - $critcopy->setLimit( 1 ); - $objects = ApplicationPeer::doSelect( $critcopy, $con ); + $critcopy->setLimit(1); + $objects = ApplicationPeer::doSelect($critcopy, $con); if ($objects) { return $objects[0]; } @@ -347,18 +312,18 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - private function createSelectSql ($criteria, $tableName, &$params) + private function createSelectSql($criteria, $tableName, &$params) { - $db = Propel::getDB( $criteria->getDbName() ); + $db = Propel::getDB($criteria->getDbName()); // redundant definition $selectModifiers = array(); - $selectClause = array (); - $fromClause = array (); - $joinClause = array (); - $joinTables = array (); - $whereClause = array (); - $orderByClause = array (); - $groupByClause = array (); + $selectClause = array(); + $fromClause = array(); + $joinClause = array(); + $joinTables = array(); + $whereClause = array(); + $orderByClause = array(); + $groupByClause = array(); $orderBy = $criteria->getOrderByColumns(); $groupBy = $criteria->getGroupByColumns(); @@ -376,8 +341,8 @@ abstract class ArrayBasePeer $selectClause[] = $columnName; // the full column name: e.g. MAX(books.price) - $parenPos = strpos( $columnName, '(' ); - $dotPos = strpos( $columnName, '.' ); + $parenPos = strpos($columnName, '('); + $dotPos = strpos($columnName, '.'); // [HL] I think we really only want to worry about adding stuff to // the fromClause if this function has a TABLE.COLUMN in it at all. @@ -386,18 +351,18 @@ abstract class ArrayBasePeer if ($dotPos !== false) { if ($parenPos === false) { // table.column - $tableName = substr( $columnName, 0, $dotPos ); + $tableName = substr($columnName, 0, $dotPos); } else { // FUNC(table.column) - $tableName = substr( $columnName, $parenPos + 1, $dotPos - ($parenPos + 1) ); + $tableName = substr($columnName, $parenPos + 1, $dotPos - ($parenPos + 1)); // functions may contain qualifiers so only take the last // word as the table name. // COUNT(DISTINCT books.price) - $lastSpace = strpos( $tableName, ' ' ); + $lastSpace = strpos($tableName, ' '); if ($lastSpace !== false) { // COUNT(DISTINCT books.price) - $tableName = substr( $tableName, $lastSpace + 1 ); + $tableName = substr($tableName, $lastSpace + 1); } } - $tableName2 = $criteria->getTableForAlias( $tableName ); + $tableName2 = $criteria->getTableForAlias($tableName); if ($tableName2 !== null) { $fromClause[] = $tableName2 . ' ' . $tableName; } else { @@ -415,13 +380,13 @@ abstract class ArrayBasePeer // add the criteria to WHERE clause foreach ($criteria->keys() as $key) { - $criterion = $criteria->getCriterion( $key ); + $criterion = $criteria->getCriterion($key); $someCriteria = $criterion->getAttachedCriterion(); - $someCriteriaLength = count( $someCriteria ); + $someCriteriaLength = count($someCriteria); $table = null; - for ($i = 0; $i < $someCriteriaLength; $i ++) { + for ($i = 0; $i < $someCriteriaLength; $i++) { $tableName = $someCriteria[$i]->getTable(); - $table = $criteria->getTableForAlias( $tableName ); + $table = $criteria->getTableForAlias($tableName); if ($table !== null) { $fromClause[] = $table . ' ' . $tableName; } else { @@ -429,11 +394,11 @@ abstract class ArrayBasePeer $table = $tableName; } - $ignoreCase = (($criteria->isIgnoreCase() || $someCriteria[$i]->isIgnoreCase()) && ($dbMap->getTable( $table )->getColumn( $someCriteria[$i]->getColumn() )->getType() == "string")); + $ignoreCase = (($criteria->isIgnoreCase() || $someCriteria[$i]->isIgnoreCase()) && ($dbMap->getTable($table)->getColumn($someCriteria[$i]->getColumn())->getType() == "string")); - $someCriteria[$i]->setIgnoreCase( $ignoreCase ); + $someCriteria[$i]->setIgnoreCase($ignoreCase); } - $criterion->setDB( $db ); + $criterion->setDB($db); $cri['table'] = $criterion->table; $cri['field'] = $criterion->column; @@ -449,41 +414,41 @@ abstract class ArrayBasePeer } // Unique from clause elements - $fromClause = array_unique( $fromClause ); + $fromClause = array_unique($fromClause); - if (! empty( $orderBy )) { + if (!empty($orderBy)) { foreach ($orderBy as $orderByColumn) { // Add function expression as-is. - if (strpos( $orderByColumn, '(' ) !== false) { + if (strpos($orderByColumn, '(') !== false) { $orderByClause[] = $orderByColumn; continue; } // Split orderByColumn (i.e. "table.column DESC") - $dotPos = strpos( $orderByColumn, '.' ); + $dotPos = strpos($orderByColumn, '.'); if ($dotPos !== false) { - $tableName = substr( $orderByColumn, 0, $dotPos ); - $columnName = substr( $orderByColumn, $dotPos + 1 ); + $tableName = substr($orderByColumn, 0, $dotPos); + $columnName = substr($orderByColumn, $dotPos + 1); } else { $tableName = ''; $columnName = $orderByColumn; } - $spacePos = strpos( $columnName, ' ' ); + $spacePos = strpos($columnName, ' '); if ($spacePos !== false) { - $direction = substr( $columnName, $spacePos ); - $columnName = substr( $columnName, 0, $spacePos ); + $direction = substr($columnName, $spacePos); + $columnName = substr($columnName, 0, $spacePos); } else { $direction = ''; } - $orderByClause[] = array ('columnName' => $columnName,'direction' => $direction + $orderByClause[] = array('columnName' => $columnName, 'direction' => $direction ); } } // Build the SQL from the arrays we compiled - $sql = "SELECT " . ($selectModifiers ? implode( " ", $selectModifiers ) . " " : "") . implode( ", ", $selectClause ) . " FROM " . $fromClause[0] . ($whereClause ? " WHERE " . implode( " AND ", $whereClause ) : "") . ($groupByClause ? " GROUP BY " . implode( ",", $groupByClause ) : ""); + $sql = "SELECT " . ($selectModifiers ? implode(" ", $selectModifiers) . " " : "") . implode(", ", $selectClause) . " FROM " . $fromClause[0] . ($whereClause ? " WHERE " . implode(" AND ", $whereClause) : "") . ($groupByClause ? " GROUP BY " . implode(",", $groupByClause) : ""); $dataSql['selectClause'] = $selectClause; $dataSql['fromClause'] = $fromClause; @@ -503,27 +468,27 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doSelect (Criteria $criteria, $tableName, $con = null) + public static function doSelect(Criteria $criteria, $tableName, $con = null) { - $dbMap = Propel::getDatabaseMap( $criteria->getDbName() ); + $dbMap = Propel::getDatabaseMap($criteria->getDbName()); $stmt = null; try { - $params = array (); - $sql = self::createSelectSql( $criteria, $tableName, $params ); + $params = array(); + $sql = self::createSelectSql($criteria, $tableName, $params); $sql['params'] = $params; - $stmt = $con->prepareStatement( $sql ); + $stmt = $con->prepareStatement($sql); //$stmt->setLimit($criteria->getLimit()); $sql['limit'] = $criteria->getLimit(); //$stmt->setOffset($criteria->getOffset()); $sql['offset'] = $criteria->getOffset(); //$rs = $stmt->executeQuery(ResultSet::FETCHMODE_NUM); - $rs = $con->executeQuery( $sql, ResultSet::FETCHMODE_NUM ); + $rs = $con->executeQuery($sql, ResultSet::FETCHMODE_NUM); } catch (Exception $e) { if ($stmt) $stmt->close(); - throw new PropelException( $e ); + throw new PropelException($e); } return $rs; @@ -543,34 +508,34 @@ abstract class ArrayBasePeer * @return ResultSet The resultset object with numerically-indexed fields. * @see BasePeer::doSelect() */ - public static function doSelectRS (Criteria $criteria, $con = null) + public static function doSelectRS(Criteria $criteria, $con = null) { global $_DBArray; - if (! isset( $_DBArray )) { + if (!isset($_DBArray)) { $_DBArray = $_SESSION['_DBArray']; } $tableName = $criteria->getDBArrayTable(); - if (! isset( $_DBArray[$tableName] )) { - throw new Exception( "Error: the table '$tableName' doesn't exist in DBArray " ); + if (!isset($_DBArray[$tableName])) { + throw new Exception("Error: the table '$tableName' doesn't exist in DBArray "); } $arrayTable = $_DBArray[$tableName]; if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } - if (! $criteria->getSelectColumns()) { - foreach (array_keys( $_DBArray[$tableName][0] ) as $key => $val) - $criteria->addSelectColumn( $tableName . '.' . $val ); + if (!$criteria->getSelectColumns()) { + foreach (array_keys($_DBArray[$tableName][0]) as $key => $val) + $criteria->addSelectColumn($tableName . '.' . $val); } // Set the correct dbName - $criteria->setDbName( self::DATABASE_NAME ); + $criteria->setDbName(self::DATABASE_NAME); // BasePeer returns a Creole ResultSet, set to return // rows indexed numerically. - return ArrayBasePeer::doSelect( $criteria, $tableName, $con ); + return ArrayBasePeer::doSelect($criteria, $tableName, $con); } /** @@ -580,17 +545,17 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function populateObjects (ResultSet $rs) + public static function populateObjects(ResultSet $rs) { - $results = array (); + $results = array(); // set the class once to avoid overhead in the loop $cls = ApplicationPeer::getOMClass(); - $cls = Propel::import( $cls ); + $cls = Propel::import($cls); // populate the object(s) while ($rs->next()) { $obj = new $cls(); - $obj->hydrate( $rs ); + $obj->hydrate($rs); $results[] = $obj; } return $results; @@ -604,9 +569,9 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function getTableMap () + public static function getTableMap() { - return Propel::getDatabaseMap( self::DATABASE_NAME )->getTable( self::TABLE_NAME ); + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); } /** @@ -618,7 +583,7 @@ abstract class ArrayBasePeer * * @return string path.to.ClassName */ - public static function getOMClass () + public static function getOMClass() { return ApplicationPeer::CLASS_DEFAULT; } @@ -632,10 +597,10 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doInsert ($values, $con = null) + public static function doInsert($values, $con = null) { if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } if ($values instanceof Criteria) { @@ -645,13 +610,13 @@ abstract class ArrayBasePeer } // Set the correct dbName - $criteria->setDbName( self::DATABASE_NAME ); + $criteria->setDbName(self::DATABASE_NAME); try { // use transaction because $criteria could contain info // for more than one table (I guess, conceivably) $con->begin(); - $pk = BasePeer::doInsert( $criteria, $con ); + $pk = BasePeer::doInsert($criteria, $con); $con->commit(); } catch (PropelException $e) { $con->rollback(); @@ -670,20 +635,20 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doUpdate ($values, $con = null) + public static function doUpdate($values, $con = null) { if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } - $selectCriteria = new Criteria( self::DATABASE_NAME ); + $selectCriteria = new Criteria(self::DATABASE_NAME); if ($values instanceof Criteria) { $criteria = clone $values; // rename for clarity - $comparison = $criteria->getComparison( ApplicationPeer::APP_UID ); - $selectCriteria->add( ApplicationPeer::APP_UID, $criteria->remove( ApplicationPeer::APP_UID ), $comparison ); + $comparison = $criteria->getComparison(ApplicationPeer::APP_UID); + $selectCriteria->add(ApplicationPeer::APP_UID, $criteria->remove(ApplicationPeer::APP_UID), $comparison); } else { // $values is Application object $criteria = $values->buildCriteria(); // gets full criteria @@ -691,9 +656,9 @@ abstract class ArrayBasePeer } // set the correct dbName - $criteria->setDbName( self::DATABASE_NAME ); + $criteria->setDbName(self::DATABASE_NAME); - return BasePeer::doUpdate( $selectCriteria, $criteria, $con ); + return BasePeer::doUpdate($selectCriteria, $criteria, $con); } /** @@ -702,17 +667,17 @@ abstract class ArrayBasePeer * @param Connection $con The connection to use * @return int The number of affected rows (if supported by underlying database driver). */ - public static function doDeleteAll ($con = null) + public static function doDeleteAll($con = null) { if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->begin(); - $affectedRows += BasePeer::doDeleteAll( ApplicationPeer::TABLE_NAME, $con ); + $affectedRows += BasePeer::doDeleteAll(ApplicationPeer::TABLE_NAME, $con); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -732,10 +697,10 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function doDelete ($values, $con = null) + public static function doDelete($values, $con = null) { if ($con === null) { - $con = Propel::getConnection( ApplicationPeer::DATABASE_NAME ); + $con = Propel::getConnection(ApplicationPeer::DATABASE_NAME); } if ($values instanceof Criteria) { @@ -745,12 +710,12 @@ abstract class ArrayBasePeer $criteria = $values->buildPkeyCriteria(); } else { // it must be the primary key - $criteria = new Criteria( self::DATABASE_NAME ); - $criteria->add( ApplicationPeer::APP_UID, (array) $values, Criteria::IN ); + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(ApplicationPeer::APP_UID, (array)$values, Criteria::IN); } } // Set the correct dbName - $criteria->setDbName( self::DATABASE_NAME ); + $criteria->setDbName(self::DATABASE_NAME); $affectedRows = 0; // initialize var to track total num of affected rows @@ -760,7 +725,7 @@ abstract class ArrayBasePeer // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->begin(); - $affectedRows += BasePeer::doDelete( $criteria, $con ); + $affectedRows += BasePeer::doDelete($criteria, $con); $con->commit(); return $affectedRows; } catch (PropelException $e) { @@ -781,33 +746,33 @@ abstract class ArrayBasePeer * * @return mixed TRUE if all columns are valid or the error message of the first invalid column. */ - public static function doValidate (Application $obj, $cols = null) + public static function doValidate(Application $obj, $cols = null) { - $columns = array (); + $columns = array(); if ($cols) { - $dbMap = Propel::getDatabaseMap( ApplicationPeer::DATABASE_NAME ); - $tableMap = $dbMap->getTable( ApplicationPeer::TABLE_NAME ); + $dbMap = Propel::getDatabaseMap(ApplicationPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(ApplicationPeer::TABLE_NAME); - if (! is_array( $cols )) { - $cols = array ($cols + if (!is_array($cols)) { + $cols = array($cols ); } foreach ($cols as $colName) { - if ($tableMap->containsColumn( $colName )) { - $get = 'get' . $tableMap->getColumn( $colName )->getPhpName(); + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); $columns[$colName] = $obj->$get(); } } } else { - if ($obj->isNew() || $obj->isColumnModified( ApplicationPeer::APP_STATUS )) + if ($obj->isNew() || $obj->isColumnModified(ApplicationPeer::APP_STATUS)) $columns[ApplicationPeer::APP_STATUS] = $obj->getAppStatus(); } - return BasePeer::doValidate( ApplicationPeer::DATABASE_NAME, ApplicationPeer::TABLE_NAME, $columns ); + return BasePeer::doValidate(ApplicationPeer::DATABASE_NAME, ApplicationPeer::TABLE_NAME, $columns); } /** @@ -817,19 +782,19 @@ abstract class ArrayBasePeer * @param Connection $con the connection to use * @return Application */ - public static function retrieveByPK ($pk, $con = null) + public static function retrieveByPK($pk, $con = null) { if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } - $criteria = new Criteria( ApplicationPeer::DATABASE_NAME ); + $criteria = new Criteria(ApplicationPeer::DATABASE_NAME); - $criteria->add( ApplicationPeer::APP_UID, $pk ); + $criteria->add(ApplicationPeer::APP_UID, $pk); - $v = ApplicationPeer::doSelect( $criteria, $con ); + $v = ApplicationPeer::doSelect($criteria, $con); - return ! empty( $v ) > 0 ? $v[0] : null; + return !empty($v) > 0 ? $v[0] : null; } /** @@ -840,38 +805,21 @@ abstract class ArrayBasePeer * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ - public static function retrieveByPKs ($pks, $con = null) + public static function retrieveByPKs($pks, $con = null) { if ($con === null) { - $con = Propel::getConnection( self::DATABASE_NAME ); + $con = Propel::getConnection(self::DATABASE_NAME); } $objs = null; - if (empty( $pks )) { - $objs = array (); + if (empty($pks)) { + $objs = array(); } else { $criteria = new Criteria(); - $criteria->add( ApplicationPeer::APP_UID, $pks, Criteria::IN ); - $objs = ApplicationPeer::doSelect( $criteria, $con ); + $criteria->add(ApplicationPeer::APP_UID, $pks, Criteria::IN); + $objs = ApplicationPeer::doSelect($criteria, $con); } return $objs; } } // BaseApplicationPeer - - -// static code to register the map builder for this Peer with the main Propel class -if (Propel::isInit()) { - // the MapBuilder classes register themselves with Propel during initialization - // so we need to load them here. - try { - BaseApplicationPeer::getMapBuilder(); - } catch (Exception $e) { - Propel::log( 'Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR ); - } -} else { - // even if Propel is not yet initialized, the map builder class can be registered - // now and then it will be loaded when Propel initializes. - require_once 'classes/model/map/ApplicationMapBuilder.php'; - Propel::registerMapBuilder( 'classes.model.map.ApplicationMapBuilder' ); -} diff --git a/workflow/engine/classes/BpmnEngineSearchIndexAccessSolr.php b/workflow/engine/classes/BpmnEngineSearchIndexAccessSolr.php new file mode 100644 index 000000000..40bb64346 --- /dev/null +++ b/workflow/engine/classes/BpmnEngineSearchIndexAccessSolr.php @@ -0,0 +1,601 @@ +_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; + // 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) + { + // get total number of documents in registry + $solrIntruct = (substr($this->_solrHost, -1) == "/") ? $this->_solrHost : $this->_solrHost . "/"; + $solrIntruct .= $workspace; + $solrIntruct .= "/select/?q=*:*"; + $solrIntruct .= self::SOLR_VERSION; + $solrIntruct .= "&start=0&rows=0&echoParams=none&wt=json"; + + $handlerTotal = curl_init($solrIntruct); + curl_setopt($handlerTotal, CURLOPT_RETURNTRANSFER, true); + + //Apply proxy settings + $sysConf = System::getSystemConfiguration(); + if ($sysConf['proxy_host'] != '') { + curl_setopt($handlerTotal, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); + if ($sysConf['proxy_port'] != '') { + curl_setopt($handlerTotal, CURLOPT_PROXYPORT, $sysConf['proxy_port']); + } + if ($sysConf['proxy_user'] != '') { + curl_setopt($handlerTotal, CURLOPT_PROXYUSERPWD, $sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : '')); + } + curl_setopt($handlerTotal, CURLOPT_HTTPHEADER, array('Expect:')); + } + + $responseTotal = curl_exec($handlerTotal); + curl_close($handlerTotal); + + // verify the result of solr + $responseSolrTotal = G::json_decode($responseTotal); + if ($responseSolrTotal->responseHeader->status != 0) { + throw new Exception(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) + { + $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); + + //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(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) + { + $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' + )); + 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(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) + { + $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' + )); + 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(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) + { + $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' + )); + 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(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) + { + $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' + )); + 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(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) + { + $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(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) + { + $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); + + //there's no response + if (!$response) { + return false; + } + + // 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; + } + + /** + * Delete all documents from index + * @gearman = false + * @rest = false + * @background = false + * + * @return solr response + */ + public function deleteAllDocuments($workspace) + { + $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' + )); + 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(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) + { + $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' + )); + 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(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 EntityFacetRequest $facetRequestEntity + * @return solr response: list of facets array + */ + public function getFacetsList($facetRequest) + { + $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; + } + + $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(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/BpmnEngineServicesSearchIndex.php b/workflow/engine/classes/BpmnEngineServicesSearchIndex.php new file mode 100644 index 000000000..5d6687f33 --- /dev/null +++ b/workflow/engine/classes/BpmnEngineServicesSearchIndex.php @@ -0,0 +1,346 @@ +_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('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('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 [] = EntitySelectedFacetGroupItem::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 + )); + } + + 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 = EntityFacetItem::createForInsert($dataItem); + $facetItems [] = $newFacetItem; + } + $data ['facetItems'] = $facetItems; + $newFacetGroup = EntityFacetGroup::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 = EntityFacetItem::createForInsert($dataItem); + $facetItems [] = $newFacetItem; + } + } + + $data ['facetItems'] = $facetItems; + $newFacetGroup = EntityFacetGroup::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); + + // Create result + $dataFacetResult = array( + 'aFacetGroups' => $facetGroups, + 'aSelectedFacetGroups' => $aSelectedFacetGroups, + 'sFilterText' => $filterText + ); + $facetResult = EntityFacetResult::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'); + $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) + { + $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) + { + $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) + { + $solr = new BpmnEngine_SearchIndexAccess_Solr($this->_solrIsEnabled, $this->_solrHost); + + // commit + $solr->commitChanges($workspace); + } + + /** + * Optimize index changes + * @param string $workspace + */ + public function optimizeIndexChanges($workspace) + { + $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 EntitySolrQueryResult + */ + public function getDataTablePaginatedList($solrRequestData) + { + require_once('class.solr.php'); + require_once('entities/SolrRequestData.php'); + require_once('entities/SolrQueryResult.php'); + + // 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; + + // 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 = EntitySolrQueryResult::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); + + $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); + + // Maintain case sensitive variable names + $listFields [$originalFieldName] = $key; + } else { + // Maintain case sensitive variable names + $listFields [$key] = $key; + } + } + + return $listFields; + } +} diff --git a/workflow/engine/classes/BzipFile.php b/workflow/engine/classes/BzipFile.php new file mode 100644 index 000000000..4cf6414cf --- /dev/null +++ b/workflow/engine/classes/BzipFile.php @@ -0,0 +1,59 @@ +tar_file($name); + $this->options['type'] = "bzip"; + } + + /** + * This function is employed to create files . + * bzip + * + * @return boolean + */ + public function create_bzip() + { + if ($this->options['inmemory'] == 0) { + $pwd = getcwd(); + chdir($this->options['basedir']); + if ($fp = bzopen($this->options['name'], "wb")) { + fseek($this->archive, 0); + while ($temp = fread($this->archive, 1048576)) { + bzwrite($fp, $temp); + } + bzclose($fp); + chdir($pwd); + } else { + $this->error[] = "Could not open {$this->options['name']} for writing."; + chdir($pwd); + return 0; + } + } else { + $this->archive = bzcompress($this->archive, $this->options['level']); + } + return 1; + } + + /** + * This function open a archive of the class bzip_file + * + * @return void + */ + public function open_archive() + { + return @bzopen($this->options['name'], "rb"); + } +} diff --git a/workflow/engine/classes/class.cli.php b/workflow/engine/classes/CLI.php similarity index 99% rename from workflow/engine/classes/class.cli.php rename to workflow/engine/classes/CLI.php index 8a587bfc3..1a973f86b 100644 --- a/workflow/engine/classes/class.cli.php +++ b/workflow/engine/classes/CLI.php @@ -31,7 +31,11 @@ * * @package workflow.engine.classes */ -class CLI + +/** + * + * @package workflow.engine.classes + */class CLI { public static $tasks = array (); public static $currentTask = null; @@ -384,4 +388,3 @@ EOT; } } } - diff --git a/workflow/engine/classes/class.case.php b/workflow/engine/classes/Cases.php similarity index 97% rename from workflow/engine/classes/class.case.php rename to workflow/engine/classes/Cases.php index 2a37048bb..30321f0e7 100644 --- a/workflow/engine/classes/class.case.php +++ b/workflow/engine/classes/Cases.php @@ -1,32 +1,7 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; /** @@ -36,7 +11,6 @@ use ProcessMaker\Plugins\PluginRegistry; */ class Cases { - private $appSolr = null; public $dir = 'ASC'; public $sort = 'APP_MSG_DATE'; @@ -45,7 +19,7 @@ class Cases public function __construct() { //get Solr initialization variables - if (($solrConf = PmSystem::solrEnv()) !== false) { + if (($solrConf = System::solrEnv()) !== false) { $this->appSolr = new AppSolr($solrConf['solr_enabled'], $solrConf['solr_host'], $solrConf['solr_instance']); } } @@ -167,7 +141,7 @@ class Cases $c->addSelectColumn(TaskPeer::TAS_TITLE); $c->addSelectColumn(TaskPeer::PRO_UID); $c->addSelectColumn(ProcessPeer::PRO_TITLE); - $c->addJoin (TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $c->addJoin(TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); $c->add(TaskPeer::TAS_UID, $tasks, Criteria::IN); $c->addAscendingOrderByColumn(ProcessPeer::PRO_TITLE); $c->addAscendingOrderByColumn(TaskPeer::TAS_TITLE); @@ -278,7 +252,7 @@ class Cases $aConditions[] = array('PCS.PRO_CATEGORY', 'PCSCAT.CATEGORY_UID'); $c->addJoinMC($aConditions, Criteria::LEFT_JOIN); } - $c->addJoin (TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $c->addJoin(TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); $c->add(TaskPeer::TAS_UID, $tasks, Criteria::IN); $c->add(ProcessPeer::PRO_SUBPROCESS, '0'); $c->addAscendingOrderByColumn(ProcessPeer::PRO_TITLE); @@ -385,7 +359,7 @@ class Cases $c->addSelectColumn(TaskPeer::TAS_TITLE); $c->addSelectColumn(TaskPeer::PRO_UID); $c->addSelectColumn(ProcessPeer::PRO_TITLE); - $c->addJoin (TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $c->addJoin(TaskPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); $c->add(TaskPeer::TAS_UID, $tasks, Criteria::IN); $c->addAscendingOrderByColumn(ProcessPeer::PRO_TITLE); $c->addAscendingOrderByColumn(TaskPeer::TAS_TITLE); @@ -538,14 +512,13 @@ class Cases $aFields['CURRENT_USER'] = implode(" - ", array_values($aFields['CURRENT_USER'])); $tasksArray = array_filter(explode('|', $aFields['TAS_UID'])); - if(count($tasksArray) == 1) { + if (count($tasksArray) == 1) { $aFields['TAS_UID'] = $tasksArray[0]; } } else { $oCurUser->load($aAppDel['USR_UID']); $aFields['CURRENT_USER'] = $oCurUser->getUsrFirstname() . ' ' . $oCurUser->getUsrLastname(); } - } catch (Exception $oError) { $aFields['CURRENT_USER'] = ''; } @@ -714,7 +687,7 @@ class Cases $cri->addSelectColumn(AppDelegationPeer::TAS_UID); $cri->add(AppDelegationPeer::APP_UID, $sAppUid); $cri->add(AppDelegationPeer::DEL_THREAD_STATUS, "OPEN"); - if(isset($fields['DEL_INDEX'])){ + if (isset($fields['DEL_INDEX'])) { $cri->add(AppDelegationPeer::DEL_INDEX, $fields['DEL_INDEX']); } $rsCri = AppDelegationPeer::doSelectRS($cri); @@ -843,7 +816,8 @@ class Cases return $aReturn; } - public function array_key_intersect(&$a, &$b) { + public function array_key_intersect(&$a, &$b) + { $array = array(); while (list($key, $value) = each($a)) { if (isset($b[$key])) { @@ -893,7 +867,7 @@ class Cases if (isset($Fields['APP_DESCRIPTION'])) { $appFields['APP_DESCRIPTION'] = $Fields['APP_DESCRIPTION']; } - if(isset($Fields['DEL_INDEX'])){ + if (isset($Fields['DEL_INDEX'])) { $appFields['DEL_INDEX'] = $Fields['DEL_INDEX']; } @@ -908,9 +882,9 @@ class Cases //Add fields that weren't in previous version foreach ($aApplicationFields as $key => $value) { if (is_array($value) && isset($fieldsOnBoth[$key]) && is_array($fieldsOnBoth[$key])) { - $afieldDifference = $this->arrayRecursiveDiff($value,$fieldsOnBoth[$key]); - $dfieldDifference = $this->arrayRecursiveDiff($fieldsOnBoth[$key],$value); - if ($afieldDifference || $dfieldDifference){ + $afieldDifference = $this->arrayRecursiveDiff($value, $fieldsOnBoth[$key]); + $dfieldDifference = $this->arrayRecursiveDiff($fieldsOnBoth[$key], $value); + if ($afieldDifference || $dfieldDifference) { $FieldsDifference[$key] = $value; } } else { @@ -1015,8 +989,8 @@ class Cases } /*----------------------------------********---------------------------------*/ - if(!isset($Fields['DEL_INDEX'])){ - $Fields['DEL_INDEX'] = 1; + if (!isset($Fields['DEL_INDEX'])) { + $Fields['DEL_INDEX'] = 1; } $inbox = new ListInbox(); unset($Fields['DEL_INIT_DATE']); @@ -1046,7 +1020,7 @@ class Cases $oAppDocument = new AppDocument(); - if($deleteDelegation) { + if ($deleteDelegation) { //Delete the delegations of a application $this->deleteDelegation($sAppUid); } @@ -1103,7 +1077,7 @@ class Cases $oDerivation = new Derivation(); $oDerivation->verifyIsCaseChild($sAppUid); } - } catch(Exception $e) { + } catch (Exception $e) { Bootstrap::registerMonolog('DeleteCases', 200, 'Error in sub-process when trying to route a child case related to the case', ['application_uid' => $sAppUid, 'error' => $e->getMessage()], SYS_SYS, 'processmaker.log'); } @@ -1246,13 +1220,13 @@ class Cases } - /* - * Determines if the all threads of a multiinstance task are closed - * - * @$appUid string appUid of the instance to be tested - * @$tasUid string task uid of the multiinstance task - * @$previousDelIndex int previous del index of the instance corresponding to the multiinstance task - */ + /* + * Determines if the all threads of a multiinstance task are closed + * + * @$appUid string appUid of the instance to be tested + * @$tasUid string task uid of the multiinstance task + * @$previousDelIndex int previous del index of the instance corresponding to the multiinstance task + */ public function multiInstanceIsCompleted($appUid, $tasUid, $previousDelIndex) { @@ -1267,15 +1241,14 @@ class Cases $rs = AppDelegationPeer::doSelectRs($c); if ($rs->next()) { - $result = false; + $result = false; } else { $result = true; } - } catch (exception $e) { throw ($e); } finally { - return $result; + return $result; } } @@ -1434,7 +1407,8 @@ class Cases * @param array $previousTasks * @return array $taskReviewed */ - public function getReviewedTasksRecursive($taskUid, $appUid, $previousTasks) { + public function getReviewedTasksRecursive($taskUid, $appUid, $previousTasks) + { $taskReviewed = array(); $oCriteria = new Criteria('workflow'); $oCriteria->add(RoutePeer::ROU_NEXT_TASK, $taskUid); @@ -1494,11 +1468,11 @@ class Cases //If exist paused cases $closedTasks[] = $row; $aIndex[] = $row['DEL_INDEX']; - $res = $this->GetAllOpenDelegation( array('APP_UID'=>$sAppUid, 'APP_THREAD_PARENT'=>$row['DEL_PREVIOUS']), 'NONE' ); + $res = $this->GetAllOpenDelegation(array('APP_UID'=>$sAppUid, 'APP_THREAD_PARENT'=>$row['DEL_PREVIOUS']), 'NONE'); foreach ($res as $in) { $aIndex[] = $in['DEL_INDEX']; } - $pausedTasks = $this->getReviewedTasksPaused($sAppUid,$aIndex); + $pausedTasks = $this->getReviewedTasksPaused($sAppUid, $aIndex); } } @@ -1516,7 +1490,7 @@ class Cases * @return array within the paused tasks * false -> when has not any delegation started for that task */ - public function getReviewedTasksPaused($sAppUid,$aDelIndex) + public function getReviewedTasksPaused($sAppUid, $aDelIndex) { $oCriteria = new Criteria('workflow'); $oCriteria->add(AppDelayPeer::APP_UID, $sAppUid); @@ -2157,19 +2131,19 @@ class Cases $aUserFields = array(); $taskAssignType = $task->getTasAssignType(); $nextTaskAssignVariable = $task->getTasAssignVariable(); - if($taskAssignType == "MULTIPLE_INSTANCE" || $taskAssignType == "MULTIPLE_INSTANCE_VALUE_BASED"){ + if ($taskAssignType == "MULTIPLE_INSTANCE" || $taskAssignType == "MULTIPLE_INSTANCE_VALUE_BASED") { switch ($taskAssignType) { case 'MULTIPLE_INSTANCE': $userFields = $oDerivation->getUsersFullNameFromArray($oDerivation->getAllUsersFromAnyTask($sTasUid)); break; default: - throw (new Exception( 'Invalid Task Assignment method' )); + throw (new Exception('Invalid Task Assignment method')); break; } $userFields = $oDerivation->getUsersFullNameFromArray($oDerivation->getAllUsersFromAnyTask($sTasUid)); $count = 0; - foreach($userFields as $rowUser){ - if($rowUser["USR_UID"] != $sUsrUid){ + foreach ($userFields as $rowUser) { + if ($rowUser["USR_UID"] != $sUsrUid) { //appDelegation $AppDelegation = new AppDelegation; $iAppThreadIndex ++; // Start Thread @@ -2193,13 +2167,13 @@ class Cases (empty($user)) ? 0 : $user->getUsrId(), $this->Process->getProId() ); - //appThread - $AppThread = new AppThread; - $iAppThreadIndex = $AppThread->createAppThread($sAppUid, $iDelIndex1, 0); - //Save Information - $aUserFields[$count] = $rowUser; - $aUserFields[$count]["DEL_INDEX"] = $iDelIndex1; - $count++; + //appThread + $AppThread = new AppThread; + $iAppThreadIndex = $AppThread->createAppThread($sAppUid, $iDelIndex1, 0); + //Save Information + $aUserFields[$count] = $rowUser; + $aUserFields[$count]["DEL_INDEX"] = $iDelIndex1; + $count++; } } } @@ -2343,7 +2317,6 @@ class Cases $iPosition += 1; $aNextStep = null; if ($iPosition <= $iLastStep) { - while ($iPosition <= $iLastStep) { $bAccessStep = false; //step @@ -2374,25 +2347,25 @@ class Cases $sAction = ''; break; } - if(array_key_exists('gmail',$_SESSION) || (array_key_exists('gmail',$_GET) && $_GET['gmail'] == 1)){ - $aNextStep = array( - 'TYPE' => $oStep->getStepTypeObj(), - 'UID' => $oStep->getStepUidObj(), - 'POSITION' => $oStep->getStepPosition(), - 'PAGE' => 'cases_Step?TYPE=' . $oStep->getStepTypeObj() . '&UID=' . - $oStep->getStepUidObj() . '&POSITION=' . $oStep->getStepPosition() . - '&ACTION=' . $sAction . - '&gmail=1' - ); - } else{ - $aNextStep = array( - 'TYPE' => $oStep->getStepTypeObj(), - 'UID' => $oStep->getStepUidObj(), - 'POSITION' => $oStep->getStepPosition(), - 'PAGE' => 'cases_Step?TYPE=' . $oStep->getStepTypeObj() . '&UID=' . - $oStep->getStepUidObj() . '&POSITION=' . $oStep->getStepPosition() . - '&ACTION=' . $sAction - ); + if (array_key_exists('gmail', $_SESSION) || (array_key_exists('gmail', $_GET) && $_GET['gmail'] == 1)) { + $aNextStep = array( + 'TYPE' => $oStep->getStepTypeObj(), + 'UID' => $oStep->getStepUidObj(), + 'POSITION' => $oStep->getStepPosition(), + 'PAGE' => 'cases_Step?TYPE=' . $oStep->getStepTypeObj() . '&UID=' . + $oStep->getStepUidObj() . '&POSITION=' . $oStep->getStepPosition() . + '&ACTION=' . $sAction . + '&gmail=1' + ); + } else { + $aNextStep = array( + 'TYPE' => $oStep->getStepTypeObj(), + 'UID' => $oStep->getStepUidObj(), + 'POSITION' => $oStep->getStepPosition(), + 'PAGE' => 'cases_Step?TYPE=' . $oStep->getStepTypeObj() . '&UID=' . + $oStep->getStepUidObj() . '&POSITION=' . $oStep->getStepPosition() . + '&ACTION=' . $sAction + ); } $iPosition = $iLastStep; } @@ -2401,21 +2374,21 @@ class Cases } } if (!$aNextStep) { - if(array_key_exists('gmail',$_SESSION) || (array_key_exists('gmail',$_GET) && $_GET['gmail'] == 1)){ - $aNextStep = array( - 'TYPE' => 'DERIVATION', - 'UID' => -1, - 'POSITION' => ($iLastStep + 1), - 'PAGE' => 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN&gmail=1' - ); - }else { - $aNextStep = array( - 'TYPE' => 'DERIVATION', - 'UID' => -1, - 'POSITION' => ($iLastStep + 1), - 'PAGE' => 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN' - ); - } + if (array_key_exists('gmail', $_SESSION) || (array_key_exists('gmail', $_GET) && $_GET['gmail'] == 1)) { + $aNextStep = array( + 'TYPE' => 'DERIVATION', + 'UID' => -1, + 'POSITION' => ($iLastStep + 1), + 'PAGE' => 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN&gmail=1' + ); + } else { + $aNextStep = array( + 'TYPE' => 'DERIVATION', + 'UID' => -1, + 'POSITION' => ($iLastStep + 1), + 'PAGE' => 'cases_Step?TYPE=ASSIGN_TASK&UID=-1&POSITION=10000&ACTION=ASSIGN' + ); + } } return $aNextStep; } catch (exception $e) { @@ -2621,7 +2594,6 @@ class Cases ///-- $c->addAsColumn('USR_NAME', "CONCAT(USR_LASTNAME, ' ', USR_FIRSTNAME)"); $sDataBase = 'database_' . strtolower(DB_ADAPTER); if (G::LoadSystemExist($sDataBase)) { - $oDataBase = new database(); $c->addAsColumn('USR_NAME', $oDataBase->concatString("USR_LASTNAME", "' '", "USR_FIRSTNAME")); $c->addAsColumn( @@ -3373,7 +3345,7 @@ class Cases if (!is_null($oApplication)) { return $oApplication->getDelIndex(); } - throw ( new Exception('This case has 0 current delegations') ); + throw (new Exception('This case has 0 current delegations')); } /* @@ -4011,11 +3983,12 @@ class Cases * @param string $iDelegation * @return boolean */ - public static function isUnassignedPauseCase($sAppUid, $iDelegation){ + public static function isUnassignedPauseCase($sAppUid, $iDelegation) + { $oAppDelegation = new AppDelegation(); $aFieldsDel = $oAppDelegation->Load($sAppUid, $iDelegation); $usrUid = $aFieldsDel['USR_UID']; - if($usrUid === ''){ + if ($usrUid === '') { return true; } else { return false; @@ -4036,8 +4009,8 @@ class Cases public function pauseCase($sApplicationUID, $iDelegation, $sUserUID, $sUnpauseDate = null, $appTitle = null) { // Check if the case is unassigned - if($this->isUnassignedPauseCase($sApplicationUID, $iDelegation)){ - throw new Exception( G::LoadTranslation("ID_CASE_NOT_PAUSED", array(G::LoadTranslation("ID_UNASSIGNED_STATUS"))) ); + if ($this->isUnassignedPauseCase($sApplicationUID, $iDelegation)) { + throw new Exception(G::LoadTranslation("ID_CASE_NOT_PAUSED", array(G::LoadTranslation("ID_UNASSIGNED_STATUS")))); } $oApplication = new Application(); @@ -4295,7 +4268,7 @@ class Cases $this->appSolr->updateApplicationSearchIndex($sApplicationUID); } /*----------------------------------********---------------------------------*/ - $data = array ( + $data = array( 'APP_UID' => $sApplicationUID, 'DEL_INDEX' => $iIndex, 'USR_UID' => $user_logged, @@ -5531,7 +5504,7 @@ class Cases } if ($sTo != null) { - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($dataLastEmail['configuration']); $oSpool->create(array( @@ -5599,10 +5572,10 @@ class Cases { $sTo = null; $sCc = null; - $arrayResp = array (); + $arrayResp = array(); $tasks = new Tasks(); - $group = new Groups (); - $oUser = new Users (); + $group = new Groups(); + $oUser = new Users(); $task = TaskPeer::retrieveByPK($taskUid); @@ -5693,14 +5666,14 @@ class Cases $arrayResp['to'] = $to; $arrayResp['cc'] = $cc; break; - case "MULTIPLE_INSTANCE" : + case "MULTIPLE_INSTANCE": $to = null; $cc = null; $sw = 1; - $oDerivation = new Derivation (); - $userFields = $oDerivation->getUsersFullNameFromArray ( $oDerivation->getAllUsersFromAnyTask ( $taskUid ) ); - if (isset ( $userFields )) { - foreach ( $userFields as $row ) { + $oDerivation = new Derivation(); + $userFields = $oDerivation->getUsersFullNameFromArray($oDerivation->getAllUsersFromAnyTask($taskUid)); + if (isset($userFields)) { + foreach ($userFields as $row) { $toAux = ((($row ["USR_FIRSTNAME"] != "") || ($row ["USR_LASTNAME"] != "")) ? $row ["USR_FIRSTNAME"] . " " . $row ["USR_LASTNAME"] . " " : "") . "<" . $row ["USR_EMAIL"] . ">"; if ($sw == 1) { $to = $toAux; @@ -5713,19 +5686,19 @@ class Cases $arrayResp ['cc'] = $cc; } break; - case "MULTIPLE_INSTANCE_VALUE_BASED" : - $oTask = new Task (); - $aTaskNext = $oTask->load ( $taskUid ); - if (isset ( $aTaskNext ["TAS_ASSIGN_VARIABLE"] ) && ! empty ( $aTaskNext ["TAS_ASSIGN_VARIABLE"] )) { + case "MULTIPLE_INSTANCE_VALUE_BASED": + $oTask = new Task(); + $aTaskNext = $oTask->load($taskUid); + if (isset($aTaskNext ["TAS_ASSIGN_VARIABLE"]) && ! empty($aTaskNext ["TAS_ASSIGN_VARIABLE"])) { $to = null; $cc = null; $sw = 1; - $nextTaskAssignVariable = trim ( $aTaskNext ["TAS_ASSIGN_VARIABLE"], " @#" ); + $nextTaskAssignVariable = trim($aTaskNext ["TAS_ASSIGN_VARIABLE"], " @#"); $arrayUsers = $arrayData [$nextTaskAssignVariable]; - $oDerivation = new Derivation (); - $userFields = $oDerivation->getUsersFullNameFromArray ( $arrayUsers ); + $oDerivation = new Derivation(); + $userFields = $oDerivation->getUsersFullNameFromArray($arrayUsers); - foreach ( $userFields as $row ) { + foreach ($userFields as $row) { $toAux = ((($row ["USR_FIRSTNAME"] != "") || ($row ["USR_LASTNAME"] != "")) ? $row ["USR_FIRSTNAME"] . " " . $row ["USR_LASTNAME"] . " " : "") . "<" . $row ["USR_EMAIL"] . ">"; if ($sw == 1) { $to = $toAux; @@ -5738,7 +5711,7 @@ class Cases $arrayResp ['cc'] = $cc; } break; - default : + default: if (isset($userUid) && !empty($userUid)) { $aUser = $oUser->load($userUid); @@ -5762,9 +5735,9 @@ class Cases */ public function getAllObjects($PRO_UID, $APP_UID, $TAS_UID = '', $USR_UID = '', $delIndex = 0) { - $ACTIONS = Array('VIEW', 'BLOCK', 'DELETE'); //TO COMPLETE - $MAIN_OBJECTS = Array(); - $RESULT_OBJECTS = Array(); + $ACTIONS = array('VIEW', 'BLOCK', 'DELETE'); //TO COMPLETE + $MAIN_OBJECTS = array(); + $RESULT_OBJECTS = array(); foreach ($ACTIONS as $action) { $MAIN_OBJECTS[$action] = $this->getAllObjectsFrom($PRO_UID, $APP_UID, $TAS_UID, $USR_UID, $action, $delIndex); @@ -5988,9 +5961,9 @@ class Cases "OUTPUT_DOCUMENTS" => $result['OUTPUT'], "CASES_NOTES" => $result['CASES_NOTES'], "MSGS_HISTORY" => $result['MSGS_HISTORY'] - /*----------------------------------********---------------------------------*/ + /*----------------------------------********---------------------------------*/ ,"SUMMARY_FORM" => $result['SUMMARY_FORM'] - /*----------------------------------********---------------------------------*/ + /*----------------------------------********---------------------------------*/ ); } @@ -6416,7 +6389,7 @@ class Cases $oCriteria = new Criteria('dbarray'); $oCriteria->setDBArrayTable('messages'); - usort( $aMessages, array($this, "ordProcess") ); + usort($aMessages, array($this, "ordProcess")); return $aMessages; } @@ -6455,7 +6428,7 @@ class Cases public function getAllObjectsFromProcess($PRO_UID, $OBJ_TYPE = '%') { - $RESULT = Array(); + $RESULT = array(); $oCriteria = new Criteria('workflow'); $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_UID); $oCriteria->addSelectColumn(AppDocumentPeer::APP_UID); @@ -6753,7 +6726,7 @@ class Cases $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); if (isset($sumary) && $sumary === true) { - $sumary = Array(); + $sumary = array(); while ($rs->next()) { $nCount++; $row = $rs->getRow(); @@ -6764,7 +6737,7 @@ class Cases $sumary[$row['PRO_UID']]['name'] = $row['APP_PRO_TITLE']; } } - return Array('count' => $nCount, 'sumary' => $sumary); + return array('count' => $nCount, 'sumary' => $sumary); } else { while ($rs->next()) { $nCount++; @@ -6783,7 +6756,7 @@ class Cases */ public function getAllConditionCasesCount($types, $sumary = null) { - $aResult = Array(); + $aResult = array(); foreach ($types as $type) { $aResult[$type] = $this->getConditionCasesCount($type, $sumary); } @@ -6890,7 +6863,7 @@ class Cases $c = new Criteria(); $c->add(AppDelegationPeer::APP_UID, $aData['APP_UID']); $c->add(AppDelegationPeer::DEL_PREVIOUS, $aData['APP_THREAD_PARENT']); - if($status === 'OPEN'){ + if ($status === 'OPEN') { $c->add(AppDelegationPeer::DEL_THREAD_STATUS, 'OPEN'); } $rs = AppDelegationPeer::doSelectRs($c); @@ -6954,7 +6927,7 @@ class Cases global $RBAC; //Adding the actual user if this has the PM_SUPERVISOR permission assigned. if ($RBAC->userCanAccess('PM_SUPERVISOR') == 1) { - if(!in_array($RBAC->aUserInfo['USER_INFO']['USR_UID'], $row)) { + if (!in_array($RBAC->aUserInfo['USER_INFO']['USR_UID'], $row)) { $row[] = $RBAC->aUserInfo['USER_INFO']['USR_UID']; } } @@ -6969,7 +6942,7 @@ class Cases $rs = UsersPeer::doSelectRs($c); $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $rows = Array(); + $rows = array(); while ($rs->next()) { $rows[] = $rs->getRow(); } @@ -6995,8 +6968,8 @@ class Cases $flagSupervisors = false; if ($oDataset->next()) { - if (!in_array($USR_UID,$row)) { - $rows[] = $oDataset->getRow(); + if (!in_array($USR_UID, $row)) { + $rows[] = $oDataset->getRow(); } $flagSupervisors = true; } @@ -7025,7 +6998,7 @@ class Cases $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); if ($oDataset->next()) { - if (!in_array($USR_UID,$row)) { + if (!in_array($USR_UID, $row)) { $rows[] = $oDataset->getRow(); } } @@ -7051,7 +7024,7 @@ class Cases $c->addSelectColumn(UsersPeer::USR_USERNAME); $c->addSelectColumn(UsersPeer::USR_EMAIL); - if($usrStatus != '') { + if ($usrStatus != '') { $c->add(UsersPeer::USR_STATUS, $usrStatus, CRITERIA::EQUAL); } @@ -7064,7 +7037,7 @@ class Cases $rs->next(); while ($row = $rs->getRow()) { //In some cases the thread does not have a User Script task, Itee - if($row['USR_UID'] !== ''){ + if ($row['USR_UID'] !== '') { $rows[$row['USR_UID']] = $row; } $rs->next(); @@ -7076,7 +7049,7 @@ class Cases public function getCaseNotes($applicationID, $type = 'array', $userUid = '') { - require_once ( "classes/model/AppNotes.php" ); + require_once("classes/model/AppNotes.php"); $appNotes = new AppNotes(); $appNotes = $appNotes->getNotesList($applicationID, $userUid); $response = ''; @@ -7201,27 +7174,26 @@ class Cases $pmTableName = $pmTable->toCamelCase($tableName); //DELETE - require_once (PATH_WORKSPACE . "classes" . PATH_SEP . "$pmTableName.php"); + require_once(PATH_WORKSPACE . "classes" . PATH_SEP . "$pmTableName.php"); $criteria3 = new Criteria("workflow"); eval("\$criteria3->add(" . $pmTableName . "Peer::APP_UID, \$applicationUid);"); eval($pmTableName . "Peer::doDelete(\$criteria3);"); - } catch (Exception $e) { throw $e; } } } - public function ordProcess ($a, $b) + public function ordProcess($a, $b) { - if ($this->sort == '') { - $this->sort = 'APP_MSG_DATE'; - } - if ($this->dir=='ASC') { - if ($a[$this->sort] > $b[$this->sort]) { - return 1; + if ($this->sort == '') { + $this->sort = 'APP_MSG_DATE'; + } + if ($this->dir=='ASC') { + if ($a[$this->sort] > $b[$this->sort]) { + return 1; } elseif ($a[$this->sort] < $b[$this->sort]) { return - 1; } else { @@ -7229,16 +7201,17 @@ class Cases } } else { if ($a[$this->sort] > $b[$this->sort]) { - return - 1; + return - 1; } elseif ($a[$this->sort] < $b[$this->sort]) { - return 1; + return 1; } else { - return 0; + return 0; } } } - public function unserializeData($data) { + public function unserializeData($data) + { $unserializedData = @unserialize($data); // BUG 8134, FIX!// for single/double quote troubles // Unserialize with utf8 content get trouble @@ -7310,26 +7283,27 @@ class Cases } } - private function orderStartCasesByCategoryAndName ($rows) { + private function orderStartCasesByCategoryAndName($rows) + { //now we order in category, proces_name order: $comparatorSequence = array( - function($a, $b) { + function ($a, $b) { $retval = 0; - if(array_key_exists('catname', $a) && array_key_exists('catname', $b)) { + if (array_key_exists('catname', $a) && array_key_exists('catname', $b)) { $retval = strcmp($a['catname'], $b['catname']); } return $retval; } - , function($a, $b) { - $retval = 0; - if(array_key_exists('value', $a) && array_key_exists('value', $b)) { - $retval = strcmp($a['value'], $b['value']); - } - return $retval; + , function ($a, $b) { + $retval = 0; + if (array_key_exists('value', $a) && array_key_exists('value', $b)) { + $retval = strcmp($a['value'], $b['value']); } + return $retval; + } ); - usort($rows, function($a, $b) use ($comparatorSequence) { + usort($rows, function ($a, $b) use ($comparatorSequence) { foreach ($comparatorSequence as $cmpFn) { $diff = call_user_func($cmpFn, $a, $b); if ($diff !== 0) { diff --git a/workflow/engine/classes/class.configuration.php b/workflow/engine/classes/Configurations.php similarity index 95% rename from workflow/engine/classes/class.configuration.php rename to workflow/engine/classes/Configurations.php index eb548ba5b..b7b798749 100644 --- a/workflow/engine/classes/class.configuration.php +++ b/workflow/engine/classes/Configurations.php @@ -1,57 +1,14 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ -// -// It works with the table CONFIGURATION in a WF dataBase -// Copyright (C) 2007 COLOSA -// License: LGPL, see LICENSE -//////////////////////////////////////////////////// - - -/** - * ProcessConfiguration - ProcessConfiguration class - * - * @author David S. Callizaya S. - * @copyright 2007 COLOSA - */ -require_once 'classes/model/Configuration.php'; - /** + * ProcessConfiguration - ProcessConfiguration * Extends Configuration * - * - * @copyright 2007 COLOSA * @version Release: @package_version@ * @package workflow.engine.ProcessMaker */ class Configurations // extends Configuration { - public $aConfig = array(); private $Configuration = null; private $UserConfig = null; @@ -81,16 +38,16 @@ class Configurations // extends Configuration $this->arrayClone($object[$k], $cloneObject[$k]); } } else { - if (is_object( $object )) { + if (is_object($object)) { } else { $cloneObject = null; } } } - public function exists($cfgID,$objID='') + public function exists($cfgID, $objID='') { - return $this->Configuration->exists($cfgID,$objID,'','',''); + return $this->Configuration->exists($cfgID, $objID, '', '', ''); } /** @@ -169,7 +126,6 @@ class Configurations // extends Configuration try { $this->Fields = $this->Configuration->load($cfg, $obj, $pro, $usr, $app); } catch (Exception $e) { - } // the configuration does not exist @@ -178,7 +134,7 @@ class Configurations // extends Configuration } if (!is_array($this->aConfig)) { - $this->aConfig = Array(); + $this->aConfig = array(); } return $this->aConfig; @@ -325,8 +281,8 @@ class Configurations // extends Configuration $theFormat = $this->UserConfig['format']; $fname = $oUser->getUsrFirstname(); $lname = $oUser->getUsrLastname(); - if (strpos($theFormat, ',') !== false && ( trim($fname) == '' || trim($lname) == '')) { - $theFormat = str_replace(',', '', $theFormat); + if (strpos($theFormat, ',') !== false && (trim($fname) == '' || trim($lname) == '')) { + $theFormat = str_replace(',', '', $theFormat); } $aux = str_replace('@userName', trim($username), $theFormat); @@ -537,15 +493,15 @@ class Configurations // extends Configuration public function getUserNameFormats() { - $formats[] = Array('id' => '@firstName @lastName', //the id , don't translate + $formats[] = array('id' => '@firstName @lastName', //the id , don't translate 'name' => G::loadTranslation('ID_USERNAME_FORMAT_1') //label displayed, can be translated ); - $formats[] = Array('id' => '@firstName @lastName (@userName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_2')); - $formats[] = Array('id' => '@userName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_3')); - $formats[] = Array('id' => '@userName (@firstName @lastName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_4')); - $formats[] = Array('id' => '@lastName @firstName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_5')); - $formats[] = Array('id' => '@lastName, @firstName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_6')); - $formats[] = Array('id' => '@lastName, @firstName (@userName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_7')); + $formats[] = array('id' => '@firstName @lastName (@userName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_2')); + $formats[] = array('id' => '@userName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_3')); + $formats[] = array('id' => '@userName (@firstName @lastName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_4')); + $formats[] = array('id' => '@lastName @firstName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_5')); + $formats[] = array('id' => '@lastName, @firstName', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_6')); + $formats[] = array('id' => '@lastName, @firstName (@userName)', 'name' => G::loadTranslation('ID_USERNAME_FORMAT_7')); return $formats; } @@ -560,9 +516,9 @@ class Configurations // extends Configuration $creationDateMask = ($creationDateMask == '') ? $dateFormat : $creationDateMask; if ($creationDateMask != '') { if (strpos($dateTime, ' ') !== false) { - list ($date, $time) = explode(' ', $dateTime); - list ($y, $m, $d) = explode('-', $date); - list ($h, $i, $s) = explode(':', $time); + list($date, $time) = explode(' ', $dateTime); + list($y, $m, $d) = explode('-', $date); + list($h, $i, $s) = explode(':', $time); $newCreation = ''; $maskTime = array('d' => '%d', 'D' => '%A', 'j' => '%d', 'l' => '%A', 'G' => '%I', 'g' => '%i', 'N' => '%u', 'S' => '%d', 'w' => '%w', 'z' => '%j', 'W' => '%W', 'F' => '%B', 'm' => '%m', 'M' => '%B', 'n' => '%m', 'o' => '%Y', 'Y' => '%Y', 'y' => '%g', 'a' => '%p', 'A' => '%p', 'g' => '%I', 'G' => '%H', 'h' => '%I', 'H' => '%H', 'i' => '%M', 's' => '%S'); $creationDateMask = trim($creationDateMask); @@ -589,9 +545,9 @@ class Configurations // extends Configuration if (G::toLower(PHP_OS) == 'linux' || G::toLower(PHP_OS) == 'darwin') { if (SYS_LANG == 'es') { $langLocate = 'es_ES'; - } else if (strlen(SYS_LANG) > 2) { + } elseif (strlen(SYS_LANG) > 2) { $langLocate = str_replace('-', '_', SYS_LANG); - } else if ($location != '') { + } elseif ($location != '') { $langLocate = SYS_LANG.'_'.$location; } else { $langLocate = 'en_US'; @@ -1006,4 +962,3 @@ class Configurations // extends Configuration return $ver; } } - diff --git a/workflow/engine/classes/class.consolidatedCases.php b/workflow/engine/classes/ConsolidatedCases.php similarity index 99% rename from workflow/engine/classes/class.consolidatedCases.php rename to workflow/engine/classes/ConsolidatedCases.php index c0c261b4d..f3ffd8453 100644 --- a/workflow/engine/classes/class.consolidatedCases.php +++ b/workflow/engine/classes/ConsolidatedCases.php @@ -1,5 +1,6 @@ deleteAllReportVars($_POST['form']['REP_TAB_UID']); - $pmDyna = new pmDynaform(array()); + $pmDyna = new PmDynaform(array()); $pmDyna->fields["CURRENT_DYNAFORM"] = $DynUid; $dataDyna = $pmDyna->getDynaform(); $json = G::json_decode($dataDyna["DYN_CONTENT"]); diff --git a/workflow/engine/classes/class.dashboards.php b/workflow/engine/classes/Dashboards.php similarity index 95% rename from workflow/engine/classes/class.dashboards.php rename to workflow/engine/classes/Dashboards.php index 12ef77820..5aefc8667 100644 --- a/workflow/engine/classes/class.dashboards.php +++ b/workflow/engine/classes/Dashboards.php @@ -1,16 +1,11 @@ w = $width; $g->value = $this->value; diff --git a/workflow/engine/classes/class.dashletProcessMakerCommunity.php b/workflow/engine/classes/DashletProcessMakerCommunity.php similarity index 96% rename from workflow/engine/classes/class.dashletProcessMakerCommunity.php rename to workflow/engine/classes/DashletProcessMakerCommunity.php index 459a4a849..79eb061f0 100644 --- a/workflow/engine/classes/class.dashletProcessMakerCommunity.php +++ b/workflow/engine/classes/DashletProcessMakerCommunity.php @@ -1,8 +1,8 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * / - * - * /* - * Created on 21/01/2008 - * This class is used for handling dates - * - * @author David Callizaya - */ -require_once ("classes/model/TaskPeer.php"); -require_once ("classes/model/HolidayPeer.php"); - -/** - * - * @package workflow.engine.classes - */ -class dates +class Dates { private $holidays = array(); @@ -529,4 +491,3 @@ class dates return $iDate; } } - diff --git a/workflow/engine/classes/class.dbConnections.php b/workflow/engine/classes/DbConnections.php similarity index 97% rename from workflow/engine/classes/class.dbConnections.php rename to workflow/engine/classes/DbConnections.php index 3eb1929c1..76332fe50 100644 --- a/workflow/engine/classes/class.dbConnections.php +++ b/workflow/engine/classes/DbConnections.php @@ -1,26 +1,5 @@ - * Description:This is a class for load all additional connections; if exist in a particular proccess - * Date: 15-05-2008 - * - * - * class.dbConnections.php - * - * Email bugs/suggestions to erik@colosa.com - */ -require_once 'model/DbSource.php'; -require_once 'model/Content.php'; - -/** - * dbConnections - * - * - * @copyright 2008 Colosa - * @package workflow.engine.classes - * - */ class DbConnections { private $PRO_UID; diff --git a/workflow/engine/classes/class.derivation.php b/workflow/engine/classes/Derivation.php similarity index 99% rename from workflow/engine/classes/class.derivation.php rename to workflow/engine/classes/Derivation.php index 9dbd41bcc..8e5326f42 100644 --- a/workflow/engine/classes/class.derivation.php +++ b/workflow/engine/classes/Derivation.php @@ -1,12 +1,5 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * Dynaform Field - DynaformField class - * - * @package workflow.engine.classes - */ class DynaFormField extends DBTable { diff --git a/workflow/engine/classes/DynaformEditor.php b/workflow/engine/classes/DynaformEditor.php new file mode 100644 index 000000000..983b04b1b --- /dev/null +++ b/workflow/engine/classes/DynaformEditor.php @@ -0,0 +1,293 @@ + array('left' => '0', 'top' => '0', 'width' => 'document.body.clientWidth-4', 'height' => 'document.body.clientHeight-4'), + 'Toolbar' => array('left' => 'document.body.clientWidth-2-toolbar.clientWidth-24-3+7', 'top' => '52'), + 'FieldsList' => array('left' => '4+toolbar.clientWidth+24', 'top' => 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))', 'width' => 244, 'height' => 400) + ); + public $panelConf = array('style' => array('title' => array('textAlign' => 'center')), + 'width' => 700, 'height' => 600, 'tabWidth' => 120, 'modal' => true, 'drag' => false, 'resize' => false, 'blinkToFront' => false + ); + + /** + * Constructor of the class dynaformEditor + * + * @param string $get + * @return void + */ + public function __construct($get) + { + $this->panelConf = array_merge($this->panelConf, $this->defaultConfig['Editor']); + //'title' => G::LoadTranslation('ID_DYNAFORM_EDITOR').' - ['.$this->title.']', + } + + /** + * Create the xml form default + * + * @param string $filename + * @return void + */ + public function _createDefaultXmlForm($fileName) + { + //Create the default Dynaform + $sampleForm = '' . "\n"; + $sampleForm .= '' . "\n"; + switch ($this->dyn_type) { + case "xmlform": + /* $sampleForm.='' . "\n" . + ' <en>Sample form</en>' . "\n" . + ''."\n"; + $sampleForm.='' . "\n" . + ' Submit' . "\n" . + ''."\n"; */ + break; + case "grid": + /* $sampleForm.='' . "\n" . + 'A' . "\n" . + ''."\n"; + $sampleForm.='' . "\n" . + 'B' . "\n" . + ''."\n"; */ + break; + } + $sampleForm .= ''; + G::verifyPath(dirname($fileName), true); + $fp = fopen($fileName, 'w'); + $sampleForm = str_replace('name=""', 'name="' . $this->_getFilename($this->file) . '"', $sampleForm); + fwrite($fp, $sampleForm); + fclose($fp); + } + + /** + * Prints the DynaformEditor + * + * @return void + */ + public function _render() + { + global $G_PUBLISH; + $script = ''; + + /* Start Block: Load (Create if doesn't exist) the xmlform */ + $Parameters = array('SYS_LANG' => SYS_LANG, 'URL' => G::encrypt($this->file, URL_KEY), 'DYN_UID' => $this->dyn_uid, 'PRO_UID' => $this->pro_uid, 'DYNAFORM_NAME' => $this->dyn_title, 'FILE' => $this->file, 'DYN_EDITOR' => $this->dyn_editor + ); + $_SESSION['Current_Dynafom']['Parameters'] = $Parameters; + + $XmlEditor = array('URL' => G::encrypt($this->file, URL_KEY), 'XML' => '' //$openDoc->getXml() + ); + $JSEditor = array('URL' => G::encrypt($this->file, URL_KEY) + ); + + $A = G::encrypt($this->file, URL_KEY); + + try { + $openDoc = new Xml_Document(); + $fileName = $this->home . $this->file . '.xml'; + if (file_exists($fileName)) { + $openDoc->parseXmlFile($fileName); + } else { + $this->_createDefaultXmlForm($fileName); + $openDoc->parseXmlFile($fileName); + } + //$form = new Form( $this->file , $this->home, SYS_LANG, true ); + $Properties = DynaformEditorAjax::get_properties($A, $this->dyn_uid); + /* Start Block: Prepare the XMLDB connection */ + define('DB_XMLDB_HOST', PATH_DYNAFORM . $this->file . '.xml'); + define('DB_XMLDB_USER', ''); + define('DB_XMLDB_PASS', ''); + define('DB_XMLDB_NAME', ''); + define('DB_XMLDB_TYPE', 'myxml'); + /* Start Block: Prepare the dynaformEditor */ + $G_PUBLISH = new Publisher(); + $sName = 'dynaformEditor'; + $G_PUBLISH->publisherId = $sName; + $oHeadPublisher = & headPublisher::getSingleton(); + $oHeadPublisher->setTitle(G::LoadTranslation('ID_DYNAFORM_EDITOR') . ' - ' . $Properties['DYN_TITLE']); + $G_PUBLISH->AddContent('blank'); + $this->panelConf['title'] = ''; + $G_PUBLISH->AddContent('panel-init', 'mainPanel', $this->panelConf); + if ($Properties['DYN_TYPE'] == 'xmlform') { + $G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_Toolbar', 'display:none', $Parameters, '', ''); + } else { + $G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_ToolbarGrid', 'display:none', $Parameters, '', ''); + } + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Editor', 'display:none', $Parameters, '', ''); + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_XmlEditor', 'display:none', $XmlEditor, '', ''); + $G_PUBLISH->AddContent('blank'); + $i = 0; + $aFields = array(); + $aFields[] = array('XMLNODE_NAME' => 'char', 'TYPE' => 'char', 'UP' => 'char', 'DOWN' => 'char' + ); + $oSession = new DBSession(new DBConnection(PATH_DYNAFORM . $this->file . '.xml', '', '', '', 'myxml')); + $oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE NOT( XMLNODE_NAME = "" ) AND TYPE <> "pmconnection"'); + $iMaximun = $oDataset->count(); + while ($aRow = $oDataset->Read()) { + $aFields[] = array('XMLNODE_NAME' => $aRow['XMLNODE_NAME'], 'TYPE' => $aRow['TYPE'], 'UP' => ($i > 0 ? G::LoadTranslation('ID_UP') : ''), 'DOWN' => ($i < $iMaximun - 1 ? G::LoadTranslation('ID_DOWN') : ''), 'row__' => ($i + 1) + ); + $i++; + break; + } + global $_DBArray; + $_DBArray['fields'] = $aFields; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('fields'); + /** + * *@Erik-> this is deprecated,. + * (unuseful) $G_PUBLISH->AddContent('propeltable', 'paged-table', 'dynaforms/fields_List', $oCriteria, $Parameters, '', SYS_URI.'dynaforms/dynaforms_PagedTableAjax');** + */ + $G_PUBLISH->AddContent('blank'); + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_JSEditor', 'display:none', $JSEditor, '', ''); + } catch (Exception $e) { + + } + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Properties', 'display:none', $Properties, '', ''); + //for showHide tab option @Neyek + $G_PUBLISH->AddContent('blank'); + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_PREVIEW"), $sName . '[3]', 'dynaformEditor.changeToPreview', 'dynaformEditor.saveCurrentView'); + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_XML"), $sName . '[4]', 'dynaformEditor.changeToXmlCode', 'dynaformEditor.saveCurrentView'); + if ($Properties['DYN_TYPE'] != 'grid') { + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_HTML"), $sName . '[5]', 'dynaformEditor.changeToHtmlCode', 'dynaformEditor.saveCurrentView'); + } + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_FIELDS_LIST"), $sName . '[6]', 'dynaformEditor.changeToFieldsList', 'dynaformEditor.saveCurrentView'); + if ($Properties["DYN_TYPE"] != "grid") { + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_JAVASCRIPTS"), $sName . '[7]', 'dynaformEditor.changeToJavascripts', 'dynaformEditor.saveCurrentView'); + } + $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_PROPERTIES"), $sName . '[8]', 'dynaformEditor.changeToProperties', 'dynaformEditor.saveCurrentView'); + + //for showHide tab option @Neyek + if ($Properties["DYN_TYPE"] != "grid") { + $G_PUBLISH->AddContent("panel-tab", G::LoadTranslation("ID_CONDITIONS_EDITOR"), $sName . "[9]", "dynaformEditor.changeToShowHide", "dynaformEditor.saveShowHide"); + } + + $G_PUBLISH->AddContent('panel-close'); + $oHeadPublisher->addScriptFile("/js/maborak/core/maborak.loader.js",2); + $oHeadPublisher->addScriptFile('/jscore/dynaformEditor/core/dynaformEditor.js'); + + $oHeadPublisher->addScriptFile('/js/codemirrorOld/js/codemirror.js',1); + + $oHeadPublisher->addScriptFile('/js/grid/core/grid.js'); + $oHeadPublisher->addScriptCode(' + var DYNAFORM_URL="' . $Parameters['URL'] . '"; + leimnud.event.add(window,"load",function(){ loadEditor(); }); + '); + $oHeadPublisher->addScriptCode(' var jsMeta;var __usernameLoggedDE__ = "' . (isset($_SESSION['USR_USERNAME']) ? $_SESSION['USR_USERNAME'] : '') . '";var SYS_LANG = "' . SYS_LANG . '";var __DYN_UID__ = "' . $this->dyn_uid . '";'); + + $arrayParameterAux = $Parameters; + $arrayParameterAux["DYNAFORM_NAME"] = base64_encode($arrayParameterAux["DYNAFORM_NAME"]); + $oHeadPublisher->addScriptCode('var dynaformEditorParams = \'' . serialize($arrayParameterAux) . '\';'); + + G::RenderPage("publish", 'blank'); + } + + /** + * Get the filename + * + * @param string $file + * @return string + */ + public function _getFilename($file) + { + return (strcasecmp(substr($file, - 5), '_tmp0') == 0) ? substr($file, 0, strlen($file) - 5) : $file; + } + + /** + * Set the temporal copy + * + * @param string $onOff + * @return void + */ + public function _setUseTemporalCopy($onOff) + { + $file = self::_getFilename($this->file); + if ($onOff) { + $this->file = $file . '_tmp0'; + self::_setTmpData(array('useTmpCopy' => true )); + if (!file_exists(PATH_DYNAFORM . $file . '.xml')) { + $this->_createDefaultXmlForm(PATH_DYNAFORM . $file . '.xml'); + } + //Creates a copy if it doesn't exist, else, use the old copy + if (!file_exists(PATH_DYNAFORM . $this->file . '.xml')) { + self::_copyFile(PATH_DYNAFORM . $file . '.xml', PATH_DYNAFORM . $this->file . '.xml'); + } + if (!file_exists(PATH_DYNAFORM . $this->file . '.html') && file_exists(PATH_DYNAFORM . $file . '.html')) { + self::_copyFile(PATH_DYNAFORM . $file . '.html', PATH_DYNAFORM . $this->file . '.html'); + } + } else { + $this->file = $file; + self::_setTmpData(array()); + } + } + + /** + * Set temporal data + * + * @param $data + * @return void + */ + public function _setTmpData($data) + { + G::verifyPath(PATH_C . 'dynEditor/', true); + $fp = fopen(PATH_C . 'dynEditor/' . session_id() . '.php', 'w'); + fwrite($fp, '$tmpData=unserialize(\'' . addcslashes(serialize($data), '\\\'') . '\');'); + fclose($fp); + } + + /** + * Get temporal data + * + * @param string $filename + * @return array + */ + public function _getTmpData() + { + $tmpData = array(); + $file = PATH_C . 'dynEditor/' . session_id() . '.php'; + if (file_exists($file)) { + eval(implode('', file($file))); + } + return $tmpData; + } + + /** + * Copy files + * + * @param file $from + * @param file $to + * @return void + */ + public function _copyFile($from, $to) + { + $copy = implode('', file($from)); + $fcopy = fopen($to, "w"); + fwrite($fcopy, $copy); + fclose($fcopy); + } +} diff --git a/workflow/engine/classes/class.dynaformEditor.php b/workflow/engine/classes/DynaformEditorAjax.php similarity index 62% rename from workflow/engine/classes/class.dynaformEditor.php rename to workflow/engine/classes/DynaformEditorAjax.php index 7f402904b..a27f73dbb 100644 --- a/workflow/engine/classes/class.dynaformEditor.php +++ b/workflow/engine/classes/DynaformEditorAjax.php @@ -1,1019 +1,694 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ -/** - * Created on 21/12/2007 - * Dynaform - Dynaform class - * - * @copyright 2007 COLOSA - * @author David Callizaya - */ - -/** - * - * @package workflow.engine.classes - */ -class dynaformEditor extends WebResource -{ - - private $isOldCopy = false; - public $file = ''; - public $title = 'New Dynaform'; - public $dyn_uid = ''; - public $dyn_type = ''; - public $home = ''; - - /** - * Other Options for Editor: - * left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))', - * top: 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))', - * height: '3/4*(document.body.clientWidth-getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))*2)', - * left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))' - * left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))' - * - * Other Options for Toolbar: - * left: 'getAbsoluteLeft(document.getElementById("dynaformEditor[0]"))', - * top: 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))', - */ - public $defaultConfig = array('Editor' => array('left' => '0', 'top' => '0', 'width' => 'document.body.clientWidth-4', 'height' => 'document.body.clientHeight-4'), - 'Toolbar' => array('left' => 'document.body.clientWidth-2-toolbar.clientWidth-24-3+7', 'top' => '52'), - 'FieldsList' => array('left' => '4+toolbar.clientWidth+24', 'top' => 'getAbsoluteTop(document.getElementById("dynaformEditor[0]"))', 'width' => 244, 'height' => 400) - ); - public $panelConf = array('style' => array('title' => array('textAlign' => 'center')), - 'width' => 700, 'height' => 600, 'tabWidth' => 120, 'modal' => true, 'drag' => false, 'resize' => false, 'blinkToFront' => false - ); - - /** - * Constructor of the class dynaformEditor - * - * @param string $get - * @return void - */ - public function dynaformEditor($get) - { - $this->panelConf = array_merge($this->panelConf, $this->defaultConfig['Editor']); - //'title' => G::LoadTranslation('ID_DYNAFORM_EDITOR').' - ['.$this->title.']', - } - - /** - * Create the xml form default - * - * @param string $filename - * @return void - */ - public function _createDefaultXmlForm($fileName) - { - //Create the default Dynaform - $sampleForm = '' . "\n"; - $sampleForm .= '' . "\n"; - switch ($this->dyn_type) { - case "xmlform": - /* $sampleForm.='' . "\n" . - ' <en>Sample form</en>' . "\n" . - ''."\n"; - $sampleForm.='' . "\n" . - ' Submit' . "\n" . - ''."\n"; */ - break; - case "grid": - /* $sampleForm.='' . "\n" . - 'A' . "\n" . - ''."\n"; - $sampleForm.='' . "\n" . - 'B' . "\n" . - ''."\n"; */ - break; - } - $sampleForm .= ''; - G::verifyPath(dirname($fileName), true); - $fp = fopen($fileName, 'w'); - $sampleForm = str_replace('name=""', 'name="' . $this->_getFilename($this->file) . '"', $sampleForm); - fwrite($fp, $sampleForm); - fclose($fp); - } - - /** - * Prints the DynaformEditor - * - * @return void - */ - public function _render() - { - global $G_PUBLISH; - $script = ''; - - /* Start Block: Load (Create if doesn't exist) the xmlform */ - $Parameters = array('SYS_LANG' => SYS_LANG, 'URL' => G::encrypt($this->file, URL_KEY), 'DYN_UID' => $this->dyn_uid, 'PRO_UID' => $this->pro_uid, 'DYNAFORM_NAME' => $this->dyn_title, 'FILE' => $this->file, 'DYN_EDITOR' => $this->dyn_editor - ); - $_SESSION['Current_Dynafom']['Parameters'] = $Parameters; - - $XmlEditor = array('URL' => G::encrypt($this->file, URL_KEY), 'XML' => '' //$openDoc->getXml() - ); - $JSEditor = array('URL' => G::encrypt($this->file, URL_KEY) - ); - - $A = G::encrypt($this->file, URL_KEY); - - try { - $openDoc = new Xml_Document(); - $fileName = $this->home . $this->file . '.xml'; - if (file_exists($fileName)) { - $openDoc->parseXmlFile($fileName); - } else { - $this->_createDefaultXmlForm($fileName); - $openDoc->parseXmlFile($fileName); - } - //$form = new Form( $this->file , $this->home, SYS_LANG, true ); - $Properties = dynaformEditorAjax::get_properties($A, $this->dyn_uid); - /* Start Block: Prepare the XMLDB connection */ - define('DB_XMLDB_HOST', PATH_DYNAFORM . $this->file . '.xml'); - define('DB_XMLDB_USER', ''); - define('DB_XMLDB_PASS', ''); - define('DB_XMLDB_NAME', ''); - define('DB_XMLDB_TYPE', 'myxml'); - /* Start Block: Prepare the dynaformEditor */ - $G_PUBLISH = new Publisher(); - $sName = 'dynaformEditor'; - $G_PUBLISH->publisherId = $sName; - $oHeadPublisher = & headPublisher::getSingleton(); - $oHeadPublisher->setTitle(G::LoadTranslation('ID_DYNAFORM_EDITOR') . ' - ' . $Properties['DYN_TITLE']); - $G_PUBLISH->AddContent('blank'); - $this->panelConf['title'] = ''; - $G_PUBLISH->AddContent('panel-init', 'mainPanel', $this->panelConf); - if ($Properties['DYN_TYPE'] == 'xmlform') { - $G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_Toolbar', 'display:none', $Parameters, '', ''); - } else { - $G_PUBLISH->AddContent('xmlform', 'toolbar', 'dynaforms/fields_ToolbarGrid', 'display:none', $Parameters, '', ''); - } - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Editor', 'display:none', $Parameters, '', ''); - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_XmlEditor', 'display:none', $XmlEditor, '', ''); - $G_PUBLISH->AddContent('blank'); - $i = 0; - $aFields = array(); - $aFields[] = array('XMLNODE_NAME' => 'char', 'TYPE' => 'char', 'UP' => 'char', 'DOWN' => 'char' - ); - $oSession = new DBSession(new DBConnection(PATH_DYNAFORM . $this->file . '.xml', '', '', '', 'myxml')); - $oDataset = $oSession->Execute('SELECT * FROM dynaForm WHERE NOT( XMLNODE_NAME = "" ) AND TYPE <> "pmconnection"'); - $iMaximun = $oDataset->count(); - while ($aRow = $oDataset->Read()) { - $aFields[] = array('XMLNODE_NAME' => $aRow['XMLNODE_NAME'], 'TYPE' => $aRow['TYPE'], 'UP' => ($i > 0 ? G::LoadTranslation('ID_UP') : ''), 'DOWN' => ($i < $iMaximun - 1 ? G::LoadTranslation('ID_DOWN') : ''), 'row__' => ($i + 1) - ); - $i++; - break; - } - global $_DBArray; - $_DBArray['fields'] = $aFields; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria('dbarray'); - $oCriteria->setDBArrayTable('fields'); - /** - * *@Erik-> this is deprecated,. - * (unuseful) $G_PUBLISH->AddContent('propeltable', 'paged-table', 'dynaforms/fields_List', $oCriteria, $Parameters, '', SYS_URI.'dynaforms/dynaforms_PagedTableAjax');** - */ - $G_PUBLISH->AddContent('blank'); - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_JSEditor', 'display:none', $JSEditor, '', ''); - } catch (Exception $e) { - - } - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_Properties', 'display:none', $Properties, '', ''); - //for showHide tab option @Neyek - $G_PUBLISH->AddContent('blank'); - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_PREVIEW"), $sName . '[3]', 'dynaformEditor.changeToPreview', 'dynaformEditor.saveCurrentView'); - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_XML"), $sName . '[4]', 'dynaformEditor.changeToXmlCode', 'dynaformEditor.saveCurrentView'); - if ($Properties['DYN_TYPE'] != 'grid') { - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_HTML"), $sName . '[5]', 'dynaformEditor.changeToHtmlCode', 'dynaformEditor.saveCurrentView'); - } - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_FIELDS_LIST"), $sName . '[6]', 'dynaformEditor.changeToFieldsList', 'dynaformEditor.saveCurrentView'); - if ($Properties["DYN_TYPE"] != "grid") { - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_JAVASCRIPTS"), $sName . '[7]', 'dynaformEditor.changeToJavascripts', 'dynaformEditor.saveCurrentView'); - } - $G_PUBLISH->AddContent('panel-tab', G::LoadTranslation("ID_PROPERTIES"), $sName . '[8]', 'dynaformEditor.changeToProperties', 'dynaformEditor.saveCurrentView'); - - //for showHide tab option @Neyek - if ($Properties["DYN_TYPE"] != "grid") { - $G_PUBLISH->AddContent("panel-tab", G::LoadTranslation("ID_CONDITIONS_EDITOR"), $sName . "[9]", "dynaformEditor.changeToShowHide", "dynaformEditor.saveShowHide"); - } - - $G_PUBLISH->AddContent('panel-close'); - $oHeadPublisher->addScriptFile("/js/maborak/core/maborak.loader.js",2); - $oHeadPublisher->addScriptFile('/jscore/dynaformEditor/core/dynaformEditor.js'); - - $oHeadPublisher->addScriptFile('/js/codemirrorOld/js/codemirror.js',1); - - $oHeadPublisher->addScriptFile('/js/grid/core/grid.js'); - $oHeadPublisher->addScriptCode(' - var DYNAFORM_URL="' . $Parameters['URL'] . '"; - leimnud.event.add(window,"load",function(){ loadEditor(); }); - '); - $oHeadPublisher->addScriptCode(' var jsMeta;var __usernameLoggedDE__ = "' . (isset($_SESSION['USR_USERNAME']) ? $_SESSION['USR_USERNAME'] : '') . '";var SYS_LANG = "' . SYS_LANG . '";var __DYN_UID__ = "' . $this->dyn_uid . '";'); - - $arrayParameterAux = $Parameters; - $arrayParameterAux["DYNAFORM_NAME"] = base64_encode($arrayParameterAux["DYNAFORM_NAME"]); - $oHeadPublisher->addScriptCode('var dynaformEditorParams = \'' . serialize($arrayParameterAux) . '\';'); - - G::RenderPage("publish", 'blank'); - } - - /** - * Get the filename - * - * @param string $file - * @return string - */ - public function _getFilename($file) - { - return (strcasecmp(substr($file, - 5), '_tmp0') == 0) ? substr($file, 0, strlen($file) - 5) : $file; - } - - /** - * Set the temporal copy - * - * @param string $onOff - * @return void - */ - public function _setUseTemporalCopy($onOff) - { - $file = self::_getFilename($this->file); - if ($onOff) { - $this->file = $file . '_tmp0'; - self::_setTmpData(array('useTmpCopy' => true )); - if (!file_exists(PATH_DYNAFORM . $file . '.xml')) { - $this->_createDefaultXmlForm(PATH_DYNAFORM . $file . '.xml'); - } - //Creates a copy if it doesn't exist, else, use the old copy - if (!file_exists(PATH_DYNAFORM . $this->file . '.xml')) { - self::_copyFile(PATH_DYNAFORM . $file . '.xml', PATH_DYNAFORM . $this->file . '.xml'); - } - if (!file_exists(PATH_DYNAFORM . $this->file . '.html') && file_exists(PATH_DYNAFORM . $file . '.html')) { - self::_copyFile(PATH_DYNAFORM . $file . '.html', PATH_DYNAFORM . $this->file . '.html'); - } - } else { - $this->file = $file; - self::_setTmpData(array()); - } - } - - /** - * Set temporal data - * - * @param $data - * @return void - */ - public function _setTmpData($data) - { - G::verifyPath(PATH_C . 'dynEditor/', true); - $fp = fopen(PATH_C . 'dynEditor/' . session_id() . '.php', 'w'); - fwrite($fp, '$tmpData=unserialize(\'' . addcslashes(serialize($data), '\\\'') . '\');'); - fclose($fp); - } - - /** - * Get temporal data - * - * @param string $filename - * @return array - */ - public function _getTmpData() - { - $tmpData = array(); - $file = PATH_C . 'dynEditor/' . session_id() . '.php'; - if (file_exists($file)) { - eval(implode('', file($file))); - } - return $tmpData; - } - - /** - * Copy files - * - * @param file $from - * @param file $to - * @return void - */ - public function _copyFile($from, $to) - { - $copy = implode('', file($from)); - $fcopy = fopen($to, "w"); - fwrite($fcopy, $copy); - fclose($fcopy); - } -} - -interface iDynaformEditorAjax -{ - //public function render_preview($A); -} - -/** - * DynaformEditorAjax - DynaformEditorAjax class - * - * @package workflow.engine.classes - */ -class dynaformEditorAjax extends dynaformEditor implements iDynaformEditorAjax -{ - - /** - * Constructor of the class dynaformEditorAjax - * - * @param var $post - * @return void - */ - public function dynaformEditorAjax($post) - { - $this->_run($post); - } - - /** - * Function Run - * - * @param var $post - * @return void - */ - public function _run($post) - { - WebResource::WebResource($_SERVER['REQUEST_URI'], $post); - } - - /** - * Prints the DynaformEditorAjax - * - * @param object $A - * @return ob_get_clean - */ - public function render_preview($A) - { - ob_start(); - $file = G::decrypt($A, URL_KEY); - global $G_PUBLISH; - $G_PUBLISH = new Publisher(); - $G_PUBLISH->publisherId = 'preview'; - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true, $G_PUBLISH->publisherId); - switch (basename($form->template, '.html')) { - case 'grid': - $template = 'grid'; - $aAux = array_keys($form->fields); - if (count($aAux) > 0) { - $aFields = (array_combine($aAux, $aAux)); - } else { - $aFields = $aAux; - } - if (is_array($aFields)) { - foreach ($aFields as $key => $val) { - $aFields[$key] = array(1 => "", 2 => "", 3 => "", 4 => "", 5 => ""); - } - } - break; - default: - $template = 'xmlform_' . $G_PUBLISH->publisherId; - $aFields = array('__DYNAFORM_OPTIONS' => array('PREVIOUS_STEP' => '#', 'NEXT_STEP' => '#', 'NEXT_STEP_LABEL' => G::loadTranslation('ID_NEXT_STEP'), 'PREVIOUS_ACTION' => 'return false;', 'NEXT_ACTION' => 'return false;' - ) - ); - } - $G_PUBLISH->AddContent('dynaform', $template, $file, '', $aFields, ''); - G::RenderPage('publish', 'raw'); - return ob_get_clean(); - } - - /** - * Prints the Dynaform in format HTML - * - * @param object $A - * @return array - */ - public function render_htmledit($A) - { - $script = ''; - $file = G::decrypt($A, URL_KEY); - ob_start(); - global $G_PUBLISH; - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $G_PUBLISH = new Publisher(); - $G_PUBLISH->publisherId = ''; - $html = $this->get_htmlcode($A); - if (!is_string($html)) { - $error = $html; - $html = ''; - } else { - $error = 0; - } - $HtmlEditor = array('URL' => $A, 'HTML' => $html, 'DYN_UID' => $file ); - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_HtmlEditor', '', $HtmlEditor, '', ''); - G::RenderPage("publish", 'raw'); - return array('error' => $error, 'html' => ob_get_clean() - ); - } - - /** - * Get the html code - * Loads the stored HTML or the default Template if - * it doesn't exist. - * - * @param object $A - * @return code html - */ - public function get_htmlcode($A) - { - try { - $script = null; - $fileTmp = G::decrypt($A, URL_KEY); - $form = new Form($fileTmp, PATH_DYNAFORM, SYS_LANG, true); - - //Navigation Bar - $form->fields = G::array_merges(array("__DYNAFORM_OPTIONS" => new XmlForm_Field_XmlMenu(new Xml_Node("__DYNAFORM_OPTIONS", "complete", "", array("type" => "xmlmenu", "xmlfile" => "gulliver/dynaforms_Options" - )), SYS_LANG, PATH_XMLFORM, $form) - ), $form->fields); - - //Loads the stored HTML or the default Template if - //it doesn't exist. - $filename = substr($form->fileName, 0, - 3) . ($form->type === "xmlform" ? "" : "." . $form->type) . "html"; - - if (!file_exists($filename)) { - $html = $form->printTemplate($form->template, $script); - } else { - $html = implode("", file($filename)); - } - - /* - * It adds the new fields automatically at the bottom of the form. - * TODO: �TOP OR BOTTOM? - * Improving detection algorithm of new fields. - * Current: Do not check the fields that have already been reviewed (saving) - * Already checked the temporary file dynaforms editor. - */ - $tmp = self::_getTmpData(); - if (!isset($tmp['OLD_FIELDS'])) { - $tmp['OLD_FIELDS'] = array(); //var_dump($html);die; - } - $aAux = explode('', $html); - foreach ($form->fields as $field) { - if ((strpos($html, '{$form.' . $field->name . '}') === false) && (strpos($html, '{$' . $field->name . '}') === false)) { - //Aparantly is new (but could be a deleted or non visible like private type fields) - switch (strtolower($field->type)) { - case 'private': - case 'phpvariable': - break; - default: - if (array_search($field->name, $tmp['OLD_FIELDS']) === false) { - //TOP - $aAux[0] .= '
{$' . $field->name . '}' . '{$form.' . $field->name . '}'; - //$html.='
{$'.$field->name.'}'.'{$form.'.$field->name.'}'; - //BOTTOM - //$html='{$'.$field->name.'}'.'{$form.'.$field->name.'}'.$html; - //$tmp['OLD_FIELDS'][]=$field->name; - } - } - } - } - self::_setTmpData($tmp); - //$html=str_replace('{$form_className}','formDefault', $html ); - $html = str_replace('{$form_className}', 'formDefault', $aAux[0] . ''); - - return $html; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Restore the html code - * - * @param object $A - * @return code html - */ - public function restore_html($A) - { - - $filter = new InputFilter(); - $script = null; - $fileTmp = G::decrypt($A, URL_KEY); - $form = new Form($fileTmp, PATH_DYNAFORM, SYS_LANG, true); - - //Navigation Bar - $form->fields = G::array_merges(array("__DYNAFORM_OPTIONS" => new XmlForm_Field_XmlMenu(new Xml_Node("__DYNAFORM_OPTIONS", "complete", "", array("type" => "xmlmenu", "xmlfile" => "gulliver/dynaforms_Options" - )), SYS_LANG, PATH_XMLFORM, $form) - ), $form->fields); - - $form->enableTemplate = false; - $html = $form->printTemplate($form->template, $script); - $html = str_replace('{$form_className}', 'formDefault', $html); - $pathTmp = $filter->xssFilterHard(PATH_DYNAFORM . $fileTmp . '.html', 'path'); - if (file_exists($pathTmp)) { - unlink($pathTmp); - } - $fp = fopen($pathTmp, 'w'); - fwrite($fp, $html); - fclose($fp); - - return $html; - } - - /** - * Set the html code - * - * @param object $A - * @return array - */ - public function set_htmlcode($A, $htmlcode) - { - try { - - $filter = new InputFilter(); - $iOcurrences = preg_match_all('/\{\$.*?\}/im', $htmlcode, $matches); - if ($iOcurrences) { - if (isset($matches[0])) { - $tagsHtml = $matches[0]; - foreach ($tagsHtml as $value) { - $aTagVar = strip_tags($value); - if ($value != $aTagVar) { - $htmlcode = str_replace($value, $aTagVar, $htmlcode); - } - } - } - } - $file = G::decrypt($A, URL_KEY); - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $filename = substr($form->fileName, 0, - 3) . ($form->type === 'xmlform' ? '' : '.' . $form->type) . 'html'; - $filename = $filter->xssFilterHard($filename, 'path'); - $fp = fopen($filename, 'w'); - fwrite($fp, $htmlcode); - fclose($fp); - return 0; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Get the xml code - * - * @param object $A - * @return array - */ - public function get_xmlcode($A) - { - try { - $file = G::decrypt($A, URL_KEY); - $xmlcode = implode('', file(PATH_DYNAFORM . $file . '.xml')); - return array("xmlcode" => $xmlcode, "error" => 0 - ); - } catch (Exception $e) { - return array("xmlcode" => "", "error" => (array) $e - ); - } - } - - /** - * Set the xml code - * - * @param object $A - * @param array $xmlcode - * @return string - */ - public function set_xmlcode($A, $xmlcode) - { - - $filter = new InputFilter(); - $xmlcode = urldecode($xmlcode); - $file = G::decrypt($A, URL_KEY); - $xmlcode = str_replace(' ', ' ', trim($xmlcode)); - $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . $file . '.xml', "path"); - $fp = fopen($pathFile, 'w'); - fwrite($fp, $xmlcode); - fclose($fp); - return ""; - } - - /** - * Get the javascript code - * - * @param object $A - * @param string $fieldName - * @return array - */ - public function get_javascripts($A, $fieldName) - { - try { - $file = G::decrypt($A, URL_KEY); - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $aOptions = array(); - $sCode = ''; - foreach ($form->fields as $name => $value) { - if (strcasecmp($value->type, "javascript") == 0) { - $aOptions[] = array('key' => $name, 'value' => $name - ); - if ($name == $fieldName) { - $sCode = $value->code; - } - } - } - return array('aOptions' => $aOptions, 'sCode' => $sCode - ); - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Set the javascript code - * - * @param object $A - * @param string $fieldName - * @param string $sCode - * @return array - */ - public function set_javascript($A, $fieldName, $sCode, $meta = '') - { - - $filter = new InputFilter(); - $fieldName = $filter->xssFilterHard($fieldName, 'path'); - if ($fieldName == '___pm_boot_strap___') { - return 0; - } - - $sCode = urldecode($sCode); - try { - $sCode = rtrim($sCode); - $file = G::decrypt($A, URL_KEY); - /* $dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml' ,'','','','myxml' ); - $ses2 = new DBSession($dbc2); - $ses2->execute(G::replaceDataField("UPDATE dynaForm SET XMLNODE_VALUE = @@CODE WHERE XMLNODE_NAME = @@FIELDNAME ", array('FIELDNAME'=>$fieldName,'CODE'=>$sCode), "myxml" )); - */ - - - $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); - $dynaform = new DynaformHandler($pathFile); - $dynaform->replace($fieldName, $fieldName, Array('type' => 'javascript', 'meta' => $meta, '#cdata' => $sCode - )); - - return 0; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Get properties of the dynaForm - * - * @param file $A - * @param string $DYN_UID - * @return array - */ - public function get_properties($A, $DYN_UID) - { - $file = G::decrypt($A, URL_KEY); - $tmp = self::_getTmpData(); - if (!(isset($tmp['Properties']) && isset($tmp['useTmpCopy']))) { - $dynaform = new Dynaform(); - $dynaform->load($DYN_UID); - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $Properties = array('A' => $A, 'DYN_UID' => $dynaform->getDynUid(), 'PRO_UID' => $dynaform->getProUid(), 'DYN_TITLE' => $dynaform->getDynTitle(), 'DYN_TYPE' => $dynaform->getDynType(), 'DYN_DESCRIPTION' => $dynaform->getDynDescription(), 'WIDTH' => $form->width, - //'ENABLETEMPLATE'=> $form->enableTemplate, - 'MODE' => $form->mode, 'PRINTDYNAFORM' => $form->printdynaform, 'ADJUSTGRIDSWIDTH' => $form->adjustgridswidth, 'NEXTSTEPSAVE' => $form->nextstepsave - ); - $tmp['Properties'] = $Properties; - self::_setTmpData($tmp); - } else { - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $Properties = $tmp['Properties']; - if (!isset($Properties['ENABLETEMPLATE'])) { - $Properties['ENABLETEMPLATE'] = "0"; - } - $Properties['WIDTH'] = $form->width; - $Properties['MODE'] = $form->mode; - } - return $Properties; - } - - /** - * Set properties of the dynaForm - * - * @param file $A - * @param string $DYN_UID - * @param array $getFields - * @return array - */ - public function set_properties($A, $DYN_UID, $getFields) - { - try { - - $filter = new InputFilter(); - $post = array(); - parse_str($getFields, $post); - $Fields = $post['form']; - //if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0"; - $file = G::decrypt($A, URL_KEY); - $tmp = self::_getTmpData(); - if (!isset($tmp['useTmpCopy'])) { - $dynaform = new Dynaform(); - $dynaform->update($Fields); - } else { - $tmp['Properties'] = $Fields; - self::_setTmpData($tmp); - } - $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); - $dynaform = new DynaformHandler($pathFile); - $dbc2 = new DBConnection($pathFile, '', '', '', 'myxml'); - $ses2 = new DBSession($dbc2); - //if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0"; - - /* if (isset($Fields['ENABLETEMPLATE'])) { - $ses2->execute(G::replaceDataField("UPDATE . SET ENABLETEMPLATE = @@ENABLETEMPLATE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields)); - } */ - if (isset($Fields['DYN_TYPE'])) { - //$ses2->execute( G::replaceDataField( "UPDATE . SET TYPE = @@DYN_TYPE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('type', $Fields['DYN_TYPE']); - } - if (isset($Fields['WIDTH'])) { - // $ses2->execute( G::replaceDataField( "UPDATE . SET WIDTH = @@WIDTH WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('width', $Fields['WIDTH']); - //g::pr($dynaform->getHeaderAttribute('width')); - } - if (isset($Fields['MODE'])) { - // $ses2->execute( G::replaceDataField( "UPDATE . SET MODE = @@MODE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('mode', $Fields['MODE']); - } - if (isset($Fields['NEXTSTEPSAVE'])) { - //$ses2->execute( G::replaceDataField( "UPDATE . SET NEXTSTEPSAVE = @@NEXTSTEPSAVE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('nextstepsave', $Fields['NEXTSTEPSAVE']); - } - if (isset($Fields['PRINTDYNAFORM'])) { - //$ses2->execute( G::replaceDataField( "UPDATE . SET PRINTDYNAFORM = @@PRINTDYNAFORM WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('printdynaform', $Fields['PRINTDYNAFORM']); - } - if (isset($Fields['ADJUSTGRIDSWIDTH'])) { - //$ses2->execute( G::replaceDataField( "UPDATE . SET ADJUSTGRIDSWIDTH = @@ADJUSTGRIDSWIDTH WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); - $dynaform->modifyHeaderAttribute('adjustgridswidth', $Fields['ADJUSTGRIDSWIDTH']); - } - - return 0; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Get enable template - * - * @param object $A - * @return string - */ - public function get_enabletemplate($A) - { - $file = G::decrypt($A, URL_KEY); - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - return $form->enableTemplate; - } - - /** - * Set enable template - * - * @param object $A - * @param string $value - * @return string - */ - public function set_enabletemplate($A, $value) - { - - $filter = new InputFilter(); - $file = G::decrypt($A, URL_KEY); - $value = $value == "1" ? "1" : "0"; - // $dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml', '', '', '', 'myxml' ); - // $ses2 = new DBSession( $dbc2 ); - // $ses2->execute( "UPDATE . SET ENABLETEMPLATE = '$value'" ); - $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); - $dynaform = new DynaformHandler($pathFile); - $dynaform->modifyHeaderAttribute('enabletemplate', $value); - - return $value; - } - - /** - * Save a dynaForm - * - * @param object $A - * @param string $DYN_UID - * @return array - */ - public function save($A, $DYN_UID) - { - try { - $answer = 0; - $file = G::decrypt($A, URL_KEY); - $tmp = self::_getTmpData(); - if (isset($tmp['Properties'])){ - $fileFirst = $tmp['Properties']['PRO_UID'].'/'.$tmp['Properties']['DYN_UID']; - } - if (isset($tmp['useTmpCopy'])) { - /* Save Register */ - $dynaform = new Dynaform(); - $dynaform->update($tmp['Properties']); - /* Save file */ - $copyFirst = implode('', file(PATH_DYNAFORM . $fileFirst . '.xml')); - $copy = implode('', file(PATH_DYNAFORM . $file . '.xml')); - /*Check differences between XML*/ - $elementFirst = new SimpleXMLElement($copyFirst); - $elementCopy = new SimpleXMLElement($copy); - $desAdd = ''; - $desDel = ''; - //Check the new fields - foreach ($elementCopy as $key1 => $row1){ - $swAll = true; - foreach ($elementFirst as $key2 => $row2){ - if ($key1 == $key2){ - $swAll = false; - break; - } - } - if ($swAll){ - $desAdd .= $key1." "; - } - } - //Check the delete fields - foreach ($elementFirst as $key1 => $row1){ - $swAll = true; - foreach ($elementCopy as $key2 => $row2){ - if ($key1 == $key2){ - $swAll = false; - break; - } - } - if ($swAll){ - $desDel .= $key1." "; - } - } - - $mode = empty($tmp['Properties']['MODE'])? 'Determined by Fields' : $tmp['Properties']['MODE']; - $auditDescription = "Dynaform Title: ".$tmp['Properties']['DYN_TITLE'].", Type: ".$tmp['Properties']['DYN_TYPE'].", Description: ".$tmp['Properties']['DYN_DESCRIPTION'].", Mode: ".$mode; - if($desAdd != ''){ - $auditDescription .= ", Field(s) Add: ".$desAdd; - } - if($desDel != ''){ - $auditDescription .= ", Field(s) Delete: ".$desDel; - } - //Add Audit Log - G::auditLog("UpdateDynaform", $auditDescription); - - - /* - * added by krlos carlos/a/colosa.com - * in here we are validation if a xmlform has a submit action - */ - // if (!preg_match("/type=\"submit\"/",$copy) && !preg_match("/type=\"grid\"/",$copy) && !isset($_SESSION['submitAction']) ){ - if (!preg_match("/type=\"submit\"/", $copy) && !preg_match("/type=\"grid\"/", $copy)) { - // $_SESSION['submitAction'] = 1; - $answer = 'noSub'; - } - $copyHtml = false; - if (file_exists(PATH_DYNAFORM . $file . '.html')) { - $copyHtml = implode('', file(PATH_DYNAFORM . $file . '.html')); - } - $file = dynaformEditor::_getFilename($file); - $fcopy = fopen(PATH_DYNAFORM . $file . '.xml', "w"); - fwrite($fcopy, $copy); - fclose($fcopy); - if ($copyHtml) { - $fcopy = fopen(PATH_DYNAFORM . $file . '.html', "w"); - fwrite($fcopy, $copyHtml); - fclose($fcopy); - } - } else { - //throw new Exception("It should not come here unless you have disabled the temporary copy."); - } - return $answer; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Close a dynaform - * - * @param object $A - * @return array - */ - public function close($A) - { - try { - /* - * we are unseting this variable. It's our control about to save the xmlfrom - */ - // unset($_SESSION['submitAction']); - $file = G::decrypt($A, URL_KEY); - //return(array('response'=>PATH_DYNAFORM . $file . '.xml')); - /* Delete the temporal copy */ - $tmp = self::_getTmpData(); - $xmlFile = PATH_DYNAFORM . $file . '.xml'; - $htmlFile = PATH_DYNAFORM . $file . '.html'; - //return(array('response'=>$tmp['useTmpCopy'])); - if (isset($tmp['useTmpCopy'])) { - //return(array('response'=>PATH_DYNAFORM . $file . '.xml')); - if ($file !== dynaformEditor::_getFilename($file)) { - // return(array('response'=>PATH_DYNAFORM . $file . '.xml')); - if (file_exists($xmlFile)) { - unlink($xmlFile); - } - if (file_exists($htmlFile)) { - unlink($htmlFile); - } - } - } - return 0; - } catch (Exception $e) { - return (array) $e; - } - } - - /** - * Checks if a dynaform was changed - * - * @param file $A - * @param string $DYN_UID - * @return array - */ - public function is_modified($A, $DYN_UID) - { - $file = G::decrypt($A, URL_KEY); - try { - /* Compare Properties */ - $dynaform = new Dynaform(); - $dynaform->load($DYN_UID); - $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); - $sp = array('A' => $A, 'DYN_UID' => $dynaform->getDynUid(), 'PRO_UID' => $dynaform->getProUid(), 'DYN_TITLE' => $dynaform->getDynTitle(), 'DYN_TYPE' => $dynaform->getDynType(), 'DYN_DESCRIPTION' => $dynaform->getDynDescription(), 'WIDTH' => $form->width, 'ENABLETEMPLATE' => $form->enableTemplate, 'MODE' => $form->mode - ); - $P = self::get_properties($A, $DYN_UID); - if (!isset($P['DYN_TITLE'])) { - $P['DYN_TITLE'] = $sp['DYN_TITLE']; - } - if (!isset($P['DYN_TYPE'])) { - $P['DYN_TYPE'] = $sp['DYN_TYPE']; - } - if (!isset($P['DYN_DESCRIPTION'])) { - $P['DYN_DESCRIPTION'] = $sp['DYN_DESCRIPTION']; - } - if (!isset($P['WIDTH'])) { - $P['WIDTH'] = $sp['WIDTH']; - } - if (!isset($P['ENABLETEMPLATE'])) { - $P['ENABLETEMPLATE'] = $sp['ENABLETEMPLATE']; - } - if (!isset($P['MODE'])) { - $P['MODE'] = $sp['MODE']; - } - $modPro = ($sp['DYN_TITLE'] != $P['DYN_TITLE']) || ($sp['DYN_TYPE'] != $P['DYN_TYPE']) || ($sp['DYN_DESCRIPTION'] != $P['DYN_DESCRIPTION']); - /* || - ($sp['WIDTH']!=$P['WIDTH']) || - ($sp['ENABLETEMPLATE']!=$P['ENABLETEMPLATE']) || - ($sp['MODE']!=$P['MODE']) */ - /* Compare copies */ - $fileOrigen = dynaformEditor::_getFilename($file); - $copy = implode('', file(PATH_DYNAFORM . $file . '.xml')); - $origen = implode('', file(PATH_DYNAFORM . $fileOrigen . '.xml')); - $copyHTML = file_exists(PATH_DYNAFORM . $file . '.html') ? implode('', file(PATH_DYNAFORM . $file . '.html')) : false; - $origenHTML = file_exists(PATH_DYNAFORM . $fileOrigen . '.html') ? implode('', file(PATH_DYNAFORM . $fileOrigen . '.html')) : false; - $modFile = ($copy !== $origen) || ($origenHTML && ($copyHTML !== $origenHTML)); - //Return - //return array("*message"=>sprintf("%s, (%s= %s %s):", $modPro?"1":"0" , $modFile?"1":"0", ($copy!==$origen)?"1":"0" , ($origenHTML && ($copyHTML!==$origenHTML))?"1":"0" )); - //die("c'est fini"); - return $modPro || $modFile; - } catch (Exception $e) { - return (array) $e; - } - } - /* - Functionality: Funcion que convierte objecto en array - Parameters : Object $object que queremos convertir - Return: Array - */ - public function convertObjectToArray($object){ - if( !is_object( $object ) && !is_array( $object ) ){ - return $object; - } - if( is_object( $object ) ){ - $object = get_object_vars( $object ); - } - return array_map( 'objectToArray', $object ); - } -} +_run($post); + } + + /** + * Function Run + * + * @param var $post + * @return void + */ + public function _run($post) + { + WebResource::WebResource($_SERVER['REQUEST_URI'], $post); + } + + /** + * Prints the DynaformEditorAjax + * + * @param object $A + * @return ob_get_clean + */ + public function render_preview($A) + { + ob_start(); + $file = G::decrypt($A, URL_KEY); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->publisherId = 'preview'; + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true, $G_PUBLISH->publisherId); + switch (basename($form->template, '.html')) { + case 'grid': + $template = 'grid'; + $aAux = array_keys($form->fields); + if (count($aAux) > 0) { + $aFields = (array_combine($aAux, $aAux)); + } else { + $aFields = $aAux; + } + if (is_array($aFields)) { + foreach ($aFields as $key => $val) { + $aFields[$key] = array(1 => "", 2 => "", 3 => "", 4 => "", 5 => ""); + } + } + break; + default: + $template = 'xmlform_' . $G_PUBLISH->publisherId; + $aFields = array('__DYNAFORM_OPTIONS' => array('PREVIOUS_STEP' => '#', 'NEXT_STEP' => '#', 'NEXT_STEP_LABEL' => G::loadTranslation('ID_NEXT_STEP'), 'PREVIOUS_ACTION' => 'return false;', 'NEXT_ACTION' => 'return false;' + ) + ); + } + $G_PUBLISH->AddContent('dynaform', $template, $file, '', $aFields, ''); + G::RenderPage('publish', 'raw'); + return ob_get_clean(); + } + + /** + * Prints the Dynaform in format HTML + * + * @param object $A + * @return array + */ + public function render_htmledit($A) + { + $script = ''; + $file = G::decrypt($A, URL_KEY); + ob_start(); + global $G_PUBLISH; + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->publisherId = ''; + $html = $this->get_htmlcode($A); + if (!is_string($html)) { + $error = $html; + $html = ''; + } else { + $error = 0; + } + $HtmlEditor = array('URL' => $A, 'HTML' => $html, 'DYN_UID' => $file ); + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'dynaforms/dynaforms_HtmlEditor', '', $HtmlEditor, '', ''); + G::RenderPage("publish", 'raw'); + return array('error' => $error, 'html' => ob_get_clean() + ); + } + + /** + * Get the html code + * Loads the stored HTML or the default Template if + * it doesn't exist. + * + * @param object $A + * @return code html + */ + public function get_htmlcode($A) + { + try { + $script = null; + $fileTmp = G::decrypt($A, URL_KEY); + $form = new Form($fileTmp, PATH_DYNAFORM, SYS_LANG, true); + + //Navigation Bar + $form->fields = G::array_merges(array("__DYNAFORM_OPTIONS" => new XmlFormFieldXmlMenu(new Xml_Node("__DYNAFORM_OPTIONS", "complete", "", array("type" => "xmlmenu", "xmlfile" => "gulliver/dynaforms_Options" + )), SYS_LANG, PATH_XMLFORM, $form) + ), $form->fields); + + //Loads the stored HTML or the default Template if + //it doesn't exist. + $filename = substr($form->fileName, 0, - 3) . ($form->type === "xmlform" ? "" : "." . $form->type) . "html"; + + if (!file_exists($filename)) { + $html = $form->printTemplate($form->template, $script); + } else { + $html = implode("", file($filename)); + } + + /* + * It adds the new fields automatically at the bottom of the form. + * TODO: �TOP OR BOTTOM? + * Improving detection algorithm of new fields. + * Current: Do not check the fields that have already been reviewed (saving) + * Already checked the temporary file dynaforms editor. + */ + $tmp = self::_getTmpData(); + if (!isset($tmp['OLD_FIELDS'])) { + $tmp['OLD_FIELDS'] = array(); //var_dump($html);die; + } + $aAux = explode('', $html); + foreach ($form->fields as $field) { + if ((strpos($html, '{$form.' . $field->name . '}') === false) && (strpos($html, '{$' . $field->name . '}') === false)) { + //Aparantly is new (but could be a deleted or non visible like private type fields) + switch (strtolower($field->type)) { + case 'private': + case 'phpvariable': + break; + default: + if (array_search($field->name, $tmp['OLD_FIELDS']) === false) { + //TOP + $aAux[0] .= '
{$' . $field->name . '}' . '{$form.' . $field->name . '}'; + //$html.='
{$'.$field->name.'}'.'{$form.'.$field->name.'}'; + //BOTTOM + //$html='{$'.$field->name.'}'.'{$form.'.$field->name.'}'.$html; + //$tmp['OLD_FIELDS'][]=$field->name; + } + } + } + } + self::_setTmpData($tmp); + //$html=str_replace('{$form_className}','formDefault', $html ); + $html = str_replace('{$form_className}', 'formDefault', $aAux[0] . ''); + + return $html; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Restore the html code + * + * @param object $A + * @return code html + */ + public function restore_html($A) + { + + $filter = new InputFilter(); + $script = null; + $fileTmp = G::decrypt($A, URL_KEY); + $form = new Form($fileTmp, PATH_DYNAFORM, SYS_LANG, true); + + //Navigation Bar + $form->fields = G::array_merges(array("__DYNAFORM_OPTIONS" => new XmlFormFieldXmlMenu(new Xml_Node("__DYNAFORM_OPTIONS", "complete", "", array("type" => "xmlmenu", "xmlfile" => "gulliver/dynaforms_Options" + )), SYS_LANG, PATH_XMLFORM, $form) + ), $form->fields); + + $form->enableTemplate = false; + $html = $form->printTemplate($form->template, $script); + $html = str_replace('{$form_className}', 'formDefault', $html); + $pathTmp = $filter->xssFilterHard(PATH_DYNAFORM . $fileTmp . '.html', 'path'); + if (file_exists($pathTmp)) { + unlink($pathTmp); + } + $fp = fopen($pathTmp, 'w'); + fwrite($fp, $html); + fclose($fp); + + return $html; + } + + /** + * Set the html code + * + * @param object $A + * @return array + */ + public function set_htmlcode($A, $htmlcode) + { + try { + + $filter = new InputFilter(); + $iOcurrences = preg_match_all('/\{\$.*?\}/im', $htmlcode, $matches); + if ($iOcurrences) { + if (isset($matches[0])) { + $tagsHtml = $matches[0]; + foreach ($tagsHtml as $value) { + $aTagVar = strip_tags($value); + if ($value != $aTagVar) { + $htmlcode = str_replace($value, $aTagVar, $htmlcode); + } + } + } + } + $file = G::decrypt($A, URL_KEY); + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $filename = substr($form->fileName, 0, - 3) . ($form->type === 'xmlform' ? '' : '.' . $form->type) . 'html'; + $filename = $filter->xssFilterHard($filename, 'path'); + $fp = fopen($filename, 'w'); + fwrite($fp, $htmlcode); + fclose($fp); + return 0; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Get the xml code + * + * @param object $A + * @return array + */ + public function get_xmlcode($A) + { + try { + $file = G::decrypt($A, URL_KEY); + $xmlcode = implode('', file(PATH_DYNAFORM . $file . '.xml')); + return array("xmlcode" => $xmlcode, "error" => 0 + ); + } catch (Exception $e) { + return array("xmlcode" => "", "error" => (array) $e + ); + } + } + + /** + * Set the xml code + * + * @param object $A + * @param array $xmlcode + * @return string + */ + public function set_xmlcode($A, $xmlcode) + { + + $filter = new InputFilter(); + $xmlcode = urldecode($xmlcode); + $file = G::decrypt($A, URL_KEY); + $xmlcode = str_replace(' ', ' ', trim($xmlcode)); + $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . $file . '.xml', "path"); + $fp = fopen($pathFile, 'w'); + fwrite($fp, $xmlcode); + fclose($fp); + return ""; + } + + /** + * Get the javascript code + * + * @param object $A + * @param string $fieldName + * @return array + */ + public function get_javascripts($A, $fieldName) + { + try { + $file = G::decrypt($A, URL_KEY); + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $aOptions = array(); + $sCode = ''; + foreach ($form->fields as $name => $value) { + if (strcasecmp($value->type, "javascript") == 0) { + $aOptions[] = array('key' => $name, 'value' => $name + ); + if ($name == $fieldName) { + $sCode = $value->code; + } + } + } + return array('aOptions' => $aOptions, 'sCode' => $sCode + ); + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Set the javascript code + * + * @param object $A + * @param string $fieldName + * @param string $sCode + * @return array + */ + public function set_javascript($A, $fieldName, $sCode, $meta = '') + { + + $filter = new InputFilter(); + $fieldName = $filter->xssFilterHard($fieldName, 'path'); + if ($fieldName == '___pm_boot_strap___') { + return 0; + } + + $sCode = urldecode($sCode); + try { + $sCode = rtrim($sCode); + $file = G::decrypt($A, URL_KEY); + /* $dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml' ,'','','','myxml' ); + $ses2 = new DBSession($dbc2); + $ses2->execute(G::replaceDataField("UPDATE dynaForm SET XMLNODE_VALUE = @@CODE WHERE XMLNODE_NAME = @@FIELDNAME ", array('FIELDNAME'=>$fieldName,'CODE'=>$sCode), "myxml" )); + */ + + + $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); + $dynaform = new DynaformHandler($pathFile); + $dynaform->replace($fieldName, $fieldName, Array('type' => 'javascript', 'meta' => $meta, '#cdata' => $sCode + )); + + return 0; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Get properties of the dynaForm + * + * @param file $A + * @param string $DYN_UID + * @return array + */ + public function get_properties($A, $DYN_UID) + { + $file = G::decrypt($A, URL_KEY); + $tmp = self::_getTmpData(); + if (!(isset($tmp['Properties']) && isset($tmp['useTmpCopy']))) { + $dynaform = new Dynaform(); + $dynaform->load($DYN_UID); + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $Properties = array('A' => $A, 'DYN_UID' => $dynaform->getDynUid(), 'PRO_UID' => $dynaform->getProUid(), 'DYN_TITLE' => $dynaform->getDynTitle(), 'DYN_TYPE' => $dynaform->getDynType(), 'DYN_DESCRIPTION' => $dynaform->getDynDescription(), 'WIDTH' => $form->width, + //'ENABLETEMPLATE'=> $form->enableTemplate, + 'MODE' => $form->mode, 'PRINTDYNAFORM' => $form->printdynaform, 'ADJUSTGRIDSWIDTH' => $form->adjustgridswidth, 'NEXTSTEPSAVE' => $form->nextstepsave + ); + $tmp['Properties'] = $Properties; + self::_setTmpData($tmp); + } else { + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $Properties = $tmp['Properties']; + if (!isset($Properties['ENABLETEMPLATE'])) { + $Properties['ENABLETEMPLATE'] = "0"; + } + $Properties['WIDTH'] = $form->width; + $Properties['MODE'] = $form->mode; + } + return $Properties; + } + + /** + * Set properties of the dynaForm + * + * @param file $A + * @param string $DYN_UID + * @param array $getFields + * @return array + */ + public function set_properties($A, $DYN_UID, $getFields) + { + try { + + $filter = new InputFilter(); + $post = array(); + parse_str($getFields, $post); + $Fields = $post['form']; + //if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0"; + $file = G::decrypt($A, URL_KEY); + $tmp = self::_getTmpData(); + if (!isset($tmp['useTmpCopy'])) { + $dynaform = new Dynaform(); + $dynaform->update($Fields); + } else { + $tmp['Properties'] = $Fields; + self::_setTmpData($tmp); + } + $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); + $dynaform = new DynaformHandler($pathFile); + $dbc2 = new DBConnection($pathFile, '', '', '', 'myxml'); + $ses2 = new DBSession($dbc2); + //if (!isset($Fields['ENABLETEMPLATE'])) $Fields['ENABLETEMPLATE'] ="0"; + + /* if (isset($Fields['ENABLETEMPLATE'])) { + $ses2->execute(G::replaceDataField("UPDATE . SET ENABLETEMPLATE = @@ENABLETEMPLATE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields)); + } */ + if (isset($Fields['DYN_TYPE'])) { + //$ses2->execute( G::replaceDataField( "UPDATE . SET TYPE = @@DYN_TYPE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('type', $Fields['DYN_TYPE']); + } + if (isset($Fields['WIDTH'])) { + // $ses2->execute( G::replaceDataField( "UPDATE . SET WIDTH = @@WIDTH WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('width', $Fields['WIDTH']); + //g::pr($dynaform->getHeaderAttribute('width')); + } + if (isset($Fields['MODE'])) { + // $ses2->execute( G::replaceDataField( "UPDATE . SET MODE = @@MODE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('mode', $Fields['MODE']); + } + if (isset($Fields['NEXTSTEPSAVE'])) { + //$ses2->execute( G::replaceDataField( "UPDATE . SET NEXTSTEPSAVE = @@NEXTSTEPSAVE WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('nextstepsave', $Fields['NEXTSTEPSAVE']); + } + if (isset($Fields['PRINTDYNAFORM'])) { + //$ses2->execute( G::replaceDataField( "UPDATE . SET PRINTDYNAFORM = @@PRINTDYNAFORM WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('printdynaform', $Fields['PRINTDYNAFORM']); + } + if (isset($Fields['ADJUSTGRIDSWIDTH'])) { + //$ses2->execute( G::replaceDataField( "UPDATE . SET ADJUSTGRIDSWIDTH = @@ADJUSTGRIDSWIDTH WHERE XMLNODE_NAME = 'dynaForm' ", $Fields ) ); + $dynaform->modifyHeaderAttribute('adjustgridswidth', $Fields['ADJUSTGRIDSWIDTH']); + } + + return 0; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Get enable template + * + * @param object $A + * @return string + */ + public function get_enabletemplate($A) + { + $file = G::decrypt($A, URL_KEY); + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + return $form->enableTemplate; + } + + /** + * Set enable template + * + * @param object $A + * @param string $value + * @return string + */ + public function set_enabletemplate($A, $value) + { + + $filter = new InputFilter(); + $file = G::decrypt($A, URL_KEY); + $value = $value == "1" ? "1" : "0"; + // $dbc2 = new DBConnection( PATH_DYNAFORM . $file . '.xml', '', '', '', 'myxml' ); + // $ses2 = new DBSession( $dbc2 ); + // $ses2->execute( "UPDATE . SET ENABLETEMPLATE = '$value'" ); + $pathFile = $filter->xssFilterHard(PATH_DYNAFORM . "{$file}.xml", 'path'); + $dynaform = new DynaformHandler($pathFile); + $dynaform->modifyHeaderAttribute('enabletemplate', $value); + + return $value; + } + + /** + * Save a dynaForm + * + * @param object $A + * @param string $DYN_UID + * @return array + */ + public function save($A, $DYN_UID) + { + try { + $answer = 0; + $file = G::decrypt($A, URL_KEY); + $tmp = self::_getTmpData(); + if (isset($tmp['Properties'])){ + $fileFirst = $tmp['Properties']['PRO_UID'].'/'.$tmp['Properties']['DYN_UID']; + } + if (isset($tmp['useTmpCopy'])) { + /* Save Register */ + $dynaform = new Dynaform(); + $dynaform->update($tmp['Properties']); + /* Save file */ + $copyFirst = implode('', file(PATH_DYNAFORM . $fileFirst . '.xml')); + $copy = implode('', file(PATH_DYNAFORM . $file . '.xml')); + /*Check differences between XML*/ + $elementFirst = new SimpleXMLElement($copyFirst); + $elementCopy = new SimpleXMLElement($copy); + $desAdd = ''; + $desDel = ''; + //Check the new fields + foreach ($elementCopy as $key1 => $row1){ + $swAll = true; + foreach ($elementFirst as $key2 => $row2){ + if ($key1 == $key2){ + $swAll = false; + break; + } + } + if ($swAll){ + $desAdd .= $key1." "; + } + } + //Check the delete fields + foreach ($elementFirst as $key1 => $row1){ + $swAll = true; + foreach ($elementCopy as $key2 => $row2){ + if ($key1 == $key2){ + $swAll = false; + break; + } + } + if ($swAll){ + $desDel .= $key1." "; + } + } + + $mode = empty($tmp['Properties']['MODE'])? 'Determined by Fields' : $tmp['Properties']['MODE']; + $auditDescription = "Dynaform Title: ".$tmp['Properties']['DYN_TITLE'].", Type: ".$tmp['Properties']['DYN_TYPE'].", Description: ".$tmp['Properties']['DYN_DESCRIPTION'].", Mode: ".$mode; + if($desAdd != ''){ + $auditDescription .= ", Field(s) Add: ".$desAdd; + } + if($desDel != ''){ + $auditDescription .= ", Field(s) Delete: ".$desDel; + } + //Add Audit Log + G::auditLog("UpdateDynaform", $auditDescription); + + + /* + * added by krlos carlos/a/colosa.com + * in here we are validation if a xmlform has a submit action + */ + // if (!preg_match("/type=\"submit\"/",$copy) && !preg_match("/type=\"grid\"/",$copy) && !isset($_SESSION['submitAction']) ){ + if (!preg_match("/type=\"submit\"/", $copy) && !preg_match("/type=\"grid\"/", $copy)) { + // $_SESSION['submitAction'] = 1; + $answer = 'noSub'; + } + $copyHtml = false; + if (file_exists(PATH_DYNAFORM . $file . '.html')) { + $copyHtml = implode('', file(PATH_DYNAFORM . $file . '.html')); + } + $file = DynaformEditor::_getFilename($file); + $fcopy = fopen(PATH_DYNAFORM . $file . '.xml', "w"); + fwrite($fcopy, $copy); + fclose($fcopy); + if ($copyHtml) { + $fcopy = fopen(PATH_DYNAFORM . $file . '.html', "w"); + fwrite($fcopy, $copyHtml); + fclose($fcopy); + } + } else { + //throw new Exception("It should not come here unless you have disabled the temporary copy."); + } + return $answer; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Close a dynaform + * + * @param object $A + * @return array + */ + public function close($A) + { + try { + /* + * we are unseting this variable. It's our control about to save the xmlfrom + */ + // unset($_SESSION['submitAction']); + $file = G::decrypt($A, URL_KEY); + //return(array('response'=>PATH_DYNAFORM . $file . '.xml')); + /* Delete the temporal copy */ + $tmp = self::_getTmpData(); + $xmlFile = PATH_DYNAFORM . $file . '.xml'; + $htmlFile = PATH_DYNAFORM . $file . '.html'; + //return(array('response'=>$tmp['useTmpCopy'])); + if (isset($tmp['useTmpCopy'])) { + //return(array('response'=>PATH_DYNAFORM . $file . '.xml')); + if ($file !== DynaformEditor::_getFilename($file)) { + // return(array('response'=>PATH_DYNAFORM . $file . '.xml')); + if (file_exists($xmlFile)) { + unlink($xmlFile); + } + if (file_exists($htmlFile)) { + unlink($htmlFile); + } + } + } + return 0; + } catch (Exception $e) { + return (array) $e; + } + } + + /** + * Checks if a dynaform was changed + * + * @param file $A + * @param string $DYN_UID + * @return array + */ + public function is_modified($A, $DYN_UID) + { + $file = G::decrypt($A, URL_KEY); + try { + /* Compare Properties */ + $dynaform = new Dynaform(); + $dynaform->load($DYN_UID); + $form = new Form($file, PATH_DYNAFORM, SYS_LANG, true); + $sp = array('A' => $A, 'DYN_UID' => $dynaform->getDynUid(), 'PRO_UID' => $dynaform->getProUid(), 'DYN_TITLE' => $dynaform->getDynTitle(), 'DYN_TYPE' => $dynaform->getDynType(), 'DYN_DESCRIPTION' => $dynaform->getDynDescription(), 'WIDTH' => $form->width, 'ENABLETEMPLATE' => $form->enableTemplate, 'MODE' => $form->mode + ); + $P = self::get_properties($A, $DYN_UID); + if (!isset($P['DYN_TITLE'])) { + $P['DYN_TITLE'] = $sp['DYN_TITLE']; + } + if (!isset($P['DYN_TYPE'])) { + $P['DYN_TYPE'] = $sp['DYN_TYPE']; + } + if (!isset($P['DYN_DESCRIPTION'])) { + $P['DYN_DESCRIPTION'] = $sp['DYN_DESCRIPTION']; + } + if (!isset($P['WIDTH'])) { + $P['WIDTH'] = $sp['WIDTH']; + } + if (!isset($P['ENABLETEMPLATE'])) { + $P['ENABLETEMPLATE'] = $sp['ENABLETEMPLATE']; + } + if (!isset($P['MODE'])) { + $P['MODE'] = $sp['MODE']; + } + $modPro = ($sp['DYN_TITLE'] != $P['DYN_TITLE']) || ($sp['DYN_TYPE'] != $P['DYN_TYPE']) || ($sp['DYN_DESCRIPTION'] != $P['DYN_DESCRIPTION']); + /* || + ($sp['WIDTH']!=$P['WIDTH']) || + ($sp['ENABLETEMPLATE']!=$P['ENABLETEMPLATE']) || + ($sp['MODE']!=$P['MODE']) */ + /* Compare copies */ + $fileOrigen = DynaformEditor::_getFilename($file); + $copy = implode('', file(PATH_DYNAFORM . $file . '.xml')); + $origen = implode('', file(PATH_DYNAFORM . $fileOrigen . '.xml')); + $copyHTML = file_exists(PATH_DYNAFORM . $file . '.html') ? implode('', file(PATH_DYNAFORM . $file . '.html')) : false; + $origenHTML = file_exists(PATH_DYNAFORM . $fileOrigen . '.html') ? implode('', file(PATH_DYNAFORM . $fileOrigen . '.html')) : false; + $modFile = ($copy !== $origen) || ($origenHTML && ($copyHTML !== $origenHTML)); + //Return + //return array("*message"=>sprintf("%s, (%s= %s %s):", $modPro?"1":"0" , $modFile?"1":"0", ($copy!==$origen)?"1":"0" , ($origenHTML && ($copyHTML!==$origenHTML))?"1":"0" )); + //die("c'est fini"); + return $modPro || $modFile; + } catch (Exception $e) { + return (array) $e; + } + } + /* + Functionality: Funcion que convierte objecto en array + Parameters : Object $object que queremos convertir + Return: Array + */ + public function convertObjectToArray($object){ + if( !is_object( $object ) && !is_array( $object ) ){ + return $object; + } + if( is_object( $object ) ){ + $object = get_object_vars( $object ); + } + return array_map( 'objectToArray', $object ); + } +} diff --git a/workflow/engine/classes/class.enterprise.php b/workflow/engine/classes/EnterpriseClass.php similarity index 90% rename from workflow/engine/classes/class.enterprise.php rename to workflow/engine/classes/EnterpriseClass.php index 4d4615944..d09621f22 100644 --- a/workflow/engine/classes/class.enterprise.php +++ b/workflow/engine/classes/EnterpriseClass.php @@ -1,15 +1,6 @@ getProperty('LICENSE_INFO'); if (isset($infoLicense[SYS_SYS]['LIMIT_USERS'])) { $criteria = new Criteria('workflow'); @@ -156,8 +147,3 @@ class enterpriseClass extends PMPlugin } } } - -if (!class_exists("pmLicenseManager")) { - require_once ("classes" . PATH_SEP . "class.pmLicenseManager.php"); -} - diff --git a/workflow/engine/classes/class.enterpriseUtils.php b/workflow/engine/classes/EnterpriseUtils.php similarity index 97% rename from workflow/engine/classes/class.enterpriseUtils.php rename to workflow/engine/classes/EnterpriseUtils.php index 0a2832651..70a26187d 100644 --- a/workflow/engine/classes/class.enterpriseUtils.php +++ b/workflow/engine/classes/EnterpriseUtils.php @@ -1,5 +1,6 @@ featureName = $featureName; + $this->description = $description; + } +} diff --git a/workflow/engine/classes/class.fieldValidator.php b/workflow/engine/classes/FieldValidator.php similarity index 100% rename from workflow/engine/classes/class.fieldValidator.php rename to workflow/engine/classes/FieldValidator.php index 4ab9462aa..de01411ae 100644 --- a/workflow/engine/classes/class.fieldValidator.php +++ b/workflow/engine/classes/FieldValidator.php @@ -1,4 +1,5 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ -require_once 'classes/model/Groupwf.php'; -require_once 'classes/model/GroupUser.php'; -require_once 'classes/model/Users.php'; - + * Groups - Groups /** * Groups - Groups class * @@ -463,4 +436,3 @@ class Groups } } } - diff --git a/workflow/engine/classes/class.BasePeer.php b/workflow/engine/classes/GulliverBasePeer.php similarity index 92% rename from workflow/engine/classes/class.BasePeer.php rename to workflow/engine/classes/GulliverBasePeer.php index f3d76b637..ab6eb3ede 100644 --- a/workflow/engine/classes/class.BasePeer.php +++ b/workflow/engine/classes/GulliverBasePeer.php @@ -1,35 +1,7 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ require_once 'propel/util/BasePeer.php'; -// The object class -- needed for instanceof checks in this class. -// actual class may be a subclass -- as returned by ApplicationPeer::getOMClass() -include_once 'classes/model/Application.php'; - +// The object /** * Base static class for performing query and update operations on the 'APPLICATION' table. * @@ -702,20 +674,3 @@ abstract class GulliverBasePeer } } // BaseApplicationPeer - - -// static code to register the map builder for this Peer with the main Propel class -if (Propel::isInit()) { - // the MapBuilder classes register themselves with Propel during initialization - // so we need to load them here. - try { - BaseApplicationPeer::getMapBuilder(); - } catch (Exception $e) { - Propel::log( 'Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR ); - } -} else { - // even if Propel is not yet initialized, the map builder class can be registered - // now and then it will be loaded when Propel initializes. - require_once 'classes/model/map/ApplicationMapBuilder.php'; - Propel::registerMapBuilder( 'classes.model.map.ApplicationMapBuilder' ); -} diff --git a/workflow/engine/classes/Gzip_File.php b/workflow/engine/classes/Gzip_File.php new file mode 100644 index 000000000..17f20e956 --- /dev/null +++ b/workflow/engine/classes/Gzip_File.php @@ -0,0 +1,74 @@ +tar_file($name); + $this->options['type'] = "gzip"; + } + + /** + * This function is employed to create files . + * gzip + * + * @return boolean + */ + public function create_gzip() + { + if ($this->options['inmemory'] == 0) { + $pwd = getcwd(); + chdir($this->options['basedir']); + if ($fp = gzopen($this->options['name'], "wb{$this->options['level']}")) { + fseek($this->archive, 0); + while ($temp = fread($this->archive, 1048576)) { + gzwrite($fp, $temp); + } + gzclose($fp); + chdir($pwd); + } else { + $this->error[] = "Could not open {$this->options['name']} for writing."; + chdir($pwd); + return 0; + } + } else { + $this->archive = gzencode($this->archive, $this->options['level']); + } + return 1; + } + + /** + * This function open a archive of the class gzip_file + * + * @return void + */ + public function open_archive() + { + return @gzopen($this->options['name'], "rb"); + } +} diff --git a/workflow/engine/classes/IDynaformEditorAjax.php b/workflow/engine/classes/IDynaformEditorAjax.php new file mode 100644 index 000000000..08afbdbfd --- /dev/null +++ b/workflow/engine/classes/IDynaformEditorAjax.php @@ -0,0 +1,6 @@ +dbHost); $host = "host=".$arrayHost[0]; $port = count($arrayHost) > 1 ? ";port=".$arrayHost[1] : ""; diff --git a/workflow/engine/classes/InvalidIndexSearchTextException.php b/workflow/engine/classes/InvalidIndexSearchTextException.php new file mode 100644 index 000000000..baf8ed595 --- /dev/null +++ b/workflow/engine/classes/InvalidIndexSearchTextException.php @@ -0,0 +1,68 @@ +. + * + * For more information, contact Colosa Inc, 5304 Ventura Drive, + * Delray Beach, FL, 33484, USA, or email info@colosa.com. + * + */ + +require_once "classes/model/Application.php"; +require_once "classes/model/AppDelegation.php"; +require_once "classes/model/AppThread.php"; +require_once "classes/model/Content.php"; +require_once "classes/model/Users.php"; +require_once "classes/model/GroupUser.php"; +require_once "classes/model/Task.php"; +require_once "classes/model/TaskUser.php"; +require_once "classes/model/Dynaform.php"; +require_once "classes/model/ProcessVariables.php"; +require_once "entities/SolrRequestData.php"; +require_once "entities/SolrUpdateDocument.php"; +require_once "entities/AppSolrQueue.php"; +require_once "classes/model/AppSolrQueue.php"; + + +/** + * Invalid search text for Solr exception + * + * @author Herbert Saal Gutierrez + * + */ + +/** + * Invalid search text for Solr exception + * + * @author Herbert Saal Gutierrez + * + */class InvalidIndexSearchTextException 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"; + } +} diff --git a/workflow/engine/classes/class.javaBridgePM.php b/workflow/engine/classes/JavaBridgePM.php similarity index 98% rename from workflow/engine/classes/class.javaBridgePM.php rename to workflow/engine/classes/JavaBridgePM.php index 11c6f95b7..8dc58c7c8 100644 --- a/workflow/engine/classes/class.javaBridgePM.php +++ b/workflow/engine/classes/JavaBridgePM.php @@ -38,7 +38,11 @@ if (! defined( 'JAVA_BRIDGE_HOST' )) { * * @package workflow.engine.classes */ -class JavaBridgePM + +/** + * + * @package workflow.engine.classes + */class JavaBridgePM { public $JavaBridgeDir = JAVA_BRIDGE_PATH; public $JavaBridgePort = JAVA_BRIDGE_PORT; @@ -174,4 +178,3 @@ class JavaBridgePM printf( "saved %s bytes in file %s \n", $iSize, $reportFilename ); } } - diff --git a/workflow/engine/classes/class.labelsGmail.php b/workflow/engine/classes/LabelsGmail.php similarity index 97% rename from workflow/engine/classes/class.labelsGmail.php rename to workflow/engine/classes/LabelsGmail.php index f77f796a3..38ac6aab3 100644 --- a/workflow/engine/classes/class.labelsGmail.php +++ b/workflow/engine/classes/LabelsGmail.php @@ -1,5 +1,6 @@ setUser($mail); - $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $pmGoogle->setScope(PmGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); $labelsIds = $this->getLabelsIds($service); @@ -147,9 +148,9 @@ class labelsGmail //The Subject to search the email $subject = "[PM] " . $proName . " (" . $index . ") Case: " . $appNumber; - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $pmGoogle->setScope(PmGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); $labelsIds = $this->getLabelsIds($service); @@ -201,11 +202,11 @@ class labelsGmail //The Subject to search the email $subject = "[PM] " . $proName . " (" . $index . ") Case: " . $appNumber; - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $pmGoogle->setScope(PmGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); @@ -280,9 +281,9 @@ class labelsGmail //The Subject to search the email $subject = "[PM] " . $proName . " (" . $index . ") Case: " . $appNumber; - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $pmGoogle->setScope(PmGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); $labelsIds = $this->getLabelsIds($service); @@ -328,11 +329,11 @@ class labelsGmail */ public function deletePMGmailLabels($mail) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $pmGoogle->setScope(PmGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); diff --git a/workflow/engine/classes/class.ldapAdvanced.php b/workflow/engine/classes/LdapAdvanced.php similarity index 98% rename from workflow/engine/classes/class.ldapAdvanced.php rename to workflow/engine/classes/LdapAdvanced.php index dfcc91f3a..95f3ba322 100644 --- a/workflow/engine/classes/class.ldapAdvanced.php +++ b/workflow/engine/classes/LdapAdvanced.php @@ -1,39 +1,10 @@ "|(objectclass=inetorgperson)(objectclass=organizationalperson)(objectclass=person)(objectclass=user)", @@ -488,14 +459,14 @@ class ldapAdvanced $logFile = PATH_DATA . "log/ldapAdvanced.log"; if (!file_exists($logFile) || is_writable($logFile)) { - $fpt= fopen ($logFile, "a"); + $fpt= fopen($logFile, "a"); $ldapErrorMsg = ""; $ldapErrorNr = 0; if ($link != null) { $ldapErrorNr = ldap_errno($link); - if ( $ldapErrorNr != 0 ) { + if ($ldapErrorNr != 0) { $ldapErrorMsg = ldap_error($link); $text = $ldapErrorMsg . " : " . $text; } @@ -505,7 +476,7 @@ class ldapAdvanced fwrite($fpt, sprintf("%s %s %s %s %s \n", date("Y-m-d H:i:s"), getenv("REMOTE_ADDR"), SYS_SYS, $ldapErrorNr, $text)); fclose($fpt); } else { - error_log ("file $logFile is not writable "); + error_log("file $logFile is not writable "); } } @@ -536,11 +507,11 @@ class ldapAdvanced */ public function ldapConnection($aAuthSource) { - $pass = explode("_",$aAuthSource["AUTH_SOURCE_PASSWORD"]); + $pass = explode("_", $aAuthSource["AUTH_SOURCE_PASSWORD"]); foreach ($pass as $index => $value) { if ($value == "2NnV3ujj3w") { - $aAuthSource["AUTH_SOURCE_PASSWORD"] = G::decrypt($pass[0],$aAuthSource["AUTH_SOURCE_SERVER_NAME"]); + $aAuthSource["AUTH_SOURCE_PASSWORD"] = G::decrypt($pass[0], $aAuthSource["AUTH_SOURCE_SERVER_NAME"]); } } @@ -1076,11 +1047,11 @@ class ldapAdvanced $strUser = trim($strUser); } - if ( $strUser == "" ) { + if ($strUser == "") { return -1; } - if ( strlen( $strPass ) == 0) { + if (strlen($strPass) == 0) { return -2; } @@ -1171,7 +1142,7 @@ class ldapAdvanced $ldapcnn = $this->ldapConnection($arrayAuthSource); $flagUpdate = false; - switch(ldap_errno($ldapcnn)) { + switch (ldap_errno($ldapcnn)) { case '0x00': $flagUpdate = true; $statusRbac = 1; @@ -1226,7 +1197,7 @@ class ldapAdvanced $validUserPass = -5; } - if ( $validUserPass == 1 ) { + if ($validUserPass == 1) { $this->log($ldapcnn, "sucessful login user " . $verifiedUser["sDN"]); } else { $this->log($ldapcnn, "failure authentication for user $strUser"); @@ -1326,7 +1297,7 @@ class ldapAdvanced $entries = ldap_count_entries($ldapcnn, $oSearch); $totalUser = $entries; - if ( $entries > 0) { + if ($entries > 0) { $oEntry = ldap_first_entry($ldapcnn, $oSearch); $countEntries=0; @@ -1577,11 +1548,11 @@ class ldapAdvanced $res = 0; if (!empty($user)) { - if ($this->VerifyLogin( $user['sUsername'], $strPass) === true) { + if ($this->VerifyLogin($user['sUsername'], $strPass) === true) { $res = 1; } - if ($res == 0 && $this->VerifyLogin( $user['sDN'], $strPass) === true) { + if ($res == 0 && $this->VerifyLogin($user['sDN'], $strPass) === true) { $res = 1; } } else { @@ -1614,8 +1585,8 @@ class ldapAdvanced if (!empty($aAttributes)) { foreach ($aAttributes as $value) { - if (isset( $user[$value['attributeUser']] )) { - $aData[$value['attributeUser']] = str_replace( "*", "'", $user[$value['attributeUser']] ); + if (isset($user[$value['attributeUser']])) { + $aData[$value['attributeUser']] = str_replace("*", "'", $user[$value['attributeUser']]); if ($value['attributeUser'] == 'USR_STATUS') { $evalValue = $aData[$value['attributeUser']]; $statusValue = (isset($user['USR_STATUS'])) ? $user['USR_STATUS'] :'ACTIVE'; @@ -1626,7 +1597,7 @@ class ldapAdvanced } //req - accountexpires - if (isset($user["USR_DUE_DATE"]) && $user["USR_DUE_DATE"]!='' ) { + if (isset($user["USR_DUE_DATE"]) && $user["USR_DUE_DATE"]!='') { $aData["USR_DUE_DATE"] = $this->convertDateADtoPM($user["USR_DUE_DATE"]); } //end @@ -1799,12 +1770,12 @@ class ldapAdvanced * @param $currentDN * @return */ - public function getDepUidIfExistsDN ($currentDN) + public function getDepUidIfExistsDN($currentDN) { try { $oCriteria = new Criteria('workflow'); - $oCriteria->add(DepartmentPeer::DEP_STATUS , 'ACTIVE' ); - $oCriteria->add(DepartmentPeer::DEP_LDAP_DN, $currentDN ); + $oCriteria->add(DepartmentPeer::DEP_STATUS, 'ACTIVE'); + $oCriteria->add(DepartmentPeer::DEP_LDAP_DN, $currentDN); $oDataset = DepartmentPeer::doSelectRS($oCriteria); $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); @@ -1919,7 +1890,7 @@ class ldapAdvanced BasePeer::doUpdate($c1, $c2, $con); } - public function deactivateUser ($userUid) + public function deactivateUser($userUid) { if (!class_exists('RbacUsers')) { require_once(PATH_RBAC.'model/RbacUsers.php'); @@ -2076,7 +2047,7 @@ class ldapAdvanced $criteriaCount = new Criteria('workflow'); $criteriaCount->clearSelectColumns(); - $criteriaCount->addSelectColumn( 'COUNT(*)' ); + $criteriaCount->addSelectColumn('COUNT(*)'); $criteriaCount->add(DepartmentPeer::DEP_PARENT, $oDepartment->getDepUid(), Criteria::EQUAL); $rs = DepartmentPeer::doSelectRS($criteriaCount); $rs->next(); @@ -2085,7 +2056,7 @@ class ldapAdvanced $result[] = $node; } - if ( count($result) >= 1 ) { + if (count($result) >= 1) { $result[ count($result) -1 ]['DEP_LAST'] = 1; } @@ -2139,11 +2110,11 @@ class ldapAdvanced $attributes = $aAuthSource["AUTH_SOURCE_DATA"]; $this->sTerminatedOu = isset($attributes['AUTH_SOURCE_RETIRED_OU'])? trim($attributes['AUTH_SOURCE_RETIRED_OU']) : ''; - if ($this->sTerminatedOu == '' ) { + if ($this->sTerminatedOu == '') { return $aUsers; } - return $this->getUsersFromDepartmentByName( $this->sTerminatedOu ); + return $this->getUsersFromDepartmentByName($this->sTerminatedOu); } /** @@ -2173,8 +2144,8 @@ class ldapAdvanced $con = Propel::getConnection('rbac'); // select set $c1 = new Criteria('rbac'); - $c1->add(RbacUsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN ); - $c1->add(RbacUsersPeer::USR_STATUS, 1 ); + $c1->add(RbacUsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN); + $c1->add(RbacUsersPeer::USR_STATUS, 1); // update set $c2 = new Criteria('rbac'); $c2->add(RbacUsersPeer::USR_STATUS, '0'); @@ -2183,7 +2154,7 @@ class ldapAdvanced $con = Propel::getConnection('workflow'); // select set $c1 = new Criteria('workflow'); - $c1->add(UsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN ); + $c1->add(UsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN); // update set $c2 = new Criteria('workflow'); $c2->add(UsersPeer::USR_STATUS, 'INACTIVE'); @@ -2391,7 +2362,7 @@ class ldapAdvanced { try { $criteria = new Criteria('workflow'); - $criteria->add(GroupwfPeer::GRP_STATUS , 'ACTIVE'); + $criteria->add(GroupwfPeer::GRP_STATUS, 'ACTIVE'); $criteria->add(GroupwfPeer::GRP_LDAP_DN, $currentDN); $dataset = GroupwfPeer::doSelectRS($criteria); $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); diff --git a/workflow/engine/classes/class.license.app.php b/workflow/engine/classes/License_Application.php similarity index 94% rename from workflow/engine/classes/class.license.app.php rename to workflow/engine/classes/License_Application.php index 55facb1a8..fa1dc3fec 100644 --- a/workflow/engine/classes/class.license.app.php +++ b/workflow/engine/classes/License_Application.php @@ -1,31 +1,6 @@ - * @history--------------------------------------------- - * see CHANGELOG - */ -class license_application extends padl + +class license_application extends Padl { /** * The number of allowed differences between the $_SERVER vars and the vars @@ -513,4 +488,3 @@ class license_application extends padl return (empty($data['RESULT'])) ? 'SOCKET_FAILED' : $data['RESULT']; } } - diff --git a/workflow/engine/classes/MultipleFilesBackup.php b/workflow/engine/classes/MultipleFilesBackup.php new file mode 100644 index 000000000..8dc921cd4 --- /dev/null +++ b/workflow/engine/classes/MultipleFilesBackup.php @@ -0,0 +1,229 @@ +filename = $filename; + } + if (!empty($size) && (int) $size > 0) { + $this->fileSize = $size; + } + } + + /* Gets workspace information enough to make its backup. + * @workspace contains the workspace to be add to the commpression process. + */ + public function addToBackup($workspace) + { + //verifing if workspace exists. + if (!$workspace->workspaceExists()) { + echo "Workspace {$workspace->name} not found\n"; + return false; + } + //create destination path + if (!file_exists(PATH_DATA . "upgrade/")) { + mkdir(PATH_DATA . "upgrade/"); + } + $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); + mkdir($tempDirectory); + $metadata = $workspace->getMetadata(); + CLI::logging("Creating temporary files on database...\n"); + $metadata["databases"] = $workspace->exportDatabase($tempDirectory); + $metadata["directories"] = array("{$workspace->name}"); + $metadata["version"] = 1; + $metaFilename = "$tempDirectory/{$workspace->name}.meta"; + if (!file_put_contents($metaFilename, str_replace(array(",", "{", "}"), array(",\n ", "{\n ", "\n}\n"), G::json_encode($metadata)))) { + CLI::logging("Could not create backup metadata"); + } + CLI::logging("Adding database to backup...\n"); + $this->addDirToBackup($tempDirectory); + CLI::logging("Adding files to backup...\n"); + $this->addDirToBackup($workspace->path); + $this->tempDirectories[] = $tempDirectory; + } + + /* Add a directory containing Db files or info files to be commpressed + * @directory the name and path of the directory to be add to the commpression process. + */ + private function addDirToBackup($directory) + { + if (!empty($directory)) { + $this->dir_to_compress .= $directory . " "; + } + } + + // Commpress the DB and files into a single or several files with numerical series extentions + + public function letsBackup() + { + // creating command + $CommpressCommand = "tar czv "; + $CommpressCommand .= $this->dir_to_compress; + $CommpressCommand .= "| split -b "; + $CommpressCommand .= $this->fileSize; + $CommpressCommand .= "m -d - "; + $CommpressCommand .= $this->filename . "."; + //executing command to create the files + echo exec($CommpressCommand); + //Remove leftovers dirs. + foreach ($this->tempDirectories as $tempDirectory) { + CLI::logging("Deleting: " . $tempDirectory . "\n"); + G::rm_dir($tempDirectory); + } + } + /* Restore from file(s) commpressed by letsBackup function, into a temporary directory + * @ filename got the name and path of the compressed file(s), if there are many files with file extention as a numerical series, the extention should be discriminated. + * @ srcWorkspace contains the workspace to be restored. + * @ dstWorkspace contains the workspace to be overwriting. + * @ overwrite got the option true if the workspace will be overwrite. + */ + public static function letsRestore($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) + { + // Needed info: + // TEMPDIR /shared/workflow_data/upgrade/ + // BACKUPS /shared/workflow_data/backups/ + // Creating command cat myfiles_split.tgz_* | tar xz + $DecommpressCommand = "cat " . $filename . ".* "; + $DecommpressCommand .= " | tar xzv"; + + $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, '')); + $tempDirectoryHelp = $tempDirectory; + + $parentDirectory = PATH_DATA . "upgrade"; + if (is_writable($parentDirectory)) { + mkdir($tempDirectory); + } else { + throw new Exception("Could not create directory:" . $parentDirectory); + } + //Extract all backup files, including database scripts and workspace files + CLI::logging("Restoring into " . $tempDirectory . "\n"); + chdir($tempDirectory); + echo exec($DecommpressCommand); + CLI::logging("\nUncompressed into: " . $tempDirectory . "\n"); + + //Search for metafiles in the new standard (the old standard would contain meta files. + $decommpressedfile = scandir($tempDirectoryHelp . dirname($tempDirectoryHelp), 1); + $tempDirectory = $tempDirectoryHelp . dirname($tempDirectoryHelp) . "/" . $decommpressedfile[0]; + + $metaFiles = glob($tempDirectory . "/*.meta"); + if (empty($metaFiles)) { + $metaFiles = glob($tempDirectory . "/*.txt"); + if (!empty($metaFiles)) { + return WorkspaceTools::restoreLegacy($tempDirectory); + } else { + throw new Exception("No metadata found in backup"); + } + } else { + CLI::logging("Found " . count($metaFiles) . " workspaces in backup:\n"); + foreach ($metaFiles as $metafile) { + CLI::logging("-> " . basename($metafile) . "\n"); + } + } + if (count($metaFiles) > 1 && (!isset($srcWorkspace))) { + throw new Exception("Multiple workspaces in backup but no workspace specified to restore"); + } + if (isset($srcWorkspace) && !in_array("$srcWorkspace.meta", array_map(basename, $metaFiles))) { + throw new Exception("Workspace $srcWorkspace not found in backup"); + } + foreach ($metaFiles as $metaFile) { + $metadata = G::json_decode(file_get_contents($metaFile)); + if ($metadata->version != 1) { + throw new Exception("Backup version {$metadata->version} not supported"); + } + $backupWorkspace = $metadata->WORKSPACE_NAME; + if (isset($dstWorkspace)) { + $workspaceName = $dstWorkspace; + $createWorkspace = true; + } else { + $workspaceName = $metadata->WORKSPACE_NAME; + $createWorkspace = false; + } + if (isset($srcWorkspace) && strcmp($metadata->WORKSPACE_NAME, $srcWorkspace) != 0) { + CLI::logging(CLI::warning("> Workspace $backupWorkspace found, but not restoring.") . "\n"); + continue; + } else { + CLI::logging("> Restoring " . CLI::info($backupWorkspace) . " to " . CLI::info($workspaceName) . "\n"); + } + $workspace = new WorkspaceTools($workspaceName); + if ($workspace->workspaceExists()) { + if ($overwrite) { + CLI::logging(CLI::warning("> Workspace $workspaceName already exist, overwriting!") . "\n"); + } else { + throw new Exception("Destination workspace already exist (use -o to overwrite)"); + } + } + if (file_exists($workspace->path)) { + G::rm_dir($workspace->path); + } + + $tempDirectorySite = $tempDirectoryHelp . dirname($workspace->path); + + foreach ($metadata->directories as $dir) { + CLI::logging("+> Restoring directory '$dir'\n"); + if (!rename("$tempDirectorySite/$dir", $workspace->path)) { + throw new Exception("There was an error copying the backup files ($tempDirectory/$dir) to the workspace directory {$workspace->path}."); + } + } + + CLI::logging("> Changing file permissions\n"); + $shared_stat = stat(PATH_DATA); + if ($shared_stat !== false) { + WorkspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); + } else { + CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); + } + + list($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); + + CLI::logging("> Connecting to system database in '$dbHost'\n"); + $link = mysql_connect($dbHost, $dbUser, $dbPass); + @mysql_query("SET NAMES 'utf8';"); + @mysql_query("SET FOREIGN_KEY_CHECKS=0;"); + if (!$link) { + throw new Exception('Could not connect to system database: ' . mysql_error()); + } + + if (strpos($metadata->DB_RBAC_NAME, 'rb_') === false) { + $onedb = true; + } else { + $onedb = false; + } + + $newDBNames = $workspace->resetDBInfo($dbHost, $createWorkspace, $onedb); + $aParameters = array('dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass); + + foreach ($metadata->databases as $db) { + $dbName = $newDBNames[$db->name]; + CLI::logging("+> Restoring database {$db->name} to $dbName\n"); + $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters); + $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); + $workspace->createDBUser($dbName, $db->pass, "%", $dbName); + } + $workspace->upgradeCacheView(false); + mysql_close($link); + } + CLI::logging("Removing temporary files\n"); + G::rm_dir($tempDirectory); + CLI::logging(CLI::info("Done restoring") . "\n"); + } +} diff --git a/workflow/engine/classes/class.net.php b/workflow/engine/classes/Net.php similarity index 77% rename from workflow/engine/classes/class.net.php rename to workflow/engine/classes/Net.php index 1644b1801..cd6569207 100644 --- a/workflow/engine/classes/class.net.php +++ b/workflow/engine/classes/Net.php @@ -1,15 +1,6 @@ errstr = ""; $this->db_instance = ""; - unset( $this->db_user ); - unset( $this->db_passwd ); - unset( $this->db_sourcename ); + unset($this->db_user); + unset($this->db_passwd); + unset($this->db_sourcename); #verifing valid param if ($pHost == "") { @@ -68,7 +59,7 @@ class NET $this->errstr = "NET::You must specify a host"; //$this->showMsg(); } - $this->resolv( $pHost ); + $this->resolv($pHost); } /** @@ -77,31 +68,31 @@ class NET * @param string $pHost * @return void */ - public function resolv ($pHost) + public function resolv($pHost) { - $aHost = explode( "\\", $pHost ); - if (count( $aHost ) > 1) { + $aHost = explode("\\", $pHost); + if (count($aHost) > 1) { $ipHost = $aHost[0]; $this->db_instance = $aHost[1]; } else { $ipHost = $pHost; } - if ($this->is_ipaddress( $ipHost )) { + if ($this->is_ipaddress($ipHost)) { $this->ip = $ipHost; - if (! $this->hostname = @gethostbyaddr( $ipHost )) { + if (! $this->hostname = @gethostbyaddr($ipHost)) { $this->errno = 2000; $this->errstr = "NET::Host down"; $this->error = G::loadTranslation('ID_HOST_UNREACHABLE'); } } else { - $ip = @gethostbyname( $ipHost ); - $long = ip2long( $ip ); + $ip = @gethostbyname($ipHost); + $long = ip2long($ip); if ($long == - 1 || $long === false) { $this->errno = 2000; $this->errstr = "NET::Host down"; $this->error = G::loadTranslation('ID_HOST_UNREACHABLE'); } else { - $this->ip = @gethostbyname( $ipHost ); + $this->ip = @gethostbyname($ipHost); $this->hostname = $pHost; } } @@ -113,14 +104,14 @@ class NET * @param string $pPort * @return true */ - public function scannPort ($pPort) + public function scannPort($pPort) { - define( 'TIMEOUT', 5 ); - $hostip = @gethostbyname( $host ); // resloves IP from Hostname returns hostname on failure + define('TIMEOUT', 5); + $hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure // attempt to connect - if (@fsockopen( $this->ip, $pPort, $this->errno, $this->errstr, TIMEOUT )) { + if (@fsockopen($this->ip, $pPort, $this->errno, $this->errstr, TIMEOUT)) { return true; - @fclose( $x ); //close connection (i dont know if this is needed or not). + @fclose($x); //close connection (i dont know if this is needed or not). } else { $this->errno = 9999; $this->errstr = "NET::Port Host Unreachable"; @@ -135,16 +126,16 @@ class NET * @param string $pHost * @return true */ - public function is_ipaddress ($pHost) + public function is_ipaddress($pHost) { $key = true; #verifing if is a ip address - $tmp = explode( ".", $pHost ); + $tmp = explode(".", $pHost); #if have a ip address format - if (count( $tmp ) == 4) { + if (count($tmp) == 4) { #if a correct ip address - for ($i = 0; $i < count( $tmp ); $i ++) { - if (! is_int( $tmp[$i] )) { + for ($i = 0; $i < count($tmp); $i ++) { + if (! is_int($tmp[$i])) { $key = false; break; } @@ -161,12 +152,12 @@ class NET * @param string $pHost * @return true */ - public function ping ($pTTL = 3000) + public function ping($pTTL = 3000) { $cmd = "ping -w $pTTL $this->ip"; - $output = exec( $cmd, $a, $a1 ); + $output = exec($cmd, $a, $a1); $this->errstr = ""; - for ($i = 0; $i < count( $a ); $i ++) { + for ($i = 0; $i < count($a); $i ++) { $this->errstr += $a[$i]; } $this->errno = $a1; @@ -179,7 +170,7 @@ class NET * @param string $pPasswd * @return void */ - public function loginDbServer ($pUser, $pPasswd) + public function loginDbServer($pUser, $pPasswd) { $this->db_user = $pUser; $this->db_passwd = $pPasswd; @@ -192,7 +183,7 @@ class NET * @param string $pPort * @return void */ - public function setDataBase ($pDb, $pPort = '') + public function setDataBase($pDb, $pPort = '') { $this->db_sourcename = $pDb; $this->db_port = $pPort; @@ -208,10 +199,9 @@ class NET */ public function tryConnectServer($pDbDriver, array $arrayServerData = array(), $dbsEncode = "") { - $filter = new InputFilter(); $this->ip = $filter->validateInput($this->ip); - $this->db_port = $filter->validateInput($this->db_port,'int'); + $this->db_port = $filter->validateInput($this->db_port, 'int'); $this->db_user = $filter->validateInput($this->db_user); $this->db_passwd = $filter->validateInput($this->db_passwd); $this->db_sourcename = $filter->validateInput($this->db_sourcename); @@ -223,10 +213,10 @@ class NET if (array_key_exists("connectionType", $arrayServerData) || array_key_exists("DBS_TYPEORACLE", $arrayServerData)) { if ($arrayServerData["connectionType"] == "TNS" || $arrayServerData["DBS_TYPEORACLE"] == "TNS") { $flagTns=1; - }else{ + } else { $flagTns=0; } - }else{ + } else { $flagTns=0; } @@ -234,12 +224,12 @@ class NET switch ($pDbDriver) { case 'mysql': if ($this->db_passwd == '') { - $link = @mysql_connect( $this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user ); + $link = @mysql_connect($this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user); } else { - $link = @mysql_connect( $this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd ); + $link = @mysql_connect($this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd); } if ($link) { - if (@mysql_ping( $link )) { + if (@mysql_ping($link)) { $stat->status = 'SUCCESS'; $this->errstr = ""; $this->errno = 0; @@ -256,7 +246,7 @@ class NET break; case 'pgsql': $this->db_port = ($this->db_port == "") ? "5432" : $this->db_port; - $link = @pg_connect( "host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'" ); + $link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'"); if ($link) { $stat->status = 'SUCCESS'; $this->errstr = ""; @@ -270,10 +260,10 @@ class NET case 'mssql': if ($this->db_instance != "") { $str_port = ""; - $link = @mssql_connect( $this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd ); + $link = @mssql_connect($this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd); } else { $str_port = (($this->db_port == "") || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":" . $this->db_port; - $link = @mssql_connect( $this->ip . $str_port, $this->db_user, $this->db_passwd ); + $link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd); } if ($link) { @@ -306,7 +296,7 @@ class NET $this->errno = 30001; } } catch (Exception $e) { - throw new Exception( "[erik] Couldn't connect to Oracle Server! - " . $e->getMessage() ); + throw new Exception("[erik] Couldn't connect to Oracle Server! - " . $e->getMessage()); } break; case 'informix': @@ -315,7 +305,7 @@ class NET break; } } else { - throw new Exception( "CLASS::NET::ERROR: No connections param." ); + throw new Exception("CLASS::NET::ERROR: No connections param."); } return $stat; @@ -331,10 +321,9 @@ class NET */ public function tryOpenDataBase($pDbDriver, array $arrayServerData = array(), $dbsEncode = "") { - $filter = new InputFilter(); $this->ip = $filter->validateInput($this->ip); - $this->db_port = $filter->validateInput($this->db_port,'int'); + $this->db_port = $filter->validateInput($this->db_port, 'int'); $this->db_user = $filter->validateInput($this->db_user); $this->db_passwd = $filter->validateInput($this->db_passwd); $this->db_sourcename = $filter->validateInput($this->db_sourcename); @@ -342,32 +331,32 @@ class NET return 0; } - set_time_limit( 0 ); + set_time_limit(0); $stat = new Stat(); if (array_key_exists("connectionType", $arrayServerData) || array_key_exists("DBS_TYPEORACLE", $arrayServerData)) { if ($arrayServerData["connectionType"] == "TNS" || $arrayServerData["DBS_TYPEORACLE"] == "TNS") { $flagTns=1; - }else{ + } else { $flagTns=0; } - }else{ + } else { $flagTns=0; } if (isset($this->db_user) && (isset($this->db_passwd) || $this->db_passwd == "") && (isset($this->db_sourcename) || $flagTns == 1)) { switch ($pDbDriver) { case 'mysql': - $link = @mysql_connect( $this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd ); - $db = @mysql_select_db( $this->db_sourcename ); + $link = @mysql_connect($this->ip . (($this->db_port != '') && ($this->db_port != 0) ? ':' . $this->db_port : ''), $this->db_user, $this->db_passwd); + $db = @mysql_select_db($this->db_sourcename); if ($link) { if ($db) { - $result = @mysql_query( "show tables;" ); + $result = @mysql_query("show tables;"); if ($result) { $stat->status = 'SUCCESS'; $this->errstr = ""; $this->errno = 0; - @mysql_free_result( $result ); + @mysql_free_result($result); } else { $this->error = "the user $this->db_user doesn't have privileges to run queries!"; $this->errstr = "NET::MYSQL->Test query failed"; @@ -386,9 +375,9 @@ class NET break; case 'pgsql': $this->db_port = (($this->db_port == "") || ($this->db_port == 0)) ? "5432" : $this->db_port; - $link = @pg_connect( "host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'" ); + $link = @pg_connect("host='$this->ip' port='$this->db_port' user='$this->db_user' password='$this->db_passwd' dbname='$this->db_sourcename'"); if ($link) { - if (@pg_ping( $link )) { + if (@pg_ping($link)) { $stat->status = 'SUCCESS'; $this->errstr = ""; $this->errno = 0; @@ -408,13 +397,13 @@ class NET // $link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd); if ($this->db_instance != "") { $str_port = ""; - $link = @mssql_connect( $this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd ); + $link = @mssql_connect($this->ip . "\\" . $this->db_instance, $this->db_user, $this->db_passwd); } else { $str_port = (($this->db_port == "") || ($this->db_port == 0) || ($this->db_port == 1433)) ? "" : ":" . $this->db_port; - $link = @mssql_connect( $this->ip . $str_port, $this->db_user, $this->db_passwd ); + $link = @mssql_connect($this->ip . $str_port, $this->db_user, $this->db_passwd); } if ($link) { - $db = @mssql_select_db( $this->db_sourcename, $link ); + $db = @mssql_select_db($this->db_sourcename, $link); if ($db) { $stat->status = 'SUCCESS'; $this->errstr = ""; @@ -441,7 +430,7 @@ class NET if ($cnn) { $stid = @oci_parse($cnn, 'select AUTHENTICATION_TYPE from v$session_connect_info'); - $result = @oci_execute( $stid, OCI_DEFAULT ); + $result = @oci_execute($stid, OCI_DEFAULT); if ($result) { $stat->status = 'SUCCESS'; $this->errstr = ""; @@ -464,7 +453,7 @@ class NET break; } } else { - throw new Exception( "CLASS::NET::ERROR: No connections param." ); + throw new Exception("CLASS::NET::ERROR: No connections param."); } return $stat; } @@ -475,30 +464,29 @@ class NET * @param string $driver * @return void */ - public function getDbServerVersion ($driver) + public function getDbServerVersion($driver) { - if (! isset( $this->ip )) { - $this->ip = getenv( 'HTTP_CLIENT_IP' ); + if (! isset($this->ip)) { + $this->ip = getenv('HTTP_CLIENT_IP'); } - if (isset( $this->ip ) && isset( $this->db_user ) && isset( $this->db_passwd )) { + if (isset($this->ip) && isset($this->db_user) && isset($this->db_passwd)) { try { - if (! isset( $this->db_sourcename )) { + if (! isset($this->db_sourcename)) { $this->db_sourcename = DB_NAME; } $value = 'none'; - $sDataBase = 'database_' . strtolower( DB_ADAPTER ); - if (G::LoadSystemExist( $sDataBase )) { - + $sDataBase = 'database_' . strtolower(DB_ADAPTER); + if (G::LoadSystemExist($sDataBase)) { $oDataBase = new database(); - $value = $oDataBase->getServerVersion( $driver, $this->ip, $this->db_port, $this->db_user, $this->db_passwd, $this->db_sourcename ); + $value = $oDataBase->getServerVersion($driver, $this->ip, $this->db_port, $this->db_user, $this->db_passwd, $this->db_sourcename); } return $value; } catch (Exception $e) { - throw new Exception( $e->getMessage() ); + throw new Exception($e->getMessage()); } } else { - throw new Exception( 'NET::Error->No params for Data Base Server!' ); + throw new Exception('NET::Error->No params for Data Base Server!'); } } @@ -508,7 +496,7 @@ class NET * @param string $pAdapter * @return void */ - public function dbName ($pAdapter) + public function dbName($pAdapter) { switch ($pAdapter) { case 'mysql': @@ -538,7 +526,7 @@ class NET * @param string $pAdapter * @return void */ - public function showMsg () + public function showMsg() { if ($this->errno != 0) { $msg = " @@ -552,7 +540,7 @@ class NET
"; - print ($msg) ; + print($msg) ; } } @@ -562,7 +550,7 @@ class NET * * @return string */ - public function getErrno () + public function getErrno() { return $this->errno; } @@ -573,22 +561,8 @@ class NET * * @return string */ - public function getErrmsg () + public function getErrmsg() { return $this->errstr; } } - -/** - * - * @package workflow.engine.classes - */ -class Stat -{ - public $stutus; - - public function __construct () - { - $this->status = false; - } -} diff --git a/workflow/engine/classes/ObjectCollection.php b/workflow/engine/classes/ObjectCollection.php new file mode 100644 index 000000000..3afcff0f0 --- /dev/null +++ b/workflow/engine/classes/ObjectCollection.php @@ -0,0 +1,67 @@ +objects = array(); + $this->num = 0; + $this->swapc = $this->num; + array_push($this->objects, 'void'); + } + + /** + * add in the collecetion a new object Document + * + * @param $name name object document + * @param $type type object document + * @param $data data object document + * @param $origin origin object document + * @return void + */ + public function add($name, $type, $data, $origin) + { + $o = new ObjectDocument(); + $o->name = $name; + $o->type = $type; + $o->data = $data; + $o->origin = $origin; + + $this->num++; + array_push($this->objects, $o); + $this->swapc = $this->num; + } + + /** + * get the collection of ObjectDocument + * + * @param $name name object document + * @param $type type object document + * @param $data data object document + * @param $origin origin object document + * @return void + */ + public function get() + { + if ($this->swapc > 0) { + $e = $this->objects[$this->swapc]; + $this->swapc--; + return $e; + } else { + $this->swapc = $this->num; + return false; + } + } +} diff --git a/workflow/engine/classes/ObjectDocument.php b/workflow/engine/classes/ObjectDocument.php new file mode 100644 index 000000000..f8f746429 --- /dev/null +++ b/workflow/engine/classes/ObjectDocument.php @@ -0,0 +1,24 @@ +type = ''; + $this->name = ''; + $this->data = ''; + $this->origin = ''; + } +} diff --git a/workflow/engine/classes/class.patch.php b/workflow/engine/classes/P11835.php similarity index 89% rename from workflow/engine/classes/class.patch.php rename to workflow/engine/classes/P11835.php index 4976a0535..d072a0f9a 100644 --- a/workflow/engine/classes/class.patch.php +++ b/workflow/engine/classes/P11835.php @@ -1,20 +1,8 @@ next(); while($row = $rs->getRow()) { if ($row ['Field'] == "TAS_GROUP_VARIABLE") { - $version = PmSystem::getVersion (); + $version = System::getVersion (); $version = explode('-',$version); if ($version[0] == '2.5.1') { echo "Version " . $version[0] . " Patch\n"; @@ -98,7 +86,7 @@ class p11835 extends patch $arrayHotfix = $conf->getConfiguration("HOTFIX", ""); $arrayHotfix = (is_array($arrayHotfix))? $arrayHotfix : array($arrayHotfix); - $pmVersion = self::pmVersion(PmSystem::getVersion()) . ""; + $pmVersion = self::pmVersion(System::getVersion()) . ""; if (($pmVersion == "2.5.2.4" || $pmVersion == "2.8") && !in_array("15394", $arrayHotfix)) { $cnn = Propel::getConnection("workflow"); @@ -116,4 +104,3 @@ class p11835 extends patch echo $count . " records where patched to use SELF_SERVICE feature.\n"; } } - diff --git a/workflow/engine/classes/class.licensedFeatures.php b/workflow/engine/classes/PMLicensedFeatures.php similarity index 96% rename from workflow/engine/classes/class.licensedFeatures.php rename to workflow/engine/classes/PMLicensedFeatures.php index 0111842a7..5c0f632c7 100644 --- a/workflow/engine/classes/class.licensedFeatures.php +++ b/workflow/engine/classes/PMLicensedFeatures.php @@ -1,28 +1,5 @@ featureName = $featureName; - $this->description = $description; - } -} - - class PMLicensedFeatures { private $featuresDetails = array (); @@ -336,7 +313,7 @@ class PMLicensedFeatures $addons = AddonsManagerPeer::doSelect($criteria); foreach ($addons as $addon) { $this->features[] = $addon->getAddonId(); - $detail = new featuresDetail($addon->getAddonNick(), $addon->getAddonDescription()); + $detail = new FeaturesDetail($addon->getAddonNick(), $addon->getAddonDescription()); $this->featuresDetails[$addon->getAddonId()] = $detail; } } @@ -357,14 +334,10 @@ class PMLicensedFeatures /*----------------------------------********---------------------------------*/ public function verifyfeature ($featureName) { - if (!class_exists("pmLicenseManager")) { - require_once ("classes" . PATH_SEP . "class.pmLicenseManager.php"); - } - - $licenseManager = pmLicenseManager::getSingleton(false); + $licenseManager = PmLicenseManager::getSingleton(false); $_SESSION['__sw__'] = true; - $padl = new padl(); + $padl = new Padl(); $value = $padl->_decrypt($featureName); if (is_array($value)) { diff --git a/workflow/engine/classes/class.pluginRegistry.php b/workflow/engine/classes/PMPluginRegistry.php similarity index 95% rename from workflow/engine/classes/class.pluginRegistry.php rename to workflow/engine/classes/PMPluginRegistry.php index 675f4f535..6136b662a 100644 --- a/workflow/engine/classes/class.pluginRegistry.php +++ b/workflow/engine/classes/PMPluginRegistry.php @@ -1,90 +1,8 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ - +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; -/** - * - * @package workflow.engine.classes - */ - -require_once 'class.plugin.php'; - - -class pluginDetail -{ - public $sNamespace; - public $sClassName; - public $sFriendlyName = null; - public $sDescription = null; - public $sSetupPage = null; - public $sFilename; - public $sPluginFolder = ''; - public $sCompanyLogo = ''; - public $iVersion = 0; - public $enabled = false; - public $aWorkspaces = null; - public $bPrivate = false; - - /** - * This function is the constructor of the pluginDetail class - * - * @param string $sNamespace - * @param string $sClassName - * @param string $sFilename - * @param string $sFriendlyName - * @param string $sPluginFolder - * @param string $sDescription - * @param string $sSetupPage - * @param integer $iVersion - * @return void - */ - public function __construct ($sNamespace, $sClassName, $sFilename, $sFriendlyName = '', $sPluginFolder = '', $sDescription = '', $sSetupPage = '', $iVersion = 0) - { - $this->sNamespace = $sNamespace; - $this->sClassName = $sClassName; - $this->sFriendlyName = $sFriendlyName; - $this->sDescription = $sDescription; - $this->sSetupPage = $sSetupPage; - $this->iVersion = $iVersion; - $this->sFilename = $sFilename; - if ($sPluginFolder == '') { - $this->sPluginFolder = $sNamespace; - } else { - $this->sPluginFolder = $sPluginFolder; - } - } -} - -/** - * - * @package workflow.engine.classes - */ - class PMPluginRegistry { private $_aPluginDetails = array (); @@ -212,7 +130,7 @@ class PMPluginRegistry return; } - $detail = new pluginDetail( $sNamespace, $sClassName, $sFilename, $plugin->sFriendlyName, $plugin->sPluginFolder, $plugin->sDescription, $plugin->sSetupPage, $plugin->iVersion ); + $detail = new PluginDetail( $sNamespace, $sClassName, $sFilename, $plugin->sFriendlyName, $plugin->sPluginFolder, $plugin->sDescription, $plugin->sSetupPage, $plugin->iVersion ); if (isset( $plugin->aWorkspaces )) { $detail->aWorkspaces = $plugin->aWorkspaces; @@ -585,7 +503,7 @@ class PMPluginRegistry public function uninstallPluginWorkspaces ($arrayPlugin) { - $workspace = PmSystem::listWorkspaces(); + $workspace = System::listWorkspaces(); foreach ($workspace as $indexWS => $ws) { $wsPathDataSite = PATH_DATA . "sites" . PATH_SEP . $ws->name . PATH_SEP; @@ -1183,11 +1101,8 @@ class PMPluginRegistry public function setupPlugins () { try { - require_once(PATH_CORE . "methods" . PATH_SEP . "enterprise" . PATH_SEP . "enterprise.php"); - require_once("class.serverConfiguration.php"); - $iPlugins = 0; - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $oServerConf->addPlugin( SYS_SYS, $this->_aPluginDetails ); foreach ($this->_aPluginDetails as $namespace => $detail) { if (isset( $detail->enabled ) && $detail->enabled) { @@ -1294,7 +1209,7 @@ class PMPluginRegistry //Found a License if (class_exists( 'pmLicenseManager' )) { $sSerializedFile = PATH_DATA_SITE . 'lmn.singleton'; - $pmLicenseManagerO = & pmLicenseManager::getSingleton(); + $pmLicenseManagerO = & PmLicenseManager::getSingleton(); if (file_exists( $sSerializedFile )) { $pmLicenseManagerO->unSerializeInstance( file_get_contents( $sSerializedFile ) ); } @@ -1629,7 +1544,7 @@ class PMPluginRegistry if (isset($pluginDetails->aWorkspaces) && is_array($pluginDetails->aWorkspaces) && count($pluginDetails->aWorkspaces) > 0) { $arrayWorkspace = array(); - foreach (PmSystem::listWorkspaces() as $value) { + foreach (System::listWorkspaces() as $value) { $workspaceTools = $value; $arrayWorkspace[] = $workspaceTools->name; diff --git a/workflow/engine/classes/class.memcached.php b/workflow/engine/classes/PMmemcached.php similarity index 84% rename from workflow/engine/classes/class.memcached.php rename to workflow/engine/classes/PMmemcached.php index 3a5bbfcd4..74098d33c 100644 --- a/workflow/engine/classes/class.memcached.php +++ b/workflow/engine/classes/PMmemcached.php @@ -1,35 +1,4 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * The ProcessMaker memcached class - * - * @package workflow.engine.ProcessMaker - */ class PMmemcached { @@ -65,7 +34,6 @@ class PMmemcached $this->version = $this->mem->getVersion(); } } else { - require_once ("classes" . PATH_SEP . "class.fileCache.php"); //Create cache folder $cacheFolder = PATH_DATA . "sites". PATH_SEP . $workspace . PATH_SEP . "cachefiles" . PATH_SEP; @@ -218,4 +186,3 @@ class PMmemcached echo ""; } } - diff --git a/workflow/engine/classes/class.license.lib.php b/workflow/engine/classes/Padl.php similarity index 95% rename from workflow/engine/classes/class.license.lib.php rename to workflow/engine/classes/Padl.php index 8ae5a9be0..6aa8ebe1f 100644 --- a/workflow/engine/classes/class.license.lib.php +++ b/workflow/engine/classes/Padl.php @@ -26,7 +26,37 @@ * @history--------------------------------------------- * see CHANGELOG */ -class padl + +use ProcessMaker\Core\System; + +/** + * Project: Distrubution License Class + * File: class.license.lib.php + * + * Copyright (C) 2005 Oliver Lillie + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * @link http://www.buggedcom.co.uk/ + * @link http://www.phpclasses.org/browse/package/2298.html + * @author Oliver Lillie, buggedcom + * @version 0.1 + * @history--------------------------------------------- + * see CHANGELOG + */ +class Padl { /** * hash key 1 used to encrypt the generate key data. @@ -236,7 +266,7 @@ class padl } // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { if (!is_array($params['http'])) { $params['http'] = array(); @@ -673,32 +703,3 @@ class padl } } } - -/** - * custom functions to aid in debugging - * - * @var mixed - */ -function trace() -{ - $message = ''; - for ($i = 0; $i < func_num_args(); $i++) { - if (is_array(func_get_arg($i))) { - trace_r(func_get_arg($i)); - } else { - $message .= func_get_arg($i); - } - if ($i <= func_num_args() - 2) { - $message.=' : '; - } - } - echo "
\r\r" . $message . "\r\r"; -} - -function trace_r($array = "array is empty") -{ - echo "
\r\r";
-    print_r($array);
-    echo "\r\r
"; -} - diff --git a/workflow/engine/classes/Patch.php b/workflow/engine/classes/Patch.php new file mode 100644 index 000000000..1ebd9ddb7 --- /dev/null +++ b/workflow/engine/classes/Patch.php @@ -0,0 +1,14 @@ +sNamespace = $sNamespace; + $this->sClassName = $sClassName; + $this->sFriendlyName = $sFriendlyName; + $this->sDescription = $sDescription; + $this->sSetupPage = $sSetupPage; + $this->iVersion = $iVersion; + $this->sFilename = $sFilename; + if ($sPluginFolder == '') { + $this->sPluginFolder = $sNamespace; + } else { + $this->sPluginFolder = $sPluginFolder; + } + } +} diff --git a/workflow/engine/classes/class.pmDashlet.php b/workflow/engine/classes/PmDashlet.php similarity index 98% rename from workflow/engine/classes/class.pmDashlet.php rename to workflow/engine/classes/PmDashlet.php index fdaf5d295..13a75cc35 100644 --- a/workflow/engine/classes/class.pmDashlet.php +++ b/workflow/engine/classes/PmDashlet.php @@ -2,11 +2,8 @@ use ProcessMaker\Plugins\PluginRegistry; -require_once 'classes/interfaces/dashletInterface.php'; -require_once 'classes/model/Dashlet.php'; -require_once 'classes/model/DashletInstance.php'; -class PMDashlet extends DashletInstance implements DashletInterface +class PmDashlet extends DashletInstance implements DashletInterface { // Own properties diff --git a/workflow/engine/classes/class.pmDrive.php b/workflow/engine/classes/PmDrive.php similarity index 99% rename from workflow/engine/classes/class.pmDrive.php rename to workflow/engine/classes/PmDrive.php index 7966ea6e7..20cc3d455 100644 --- a/workflow/engine/classes/class.pmDrive.php +++ b/workflow/engine/classes/PmDrive.php @@ -6,8 +6,7 @@ * @package workflow.engine.class * */ - -class PMDrive extends PMGoogleApi +class PmDrive extends PmGoogleApi { private $folderIdPMDrive = ''; private $folderNamePMDrive; diff --git a/workflow/engine/classes/class.pmDynaform.php b/workflow/engine/classes/PmDynaform.php similarity index 99% rename from workflow/engine/classes/class.pmDynaform.php rename to workflow/engine/classes/PmDynaform.php index 3bc58a7ae..5ef326550 100644 --- a/workflow/engine/classes/class.pmDynaform.php +++ b/workflow/engine/classes/PmDynaform.php @@ -1,13 +1,12 @@ context = \Bootstrap::getDefaultContextLog(); $this->dataSources = array("database", "dataVariable"); $this->pathRTLCss = '/lib/pmdynaform/build/css/PMDynaform-rtl.css'; - $this->serverConf = &serverConf::getSingleton(); + $this->serverConf = &ServerConf::getSingleton(); $this->isRTL = ($this->serverConf->isRtl(SYS_LANG)) ? 'true' : 'false'; $this->fields = $fields; $this->propertiesToExclude = array('dataVariable'); @@ -1059,7 +1058,7 @@ class pmDynaform $javascript = " "; @@ -1406,7 +1405,7 @@ class pmDynaform $javascrip = "" . ""; + return $sc; + } +} diff --git a/workflow/engine/classes/class.processes.php b/workflow/engine/classes/Processes.php similarity index 98% rename from workflow/engine/classes/class.processes.php rename to workflow/engine/classes/Processes.php index 8b4e1281a..acb3056a9 100644 --- a/workflow/engine/classes/class.processes.php +++ b/workflow/engine/classes/Processes.php @@ -1,28 +1,6 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ + +use ProcessMaker\Core\System; class Processes { @@ -5795,7 +5773,7 @@ class Processes $endpoint = PML_WSDL_URL; $sessionId = ''; $proxy = array(); - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $proxy['proxy_host'] = $sysConf['proxy_host']; if ($sysConf['proxy_port'] != '') { @@ -5837,7 +5815,7 @@ class Processes ini_set("soap.wsdl_cache_enabled", "0"); // enabling WSDL cache try { $proxy = array(); - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $proxy['proxy_host'] = $sysConf['proxy_host']; if ($sysConf['proxy_port'] != '') { @@ -5869,7 +5847,7 @@ class Processes $endpoint = PML_WSDL_URL; $proxy = array(); - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $proxy['proxy_host'] = $sysConf['proxy_host']; @@ -5946,7 +5924,7 @@ class Processes $endpoint = PML_WSDL_URL; $proxy = array(); - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $proxy['proxy_host'] = $sysConf['proxy_host']; if ($sysConf['proxy_port'] != '') { @@ -6183,96 +6161,3 @@ class Processes return $proTitle; } } - -//end class processes - - -/** - * Object Document class - * - * @package workflow.engine.ProcessMaker - */ -class ObjectDocument -{ - public $type; - public $name; - public $data; - public $origin; - - /** - * Constructor - */ - public function __construct() - { - $this->type = ''; - $this->name = ''; - $this->data = ''; - $this->origin = ''; - } -} - -/** - * ObjectDocument Collection - * - * @package workflow.engine.ProcessMaker - */ -class ObjectCellection -{ - public $num; - public $swapc; - public $objects; - - /** - * Constructor - */ - public function __construct() - { - $this->objects = Array(); - $this->num = 0; - $this->swapc = $this->num; - array_push($this->objects, 'void'); - } - - /** - * add in the collecetion a new object Document - * - * @param $name name object document - * @param $type type object document - * @param $data data object document - * @param $origin origin object document - * @return void - */ - public function add($name, $type, $data, $origin) - { - $o = new ObjectDocument(); - $o->name = $name; - $o->type = $type; - $o->data = $data; - $o->origin = $origin; - - $this->num++; - array_push($this->objects, $o); - $this->swapc = $this->num; - } - - /** - * get the collection of ObjectDocument - * - * @param $name name object document - * @param $type type object document - * @param $data data object document - * @param $origin origin object document - * @return void - */ - public function get() - { - if ($this->swapc > 0) { - $e = $this->objects[$this->swapc]; - $this->swapc--; - return $e; - } else { - $this->swapc = $this->num; - return false; - } - } -} diff --git a/workflow/engine/classes/class.propelTable.php b/workflow/engine/classes/PropelTable.php similarity index 95% rename from workflow/engine/classes/class.propelTable.php rename to workflow/engine/classes/PropelTable.php index 2dae0fa68..39fa1c209 100644 --- a/workflow/engine/classes/class.propelTable.php +++ b/workflow/engine/classes/PropelTable.php @@ -1,42 +1,22 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ use ProcessMaker\Plugins\PluginRegistry; /** * Class pagedTable - * - * @author David S. Callizaya S. * - * @access public * @package workflow.gulliver.system * dependencies TemplatePower Form XmlForm */ -class propelTable + +/** + * Class pagedTable + * + * @access public + * @package workflow.gulliver.system + * dependencies TemplatePower Form XmlForm + */ +class PropelTable { public $xmlFormFile; public $currentPage; @@ -95,7 +75,7 @@ class propelTable public $name = 'pagedTable'; public $id = 'A1'; public $disableFooter = false; - //This attribute is used to set STYLES to groups of TD, using the field type "cellMark" (see XmlForm_Field_cellMark) + //This attribute is used to set STYLES to groups of TD, using the field type "cellMark" (see XmlFormFieldCellMark) public $tdStyle = ''; public $tdClass = ''; //Config Save definition @@ -910,4 +890,3 @@ class propelTable G::RenderPage( "publish", "blank" ); } } - diff --git a/workflow/engine/classes/class.replacementLogo.php b/workflow/engine/classes/ReplacementLogo.php similarity index 68% rename from workflow/engine/classes/class.replacementLogo.php rename to workflow/engine/classes/ReplacementLogo.php index fae2c5bf0..4a9d92d1a 100644 --- a/workflow/engine/classes/class.replacementLogo.php +++ b/workflow/engine/classes/ReplacementLogo.php @@ -1,41 +1,15 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ - /** * * @package workflow.engine.classes */ - -class replacementLogo +class ReplacementLogo { //var $dir=''; /** - * This function is the constructor of the replacementLogo class + * This function is the constructor of the ReplacementLogo class * param * * @return void @@ -109,4 +83,3 @@ class replacementLogo return ($ainfoLogo); } } - diff --git a/workflow/engine/classes/Report.php b/workflow/engine/classes/Report.php new file mode 100644 index 000000000..07f944504 --- /dev/null +++ b/workflow/engine/classes/Report.php @@ -0,0 +1,823 @@ +reportsPatch(); + + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); + + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + $aProcess[] = array('PRO_UID' => 'char', 'PRO_TITLE' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + + $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], 'PRO_TITLE' => $aRow['PRO_TITLE'], 'CANTCASES' => ApplicationPeer::doCount($oCriteria), 'MIN' => number_format($aRow['MIN'], 2), 'MAX' => number_format($aRow['MAX'], 2), 'TOTALDUR' => number_format($aRow['TOTALDUR'], 2), 'PROMEDIO' => number_format($aRow['PROMEDIO'], 2) + ); + $oDataset->next(); + } + + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function does a sql statment to a report wiht a condition + * or maybe when you're looking for some specials cases + * + * @name generatedReport1_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport1_filter($from, $to, $startedby) + { + $this->reportsPatch(); + + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(UsersPeer::USR_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $oCriteria->addJoin(AppDelegationPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); + //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $from, Criteria::GREATER_EQUAL); + //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $to, Criteria::LESS_EQUAL); + //$aAux1 = explode('-', $from); date('Y-m-d H:i:s', mktime(0, 0, 0, $aAux1[1], $aAux1[2], $aAux1[0])) + $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL))); + + if ($startedby != '') { + $oCriteria->add(ApplicationPeer::APP_INIT_USER, $startedby); + } + + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); + + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + $aProcess[] = array('PRO_UID' => 'char', 'PRO_TITLE' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + if ($startedby != '') { + $oCriteria->add(ApplicationPeer::APP_INIT_USER, $startedby); + } + + $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], 'PRO_TITLE' => $aRow['PRO_TITLE'], 'CANTCASES' => ApplicationPeer::doCount($oCriteria), 'MIN' => number_format($aRow['MIN'], 2), 'MAX' => number_format($aRow['MAX'], 2), 'TOTALDUR' => number_format($aRow['TOTALDUR'], 2), 'PROMEDIO' => number_format($aRow['PROMEDIO'], 2)); + $oDataset->next(); + } + + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function gets info about a report + * + * + * @name descriptionReport1 + * + * @param string $PRO_UID + * @return object + */ + public function descriptionReport1($PRO_UID) + { + $this->reportsPatch(); + + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Task.php'; + require_once 'classes/model/Content.php'; + + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(TaskPeer::TAS_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")"); + + $oCriteria->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN); + $oCriteria->add(AppDelegationPeer::PRO_UID, $PRO_UID); + + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addGroupByColumn(TaskPeer::TAS_TITLE); + + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + $aProcess[] = array('TAS_TITLE' => 'char', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + while ($aRow = $oDataset->getRow()) { + $aProcess[] = array('TAS_TITLE' => $aRow['TAS_TITLE'], 'MIN' => number_format($aRow['MIN'], 2), 'MAX' => number_format($aRow['MAX'], 2), 'TOTALDUR' => number_format($aRow['TOTALDUR'], 2), 'PROMEDIO' => number_format($aRow['PROMEDIO'], 2) + ); + $oDataset->next(); + } + + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function generates a other kind of report + * + * + * @name generatedReport2 + * + * param + * @return object + */ + public function generatedReport2() + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + $month = date('Y-m-d', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y"))); + $lastmonth = date('Y-m-d', mktime(0, 0, 0, date("m") - 2, date("d"), date("Y"))); + + $day = mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")); + $lastday = mktime(0, 0, 0, date("m"), date("d") - 2, date("Y")); + + $aProcess[] = array('PRO_UID' => 'char', 'PRO_TITLE' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'CASELASTMONTH' => 'integer', 'CASELASTDAY' => 'integer' + ); + + while ($aRow = $oDataset->getRow()) { + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL); + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant1 = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL); + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant2 = $aRow2['CANTCASES']; + + $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], 'PRO_TITLE' => $aRow['PRO_TITLE'], 'CANTCASES' => $cant, 'MIN' => number_format($aRow['MIN'], 2), 'MAX' => number_format($aRow['MAX'], 2), 'CASELASTMONTH' => number_format($cant1, 2), 'CASELASTDAY' => number_format($cant2, 2) + ); + $oDataset->next(); + } + + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + return $oCriteria; + } + + /** + * This function generates the description about a report + * + * + * @name reports_Description_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @param string $PRO_UID + * @return object + */ + public function reports_Description_filter($from, $to, $startedby, $PRO_UID) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Task.php'; + require_once 'classes/model/Content.php'; + require_once 'classes/model/Users.php'; + + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(TaskPeer::TAS_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")"); + + $oCriteria->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN); + $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL))); + + if ($startedby != '') { + $oCriteria->add(AppDelegationPeer::USR_UID, $startedby); + } + + $oCriteria->add(AppDelegationPeer::PRO_UID, $PRO_UID); + + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addGroupByColumn(TaskPeer::TAS_TITLE); + + return $oCriteria; + } + + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport2_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport2_filter($from, $to, $startedby) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Users.php'; + + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); + $oCriteria->addAsColumn("MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addAsColumn("MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")"); + $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $oCriteria->addGroupByColumn(AppDelegationPeer::PRO_UID); + $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); + + $oCriteria->add($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL)->addAnd($oCriteria->getNewCriterion(AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL))); + + if ($startedby != '') { + $oCriteria->add(AppDelegationPeer::USR_UID, $startedby); + } + + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + + $month = date('Y-m-d', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y"))); + $lastmonth = date('Y-m-d', mktime(0, 0, 0, date("m") - 2, date("d"), date("Y"))); + $day = mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")); + $lastday = mktime(0, 0, 0, date("m"), date("d") - 2, date("Y")); + $aProcess[] = array('PRO_UID' => 'char', 'PRO_TITLE' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'CASELASTMONTH' => 'integer', 'CASELASTDAY' => 'integer'); + + while ($aRow = $oDataset->getRow()) { + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + if ($startedby != '') { + $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); + } + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL); + if ($startedby != '') { + $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); + } + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant1 = $aRow2['CANTCASES']; + + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->addSelectColumn(ApplicationPeer::PRO_UID); + $oCriteria2->addAsColumn("CANTCASES", "COUNT(*)"); + $oCriteria2->add(ApplicationPeer::PRO_UID, $aRow['PRO_UID']); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL); + $oCriteria2->add(ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL); + if ($startedby != '') { + $oCriteria2->add(ApplicationPeer::APP_INIT_USER, $startedby); + } + $oCriteria2->addGroupByColumn(ApplicationPeer::PRO_UID); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + $aRow2 = $oDataset2->getRow(); + $cant2 = $aRow2['CANTCASES']; + + /*$aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], + 'PRO_TITLE' => $aRow['PRO_TITLE'], + 'CANTCASES' => $cant, + 'CASELASTMONTH' => $cant1, + 'CASELASTDAY' => $cant2 + );*/ + $aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], 'PRO_TITLE' => $aRow['PRO_TITLE'], 'CANTCASES' => $cant, 'MIN' => number_format($aRow['MIN'], 2), 'MAX' => number_format($aRow['MAX'], 2), 'CASELASTMONTH' => number_format($cant1, 2), 'CASELASTDAY' => number_format($cant2, 2)); + $oDataset->next(); + } + + global $_DBArray; + $_DBArray['reports'] = $aProcess; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + return $oCriteria; + } + + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport2_filter + * + * @param string $from + * @param string $to + * @param string $startedby + * @return object + */ + public function generatedReport3() + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, + COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APP_DELEGATION AS AD + LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) + WHERE AD.APP_UID<>'' AND P.PRO_STATUS<>'DISABLED' + GROUP BY FECHA"; + + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + + $ROW[] = array('FECHA' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float'); + + while ($rs->next()) { + $ROW[] = array('FECHA' => $rs->getString('FECHA'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2)); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + + } + + /** + * This function looks for an special case it has a condition + * + * + * @name generatedReport3_filter + * + * @param string $process + * @param string $task + * @return object + */ + public function generatedReport3_filter($process, $task) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " WHERE P.PRO_STATUS<>'DISABLED'"; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "'"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } + $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, + COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APP_DELEGATION AS AD + LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) + " . $var . " + GROUP BY FECHA"; + + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + $ROW[] = array('FECHA' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float'); + + while ($rs->next()) { + $ROW[] = array('FECHA' => $rs->getString('FECHA'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2)); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function generates a report + * + * + * @name generatedReport4 + * + * param + * @return object + */ + public function generatedReport4() + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + COUNT(*) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APPLICATION AS A + LEFT JOIN APP_DELEGATION AS AD ON(A.APP_UID = AD.APP_UID AND AD.DEL_INDEX=1) + LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) + WHERE A.APP_UID<>'' + GROUP BY USER"; + // AND P.PRO_STATUS<>'DISABLED' that hapens when it is created to new version it exists at the moment to import + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + + $ROW[] = array('USER' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + + while ($rs->next()) { + $ROW[] = array('USER' => $rs->getString('USER'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2) + ); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + + } + + /** + * This function generates a filter to report 4 + * + * + * @name generatedReport4_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport4_filter($process, $task) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " "; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "'"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } + + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + COUNT(*) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APPLICATION AS A + LEFT JOIN APP_DELEGATION AS AD ON(A.APP_UID = AD.APP_UID AND AD.DEL_INDEX=1) + LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) + " . $var . " + GROUP BY USER"; + + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + + $ROW[] = array('USER' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + + while ($rs->next()) { + $ROW[] = array('USER' => $rs->getString('USER'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2) + ); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function generates a Report + * + * + * @name generatedReport4_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport5() + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + COUNT(*) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APP_DELEGATION AS AD + LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) + LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) + WHERE AD.APP_UID<>'' AND AD.DEL_FINISH_DATE IS NULL + GROUP BY USER"; + + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + + $ROW[] = array('USER' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + + while ($rs->next()) { + $ROW[] = array('USER' => $rs->getString('USER'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2) + ); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + + } + + /** + * This function generates a filter to report 5 + * + * + * @name generatedReport5_filter + * + * @param string process + * @param string task + * @return object + */ + public function generatedReport5_filter($process, $task) + { + $this->reportsPatch(); + require_once 'classes/model/AppDelegation.php'; + require_once 'classes/model/Application.php'; + require_once 'classes/model/Process.php'; + require_once 'classes/model/Users.php'; + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + if ($process == '') { + $var = " WHERE AD.DEL_FINISH_DATE IS NULL"; + } else { + if ($task == '') { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.DEL_FINISH_DATE IS NULL"; + } else { + $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) + WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; + } + } + $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, + COUNT(*) AS CANTCASES, + MIN(AD.DEL_DURATION) AS MIN, + MAX(AD.DEL_DURATION) AS MAX, + SUM(AD.DEL_DURATION) AS TOTALDUR, + AVG(AD.DEL_DURATION) AS PROMEDIO + FROM APP_DELEGATION AS AD + LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) + LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) + " . $var . " + GROUP BY USER"; + + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); + $rs = $stmt->executeQuery(); + + $ROW[] = array('USER' => 'char', 'CANTCASES' => 'integer', 'MIN' => 'float', 'MAX' => 'float', 'TOTALDUR' => 'float', 'PROMEDIO' => 'float' + ); + + while ($rs->next()) { + $ROW[] = array('USER' => $rs->getString('USER'), 'CANTCASES' => $rs->getString('CANTCASES'), 'MIN' => number_format($rs->getString('MIN'), 2), 'MAX' => number_format($rs->getString('MAX'), 2), 'TOTALDUR' => number_format($rs->getString('TOTALDUR'), 2), 'PROMEDIO' => number_format($rs->getString('PROMEDIO'), 2) + ); + } + + global $_DBArray; + $_DBArray['reports'] = $ROW; + $_SESSION['_DBArray'] = $_DBArray; + $oCriteria = new Criteria('dbarray'); + $oCriteria->setDBArrayTable('reports'); + + return $oCriteria; + } + + /** + * This function returns an array, it has the reports' names + * + * + * @name getAvailableReports + * + * param + * @return array + */ + public function getAvailableReports() + { + return array('ID_REPORT1', 'ID_REPORT2', 'ID_REPORT3', 'ID_REPORT4', 'ID_REPORT5' + ); + } + + /** + * Patch for reports by The Answer (17-10-2k8) + * + * + * @name reportsPatch + * + * param + * @return void + */ + + public function reportsPatch() + { + require_once 'classes/model/AppDelegation.php'; + + $oCriteria = new Criteria('workflow'); + $del = DBAdapter::getStringDelimiter(); + $oCriteria->addSelectColumn(AppDelegationPeer::APP_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INDEX); + $oCriteria->addSelectColumn(AppDelegationPeer::TAS_UID); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_DELEGATE_DATE); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_INIT_DATE); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); + $oCriteria->addSelectColumn(AppDelegationPeer::DEL_DURATION); + $oDataset = AppDelegationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + while ($aRow = $oDataset->getRow()) { + $oAppDelegation = new AppDelegation(); + + $aData['APP_UID'] = $aRow['APP_UID']; + $aData['DEL_INDEX'] = $aRow['DEL_INDEX']; + $aData['DEL_DELEGATE_DATE'] = $aRow['DEL_DELEGATE_DATE']; + + if ($aRow['DEL_INIT_DATE'] == null) { + $aData['DEL_INIT_DATE'] = $aRow['DEL_DELEGATE_DATE']; + } else { + $aData['DEL_INIT_DATE'] = $aRow['DEL_INIT_DATE']; + } + //$aData['DEL_FINISH_DATE']=$aRow['DEL_FINISH_DATE']; + if ($aRow['DEL_DURATION'] != 0) { + $oDates = new dates(); + $aData['DEL_DURATION'] = $oDates->calculateDuration($aData['DEL_INIT_DATE'], $aRow['DEL_FINISH_DATE'], null, null, $aRow['TAS_UID']); + } + + $oAppDelegation->update($aData); + + $oDataset->next(); + } + return; + } +} diff --git a/workflow/engine/classes/class.reportTables.php b/workflow/engine/classes/ReportTables.php similarity index 64% rename from workflow/engine/classes/class.reportTables.php rename to workflow/engine/classes/ReportTables.php index 5674367f7..6f72c8a9a 100644 --- a/workflow/engine/classes/class.reportTables.php +++ b/workflow/engine/classes/ReportTables.php @@ -1,45 +1,14 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - /** - * ReportTables - Report tables class - * - * @package workflow.engine.ProcessMaker - * @author Julio Cesar Laura Avenda�o - * @copyright 2007 COLOSA + * ReportTables - Report tables */ - class ReportTables { - private $aDef = array ('mysql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' - ),'pgsql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' - ),'mssql' => array ('number' => 'FLOAT','char' => 'NVARCHAR(255)','text' => 'TEXT','date' => 'CHAR(19)' - ) /* Changed DATETIME CHAR(19) for compatibility issues. */ ); + private $aDef = array('mysql' => array('number' => 'DOUBLE', 'char' => 'VARCHAR(255)', 'text' => 'TEXT', 'date' => 'DATETIME' + ), 'pgsql' => array('number' => 'DOUBLE', 'char' => 'VARCHAR(255)', 'text' => 'TEXT', 'date' => 'DATETIME' + ), 'mssql' => array('number' => 'FLOAT', 'char' => 'NVARCHAR(255)', 'text' => 'TEXT', 'date' => 'CHAR(19)' + ) /* Changed DATETIME CHAR(19) for compatibility issues. */); //private $sPrefix = 'REP_'; private $sPrefix = ''; @@ -51,12 +20,12 @@ class ReportTables * @param string $$sRepTabUid * @return void */ - public function deleteAllReportVars ($sRepTabUid = '') + public function deleteAllReportVars($sRepTabUid = '') { try { - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); - ReportVarPeer::doDelete( $oCriteria ); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); + ReportVarPeer::doDelete($oCriteria); } catch (Exception $oError) { throw ($oError); } @@ -71,21 +40,21 @@ class ReportTables * @param string $sConnection Conexion * @return void */ - public function dropTable ($sTableName, $sConnection = 'report') + public function dropTable($sTableName, $sConnection = 'report') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection - $PropelDatabase = $this->chooseDB( $sConnection ); - $con = Propel::getConnection( $PropelDatabase ); + $PropelDatabase = $this->chooseDB($sConnection); + $con = Propel::getConnection($PropelDatabase); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { case 'mysql': - $rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`' ); + $rs = $stmt->executeQuery('DROP TABLE IF EXISTS `' . $sTableName . '`'); break; case 'mssql': - $rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL - DROP TABLE [" . $sTableName . "]" ); + $rs = $stmt->executeQuery("IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL + DROP TABLE [" . $sTableName . "]"); break; } } catch (Exception $oError) { @@ -105,12 +74,12 @@ class ReportTables * @param string $bDefaultFields * @return void */ - public function createTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) + public function createTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection - $PropelDatabase = $this->chooseDB( $sConnection ); - $con = Propel::getConnection( $PropelDatabase ); + $PropelDatabase = $this->chooseDB($sConnection); + $con = Propel::getConnection($PropelDatabase); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { @@ -142,7 +111,7 @@ class ReportTables $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } $sQuery .= ' DEFAULT CHARSET=utf8;'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); break; case 'mssql': $sQuery = 'CREATE TABLE [' . $sTableName . '] ('; @@ -174,7 +143,7 @@ class ReportTables $sQuery .= ' '; } - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); break; } @@ -196,88 +165,88 @@ class ReportTables * @param string $sGrid * @return void */ - public function populateTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') + public function populateTable($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection - $PropelDatabase = $this->chooseDB( $sConnection ); - $con = Propel::getConnection( $PropelDatabase ); + $PropelDatabase = $this->chooseDB($sConnection); + $con = Propel::getConnection($PropelDatabase); $stmt = $con->createStatement(); if ($sType == 'GRID') { - $aAux = explode( '-', $sGrid ); + $aAux = explode('-', $sGrid); $sGrid = $aAux[0]; } try { switch (DB_ADAPTER) { case 'mysql': //select cases for this Process, ordered by APP_NUMBER - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); - $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); - $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ApplicationPeer::PRO_UID, $sProcessUid); + $oCriteria->addAscendingOrderByColumn(ApplicationPeer::APP_NUMBER); + $oDataset = ApplicationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $aData = unserialize( $aRow['APP_DATA'] ); + $aData = unserialize($aRow['APP_DATA']); //delete previous record from this report table ( previous records in case this is a grid ) $deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'"; - $rsDel = $stmt->executeQuery( $deleteSql ); + $rsDel = $stmt->executeQuery($deleteSql); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aData[$aField['sFieldName']]) ? (float)str_replace(',', '', $aData[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aData[$aField['sFieldName']] )) { + if (!isset($aData[$aField['sFieldName']])) { $aData[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? @mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? @mysql_real_escape_string($aData[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $value = (isset( $aData[$aField['sFieldName']] ) && trim( $aData[$aField['sFieldName']] )) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; + $value = (isset($aData[$aField['sFieldName']]) && trim($aData[$aField['sFieldName']])) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } else { - if (isset( $aData[$sGrid] )) { + if (isset($aData[$sGrid])) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aGridRow[$aField['sFieldName']] )) { + if (!isset($aGridRow[$aField['sFieldName']])) { $aGridRow[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $value = (isset( $aGridRow[$aField['sFieldName']] ) && trim( $aGridRow[$aField['sFieldName']] )) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; + $value = (isset($aGridRow[$aField['sFieldName']]) && trim($aGridRow[$aField['sFieldName']])) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } } } @@ -289,69 +258,69 @@ class ReportTables * For SQLServer code */ case 'mssql': - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); - $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); - $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ApplicationPeer::PRO_UID, $sProcessUid); + $oCriteria->addAscendingOrderByColumn(ApplicationPeer::APP_NUMBER); + $oDataset = ApplicationPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $aData = unserialize( $aRow['APP_DATA'] ); - mysql_query( 'DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'" ); + $aData = unserialize($aRow['APP_DATA']); + mysql_query('DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'"); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER]'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aData[$aField['sFieldName']]) ? (float)str_replace(',', '', $aData[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aData[$aField['sFieldName']] )) { + if (!isset($aData[$aField['sFieldName']])) { $aData[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? mysql_real_escape_string($aData[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? $aData[$aField['sFieldName']] : '') . "'"; + $sQuery .= ",'" . (isset($aData[$aField['sFieldName']]) ? $aData[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } else { - if (isset( $aData[$sGrid] )) { + if (isset($aData[$sGrid])) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } - $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; + $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int)$aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aGridRow[$aField['sFieldName']] )) { + if (!isset($aGridRow[$aField['sFieldName']])) { $aGridRow[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } } } @@ -373,21 +342,21 @@ class ReportTables * @param boolean $bWhitType * @return void */ - public function getTableVars ($sRepTabUid, $bWhitType = false) + public function getTableVars($sRepTabUid, $bWhitType = false) { try { - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); - $oDataset = ReportVarPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); + $oDataset = ReportVarPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); - $aVars = array (); - $aImportedVars = array (); //This array will help to control if the variable already exist + $aVars = array(); + $aImportedVars = array(); //This array will help to control if the variable already exist while ($aRow = $oDataset->getRow()) { if ($bWhitType) { - if (! in_array( $aRow['REP_VAR_NAME'], $aImportedVars )) { + if (!in_array($aRow['REP_VAR_NAME'], $aImportedVars)) { $aImportedVars[] = $aRow['REP_VAR_NAME']; - $aVars[] = array ('sFieldName' => $aRow['REP_VAR_NAME'],'sType' => $aRow['REP_VAR_TYPE'] + $aVars[] = array('sFieldName' => $aRow['REP_VAR_NAME'], 'sType' => $aRow['REP_VAR_TYPE'] ); } } else { @@ -409,17 +378,17 @@ class ReportTables * @param string $sRepTabUid * @return void */ - public function deleteReportTable ($sRepTabUid) + public function deleteReportTable($sRepTabUid) { try { $oReportTable = new ReportTable(); - $aFields = $oReportTable->load( $sRepTabUid ); - if (! (empty( $aFields ))) { - $this->dropTable( $aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION'] ); - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); - $oDataset = ReportVarPeer::doDelete( $oCriteria ); - $oReportTable->remove( $sRepTabUid ); + $aFields = $oReportTable->load($sRepTabUid); + if (!(empty($aFields))) { + $this->dropTable($aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION']); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ReportVarPeer::REP_TAB_UID, $sRepTabUid); + $oDataset = ReportVarPeer::doDelete($oCriteria); + $oReportTable->remove($sRepTabUid); } } catch (Exception $oError) { throw ($oError); @@ -435,22 +404,22 @@ class ReportTables * @param string $mask * @return array */ - public function getSplitDate ($date, $mask) + public function getSplitDate($date, $mask) { $sw1 = false; - for ($i = 0; $i < 3; $i ++) { - $item = substr( $mask, $i * 2, 1 ); + for ($i = 0; $i < 3; $i++) { + $item = substr($mask, $i * 2, 1); switch ($item) { case 'Y': switch ($i) { case 0: - $d1 = substr( $date, 0, 4 ); + $d1 = substr($date, 0, 4); break; case 1: - $d1 = substr( $date, 3, 4 ); + $d1 = substr($date, 3, 4); break; case 2: - $d1 = substr( $date, 6, 4 ); + $d1 = substr($date, 6, 4); break; } $sw1 = true; @@ -458,45 +427,45 @@ class ReportTables case 'y': switch ($i) { case 0: - $d1 = substr( $date, 0, 2 ); + $d1 = substr($date, 0, 2); break; case 1: - $d1 = substr( $date, 3, 2 ); + $d1 = substr($date, 3, 2); break; case 2: - $d1 = substr( $date, 6, 2 ); + $d1 = substr($date, 6, 2); break; } break; case 'm': switch ($i) { case 0: - $d2 = substr( $date, 0, 2 ); + $d2 = substr($date, 0, 2); break; case 1: - $d2 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); + $d2 = ($sw1) ? substr($date, 5, 2) : substr($date, 3, 2); break; case 2: - $d2 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); + $d2 = ($sw1) ? substr($date, 8, 2) : substr($date, 5, 2); break; } break; case 'd': switch ($i) { case 0: - $d3 = substr( $date, 0, 2 ); + $d3 = substr($date, 0, 2); break; case 1: - $d3 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); + $d3 = ($sw1) ? substr($date, 5, 2) : substr($date, 3, 2); break; case 2: - $d3 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); + $d3 = ($sw1) ? substr($date, 8, 2) : substr($date, 5, 2); break; } break; } } - return Array (isset( $d1 ) ? $d1 : '',isset( $d2 ) ? $d2 : '',isset( $d3 ) ? $d3 : '' + return Array(isset($d1) ? $d1 : '', isset($d2) ? $d2 : '', isset($d3) ? $d3 : '' ); } @@ -509,30 +478,30 @@ class ReportTables * @param date $sMask * @return date */ - public function getFormatDate ($sDate, $sMask) + public function getFormatDate($sDate, $sMask) { //print $sDate." *** ". $sMask."
"; - $dateTime = explode( " ", $sDate ); //To accept the Hour part - $aDate = explode( '-', str_replace( "/", "-", $dateTime[0] ) ); + $dateTime = explode(" ", $sDate); //To accept the Hour part + $aDate = explode('-', str_replace("/", "-", $dateTime[0])); $bResult = true; foreach ($aDate as $sDate) { - if (! is_numeric( $sDate )) { + if (!is_numeric($sDate)) { $bResult = false; break; } } if ($sMask != '') { - $aDate = $this->getSplitDate( $dateTime[0], $sMask ); - $aDate[0] = ($aDate[0] == '') ? date( 'Y' ) : $aDate[0]; - $aDate[1] = ($aDate[1] == '') ? date( 'm' ) : $aDate[1]; - $aDate[2] = ($aDate[2] == '') ? date( 'd' ) : $aDate[2]; - if (checkdate( $aDate[1], $aDate[2], $aDate[0] )) { + $aDate = $this->getSplitDate($dateTime[0], $sMask); + $aDate[0] = ($aDate[0] == '') ? date('Y') : $aDate[0]; + $aDate[1] = ($aDate[1] == '') ? date('m') : $aDate[1]; + $aDate[2] = ($aDate[2] == '') ? date('d') : $aDate[2]; + if (checkdate($aDate[1], $aDate[2], $aDate[0])) { } else { return false; } } $sDateC = ''; - for ($i = 0; $i < count( $aDate ); $i ++) { + for ($i = 0; $i < count($aDate); $i++) { $sDateC .= (($i == 0) ? "" : "-") . $aDate[$i]; } return ($sDateC); @@ -549,7 +518,7 @@ class ReportTables * @param string $aFields * @return void */ - public function updateTables ($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) + public function updateTables($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) { try { $c = new Criteria('workflow'); @@ -562,73 +531,73 @@ class ReportTables $isBpmn = isset($row['PRJ_UID']); if (!class_exists('ReportTablePeer')) { - require_once 'classes/model/ReportTablePeer.php'; - } + require_once 'classes/model/ReportTablePeer.php'; + } //get all Active Report Tables - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->add( ReportTablePeer::PRO_UID, $sProcessUid ); - $oCriteria->add( ReportTablePeer::REP_TAB_STATUS, 'ACTIVE' ); - $oDataset = ReportTablePeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ReportTablePeer::PRO_UID, $sProcessUid); + $oCriteria->add(ReportTablePeer::REP_TAB_STATUS, 'ACTIVE'); + $oDataset = ReportTablePeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); - $aVars = array (); + $aVars = array(); while ($aRow = $oDataset->getRow()) { $aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME']; - $PropelDatabase = $this->chooseDB( $aRow['REP_TAB_CONNECTION'] ); - $con = Propel::getConnection( $PropelDatabase ); + $PropelDatabase = $this->chooseDB($aRow['REP_TAB_CONNECTION']); + $con = Propel::getConnection($PropelDatabase); $stmt = $con->createStatement(); switch (DB_ADAPTER) { case 'mysql': - $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); + $aTableFields = $this->getTableVars($aRow['REP_TAB_UID'], true); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { $sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; - $rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC ); + $rsExists = $stmt->executeQuery($sqlExists, ResultSet::FETCHMODE_ASSOC); $rsExists->next(); $aRow2 = $rsExists->getRow(); - if (is_array( $aRow2 )) { + if (is_array($aRow2)) { $sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET '; foreach ($aTableFields as $aField) { $sQuery .= '`' . $aField['sFieldName'] . '` = '; - if(!$isBpmn && !isset($aFields[$aField['sFieldName']])){ - foreach($aFields as $row){ - if(is_array($row) && isset($row[count($row)])){ - $aFields = $row[count($row)]; - } - } + if (!$isBpmn && !isset($aFields[$aField['sFieldName']])) { + foreach ($aFields as $row) { + if (is_array($row) && isset($row[count($row)])) { + $aFields = $row[count($row)]; + } + } } switch ($aField['sType']) { case 'number': - $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; + $sQuery .= (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0') . ','; break; case 'char': case 'text': - if (! isset( $aFields[$aField['sFieldName']] )) { + if (!isset($aFields[$aField['sFieldName']])) { $aFields[$aField['sFieldName']] = ''; } - if (! isset( $aFields[$aField['sFieldName'] . '_label'] )) { + if (!isset($aFields[$aField['sFieldName'] . '_label'])) { $aFields[$aField['sFieldName'] . '_label'] = ''; } - if(is_array($aFields[$aField['sFieldName']])){ - $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']][0] : '') . "',"; - }else{ - $sQuery .= '\'' . ((isset($aFields[$aField['sFieldName']]))? @mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . '\','; + if (is_array($aFields[$aField['sFieldName']])) { + $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']][0] : '') . "',"; + } else { + $sQuery .= '\'' . ((isset($aFields[$aField['sFieldName']])) ? @mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . '\','; } break; case 'date': - $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); + $mysqlDate = (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { - $mysqlDate = str_replace( '/', '-', $mysqlDate ); - $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); + $mysqlDate = str_replace('/', '-', $mysqlDate); + $mysqlDate = date('Y-m-d', strtotime($mysqlDate)); } - $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; + $value = trim($mysqlDate) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= $value . ","; break; } } - $sQuery = substr( $sQuery, 0, - 1 ); + $sQuery = substr($sQuery, 0, -1); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; @@ -636,40 +605,40 @@ class ReportTables foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aFields[$aField['sFieldName']] )) { + if (!isset($aFields[$aField['sFieldName']])) { $aFields[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); + $mysqlDate = (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { - $mysqlDate = str_replace( '/', '-', $mysqlDate ); - $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); + $mysqlDate = str_replace('/', '-', $mysqlDate); + $mysqlDate = date('Y-m-d', strtotime($mysqlDate)); } - $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; + $value = trim($mysqlDate) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; } - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } else { //remove old rows from database $sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; - $rsDelete = $stmt->executeQuery( $sqlDelete ); + $rsDelete = $stmt->executeQuery($sqlDelete); - $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); - if (isset( $aFields[$aAux[0]] )) { + $aAux = explode('-', $aRow['REP_TAB_GRID']); + if (isset($aFields[$aAux[0]])) { if (is_array($aFields[$aAux[0]])) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; @@ -677,26 +646,26 @@ class ReportTables foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aGridRow[$aField['sFieldName']] )) { + if (!isset($aGridRow[$aField['sFieldName']])) { $aGridRow[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } } } @@ -707,30 +676,30 @@ class ReportTables * For SQLServer code */ case 'mssql': - $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); + $aTableFields = $this->getTableVars($aRow['REP_TAB_UID'], true); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { - $oDataset2 = mssql_query( "SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); - if ($aRow2 = mssql_fetch_row( $oDataset2 )) { + $oDataset2 = mssql_query("SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'"); + if ($aRow2 = mssql_fetch_row($oDataset2)) { $sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET '; foreach ($aTableFields as $aField) { $sQuery .= '[' . $aField['sFieldName'] . '] = '; switch ($aField['sType']) { case 'number': - $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; + $sQuery .= (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0') . ','; break; case 'char': case 'text': - if (! isset( $aFields[$aField['sFieldName']] )) { + if (!isset($aFields[$aField['sFieldName']])) { $aFields[$aField['sFieldName']] = ''; } - $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',"; + $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "',"; break; case 'date': - $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "',"; + $sQuery .= "'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "',"; break; } } - $sQuery = substr( $sQuery, 0, - 1 ); + $sQuery = substr($sQuery, 0, -1); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; @@ -738,57 +707,57 @@ class ReportTables foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aFields[$aField['sFieldName']]) ? (float)str_replace(',', '', $aFields[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aFields[$aField['sFieldName']] )) { + if (!isset($aFields[$aField['sFieldName']])) { $aFields[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "'"; + $sQuery .= ",'" . (isset($aFields[$aField['sFieldName']]) ? $aFields[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; } - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } else { - mysql_query( 'DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); - $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); - if (isset( $aFields[$aAux[0]] )) { + mysql_query('DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'"); + $aAux = explode('-', $aRow['REP_TAB_GRID']); + if (isset($aFields[$aAux[0]])) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER],[ROW]'; foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } - $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; + $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int)$iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': - $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); + $sQuery .= ',' . (isset($aGridRow[$aField['sFieldName']]) ? (float)str_replace(',', '', $aGridRow[$aField['sFieldName']]) : '0'); break; case 'char': case 'text': - if (! isset( $aGridRow[$aField['sFieldName']] )) { + if (!isset($aGridRow[$aField['sFieldName']])) { $aGridRow[$aField['sFieldName']] = ''; } - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? mysql_real_escape_string($aGridRow[$aField['sFieldName']]) : '') . "'"; break; case 'date': - $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; + $sQuery .= ",'" . (isset($aGridRow[$aField['sFieldName']]) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; - $rs = $stmt->executeQuery( $sQuery ); + $rs = $stmt->executeQuery($sQuery); } } } @@ -809,10 +778,10 @@ class ReportTables * @access public * @return boolean */ - public function tableExist () + public function tableExist() { $bExists = true; - $sDataBase = 'database_' . strtolower( DB_ADAPTER ); + $sDataBase = 'database_' . strtolower(DB_ADAPTER); $oDataBase = new database(); $bExists = $oDataBase->reportTableExist(); @@ -828,9 +797,9 @@ class ReportTables * @param string $TabConnectionk * @return string */ - public function chooseDB ($TabConnectionk) + public function chooseDB($TabConnectionk) { - $repTabConnection = trim( strtoupper( $TabConnectionk ) ); + $repTabConnection = trim(strtoupper($TabConnectionk)); $PropelDatabase = 'rp'; if ($repTabConnection == '' || $repTabConnection == 'REPORT') { $PropelDatabase = 'rp'; @@ -844,4 +813,3 @@ class ReportTables return ($PropelDatabase); } } - diff --git a/workflow/engine/classes/class.serverConfiguration.php b/workflow/engine/classes/ServerConf.php similarity index 88% rename from workflow/engine/classes/class.serverConfiguration.php rename to workflow/engine/classes/ServerConf.php index 947c83a96..a5cb68e6b 100644 --- a/workflow/engine/classes/class.serverConfiguration.php +++ b/workflow/engine/classes/ServerConf.php @@ -1,39 +1,9 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. + * ServerConfiguration - serverConf */ - -/** - * ServerConfiguration - serverConf class - * - * @author Hugo Loza - * @copyright 2010 COLOSA - * @license GNU Affero General Public License - * @package workflow.engine.ProcessMaker - */ -class serverConf +class ServerConf { private $_aProperties = array(); @@ -79,7 +49,7 @@ class serverConf public static function &getSingleton() { if (self::$instance == null) { - self::$instance = new serverConf(); + self::$instance = new ServerConf(); if ((file_exists(self::$instance->filePath)) && (filesize(self::$instance->filePath) > 0)) { self::$instance->unSerializeInstance(file_get_contents(self::$instance->filePath)); } @@ -107,10 +77,10 @@ class serverConf public function unSerializeInstance($serialized) { if (self::$instance == null) { - self::$instance = new serverConf(); + self::$instance = new ServerConf(); } - if ($instance = @unserialize($serialized)) { + if ($instance = unserialize($serialized)) { self::$instance = $instance; } } @@ -271,11 +241,10 @@ class serverConf $wsInfo = $this->aWSinfo[$file]; } else { $wsInfo['num_processes'] = "not gathered yet"; - $wsInfo['num_cases'] = "not gathered yet"; - ; + $wsInfo['num_cases'] = "not gathered yet";; $wsInfo['num_users'] = "not gathered yet"; } - $wsArray[$file] = array ('WSP_ID' => $file,'WSP_NAME' => $file,'WSP_STATUS' => $statusl,'WSP_PROCESS_COUNT' => $wsInfo['num_processes'],'WSP_CASES_COUNT' => $wsInfo['num_cases'],'WSP_USERS_COUNT' => isset( $wsInfo['num_users'] ) ? $wsInfo['num_users'] : ""); + $wsArray[$file] = array('WSP_ID' => $file, 'WSP_NAME' => $file, 'WSP_STATUS' => $statusl, 'WSP_PROCESS_COUNT' => $wsInfo['num_processes'], 'WSP_CASES_COUNT' => $wsInfo['num_cases'], 'WSP_USERS_COUNT' => isset($wsInfo['num_users']) ? $wsInfo['num_users'] : ""); if (isset($this->workspaces[$file]['WSP_LOGINS'])) { $wsArray[$file]['WSP_LOGINS'] = $this->workspaces[$file]['WSP_LOGINS']; } @@ -317,7 +286,7 @@ class serverConf $Criteria = new Criteria('workflow'); $Criteria->add(UsersPeer::USR_STATUS, array('DELETED', 'DISABLED' - ), CRITERIA::NOT_IN); + ), CRITERIA::NOT_IN); $aResult['num_users'] = UsersPeer::doCount($Criteria); return $aResult; } @@ -346,7 +315,7 @@ class serverConf { $sMySQLVersion = '?????'; if (defined("DB_HOST")) { - $dbNetView = new NET(DB_HOST); + $dbNetView = new Net(DB_HOST); $dbNetView->loginDbServer(DB_USER, DB_PASS); $dbConns = new DbConnections(''); diff --git a/workflow/engine/classes/class.sessions.php b/workflow/engine/classes/Sessions.php similarity index 59% rename from workflow/engine/classes/class.sessions.php rename to workflow/engine/classes/Sessions.php index 6cd403807..efd81fa56 100644 --- a/workflow/engine/classes/class.sessions.php +++ b/workflow/engine/classes/Sessions.php @@ -27,13 +27,11 @@ require_once 'classes/model/Session.php'; /** + * Sessions - Sessions + * /** * Sessions - Sessions class - * * @package workflow.engine.ProcessMaker - * @author Everth S. Berrios Morales - * @copyright 2008 COLOSA */ - class Sessions { @@ -47,7 +45,7 @@ class Sessions * @param string $sSessionId * @return void */ - public function __construct ($sSessionId = NULL) + public function __construct($sSessionId = NULL) { $this->sessionId = $sSessionId; } @@ -61,27 +59,27 @@ class Sessions * @param string sSessionId * @return array */ - public function getSessionUser ($sSessionId = NULL) + public function getSessionUser($sSessionId = NULL) { try { if ($sSessionId != NULL) { $this->sessionId = $sSessionId; } else if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( SessionPeer::USR_UID ); - $oCriteria->addSelectColumn( SessionPeer::SES_STATUS ); - $oCriteria->addSelectColumn( SessionPeer::SES_DUE_DATE ); - $oCriteria->add( SessionPeer::SES_UID, $this->sessionId ); + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(SessionPeer::USR_UID); + $oCriteria->addSelectColumn(SessionPeer::SES_STATUS); + $oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE); + $oCriteria->add(SessionPeer::SES_UID, $this->sessionId); - $oDataset = SessionPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset = SessionPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); $aRow = $oDataset->getRow(); - if (! is_array( $aRow )) { + if (!is_array($aRow)) { $this->deleteTmpfile(); } return $aRow; @@ -99,30 +97,30 @@ class Sessions * @param string sSessionId * @return array */ - public function verifySession ($sSessionId = NULL) + public function verifySession($sSessionId = NULL) { try { if ($sSessionId != NULL) { $this->sessionId = $sSessionId; } else if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } - $date = date( 'Y-m-d H:i:s' ); - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( SessionPeer::USR_UID ); - $oCriteria->addSelectColumn( SessionPeer::SES_STATUS ); - $oCriteria->addSelectColumn( SessionPeer::SES_DUE_DATE ); - $oCriteria->add( SessionPeer::SES_UID, $this->sessionId ); - $oCriteria->add( SessionPeer::SES_STATUS, 'ACTIVE' ); - $oCriteria->add( SessionPeer::SES_DUE_DATE, $date, Criteria::GREATER_EQUAL ); + $date = date('Y-m-d H:i:s'); + $oCriteria = new Criteria('workflow'); + $oCriteria->addSelectColumn(SessionPeer::USR_UID); + $oCriteria->addSelectColumn(SessionPeer::SES_STATUS); + $oCriteria->addSelectColumn(SessionPeer::SES_DUE_DATE); + $oCriteria->add(SessionPeer::SES_UID, $this->sessionId); + $oCriteria->add(SessionPeer::SES_STATUS, 'ACTIVE'); + $oCriteria->add(SessionPeer::SES_DUE_DATE, $date, Criteria::GREATER_EQUAL); - $oDataset = SessionPeer::doSelectRS( $oCriteria, Propel::getDbConnection('workflow_ro') ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset = SessionPeer::doSelectRS($oCriteria, Propel::getDbConnection('workflow_ro')); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); $aRow = $oDataset->getRow(); - if (! is_array( $aRow )) { + if (!is_array($aRow)) { $this->deleteTmpfile(); } @@ -142,32 +140,32 @@ class Sessions * @param string $value * @return void */ - public function registerGlobal ($name, $value) + public function registerGlobal($name, $value) { $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } $tmpfile_content = ''; - if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { - $tmpfile_content = file_get_contents( $this->tmpfile ); + if (is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '') { + $tmpfile_content = file_get_contents($this->tmpfile); } //getting the global array if ($tmpfile_content != '') { - $this->globals = unserialize( $tmpfile_content ); + $this->globals = unserialize($tmpfile_content); } else { - $this->globals = Array (); + $this->globals = Array(); } //registering the new global variable $this->globals[$name] = $value; //saving the global array - $tmpfile_content = serialize( $this->globals ); - file_put_contents( $this->tmpfile, $tmpfile_content ); + $tmpfile_content = serialize($this->globals); + file_put_contents($this->tmpfile, $tmpfile_content); } @@ -180,28 +178,28 @@ class Sessions * @param string $name * @return string */ - public function getGlobal ($name) + public function getGlobal($name) { $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } $tmpfile_content = ''; - if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { - $tmpfile_content = file_get_contents( $this->tmpfile ); + if (is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '') { + $tmpfile_content = file_get_contents($this->tmpfile); } //getting the global array if ($tmpfile_content != '') { - $this->globals = unserialize( $tmpfile_content ); + $this->globals = unserialize($tmpfile_content); } else { - $this->globals = Array (); + $this->globals = Array(); } //getting the new global variable - if (isset( $this->globals[$name] )) { + if (isset($this->globals[$name])) { return $this->globals[$name]; } else { return ''; @@ -217,24 +215,24 @@ class Sessions * @param string $name * @return array */ - public function getGlobals () + public function getGlobals() { $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } $tmpfile_content = ''; - if (is_file( $this->tmpfile ) && trim( file_get_contents( $this->tmpfile ) ) != '') { - $tmpfile_content = file_get_contents( $this->tmpfile ); + if (is_file($this->tmpfile) && trim(file_get_contents($this->tmpfile)) != '') { + $tmpfile_content = file_get_contents($this->tmpfile); } //getting the global array if ($tmpfile_content != '') { - $this->globals = unserialize( $tmpfile_content ); + $this->globals = unserialize($tmpfile_content); } else { - $this->globals = Array (); + $this->globals = Array(); } return $this->globals; } @@ -248,31 +246,13 @@ class Sessions * param * @return void */ - private function deleteTmpfile () + private function deleteTmpfile() { if ($this->sessionId == NULL) { - throw new Exception( 'session id was not set.' ); + throw new Exception('session id was not set.'); } $this->tmpfile = G::sys_get_temp_dir() . PATH_SEP . "pm-rg-{$this->sessionId}"; - @unlink( $this->tmpfile ); + @unlink($this->tmpfile); } } - - - - - - - - - - - - - - - - - - diff --git a/workflow/engine/classes/class.spool.php b/workflow/engine/classes/SpoolRun.php similarity index 53% rename from workflow/engine/classes/class.spool.php rename to workflow/engine/classes/SpoolRun.php index 567dc7e09..d2474a5ca 100644 --- a/workflow/engine/classes/class.spool.php +++ b/workflow/engine/classes/SpoolRun.php @@ -1,30 +1,4 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - /** * spoolRun - brief send email from the spool database, and see if we have all the addresses we send to. * @@ -34,26 +8,12 @@ * @link http://www.openmail.cc */ -/** - * LOG FIXES - * ========= - * - * 24-03-2010 Erik A.O. - * class: the $ExceptionCode and $aWarnings class attributes were added - * function handleFrom(): Validations for invalid data for {$this->fileData['from_email']} were added - * function resendEmails(): handler for warnings was added and fixes - * function getWarnings(): added - * function sendMail(): now is handling the exception - */ - -require_once ('classes/model/AppMessage.php'); +use ProcessMaker\Core\System; /** - * * @package workflow.engine.ProcessMaker */ - -class spoolRun +class SpoolRun { public $config; private $fileData; @@ -61,8 +21,8 @@ class spoolRun public $status; public $error; - private $ExceptionCode = Array (); //Array to define the Expetion codes - private $aWarnings = Array (); //Array to store the warning that were throws by the class + private $ExceptionCode = Array(); //Array to define the Expetion codes + private $aWarnings = Array(); //Array to store the warning that were throws by the class private $longMailEreg; @@ -74,10 +34,10 @@ class spoolRun * @param none * @return none */ - public function __construct () + public function __construct() { - $this->config = array (); - $this->fileData = array (); + $this->config = array(); + $this->fileData = array(); $this->spool_id = ''; $this->status = 'pending'; $this->error = ''; @@ -96,35 +56,35 @@ class spoolRun * @param none * @return none */ - public function getSpoolFilesList () + public function getSpoolFilesList() { $sql = "SELECT * FROM APP_MESSAGE WHERE APP_MSG_STATUS ='pending'"; - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); + $con = Propel::getConnection("workflow"); + $stmt = $con->prepareStatement($sql); $rs = $stmt->executeQuery(); while ($rs->next()) { - $this->spool_id = $rs->getString( 'APP_MSG_UID' ); - $this->fileData['subject'] = $rs->getString( 'APP_MSG_SUBJECT' ); - $this->fileData['from'] = $rs->getString( 'APP_MSG_FROM' ); - $this->fileData['to'] = $rs->getString( 'APP_MSG_TO' ); - $this->fileData['body'] = $rs->getString( 'APP_MSG_BODY' ); - $this->fileData['date'] = $rs->getString( 'APP_MSG_DATE' ); - $this->fileData['cc'] = $rs->getString( 'APP_MSG_CC' ); - $this->fileData['bcc'] = $rs->getString( 'APP_MSG_BCC' ); - $this->fileData['template'] = $rs->getString( 'APP_MSG_TEMPLATE' ); - $this->fileData['attachments'] = array (); //$rs->getString('APP_MSG_ATTACH'); - $this->fileData['error'] = $rs->getString( 'APP_MSG_ERROR' ); + $this->spool_id = $rs->getString('APP_MSG_UID'); + $this->fileData['subject'] = $rs->getString('APP_MSG_SUBJECT'); + $this->fileData['from'] = $rs->getString('APP_MSG_FROM'); + $this->fileData['to'] = $rs->getString('APP_MSG_TO'); + $this->fileData['body'] = $rs->getString('APP_MSG_BODY'); + $this->fileData['date'] = $rs->getString('APP_MSG_DATE'); + $this->fileData['cc'] = $rs->getString('APP_MSG_CC'); + $this->fileData['bcc'] = $rs->getString('APP_MSG_BCC'); + $this->fileData['template'] = $rs->getString('APP_MSG_TEMPLATE'); + $this->fileData['attachments'] = array(); //$rs->getString('APP_MSG_ATTACH'); + $this->fileData['error'] = $rs->getString('APP_MSG_ERROR'); if ($this->config['MESS_ENGINE'] == 'OPENMAIL') { if ($this->config['MESS_SERVER'] != '') { - if (($sAux = @gethostbyaddr( $this->config['MESS_SERVER'] ))) { + if (($sAux = @gethostbyaddr($this->config['MESS_SERVER']))) { $this->fileData['domain'] = $sAux; } else { $this->fileData['domain'] = $this->config['MESS_SERVER']; } } else { - $this->fileData['domain'] = gethostbyaddr( '127.0.0.1' ); + $this->fileData['domain'] = gethostbyaddr('127.0.0.1'); } } $this->sendMail(); @@ -137,7 +97,7 @@ class spoolRun * @param array $aData * @return none */ - public function create ($aData) + public function create($aData) { if (is_array($aData['app_msg_attach'])) { $attachment = $aData['app_msg_attach']; @@ -149,16 +109,16 @@ class spoolRun } $aData['app_msg_attach'] = serialize($attachment); $aData['app_msg_show_message'] = (isset($aData['app_msg_show_message'])) ? $aData['app_msg_show_message'] : 1; - $aData["app_msg_error"] = (isset($aData["app_msg_error"]))? $aData["app_msg_error"] : ''; - $sUID = $this->db_insert( $aData ); + $aData["app_msg_error"] = (isset($aData["app_msg_error"])) ? $aData["app_msg_error"] : ''; + $sUID = $this->db_insert($aData); - $aData['app_msg_date'] = isset( $aData['app_msg_date'] ) ? $aData['app_msg_date'] : ''; + $aData['app_msg_date'] = isset($aData['app_msg_date']) ? $aData['app_msg_date'] : ''; - if (isset( $aData['app_msg_status'] )) { - $this->status = strtolower( $aData['app_msg_status'] ); + if (isset($aData['app_msg_status'])) { + $this->status = strtolower($aData['app_msg_status']); } - $aData["contentTypeIsHtml"] = (isset($aData["contentTypeIsHtml"]))? $aData["contentTypeIsHtml"] : true; + $aData["contentTypeIsHtml"] = (isset($aData["contentTypeIsHtml"])) ? $aData["contentTypeIsHtml"] : true; $this->setData($sUID, $aData["app_msg_subject"], $aData["app_msg_from"], $aData["app_msg_to"], $aData["app_msg_body"], $aData["app_msg_date"], $aData["app_msg_cc"], $aData["app_msg_bcc"], $aData["app_msg_template"], $aData["app_msg_attach"], $aData["contentTypeIsHtml"], $aData["app_msg_error"]); } @@ -169,7 +129,7 @@ class spoolRun * @param array $aConfig * @return none */ - public function setConfig ($aConfig) + public function setConfig($aConfig) { // Processing password $passwd = isset($aConfig['MESS_PASSWORD']) ? $aConfig['MESS_PASSWORD'] : ''; @@ -186,17 +146,17 @@ class spoolRun $aConfig['MESS_PASSWORD'] = $passwd; // Validating authorization flag - if(!isset($aConfig['SMTPAuth'])){ - if (isset($aConfig['MESS_RAUTH'])) { - if ($aConfig['MESS_RAUTH'] == false || (is_string($aConfig['MESS_RAUTH']) && $aConfig['MESS_RAUTH'] == 'false')) { - $aConfig['MESS_RAUTH'] = 0; - } else { - $aConfig['MESS_RAUTH'] = 1; - } - } else { - $aConfig['MESS_RAUTH'] = 0; - } - $aConfig['SMTPAuth'] = $aConfig['MESS_RAUTH']; + if (!isset($aConfig['SMTPAuth'])) { + if (isset($aConfig['MESS_RAUTH'])) { + if ($aConfig['MESS_RAUTH'] == false || (is_string($aConfig['MESS_RAUTH']) && $aConfig['MESS_RAUTH'] == 'false')) { + $aConfig['MESS_RAUTH'] = 0; + } else { + $aConfig['MESS_RAUTH'] = 1; + } + } else { + $aConfig['MESS_RAUTH'] = 0; + } + $aConfig['SMTPAuth'] = $aConfig['MESS_RAUTH']; } // Validating for old configurations @@ -213,7 +173,7 @@ class spoolRun /** * set email parameters * - * @param string $sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate, $sCC, $sBCC, $sTemplate + * @param string $sAppMsgUid , $sSubject, $sFrom, $sTo, $sBody, $sDate, $sCC, $sBCC, $sTemplate * @return none */ public function setData($sAppMsgUid, $sSubject, $sFrom, $sTo, $sBody, $sDate = "", $sCC = "", $sBCC = "", $sTemplate = "", $aAttachment = array(), $bContentTypeIsHtml = true, $sError = "") @@ -223,25 +183,25 @@ class spoolRun $this->fileData['from'] = $sFrom; $this->fileData['to'] = $sTo; $this->fileData['body'] = $sBody; - $this->fileData['date'] = ($sDate != '' ? $sDate : date( 'Y-m-d H:i:s' )); + $this->fileData['date'] = ($sDate != '' ? $sDate : date('Y-m-d H:i:s')); $this->fileData['cc'] = $sCC; $this->fileData['bcc'] = $sBCC; $this->fileData['template'] = $sTemplate; $this->fileData['attachments'] = $aAttachment; - $this->fileData['envelope_to'] = array (); + $this->fileData['envelope_to'] = array(); $this->fileData["contentTypeIsHtml"] = $bContentTypeIsHtml; $this->fileData["error"] = $sError; - if (array_key_exists('MESS_ENGINE',$this->config)) { + if (array_key_exists('MESS_ENGINE', $this->config)) { if ($this->config['MESS_ENGINE'] == 'OPENMAIL') { if ($this->config['MESS_SERVER'] != '') { - if (($sAux = @gethostbyaddr( $this->config['MESS_SERVER'] ))) { + if (($sAux = @gethostbyaddr($this->config['MESS_SERVER']))) { $this->fileData['domain'] = $sAux; } else { $this->fileData['domain'] = $this->config['MESS_SERVER']; } } else { - $this->fileData['domain'] = gethostbyaddr( '127.0.0.1' ); + $this->fileData['domain'] = gethostbyaddr('127.0.0.1'); } } } @@ -253,7 +213,7 @@ class spoolRun * @param none * @return boolean true or exception */ - public function sendMail () + public function sendMail() { try { $this->handleFrom(); @@ -272,15 +232,15 @@ class spoolRun * @param none * @return none */ - private function updateSpoolStatus () + private function updateSpoolStatus() { - $oAppMessage = AppMessagePeer::retrieveByPK( $this->spool_id ); - if (is_array( $this->fileData['attachments'] )) { - $attachment = implode( ",", $this->fileData['attachments'] ); - $oAppMessage->setappMsgAttach( $attachment ); + $oAppMessage = AppMessagePeer::retrieveByPK($this->spool_id); + if (is_array($this->fileData['attachments'])) { + $attachment = implode(",", $this->fileData['attachments']); + $oAppMessage->setappMsgAttach($attachment); } - $oAppMessage->setappMsgstatus( $this->status ); - $oAppMessage->setappMsgsenddate( date( 'Y-m-d H:i:s' ) ); + $oAppMessage->setappMsgstatus($this->status); + $oAppMessage->setappMsgsenddate(date('Y-m-d H:i:s')); $oAppMessage->save(); } @@ -290,35 +250,35 @@ class spoolRun * @param none * @return boolean true or exception */ - private function handleFrom () + private function handleFrom() { $eregA = "/^'.*@.*$/"; - if (strpos( $this->fileData['from'], '<' ) !== false) { + if (strpos($this->fileData['from'], '<') !== false) { //to validate complex email address i.e. Erik A. O - $ereg = (preg_match($eregA, $this->fileData["from"]))? $this->longMailEreg : "/^(.*)(<(.*)>)$/"; + $ereg = (preg_match($eregA, $this->fileData["from"])) ? $this->longMailEreg : "/^(.*)(<(.*)>)$/"; preg_match($ereg, $this->fileData["from"], $matches); - if (isset( $matches[1] ) && $matches[1] != '') { + if (isset($matches[1]) && $matches[1] != '') { //drop the " characters if they exist - $this->fileData['from_name'] = trim( str_replace( '"', '', $matches[1] ) ); + $this->fileData['from_name'] = trim(str_replace('"', '', $matches[1])); } else { //if the from name was not set $this->fileData['from_name'] = ''; } - if (! isset( $matches[3] )) { - throw new Exception( 'Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING'] ); + if (!isset($matches[3])) { + throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']); } - $this->fileData['from_email'] = trim( $matches[3] ); + $this->fileData['from_email'] = trim($matches[3]); } else { //to validate simple email address i.e. erik@colosa.com - $ereg = (preg_match($eregA, $this->fileData["from"]))? $this->mailEreg : "/^(.*)$/"; + $ereg = (preg_match($eregA, $this->fileData["from"])) ? $this->mailEreg : "/^(.*)$/"; preg_match($ereg, $this->fileData["from"], $matches); - if (! isset( $matches[0] )) { - throw new Exception( 'Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING'] ); + if (!isset($matches[0])) { + throw new Exception('Invalid email address in FROM parameter (' . $this->fileData['from'] . ')', $this->ExceptionCode['WARNING']); } $this->fileData['from_name'] = ''; @@ -326,12 +286,12 @@ class spoolRun } // Set reply to - preg_match( $this->longMailEreg, $this->fileData['from_name'], $matches ); + preg_match($this->longMailEreg, $this->fileData['from_name'], $matches); if (isset($matches[3])) { $this->fileData['reply_to'] = $matches[3]; $this->fileData['reply_to_name'] = isset($matches[1]) ? $matches[1] : $this->fileData['from_name']; } else { - preg_match( $this->mailEreg, $this->fileData['from_name'], $matches ); + preg_match($this->mailEreg, $this->fileData['from_name'], $matches); if (isset($matches[1])) { $this->fileData['reply_to'] = $matches[1]; $this->fileData['reply_to_name'] = ''; @@ -349,65 +309,65 @@ class spoolRun * @param none * @return boolean true or exception */ - private function handleEnvelopeTo () + private function handleEnvelopeTo() { - $hold = array (); - $holdcc = array (); - $holdbcc = array (); - $text = trim( $this->fileData['to'] ); + $hold = array(); + $holdcc = array(); + $holdbcc = array(); + $text = trim($this->fileData['to']); $textcc = ''; $textbcc = ''; - if (isset( $this->fileData['cc'] ) && trim( $this->fileData['cc'] ) != '') { - $textcc = trim( $this->fileData['cc'] ); + if (isset($this->fileData['cc']) && trim($this->fileData['cc']) != '') { + $textcc = trim($this->fileData['cc']); } - if (isset( $this->fileData['bcc'] ) && trim( $this->fileData['bcc'] ) != '') { - $textbcc = trim( $this->fileData['bcc'] ); + if (isset($this->fileData['bcc']) && trim($this->fileData['bcc']) != '') { + $textbcc = trim($this->fileData['bcc']); } - if (false !== (strpos( $text, ',' ))) { - $hold = explode( ',', $text ); + if (false !== (strpos($text, ','))) { + $hold = explode(',', $text); foreach ($hold as $val) { - if (strlen( $val ) > 0) { + if (strlen($val) > 0) { $this->fileData['envelope_to'][] = "$val"; } } } elseif ($text != '') { $this->fileData['envelope_to'][] = "$text"; } else { - $this->fileData['envelope_to'] = Array (); + $this->fileData['envelope_to'] = Array(); } //CC - if (false !== (strpos( $textcc, ',' ))) { - $holdcc = explode( ',', $textcc ); + if (false !== (strpos($textcc, ','))) { + $holdcc = explode(',', $textcc); foreach ($holdcc as $valcc) { - if (strlen( $valcc ) > 0) { + if (strlen($valcc) > 0) { $this->fileData['envelope_cc'][] = "$valcc"; } } } elseif ($textcc != '') { $this->fileData['envelope_cc'][] = "$textcc"; } else { - $this->fileData['envelope_cc'] = Array (); + $this->fileData['envelope_cc'] = Array(); } //BCC - if (false !== (strpos( $textbcc, ',' ))) { - $holdbcc = explode( ',', $textbcc ); + if (false !== (strpos($textbcc, ','))) { + $holdbcc = explode(',', $textbcc); foreach ($holdbcc as $valbcc) { - if (strlen( $valbcc ) > 0) { + if (strlen($valbcc) > 0) { $this->fileData['envelope_bcc'][] = "$valbcc"; } } } elseif ($textbcc != '') { $this->fileData['envelope_bcc'][] = "$textbcc"; } else { - $this->fileData['envelope_bcc'] = Array (); + $this->fileData['envelope_bcc'] = Array(); } } @@ -418,121 +378,121 @@ class spoolRun * @param none * @return none */ - private function handleMail () + private function handleMail() { - if (count( $this->fileData['envelope_to'] ) > 0) { - if (array_key_exists('MESS_ENGINE',$this->config)) { + if (count($this->fileData['envelope_to']) > 0) { + if (array_key_exists('MESS_ENGINE', $this->config)) { switch ($this->config['MESS_ENGINE']) { case 'MAIL': case 'PHPMAILER': - + switch ($this->config['MESS_ENGINE']) { case 'MAIL': $oPHPMailer = new PHPMailer(); $oPHPMailer->Mailer = 'mail'; break; case 'PHPMAILER': - $oPHPMailer = new PHPMailer( true ); + $oPHPMailer = new PHPMailer(true); $oPHPMailer->Mailer = 'smtp'; break; } - - $oPHPMailer->SMTPAuth = (isset( $this->config['SMTPAuth'] ) ? $this->config['SMTPAuth'] : ''); - + + $oPHPMailer->SMTPAuth = (isset($this->config['SMTPAuth']) ? $this->config['SMTPAuth'] : ''); + switch ($this->config['MESS_ENGINE']) { case 'MAIL': break; case 'PHPMAILER': //Posible Options for SMTPSecure are: "", "ssl" or "tls" - if (isset( $this->config['SMTPSecure'] ) && preg_match( '/^(ssl|tls)$/', $this->config['SMTPSecure'] )) { + if (isset($this->config['SMTPSecure']) && preg_match('/^(ssl|tls)$/', $this->config['SMTPSecure'])) { $oPHPMailer->SMTPSecure = $this->config['SMTPSecure']; } break; - } + } $oPHPMailer->CharSet = "UTF-8"; $oPHPMailer->Encoding = "8bit"; $oPHPMailer->Host = $this->config['MESS_SERVER']; $oPHPMailer->Port = $this->config['MESS_PORT']; $oPHPMailer->Username = $this->config['MESS_ACCOUNT']; $oPHPMailer->Password = $this->config['MESS_PASSWORD']; - $oPHPMailer->SetFrom($this->fileData['from_email'], utf8_decode($this->fileData['from_name'])); - + $oPHPMailer->SetFrom($this->fileData['from_email'], utf8_decode($this->fileData['from_name'])); + if (isset($this->fileData['reply_to'])) { if ($this->fileData['reply_to'] != '') { $oPHPMailer->AddReplyTo($this->fileData['reply_to'], $this->fileData['reply_to_name']); } } - + $msSubject = $this->fileData['subject']; - - if (! (mb_detect_encoding( $msSubject, "UTF-8" ) == "UTF-8")) { - $msSubject = utf8_encode( $msSubject ); + + if (!(mb_detect_encoding($msSubject, "UTF-8") == "UTF-8")) { + $msSubject = utf8_encode($msSubject); } - + $oPHPMailer->Subject = $msSubject; - + $msBody = $this->fileData['body']; - - if (! (mb_detect_encoding( $msBody, "UTF-8" ) == "UTF-8")) { - $msBody = utf8_encode( $msBody ); + + if (!(mb_detect_encoding($msBody, "UTF-8") == "UTF-8")) { + $msBody = utf8_encode($msBody); } - + $oPHPMailer->Body = $msBody; - + $attachment = @unserialize($this->fileData['attachments']); if ($attachment === false) { $attachment = $this->fileData['attachments']; } if (is_array($attachment)) { foreach ($attachment as $key => $fileAttach) { - if (file_exists( $fileAttach )) { - $oPHPMailer->AddAttachment( $fileAttach, is_int( $key ) ? '' : $key ); + if (file_exists($fileAttach)) { + $oPHPMailer->AddAttachment($fileAttach, is_int($key) ? '' : $key); } } } - + foreach ($this->fileData['envelope_to'] as $sEmail) { - if (strpos( $sEmail, '<' ) !== false) { - preg_match( $this->longMailEreg, $sEmail, $matches ); - $sTo = trim( $matches[3] ); - $sToName = trim( $matches[1] ); - $oPHPMailer->AddAddress( $sTo, $sToName ); + if (strpos($sEmail, '<') !== false) { + preg_match($this->longMailEreg, $sEmail, $matches); + $sTo = trim($matches[3]); + $sToName = trim($matches[1]); + $oPHPMailer->AddAddress($sTo, $sToName); } else { - $oPHPMailer->AddAddress( $sEmail ); + $oPHPMailer->AddAddress($sEmail); } } - + //CC foreach ($this->fileData['envelope_cc'] as $sEmail) { - if (strpos( $sEmail, '<' ) !== false) { - preg_match( $this->longMailEreg, $sEmail, $matches ); - $sTo = trim( $matches[3] ); - $sToName = trim( $matches[1] ); - $oPHPMailer->AddCC( $sTo, $sToName ); + if (strpos($sEmail, '<') !== false) { + preg_match($this->longMailEreg, $sEmail, $matches); + $sTo = trim($matches[3]); + $sToName = trim($matches[1]); + $oPHPMailer->AddCC($sTo, $sToName); } else { - $oPHPMailer->AddCC( $sEmail ); + $oPHPMailer->AddCC($sEmail); } } - + //BCC foreach ($this->fileData['envelope_bcc'] as $sEmail) { - if (strpos( $sEmail, '<' ) !== false) { - preg_match( $this->longMailEreg, $sEmail, $matches ); - $sTo = trim( $matches[3] ); - $sToName = trim( $matches[1] ); - $oPHPMailer->AddBCC( $sTo, $sToName ); + if (strpos($sEmail, '<') !== false) { + preg_match($this->longMailEreg, $sEmail, $matches); + $sTo = trim($matches[3]); + $sToName = trim($matches[1]); + $oPHPMailer->AddBCC($sTo, $sToName); } else { - $oPHPMailer->AddBCC( $sEmail ); + $oPHPMailer->AddBCC($sEmail); } } - + $oPHPMailer->IsHTML($this->fileData["contentTypeIsHtml"]); - - if ( $this->config['MESS_ENGINE'] == 'MAIL') { + + if ($this->config['MESS_ENGINE'] == 'MAIL') { $oPHPMailer->WordWrap = 300; } - + if ($oPHPMailer->Send()) { $this->error = ''; $this->status = 'sent'; @@ -542,38 +502,38 @@ class spoolRun } break; case 'OPENMAIL': - $pack = new package( $this->fileData ); + $pack = new package($this->fileData); $header = $pack->returnHeader(); $body = $pack->returnBody(); $send = new smtp(); - $send->setServer( $this->config['MESS_SERVER'] ); - $send->setPort( $this->config['MESS_PORT'] ); - $send->setUsername( $this->config['MESS_ACCOUNT'] ); - + $send->setServer($this->config['MESS_SERVER']); + $send->setPort($this->config['MESS_PORT']); + $send->setUsername($this->config['MESS_ACCOUNT']); + $passwd = $this->config['MESS_PASSWORD']; - $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); - $auxPass = explode( 'hash:', $passwdDec ); - - if (count( $auxPass ) > 1) { - if (count( $auxPass ) == 2) { + $passwdDec = G::decrypt($passwd, 'EMAILENCRYPT'); + $auxPass = explode('hash:', $passwdDec); + + if (count($auxPass) > 1) { + if (count($auxPass) == 2) { $passwd = $auxPass[1]; } else { - array_shift( $auxPass ); - $passwd = implode( '', $auxPass ); + array_shift($auxPass); + $passwd = implode('', $auxPass); } } - + $this->config['MESS_PASSWORD'] = $passwd; - $send->setPassword( $this->config['MESS_PASSWORD'] ); - $send->setReturnPath( $this->fileData['from_email'] ); - $send->setHeaders( $header ); - $send->setBody( $body ); - $send->setEnvelopeTo( $this->fileData['envelope_to'] ); + $send->setPassword($this->config['MESS_PASSWORD']); + $send->setReturnPath($this->fileData['from_email']); + $send->setHeaders($header); + $send->setBody($body); + $send->setEnvelopeTo($this->fileData['envelope_to']); if ($send->sendMessage()) { $this->error = ''; $this->status = 'sent'; } else { - $this->error = implode( ', ', $send->returnErrors() ); + $this->error = implode(', ', $send->returnErrors()); $this->status = 'failed'; } break; @@ -588,34 +548,34 @@ class spoolRun * @param string $dateResend * @return none or exception */ - public function resendEmails ($dateResend = null, $cron = 0) + public function resendEmails($dateResend = null, $cron = 0) { - $aConfiguration = PmSystem::getEmailConfiguration(); + $aConfiguration = System::getEmailConfiguration(); if (!isset($aConfiguration["MESS_ENABLED"])) { $aConfiguration["MESS_ENABLED"] = '0'; } if ($aConfiguration["MESS_ENABLED"] == "1") { - require_once ("classes/model/AppMessage.php"); + require_once("classes/model/AppMessage.php"); $this->setConfig($aConfiguration); - $criteria = new Criteria( "workflow" ); - $criteria->add( AppMessagePeer::APP_MSG_STATUS, "sent", Criteria::NOT_EQUAL ); + $criteria = new Criteria("workflow"); + $criteria->add(AppMessagePeer::APP_MSG_STATUS, "sent", Criteria::NOT_EQUAL); if ($dateResend != null) { - $criteria->add( AppMessagePeer::APP_MSG_DATE, $dateResend, Criteria::GREATER_EQUAL ); + $criteria->add(AppMessagePeer::APP_MSG_DATE, $dateResend, Criteria::GREATER_EQUAL); } - $rsCriteria = AppMessagePeer::doSelectRS( $criteria ); - $rsCriteria->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $rsCriteria = AppMessagePeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); while ($rsCriteria->next()) { if ($cron == 1) { - $arrayCron = unserialize( trim( @file_get_contents( PATH_DATA . "cron" ) ) ); + $arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron"))); $arrayCron["processcTimeStart"] = time(); - @file_put_contents( PATH_DATA . "cron", serialize( $arrayCron ) ); + @file_put_contents(PATH_DATA . "cron", serialize($arrayCron)); } $row = $rsCriteria->getRow(); @@ -623,17 +583,17 @@ class spoolRun try { $sFrom = G::buildFrom($aConfiguration, $row["APP_MSG_FROM"]); - $this->setData( $row["APP_MSG_UID"], $row["APP_MSG_SUBJECT"], $sFrom, $row["APP_MSG_TO"], $row["APP_MSG_BODY"], date( "Y-m-d H:i:s" ), $row["APP_MSG_CC"], $row["APP_MSG_BCC"], $row["APP_MSG_TEMPLATE"], $row["APP_MSG_ATTACH"] ); + $this->setData($row["APP_MSG_UID"], $row["APP_MSG_SUBJECT"], $sFrom, $row["APP_MSG_TO"], $row["APP_MSG_BODY"], date("Y-m-d H:i:s"), $row["APP_MSG_CC"], $row["APP_MSG_BCC"], $row["APP_MSG_TEMPLATE"], $row["APP_MSG_ATTACH"]); $this->sendMail(); } catch (Exception $e) { $strAux = "Spool::resendEmails(): Using " . $aConfiguration["MESS_ENGINE"] . " for APP_MGS_UID=" . $row["APP_MSG_UID"] . " -> With message: " . $e->getMessage(); if ($e->getCode() == $this->ExceptionCode["WARNING"]) { - array_push( $this->aWarnings, $strAux ); + array_push($this->aWarnings, $strAux); continue; } else { - error_log('<400> '.$strAux); + error_log('<400> ' . $strAux); continue; } } @@ -647,9 +607,9 @@ class spoolRun * @param none * @return string $this->aWarnings */ - public function getWarnings () + public function getWarnings() { - if (sizeof( $this->aWarnings ) != 0) { + if (sizeof($this->aWarnings) != 0) { return $this->aWarnings; } @@ -662,36 +622,36 @@ class spoolRun * @param array $db_spool * @return string $sUID; */ - public function db_insert ($db_spool) + public function db_insert($db_spool) { $sUID = G::generateUniqueID(); $spool = new AppMessage(); - $spool->setAppMsgUid( $sUID ); - $spool->setMsgUid( $db_spool['msg_uid'] ); - $spool->setAppUid( $db_spool['app_uid'] ); - $spool->setDelIndex( $db_spool['del_index'] ); - $spool->setAppMsgType( $db_spool['app_msg_type'] ); - $spool->setAppMsgSubject( $db_spool['app_msg_subject'] ); - $spool->setAppMsgFrom( $db_spool['app_msg_from'] ); - $spool->setAppMsgTo( $db_spool['app_msg_to'] ); - $spool->setAppMsgBody( $db_spool['app_msg_body'] ); - $spool->setAppMsgDate( date( 'Y-m-d H:i:s' ) ); - $spool->setAppMsgCc( $db_spool['app_msg_cc'] ); - $spool->setAppMsgBcc( $db_spool['app_msg_bcc'] ); - $spool->setappMsgAttach( $db_spool['app_msg_attach'] ); - $spool->setAppMsgTemplate( $db_spool['app_msg_template'] ); - $spool->setAppMsgStatus( $db_spool['app_msg_status'] ); - $spool->setAppMsgSendDate( date( 'Y-m-d H:i:s' ) ); // Add by Ankit - $spool->setAppMsgShowMessage( $db_spool['app_msg_show_message'] ); // Add by Ankit - $spool->setAppMsgError( $db_spool['app_msg_error'] ); + $spool->setAppMsgUid($sUID); + $spool->setMsgUid($db_spool['msg_uid']); + $spool->setAppUid($db_spool['app_uid']); + $spool->setDelIndex($db_spool['del_index']); + $spool->setAppMsgType($db_spool['app_msg_type']); + $spool->setAppMsgSubject($db_spool['app_msg_subject']); + $spool->setAppMsgFrom($db_spool['app_msg_from']); + $spool->setAppMsgTo($db_spool['app_msg_to']); + $spool->setAppMsgBody($db_spool['app_msg_body']); + $spool->setAppMsgDate(date('Y-m-d H:i:s')); + $spool->setAppMsgCc($db_spool['app_msg_cc']); + $spool->setAppMsgBcc($db_spool['app_msg_bcc']); + $spool->setappMsgAttach($db_spool['app_msg_attach']); + $spool->setAppMsgTemplate($db_spool['app_msg_template']); + $spool->setAppMsgStatus($db_spool['app_msg_status']); + $spool->setAppMsgSendDate(date('Y-m-d H:i:s')); // Add by Ankit + $spool->setAppMsgShowMessage($db_spool['app_msg_show_message']); // Add by Ankit + $spool->setAppMsgError($db_spool['app_msg_error']); - if (! $spool->validate()) { + if (!$spool->validate()) { $errors = $spool->getValidationFailures(); $this->status = 'error'; foreach ($errors as $key => $value) { - echo "Validation error - " . $value->getMessage( $key ) . "\n"; + echo "Validation error - " . $value->getMessage($key) . "\n"; } } else { //echo "Saving - validation ok\n"; @@ -702,4 +662,3 @@ class spoolRun return $sUID; } } - diff --git a/workflow/engine/classes/Stat.php b/workflow/engine/classes/Stat.php new file mode 100644 index 000000000..15a13c929 --- /dev/null +++ b/workflow/engine/classes/Stat.php @@ -0,0 +1,11 @@ +status = false; + } +} diff --git a/workflow/engine/classes/TarFile.php b/workflow/engine/classes/TarFile.php new file mode 100644 index 000000000..626b4da95 --- /dev/null +++ b/workflow/engine/classes/TarFile.php @@ -0,0 +1,150 @@ +archive($name); + $this->options['type'] = "tar"; + } + + /** + * This function create a file . + * tar + * + * @return boolean + */ + public function create_tar() + { + $pwd = getcwd(); + chdir($this->options['basedir']); + foreach ($this->files as $current) { + if ($current['name'] == $this->options['name']) { + continue; + } + if (strlen($current['name2']) > 99) { + $path = substr($current['name2'], 0, strpos($current['name2'], "/", strlen($current['name2']) - 100) + 1); + $current['name2'] = substr($current['name2'], strlen($path)); + if (strlen($path) > 154 || strlen($current['name2']) > 99) { + $this->error[] = "Could not add {$path}{$current['name2']} to archive because the filename is too long."; + continue; + } + } + $block = pack("a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12", $current['name2'], sprintf("%07o", $current['stat'][2]), sprintf("%07o", $current['stat'][4]), sprintf("%07o", $current['stat'][5]), sprintf("%011o", $current['type'] == 2 ? 0 : $current['stat'][7]), sprintf("%011o", $current['stat'][9]), " ", $current['type'], $current['type'] == 2 ? @readlink($current['name']) : "", "ustar ", " ", "Unknown", "Unknown", "", "", !empty($path) ? $path : "", ""); + $checksum = 0; + for ($i = 0; $i < 512; $i++) { + $checksum += ord(substr($block, $i, 1)); + } + $checksum = pack("a8", sprintf("%07o", $checksum)); + $block = substr_replace($block, $checksum, 148, 8); + if ($current['type'] == 2 || $current['stat'][7] == 0) { + $this->add_data($block); + } elseif ($fp = @fopen($current['name'], "rb")) { + $this->add_data($block); + while ($temp = fread($fp, 1048576)) { + $this->add_data($temp); + } + if ($current['stat'][7] % 512 > 0) { + $temp = ""; + for ($i = 0; $i < 512 - $current['stat'][7] % 512; $i++) { + $temp .= "\0"; + } + $this->add_data($temp); + } + fclose($fp); + } else { + $this->error[] = "Could not open file {$current['name']} for reading. It was not added."; + } + } + $this->add_data(pack("a1024", "")); + chdir($pwd); + return 1; + } + + /** + * This function is used for extract files of the class tar_file + * + * @return void + */ + public function extract_files() + { + $pwd = getcwd(); + chdir($this->options['basedir']); + if ($fp = $this->open_archive()) { + if ($this->options['inmemory'] == 1) { + $this->files = array(); + } + while ($block = fread($fp, 512)) { + $temp = unpack("a100name/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100symlink/a6magic/a2temp/a32temp/a32temp/a8temp/a8temp/a155prefix/a12temp", $block); + $file = array('name' => $this->options['basedir'] . '/' . $temp['prefix'] . $temp['name'], 'stat' => array(2 => $temp['mode'], 4 => octdec($temp['uid']), 5 => octdec($temp['gid']), 7 => octdec($temp['size']), 9 => octdec($temp['mtime']) + ), 'checksum' => octdec($temp['checksum']), 'type' => $temp['type'], 'magic' => $temp['magic'] + ); + if ($file['checksum'] == 0x00000000) { + break; + } elseif (substr($file['magic'], 0, 5) != "ustar") { + $this->error[] = "This script does not support extracting this type of tar file."; + break; + } + $block = substr_replace($block, " ", 148, 8); + $checksum = 0; + for ($i = 0; $i < 512; $i++) { + $checksum += ord(substr($block, $i, 1)); + } + if ($file['checksum'] != $checksum) { + $this->error[] = "Could not extract from {$this->options['name']}, it is corrupt."; + } + if ($this->options['inmemory'] == 1) { + $file['data'] = fread($fp, $file['stat'][7]); + fread($fp, (512 - $file['stat'][7] % 512) == 512 ? 0 : (512 - $file['stat'][7] % 512)); + unset($file['checksum'], $file['magic']); + $this->files[] = $file; + } elseif ($file['type'] == 5) { + if (!is_dir($file['name'])) { + mkdir($file['name'], 0775); + } + } elseif ($this->options['overwrite'] == 0 && file_exists($file['name'])) { + $this->error[] = "{$file['name']} already exist."; + continue; + } elseif ($file['type'] == 2) { + symlink($temp['symlink'], $file['name']); + } elseif ($new = @fopen($file['name'], "wb")) { + fwrite($new, fread($fp, $file['stat'][7])); + if ((512 - $file['stat'][7] % 512) != 512) { + fread($fp, (512 - $file['stat'][7] % 512)); + } + fclose($new); + chmod($file['name'], 0777); + $this->files[] = $file['name']; + } else { + $this->error[] = "Could not open {$file['name']} for writing."; + continue; + } + @touch($file['name'], $file['stat'][9]); + unset($file); + } + } else { + $this->error[] = "Could not open file {$this->options['name']}"; + } + chdir($pwd); + } + + /** + * This function open a archive of the class tar_file + * + * @return void + */ + public function open_archive() + { + return @fopen($this->options['name'], "rb"); + } +} diff --git a/workflow/engine/classes/class.tasks.php b/workflow/engine/classes/Tasks.php similarity index 88% rename from workflow/engine/classes/class.tasks.php rename to workflow/engine/classes/Tasks.php index b4f7220e5..7237ecc9a 100644 --- a/workflow/engine/classes/class.tasks.php +++ b/workflow/engine/classes/Tasks.php @@ -1,49 +1,5 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ -require_once 'classes/model/GroupUser.php'; -require_once 'classes/model/Groupwf.php'; -require_once 'classes/model/ObjectPermission.php'; -require_once 'classes/model/Process.php'; -require_once 'classes/model/Route.php'; -require_once 'classes/model/Event.php'; -require_once 'classes/model/Step.php'; -require_once 'classes/model/StepTrigger.php'; -require_once 'classes/model/Task.php'; -require_once 'classes/model/TaskUser.php'; -require_once 'classes/model/Users.php'; -require_once 'classes/model/Gateway.php'; - -/** - * Tasks - Tasks class - * - * @package workflow.engine.ProcessMaker - * @author Julio Cesar Laura Avenda�o - * @copyright 2007 COLOSA - */ class Tasks { @@ -88,7 +44,7 @@ class Tasks try { $aTasks = array(); $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn( TaskPeer::TAS_UID ); + $oCriteria->addSelectColumn(TaskPeer::TAS_UID); $oCriteria->add(TaskPeer::PRO_UID, $sProUid); $oCriteria->addAscendingOrderByColumn(TaskPeer::TAS_TITLE); $oDataset = TaskPeer::doSelectRS($oCriteria); @@ -161,7 +117,6 @@ class Tasks return; } - /** * Get all Routes for any Process * @@ -209,7 +164,7 @@ class Tasks $oProcessMap = new ProcessMap(); $oTask = new Task(); $oEvent = new Event(); - //unset ($row['ROU_UID']); + //Saving Gateway into the GATEWAY table $idTask = $row['TAS_UID']; $nextTask = $row['ROU_NEXT_TASK']; @@ -305,7 +260,7 @@ class Tasks { foreach ($aRoutes as $key => $row) { $oRoute = new Route(); - //krumo ($row); + if (is_array($oRoute->load($row['ROU_UID']))) { $oRoute->remove($row['ROU_UID']); } else { @@ -383,15 +338,6 @@ class Tasks $oDataset1->next(); while ($aRow1 = $oDataset1->getRow()) { //Delete the triggers assigned to step - /* $oCriteria = new Criteria('workflow'); - $oCriteria->add(StepTriggerPeer::STEP_UID, $aRow1['STEP_UID']); - $oDataset2 = StepTriggerPeer::doSelectRS($oCriteria); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - while ($aRow2 = $oDataset2->getRow()) { - $oStepTrigger->remove($aRow2['STEP_UID'], $aRow2['TAS_UID'], $aRow2['TRI_UID'], $aRow2['ST_TYPE']); - $oDataset2->next(); - } */ $oStep->remove($aRow1['STEP_UID']); $oDataset1->next(); } @@ -564,24 +510,6 @@ class Tasks { try { $oTaskUser = new TaskUser(); - /* $oCriteria = new Criteria('workflow'); - $oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID); - $oDataset = GroupUserPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - while ($aGroupUser = $oDataset->getRow()) { - $oCriteria = new Criteria('workflow'); - $oCriteria->add(TaskUserPeer::TAS_UID, $sTaskUID); - $oCriteria->add(TaskUserPeer::USR_UID, $aGroupUser['USR_UID']); - $oDataset2 = TaskUserPeer::doSelectRS($oCriteria); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - $aRow = $oDataset2->getRow(); - if (!is_array($aRow)) { - $this->assignUser($sTaskUID, $aGroupUser['USR_UID'], $iType); - } - $oDataset->next(); - } */ return $oTaskUser->create(array('TAS_UID' => $sTaskUID, 'USR_UID' => $sGroupUID, 'TU_TYPE' => $iType, 'TU_RELATION' => 2 )); } catch (Exception $oError) { @@ -679,10 +607,6 @@ class Tasks { try { $oCriteria = new Criteria('workflow'); - //$oCriteria->add(StepPeer::PRO_UID, $sProcessUID); - //$oDataset = StepPeer::doSelectRS($oCriteria); - //$oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - //$oDataset->next(); return true; } catch (Exception $oError) { throw ($oError); @@ -700,9 +624,8 @@ class Tasks try { $aTasks = array(); $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn( TaskPeer::TAS_UID ); + $oCriteria->addSelectColumn(TaskPeer::TAS_UID); $oCriteria->add(TaskPeer::PRO_UID, $sProUid); - //$oCriteria->add(TaskPeer::TAS_USER, $sUsrUid); $oCriteria->add(TaskPeer::TAS_START, 'TRUE'); $oDataset = TaskPeer::doSelectRS($oCriteria); $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); @@ -879,4 +802,3 @@ class Tasks } } } - diff --git a/workflow/engine/classes/ToolBar.php b/workflow/engine/classes/ToolBar.php new file mode 100644 index 000000000..8fae53c1b --- /dev/null +++ b/workflow/engine/classes/ToolBar.php @@ -0,0 +1,7 @@ + - * - * This class Helps registering and implementing Wizard for Triggers - */ -use ProcessMaker\Plugins\PluginRegistry; - -/** - * - * @package workflow.engine.ProcessMaker - */ - -class triggerLibrary +class TriggerLibrary { - - private $_aTriggerClasses_ = array (); - - private static $instance = NULL; + private $_aTriggerClasses_ = array(); + private static $instance = null; /** * __construct * * @return void */ - function __construct () + public function __construct() { //Initialize the Library and register the Default - $this->registerFunctionsFileToLibrary( PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions" ); + $this->registerFunctionsFileToLibrary(PATH_CORE . "classes" . PATH_SEP . "class.pmFunctions.php", "ProcessMaker Functions"); //Register all registered PLugin Functions - if (class_exists( 'folderData' )) { - //$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid); + if (class_exists('folderData')) { $oPluginRegistry = PluginRegistry::loadSingleton(); $aAvailablePmFunctions = $oPluginRegistry->getPmFunctions(); $oPluginRegistry->setupPlugins(); //Get and setup enabled plugins foreach ($aAvailablePmFunctions as $key => $class) { $filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php'; - if (file_exists( $filePlugin ) && ! is_dir( $filePlugin )) { - $this->registerFunctionsFileToLibrary( $filePlugin, "ProcessMaker Functions" ); + if (file_exists($filePlugin) && !is_dir($filePlugin)) { + $this->registerFunctionsFileToLibrary($filePlugin, "ProcessMaker Functions"); } } - } //Add External Triggers - $dir = G::ExpandPath( "classes" ) . 'triggers'; - $filesArray = array (); + $dir = G::ExpandPath("classes") . 'triggers'; + $filesArray = array(); - if (file_exists( $dir )) { - if ($handle = opendir( $dir )) { - while (false !== ($file = readdir( $handle ))) { - if ($file != "." && $file != ".." && ! is_dir( $dir . PATH_SEP . $file )) { - $this->registerFunctionsFileToLibrary( $dir . PATH_SEP . $file, "ProcessMaker External Functions" ); + if (file_exists($dir)) { + if ($handle = opendir($dir)) { + while (false !== ($file = readdir($handle))) { + if ($file != "." && $file != ".." && !is_dir($dir . PATH_SEP . $file)) { + $this->registerFunctionsFileToLibrary($dir . PATH_SEP . $file, "ProcessMaker External Functions"); } } - closedir( $handle ); + closedir($handle); } } } @@ -66,10 +49,10 @@ class triggerLibrary * * @return self::$instance; */ - function &getSingleton () + public function &getSingleton() { - if (self::$instance == NULL) { - self::$instance = new triggerLibrary(); + if (self::$instance == null) { + self::$instance = new TriggerLibrary(); } return self::$instance; } @@ -79,9 +62,9 @@ class triggerLibrary * * @return serialize ( self::$instance ); */ - function serializeInstance () + public function serializeInstance() { - return serialize( self::$instance ); + return serialize(self::$instance); } /** @@ -90,13 +73,13 @@ class triggerLibrary * @param integer $serialized * @return void */ - function unSerializeInstance ($serialized) + public function unSerializeInstance($serialized) { - if (self::$instance == NULL) { + if (self::$instance == null) { self::$instance = new PluginRegistry(); } - $instance = unserialize( $serialized ); + $instance = unserialize($serialized); self::$instance = $instance; } @@ -107,15 +90,14 @@ class triggerLibrary * @param string $libraryName * @return void */ - function registerFunctionsFileToLibrary ($filePath, $libraryName) + public function registerFunctionsFileToLibrary($filePath, $libraryName) { - $aLibrary = $this->getMethodsFromLibraryFile( $filePath ); + $aLibrary = $this->getMethodsFromLibraryFile($filePath); $aLibrary->libraryFile = $filePath; $aLibrary->libraryName = $libraryName; - if (isset( $aLibrary->info['className'] )) { + if (isset($aLibrary->info['className'])) { $this->_aTriggerClasses_[$aLibrary->info['className']] = $aLibrary; } - } /** @@ -124,12 +106,11 @@ class triggerLibrary * @param string $file * @return object(PHPClass) $parsedLibrary */ - function getMethodsFromLibraryFile ($file) + public function getMethodsFromLibraryFile($file) { // parse class comments from file $parsedLibrary = new PHPClass(); - //$success = $parsedLibrary->parseFromFile ( PATH_CORE . "classes" . PATH_SEP . $file ); - $success = $parsedLibrary->parseFromFile( $file ); + $success = $parsedLibrary->parseFromFile($file); return $parsedLibrary; } @@ -139,7 +120,7 @@ class triggerLibrary * * @return array ($this->_aTriggerClasses_) */ - function getRegisteredClasses () + public function getRegisteredClasses() { return ($this->_aTriggerClasses_); } @@ -150,7 +131,7 @@ class triggerLibrary * @param string $libraryClassName * @return array ($this->_aTriggerClasses_[$libraryClassName]) */ - function getLibraryDefinition ($libraryClassName) + public function getLibraryDefinition($libraryClassName) { return ($this->_aTriggerClasses_[$libraryClassName]); } @@ -160,11 +141,8 @@ class triggerLibrary * * @return void */ - function __destruct () + public function __destruct() { - //TODO - Insert your code here } } - -?> \ No newline at end of file diff --git a/workflow/engine/classes/class.Upgrade.php b/workflow/engine/classes/Upgrade.php similarity index 68% rename from workflow/engine/classes/class.Upgrade.php rename to workflow/engine/classes/Upgrade.php index 7d2df591e..2721186ec 100644 --- a/workflow/engine/classes/class.Upgrade.php +++ b/workflow/engine/classes/Upgrade.php @@ -1,23 +1,7 @@ addon->getDownloadFilename(); $time = microtime(1); $archive = new Archive_Tar ($filename); - //printf("Time to open archive: %f\n", microtime(1) - $time); $time = microtime(1); $extractDir = dirname($this->addon->getDownloadFilename()) . "/extract"; $extractDir = $filter->xssFilterHard($extractDir); @@ -53,34 +35,22 @@ class Upgrade if (!is_dir($backupDir)) { mkdir($backupDir); } - //printf("Time to remove old directory: %f\n", microtime(1) - $time); + $time = microtime(1); echo "Extracting files...\n"; $archive->extractModify($extractDir, 'processmaker'); - //printf("Time to extract all files: %f\n", microtime(1) - $time); - //$time = microtime(1); - //$files = $archive->listContent(); - //printf("Time to get list of contents: %f\n", microtime(1) - $time); - /*$time = microtime(1); - foreach ($files as $fileinfo) - if (basename($fileinfo['filename']) == 'checksum.txt') { - $checksumFile = $archive->extractInString($fileinfo['filename']); - break; - } - printf("Time to get checksum.txt: %f\n", microtime(1) - $time); - */ $checksumFile = file_get_contents("$extractDir/checksum.txt"); $time = microtime(1); $checksums = array(); foreach (explode("\n", $checksumFile) as $line) { $checksums[trim(substr($line, 33))] = substr($line, 0, 32); } - //printf("Time to assemble list of checksums: %f\n", microtime(1) - $time); + $checksum = array(); $changedFiles = array(); $time = microtime(1); - $files = ls_dir($extractDir); - //printf("Time to list files: %f\n", microtime(1) - $time); + $files = $this->ls_dir($extractDir); + echo "Updating ProcessMaker files...\n"; $time = microtime(1); $checksumTime = 0; @@ -115,15 +85,14 @@ class Upgrade } } } - //printf("Time to create all checksums: %f\n", $checksumTime); - //printf("Time to copy files: %f\n", microtime(1) - $time); + printf("Updated %d files\n", count($changedFiles)); printf("Clearing cache...\n"); if (defined('PATH_C')) { G::rm_dir(PATH_C); mkdir(PATH_C, 0777, true); } - $workspaces = PmSystem::listWorkspaces(); + $workspaces = System::listWorkspaces(); $count = count($workspaces); $first = true; $num = 0; @@ -136,9 +105,24 @@ class Upgrade $first = false; } catch (Exception $e) { printf("Errors upgrading workspace {$workspace->name}: {$e->getMessage()}\n"); - //$errors = true; } } - //printf("Time to install: %f\n", microtime(1) - $start); } + + private function ls_dir($dir, $basename = null) + { + $files = array(); + if ($basename == null) { + $basename = $dir; + } + foreach (glob("$dir/*") as $filename) { + if (is_dir($filename)) { + $files = array_merge($files, $this->ls_dir($filename, $basename)); + } else { + $files[] = substr($filename, strlen($basename) + 1); + } + } + return $files; + } + } diff --git a/workflow/engine/classes/class.wsTools.php b/workflow/engine/classes/WorkspaceTools.php similarity index 98% rename from workflow/engine/classes/class.wsTools.php rename to workflow/engine/classes/WorkspaceTools.php index 336610fa8..ecf947700 100644 --- a/workflow/engine/classes/class.wsTools.php +++ b/workflow/engine/classes/WorkspaceTools.php @@ -1,5 +1,7 @@ upgradeSchema($pluginSchema); @@ -867,10 +869,10 @@ class workspaceTools public function upgradeDatabase($onedb = false, $checkOnly = false) { $this->initPropel(true); - p11835::$dbAdapter = $this->dbAdapter; - p11835::isApplicable(); - $systemSchema = PmSystem::getSystemSchema($this->dbAdapter); - $systemSchemaRbac = PmSystem::getSystemSchemaRbac($this->dbAdapter);// get the Rbac Schema + P11835::$dbAdapter = $this->dbAdapter; + P11835::isApplicable(); + $systemSchema = System::getSystemSchema($this->dbAdapter); + $systemSchemaRbac = System::getSystemSchemaRbac($this->dbAdapter);// get the Rbac Schema $this->registerSystemTables(array_merge($systemSchema, $systemSchemaRbac)); $this->upgradeSchema($systemSchema); $this->upgradeSchema($systemSchemaRbac, false, true, $onedb); // perform Upgrade to Rbac @@ -898,7 +900,7 @@ class workspaceTools $emailSever = new \ProcessMaker\BusinessModel\EmailServer(); - $emailConfiguration = PmSystem::getEmailConfiguration(); + $emailConfiguration = System::getEmailConfiguration(); if (!empty($emailConfiguration)) { $arrayData["MESS_ENGINE"] = $emailConfiguration["MESS_ENGINE"]; @@ -942,7 +944,7 @@ class workspaceTools } } - p11835::execute(); + P11835::execute(); return true; } @@ -993,7 +995,7 @@ class workspaceTools if (!$onedb) { if ($rbac) { - $rename = PmSystem::verifyRbacSchema($workspaceSchema); + $rename = System::verifyRbacSchema($workspaceSchema); if (count($rename) > 0) { foreach ($rename as $tableName) { $oDataBase->executeQuery($oDataBase->generateRenameTableSQL($tableName)); @@ -1002,7 +1004,7 @@ class workspaceTools } } $workspaceSchema = $this->getSchema($rbac); - $changes = PmSystem::compareSchema($workspaceSchema, $schema); + $changes = System::compareSchema($workspaceSchema, $schema); $changed = (count($changes['tablesToAdd']) > 0 || count($changes['tablesToAlter']) > 0 || count($changes['tablesWithNewIndex']) > 0 || count($changes['tablesToAlterIndex']) > 0); @@ -1141,11 +1143,11 @@ class workspaceTools */ public function getMetadata() { - $Fields = array_merge(PmSystem::getSysInfo(), $this->getDBInfo()); + $Fields = array_merge(System::getSysInfo(), $this->getDBInfo()); $Fields['WORKSPACE_NAME'] = $this->name; if (isset($this->dbHost)) { - $dbNetView = new NET($this->dbHost); + $dbNetView = new Net($this->dbHost); $dbNetView->loginDbServer($this->dbUser, $this->dbPass); try { if (!defined('DB_ADAPTER')) { @@ -1176,7 +1178,7 @@ class workspaceTools */ public static function printSysInfo() { - $fields = PmSystem::getSysInfo(); + $fields = System::getSysInfo(); $info = array( 'ProcessMaker Version' => $fields['PM_VERSION'], @@ -1235,11 +1237,11 @@ class workspaceTools public function printMetadata($printSysInfo = true) { if ($printSysInfo) { - workspaceTools::printSysInfo(); + WorkspaceTools::printSysInfo(); CLI::logging("\n"); } - workspaceTools::printInfo($this->getMetadata()); + WorkspaceTools::printInfo($this->getMetadata()); } /** @@ -1575,7 +1577,7 @@ class workspaceTools $data = file_get_contents($metafile); $workspaceData = G::json_decode($data); CLI::logging("\n"); - workspaceTools::printInfo((array)$workspaceData); + WorkspaceTools::printInfo((array)$workspaceData); } G::rm_dir($tempDirectory); @@ -1599,7 +1601,7 @@ class workspaceTools if (basename($item) == "." || basename($item) == "..") { continue; } - workspaceTools::dirPerms($item, $owner, $group, $perms); + WorkspaceTools::dirPerms($item, $owner, $group, $perms); } } } @@ -1638,7 +1640,7 @@ class workspaceTools if (empty($metaFiles)) { $metaFiles = glob($tempDirectory . "/*.txt"); if (!empty($metaFiles)) { - return workspaceTools::restoreLegacy($tempDirectory); + return WorkspaceTools::restoreLegacy($tempDirectory); } else { throw new Exception("No metadata found in backup"); } @@ -1655,7 +1657,7 @@ class workspaceTools throw new Exception("Workspace $srcWorkspace not found in backup"); } - $version = PmSystem::getVersion(); + $version = System::getVersion(); $pmVersion = (preg_match("/^([\d\.]+).*$/", $version, $arrayMatch)) ? $arrayMatch[1] : ""; //Otherwise: Branch master CLI::logging(CLI::warning(" @@ -1693,9 +1695,9 @@ class workspaceTools } else { CLI::logging("> Restoring " . CLI::info($backupWorkspace) . " to " . CLI::info($workspaceName) . "\n"); } - $workspace = new workspaceTools($workspaceName); + $workspace = new WorkspaceTools($workspaceName); - if (PmInstaller::isset_site($workspaceName)) { + if (Installer::isset_site($workspaceName)) { if ($overwrite) { if (!$workspace->workspaceExists()) { throw new Exception('We can not overwrite this workspace because the workspace ' . $workspaceName . ' does not exist please check the lower case and upper case.'); @@ -1726,7 +1728,7 @@ class workspaceTools $shared_stat = stat(PATH_DATA); if ($shared_stat !== false) { - workspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); + WorkspaceTools::dirPerms($workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); } @@ -1919,7 +1921,7 @@ class workspaceTools public function backupLogFiles() { - $config = PmSystem::getSystemConfiguration(); + $config = System::getSystemConfiguration(); clearstatcache(); $path = PATH_DATA . "log" . PATH_SEP; @@ -1952,7 +1954,7 @@ class workspaceTools $envFile = PATH_CONFIG . 'env.ini'; $skin ='neoclassic'; if (file_exists($envFile)) { - $sysConf = PmSystem::getSystemConfiguration($envFile); + $sysConf = System::getSystemConfiguration($envFile); $lang = $sysConf['default_lang']; $skin = $sysConf['default_skin']; } @@ -1985,7 +1987,7 @@ class workspaceTools $licensedFeatures = & PMLicensedFeatures::getSingleton(); /*----------------------------------********---------------------------------*/ if ($licensedFeatures->verifyfeature('95OY24wcXpEMzIyRmlNSnF0STNFSHJzMG9wYTJKekpLNmY2ZmRCeGtuZk5oUDloaUNhUGVjTDJBPT0=')) { - enterpriseClass::setHashPassword($response); + EnterpriseClass::setHashPassword($response); } else { return false; } @@ -2018,7 +2020,7 @@ class workspaceTools CLI::logging(" Copying Enterprise Directory to $pathNewFile...\n"); if ($shared_stat !== false) { - workspaceTools::dirPerms($pathDirectoryEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); + WorkspaceTools::dirPerms($pathDirectoryEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { CLI::logging(CLI::error("Could not get shared folder permissions, workspace permissions couldn't be changed") . "\n"); } @@ -2035,7 +2037,7 @@ class workspaceTools if (file_exists($pathFileEnterprise)) { CLI::logging(" Copying Enterprise.php file to $pathNewFile...\n"); if ($shared_stat !== false) { - workspaceTools::dirPerms($pathFileEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); + WorkspaceTools::dirPerms($pathFileEnterprise, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode']); } else { CLI::logging(CLI::error("Could not get shared folder permissions, workspace permissions couldn't be changed") . "\n"); } @@ -3525,7 +3527,7 @@ class workspaceTools public function migrateIteeToDummytask($workspaceName) { $this->initPropel(true); - $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', $workspaceName); + $arraySystemConfiguration = System::getSystemConfiguration('', '', $workspaceName); $conf = new Configurations(); \G::$sysSys = $workspaceName; \G::$pathDataSite = PATH_DATA . "sites" . PATH_SEP . \G::$sysSys . PATH_SEP; @@ -3588,7 +3590,7 @@ class workspaceTools $conf = new Configurations(); if (!$conf->exists('AUDIT_LOG', 'log')) { CLI::logging("> Updating Auditlog Config \n"); - $oServerConf = &serverConf::getSingleton(); + $oServerConf = &ServerConf::getSingleton(); $sAudit = $oServerConf->getAuditLogProperty('AL_OPTION', $workspace); $conf->aConfig = ($sAudit == 1) ? 'true' : 'false'; $conf->saveConfig('AUDIT_LOG', 'log'); @@ -3770,7 +3772,7 @@ class workspaceTools CLI::logging("-> Populating PRO_ID, USR_ID at LIST_* \n"); $con->begin(); $stmt = $con->createStatement(); - foreach (workspaceTools::$populateIdsQueries as $query) { + foreach (WorkspaceTools::$populateIdsQueries as $query) { $stmt->executeQuery($query); } $con->commit(); diff --git a/workflow/engine/classes/class.wsBase.php b/workflow/engine/classes/WsBase.php similarity index 98% rename from workflow/engine/classes/class.wsBase.php rename to workflow/engine/classes/WsBase.php index 17ac90ea8..d842e82a6 100644 --- a/workflow/engine/classes/class.wsBase.php +++ b/workflow/engine/classes/WsBase.php @@ -1,31 +1,7 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ //It works with the table CONFIGURATION in a WF dataBase - +use ProcessMaker\Core\System; /** * Copyright (C) 2009 COLOSA @@ -36,8 +12,7 @@ * * @package workflow.engine.classes */ - -class wsBase +class WsBase { public $stored_system_variables; //boolean public $wsSessionId; //web service session id, if the wsbase function is used from a WS request @@ -295,7 +270,7 @@ class wsBase try { $solrEnabled = 0; - if (($solrEnv = PmSystem::solrEnv()) !== false) { + if (($solrEnv = System::solrEnv()) !== false) { $appSolr = new AppSolr( $solrEnv["solr_enabled"], @@ -333,7 +308,7 @@ class wsBase //Add del_index dynamic fields to list of resulting columns $columsToIncludeFinal = array_merge($columsToInclude, $delegationIndexes); - $solrRequestData = Entity_SolrRequestData::createForRequestPagination( + $solrRequestData = EntitySolrRequestData::createForRequestPagination( array( "workspace" => $solrEnv["solr_instance"], "startAfter" => 0, @@ -348,7 +323,7 @@ class wsBase ); //Use search index to return list of cases - $searchIndex = new BpmnEngine_Services_SearchIndex($appSolr->isSolrEnabled(), $solrEnv["solr_host"]); + $searchIndex = new BpmnEngineServicesSearchIndex($appSolr->isSolrEnabled(), $solrEnv["solr_host"]); //Execute query $solrQueryResult = $searchIndex->getDataTablePaginatedList($solrRequestData); @@ -898,7 +873,7 @@ class wsBase } } - $aSetup = (!empty($arrayConfigAux))? $arrayConfigAux : PmSystem::getEmailConfiguration(); + $aSetup = (!empty($arrayConfigAux))? $arrayConfigAux : System::getEmailConfiguration(); if (!isset($aSetup['MESS_ENABLED'])) { $aSetup['MESS_ENABLED'] = 1; @@ -907,7 +882,7 @@ class wsBase } } else { /*----------------------------------********---------------------------------*/ - $aSetup = PmSystem::getEmailConfiguration(); + $aSetup = System::getEmailConfiguration(); /*----------------------------------********---------------------------------*/ } /*----------------------------------********---------------------------------*/ @@ -917,7 +892,7 @@ class wsBase $msgError = "The default configuration wasn't defined"; } - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aSetup); @@ -1484,7 +1459,7 @@ class wsBase { try { if (trim( $groupName ) == '') { - $result = new wsCreateGroupResponse( 25, G::loadTranslation( 'ID_GROUP_NAME_REQUIRED' ), '' ); + $result = new WsCreateGroupResponse( 25, G::loadTranslation( 'ID_GROUP_NAME_REQUIRED' ), '' ); return $result; } @@ -1494,7 +1469,7 @@ class wsBase $data['GROUP_NAME'] = $groupName; - $result = new wsCreateGroupResponse( 0, G::loadTranslation( 'ID_GROUP_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $groupId ); + $result = new WsCreateGroupResponse( 0, G::loadTranslation( 'ID_GROUP_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $groupId ); return $result; } catch (Exception $e) { @@ -1515,7 +1490,7 @@ class wsBase { try { if (trim( $departmentName ) == '') { - $result = new wsCreateDepartmentResponse( 25, G::loadTranslation( 'ID_DEPARTMENT_NAME_REQUIRED' ), '' ); + $result = new WsCreateDepartmentResponse( 25, G::loadTranslation( 'ID_DEPARTMENT_NAME_REQUIRED' ), '' ); return $result; } @@ -1523,13 +1498,13 @@ class wsBase $department = new Department(); if (($parentUID != '') && ! ($department->existsDepartment( $parentUID ))) { - $result = new wsCreateDepartmentResponse( 26, G::loadTranslation( 'ID_PARENT_DEPARTMENT_NOT_EXIST' ), $parentUID ); + $result = new WsCreateDepartmentResponse( 26, G::loadTranslation( 'ID_PARENT_DEPARTMENT_NOT_EXIST' ), $parentUID ); return $result; } if ($department->checkDepartmentName( $departmentName, $parentUID )) { - $result = new wsCreateDepartmentResponse( 27, G::loadTranslation( 'ID_DEPARTMENT_EXISTS' ), '' ); + $result = new WsCreateDepartmentResponse( 27, G::loadTranslation( 'ID_DEPARTMENT_EXISTS' ), '' ); return $result; } @@ -1543,7 +1518,7 @@ class wsBase $data['PARENT_UID'] = $parentUID; $data['DEPARTMENT_NAME'] = $departmentName; - $result = new wsCreateDepartmentResponse( 0, G::loadTranslation( 'ID_DEPARTMENT_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $departmentId ); + $result = new WsCreateDepartmentResponse( 0, G::loadTranslation( 'ID_DEPARTMENT_CREATED_SUCCESSFULLY', SYS_LANG, $data ), $departmentId ); return $result; } catch (Exception $e) { @@ -2851,7 +2826,7 @@ class wsBase $result->status_code = 0; $result->message = G::loadTranslation( 'ID_SUCESSFUL' ); $result->timestamp = date( 'Y-m-d H:i:s' ); - $result->version = PmSystem::getVersion(); + $result->version = System::getVersion(); $result->operatingSystem = $redhat; $result->webServer = getenv( 'SERVER_SOFTWARE' ); $result->serverName = getenv( 'SERVER_NAME' ); diff --git a/workflow/engine/classes/WsCreateDepartmentResponse.php b/workflow/engine/classes/WsCreateDepartmentResponse.php new file mode 100644 index 000000000..2af4099d8 --- /dev/null +++ b/workflow/engine/classes/WsCreateDepartmentResponse.php @@ -0,0 +1,32 @@ +status_code = $status; + $this->message = $message; + $this->departmentUID = $departmentUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } +} diff --git a/workflow/engine/classes/WsCreateGroupResponse.php b/workflow/engine/classes/WsCreateGroupResponse.php new file mode 100644 index 000000000..82d012692 --- /dev/null +++ b/workflow/engine/classes/WsCreateGroupResponse.php @@ -0,0 +1,32 @@ +status_code = $status; + $this->message = $message; + $this->groupUID = $groupUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } + +} diff --git a/workflow/engine/classes/WsCreateUserResponse.php b/workflow/engine/classes/WsCreateUserResponse.php new file mode 100644 index 000000000..6ac4061ad --- /dev/null +++ b/workflow/engine/classes/WsCreateUserResponse.php @@ -0,0 +1,26 @@ +status_code = $status; + $this->message = $message; + $this->userUID = $userUID; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } +} diff --git a/workflow/engine/classes/WsGetCaseNotesResponse.php b/workflow/engine/classes/WsGetCaseNotesResponse.php new file mode 100644 index 000000000..eb8fa7f6e --- /dev/null +++ b/workflow/engine/classes/WsGetCaseNotesResponse.php @@ -0,0 +1,26 @@ +status_code = $status; + $this->message = $message; + $this->notes = $notes; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } +} diff --git a/workflow/engine/classes/WsGetVariableResponse.php b/workflow/engine/classes/WsGetVariableResponse.php new file mode 100644 index 000000000..8f2501dd1 --- /dev/null +++ b/workflow/engine/classes/WsGetVariableResponse.php @@ -0,0 +1,26 @@ +status_code = $status; + $this->message = $message; + $this->variables = $variables; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } +} diff --git a/workflow/engine/classes/WsResponse.php b/workflow/engine/classes/WsResponse.php new file mode 100644 index 000000000..ea6cc4e92 --- /dev/null +++ b/workflow/engine/classes/WsResponse.php @@ -0,0 +1,51 @@ +status_code = $status; + $this->message = $message; + $this->timestamp = date( 'Y-m-d H:i:s' ); + } + + /** + * Function getPayloadString + * + * @param string $operation + * @return string + */ + function getPayloadString ($operation) + { + $res = "<$operation>\n"; + $res .= "" . $this->status_code . ""; + $res .= "" . $this->message . ""; + $res .= "" . $this->timestamp . ""; + // $res .= "" . $this->timestamp . ""; + $res .= "<$operation>"; + return $res; + } + + /** + * Function getPayloadArray + * + * @return array + */ + function getPayloadArray () + { + return array ("status_code" => $this->status_code,'message' => $this->message,'timestamp' => $this->timestamp + ); + } +} diff --git a/workflow/engine/classes/class.xmlDb.php b/workflow/engine/classes/XMLConnection.php similarity index 86% rename from workflow/engine/classes/class.xmlDb.php rename to workflow/engine/classes/XMLConnection.php index c24af1a20..3bb13096f 100644 --- a/workflow/engine/classes/class.xmlDb.php +++ b/workflow/engine/classes/XMLConnection.php @@ -1,83 +1,5 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * XMLDB - * - * ProcessMaker Open Source Edition - * - * @copyright (C) 2004 - 2008 Colosa Inc.23 - * @package workflow.engine.ProcessMaker - * - */ -class XMLDB -{ - - /** - * &connect - * - * @param string $dsn - * @return array $options - */ - public function &connect ($dsn, $options = array()) - { - //Needed for $mysql_real_escape_string - $mresdbc = new DBConnection(); - - if (! file_exists( $dsn )) { - $err = new DB_Error( "File $dsn not found." ); - return $err; - } - $dbc = new XMLConnection( $dsn ); - return $dbc; - } - - /** - * isError - * - * @param string $result - * @return boolean is_a($result, 'DB_Error') - */ - public function isError ($result) - { - return is_a( $result, 'DB_Error' ); - } -} - -/** - * XMLConnection - * - * ProcessMaker Open Source Edition - * - * @copyright (C) 2004 - 2008 Colosa Inc.23 - * @package workflow.engine.ProcessMaker - * - */ class XMLConnection { var $phptype = 'myxml'; @@ -555,73 +477,3 @@ class XMLConnection } } } - -/** - * XMLResult - * - * ProcessMaker Open Source Edition - * - * @copyright (C) 2004 - 2008 Colosa Inc.23 - * @package workflow.engine.ProcessMaker - * - */ -class XMLResult -{ - var $result = array (); - var $cursor = 0; - - /** - * XMLResult - * - * @param array $result - * @return void - */ - public function XMLResult ($result = array()) - { - $this->result = $result; - $this->cursor = 0; - } - - /** - * numRows - * - * @return integer sizeof($this->result) - */ - public function numRows () - { - return sizeof( $this->result ); - } - - /** - * fetchRow - * - * @param string $const - * @return integer $this->result[ $this->cursor-1 ]; - */ - public function fetchRow ($const) - { - if ($this->cursor >= $this->numRows()) { - return null; - } - $this->cursor ++; - return $this->result[$this->cursor - 1]; - } -} - -/** - * getNames - * - * @param object $children - * @return array $names - */ -function getNames ($children) -{ - $names = array (); - $r = 0; - foreach ($children as $child) { - $names[$r] = $child->name; - $r ++; - } - return $names; -} - diff --git a/workflow/engine/classes/XMLDB.php b/workflow/engine/classes/XMLDB.php new file mode 100644 index 000000000..fd5d04290 --- /dev/null +++ b/workflow/engine/classes/XMLDB.php @@ -0,0 +1,39 @@ +result = $result; + $this->cursor = 0; + } + + /** + * numRows + * + * @return integer sizeof($this->result) + */ + public function numRows () + { + return sizeof( $this->result ); + } + + /** + * fetchRow + * + * @param string $const + * @return integer $this->result[ $this->cursor-1 ]; + */ + public function fetchRow ($const) + { + if ($this->cursor >= $this->numRows()) { + return null; + } + $this->cursor ++; + return $this->result[$this->cursor - 1]; + } +} diff --git a/workflow/engine/classes/XmlFormFieldCheckBoxTable.php b/workflow/engine/classes/XmlFormFieldCheckBoxTable.php new file mode 100644 index 000000000..d6d3f7e29 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldCheckBoxTable.php @@ -0,0 +1,26 @@ +onclick) ? ' onclick="' . G::replaceDataField($this->onclick, $owner->values) . '" ' : ''); + $html = ' '; + return $html; + } +} diff --git a/workflow/engine/classes/XmlFormFieldHours.php b/workflow/engine/classes/XmlFormFieldHours.php new file mode 100644 index 000000000..bbd8b8ab4 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldHours.php @@ -0,0 +1,125 @@ + + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render($value = null, $owner = null) + { + if ($this->strTo === 'UPPER') { + $value = strtoupper($value); + } + if ($this->strTo === 'LOWER') { + $value = strtolower($value); + } + //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); + $onkeypress = G::replaceDataField($this->onkeypress, $owner->values); + if ($this->replaceTags == 1) { + $value = G::replaceDataField($value, $owner->values); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' readOnly="readOnly" style="' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $sShowVars; + } else { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' style="' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' style="display:none;' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $this->htmlentities($value, ENT_COMPAT, 'utf-8'); + } else { + return $this->htmlentities($value, ENT_COMPAT, 'utf-8'); + } + } + + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter array values + * @param eter string owner + * @return string + */ + public function renderGrid($values = array(), $owner) + { + $result = array(); + $r = 1; + foreach ($values as $v) { + if ($this->replaceTags == 1) { + $v = G::replaceDataField($v, $owner->values); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + //$sShowVars = ' ' . $this->symbol . ''; + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = '' . $sShowVars; + } else { + $result[] = '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + $result[] = '

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

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

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

'; + } + $r ++; + } + return $result; + } + + /** + * Function attachEvents + * + * @access public + * @param eter string $element + * @return string + */ + public function attachEvents($element) + { + return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); + myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");"; + } +} diff --git a/workflow/engine/classes/XmlFormFieldPopupOption.php b/workflow/engine/classes/XmlFormFieldPopupOption.php new file mode 100644 index 000000000..b6028b359 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldPopupOption.php @@ -0,0 +1,22 @@ +name . '",text:"' . addcslashes($this->label, '\\"') . '", launch:leimnud.closure({Function:function(target){' . $this->launch . '}, args:target})}'; + return $script; + } +} diff --git a/workflow/engine/classes/XmlFormFieldTextAreaPm.php b/workflow/engine/classes/XmlFormFieldTextAreaPm.php new file mode 100644 index 000000000..1df14af43 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldTextAreaPm.php @@ -0,0 +1,86 @@ + + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render($value = null, $owner) + { + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return '' . $sShowVars; + } else { + return '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return ''; + } else { + return ''; + } + } + + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter string values + * @param eter string owner + * @return string + */ + public function renderGrid($owner, $values = null) + { + $result = array(); + $r = 1; + foreach ($values as $v) { + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = 'htmlentities($v, ENT_COMPAT, 'utf-8') . '\' readOnly="readOnly"/>' . $sShowVars; + } else { + $result[] = 'htmlentities($v, ENT_COMPAT, 'utf-8') . '\' />' . $sShowVars; + } + } elseif ($this->mode === 'view') { + if (stristr($_SERVER['HTTP_USER_AGENT'], 'iPhone')) { + $result[] = $this->htmlentities($v, ENT_COMPAT, 'utf-8'); + } else { + $result[] = $this->htmlentities($v, ENT_COMPAT, 'utf-8'); + } + } else { + $result[] = $this->htmlentities($v, ENT_COMPAT, 'utf-8'); + } + $r ++; + } + return $result; + } +} diff --git a/workflow/engine/classes/XmlFormFieldTextPm.php b/workflow/engine/classes/XmlFormFieldTextPm.php new file mode 100644 index 000000000..20ca0d411 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldTextPm.php @@ -0,0 +1,120 @@ + + * @access public + * @param eter string value + * @param eter string owner + * @return string + */ + public function render($value = null, $owner = null) + { + //NOTE: string functions must be in G class + if ($this->strTo === 'UPPER') { + $value = strtoupper($value); + } + if ($this->strTo === 'LOWER') { + $value = strtolower($value); + } + + $onkeypress = G::replaceDataField($this->onkeypress, $owner->values); + if ($this->replaceTags == 1) { + $value = G::replaceDataField($value, $owner->values); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' readOnly="readOnly" style="' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $sShowVars; + } else { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' style="' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $sShowVars; + } + } elseif ($this->mode === 'view') { + return 'htmlentities($value, ENT_COMPAT, 'utf-8') . '\' style="display:none;' . htmlentities($this->style, ENT_COMPAT, 'utf-8') . '" onkeypress="' . htmlentities($onkeypress, ENT_COMPAT, 'utf-8') . '"/>' . $this->htmlentities($value, ENT_COMPAT, 'utf-8'); + } else { + return $this->htmlentities($value, ENT_COMPAT, 'utf-8'); + } + } + + /** + * Function renderGrid + * + * @author Julio Cesar Laura Avendano + * @access public + * @param eter array values + * @param eter string owner + * @return string + */ + public function renderGrid($values = array(), $owner) + { + $result = array(); + $r = 1; + foreach ($values as $v) { + if ($this->replaceTags == 1) { + $v = G::replaceDataField($v, $owner->values); + } + if ($this->showVars == 1) { + $this->process = G::replaceDataField($this->process, $owner->values); + $sShowVars = ' '; + } else { + $sShowVars = ''; + } + if ($this->mode === 'edit') { + if ($this->readOnly) { + $result[] = '' . $sShowVars; + } else { + $result[] = '' . $sShowVars; + } + } elseif ($this->mode === 'view') { + $result[] = $this->htmlentities($v, ENT_COMPAT, 'utf-8'); + } else { + $result[] = $this->htmlentities($v, ENT_COMPAT, 'utf-8'); + } + $r ++; + } + return $result; + } + + /** + * Function attachEvents + * + * @access public + * @param eter string $element + * @return string + */ + public function attachEvents($element) + { + return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); + myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");"; + } +} diff --git a/workflow/engine/classes/XmlFormFieldToolBar.php b/workflow/engine/classes/XmlFormFieldToolBar.php new file mode 100644 index 000000000..cfdb5bf21 --- /dev/null +++ b/workflow/engine/classes/XmlFormFieldToolBar.php @@ -0,0 +1,48 @@ +home = $home; + } + + /** + * Prints the ToolBar + * + * @param string $value + * @return string + */ + public function render($value) + { + $this->toolBar = new ToolBar($this->xmlfile, $this->home); + $template = PATH_CORE . 'templates/' . $this->type . '.html'; + $out = $this->toolBar->render($template, $scriptCode); + $oHeadPublisher = & headPublisher::getSingleton(); + $oHeadPublisher->addScriptFile($this->toolBar->scriptURL); + $oHeadPublisher->addScriptCode($scriptCode); + return $out; + } +} diff --git a/workflow/engine/classes/class.toolBar.php b/workflow/engine/classes/XmlFormFieldToolButton.php similarity index 68% rename from workflow/engine/classes/class.toolBar.php rename to workflow/engine/classes/XmlFormFieldToolButton.php index e8d66faba..855df7bab 100644 --- a/workflow/engine/classes/class.toolBar.php +++ b/workflow/engine/classes/XmlFormFieldToolButton.php @@ -1,97 +1,13 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * ToolBar - ToolBar class + * ToolBar - ToolBar + * XmlFormFieldToolButton - XmlFormFieldToolButton class * * @package workflow.engine.ProcessMaker */ -class ToolBar extends form +class XmlFormFieldToolButton extends XmlFormField { - public $type = 'toolbar'; - public $align = 'left'; -} - -/** - * XmlForm_Field_ToolBar - XmlForm_Field_ToolBar class - * - * @package workflow.engine.ProcessMaker - */ -class XmlForm_Field_ToolBar extends XmlForm_Field -{ - - public $xmlfile = ''; - public $type = 'toolbar'; - public $toolBar; - public $home = ''; - public $withoutLabel = true; - - /** - * Constructor of the class XmlForm_Field_ToolBar - * - * @param string $xmlNode - * @param string $lang - * @param string $home - * @param string $owner - * @return void - */ - public function XmlForm_Field_ToolBar($xmlNode, $lang = 'en', $home = '', $owner = ' ') - { - parent::XmlForm_Field($xmlNode, $lang, $home, $owner); - $this->home = $home; - } - - /** - * Prints the ToolBar - * - * @param string $value - * @return string - */ - public function render($value) - { - $this->toolBar = new toolBar($this->xmlfile, $this->home); - $template = PATH_CORE . 'templates/' . $this->type . '.html'; - $out = $this->toolBar->render($template, $scriptCode); - $oHeadPublisher = & headPublisher::getSingleton(); - $oHeadPublisher->addScriptFile($this->toolBar->scriptURL); - $oHeadPublisher->addScriptCode($scriptCode); - return $out; - } -} - -/** - * XmlForm_Field_toolButton - XmlForm_Field_toolButton class - * - * @package workflow.engine.ProcessMaker - */ -class XmlForm_Field_toolButton extends XmlForm_Field -{ - public $file = ''; public $fileAlt = ''; public $url = ''; @@ -152,8 +68,6 @@ class XmlForm_Field_toolButton extends XmlForm_Field break; case 'html': $html = '
' . $this->label . '
'; - - //$html=$this->label; break; case 'image/text': $html = 'style) ? ' style="' . $this->style . '"' : '') . '/>
' . $this->htmlentities($this->label, ENT_QUOTES, 'utf-8'); @@ -164,7 +78,6 @@ class XmlForm_Field_toolButton extends XmlForm_Field case 'dropdown': $html = ''; if (isset($this->owner->values['PRO_UID'])) { - $criteria = ProcessMap::getDynaformsCriteria($this->owner->values['PRO_UID']); $dataset = DynaformPeer::doSelectRS($criteria); if ($dataset->getRecordCount() > 0) { diff --git a/workflow/engine/classes/ZipFile.php b/workflow/engine/classes/ZipFile.php new file mode 100644 index 000000000..dbbfd677b --- /dev/null +++ b/workflow/engine/classes/ZipFile.php @@ -0,0 +1,109 @@ +archive($name); + $this->options['type'] = "zip"; + } + + /** + * This function is used to create archives . + * zip + * + * @return boolean + */ + public function create_zip() + { + $files = 0; + $offset = 0; + $central = ""; + if (!empty($this->options['sfx'])) { + if ($fp = @fopen($this->options['sfx'], "rb")) { + $temp = fread($fp, filesize($this->options['sfx'])); + fclose($fp); + $this->add_data($temp); + $offset += strlen($temp); + unset($temp); + } else { + $this->error[] = "Could not open sfx module from {$this->options['sfx']}."; + } + } + $pwd = getcwd(); + chdir($this->options['basedir']); + foreach ($this->files as $current) { + if ($current['name'] == $this->options['name']) { + continue; + } + $timedate = explode(" ", date("Y n j G i s", $current['stat'][9])); + $timedate = ($timedate[0] - 1980 << 25) | ($timedate[1] << 21) | ($timedate[2] << 16) | ($timedate[3] << 11) | ($timedate[4] << 5) | ($timedate[5]); + $block = pack("VvvvV", 0x04034b50, 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate); + if ($current['stat'][7] == 0 && $current['type'] == 5) { + $block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000); + $block .= $current['name2'] . "/"; + $this->add_data($block); + $central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']) + 1, 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset); + $central .= $current['name2'] . "/"; + $files++; + $offset += (31 + strlen($current['name2'])); + } elseif ($current['stat'][7] == 0) { + $block .= pack("VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000); + $block .= $current['name2']; + $this->add_data($block); + $central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, 0x00000000, 0x00000000, 0x00000000, strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset); + $central .= $current['name2']; + $files++; + $offset += (30 + strlen($current['name2'])); + } elseif ($fp = @fopen($current['name'], "rb")) { + $temp = fread($fp, $current['stat'][7]); + fclose($fp); + $crc32 = G::encryptCrc32($temp); + if (!isset($current['method']) && $this->options['method'] == 1) { + $temp = gzcompress($temp, $this->options['level']); + $size = strlen($temp) - 6; + $temp = substr($temp, 2, $size); + } else { + $size = strlen($temp); + } + $block .= pack("VVVvv", $crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000); + $block .= $current['name2']; + $this->add_data($block); + $this->add_data($temp); + unset($temp); + $central .= pack("VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset($current['method']) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, $crc32, $size, $current['stat'][7], strlen($current['name2']), 0x0000, 0x0000, 0x0000, 0x0000, 0x00000000, $offset); + $central .= $current['name2']; + $files++; + $offset += (30 + strlen($current['name2']) + $size); + } else { + $this->error[] = "Could not open file {$current['name']} for reading. It was not added."; + } + } + $this->add_data($central); + $this->add_data(pack("VvvvvVVv", 0x06054b50, 0x0000, 0x0000, $files, $files, strlen($central), $offset, !empty($this->options['comment']) ? strlen($this->options['comment']) : 0x0000)); + if (!empty($this->options['comment'])) { + $this->add_data($this->options['comment']); + } + chdir($pwd); + return 1; + } +} diff --git a/workflow/engine/classes/class.AppSolr.php b/workflow/engine/classes/class.AppSolr.php deleted file mode 100644 index 66c8f9f4c..000000000 --- a/workflow/engine/classes/class.AppSolr.php +++ /dev/null @@ -1,3092 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 5304 Ventura Drive, - * Delray Beach, FL, 33484, USA, or email info@colosa.com. - * - */ - -require_once "classes/model/Application.php"; -require_once "classes/model/AppDelegation.php"; -require_once "classes/model/AppThread.php"; -require_once "classes/model/Content.php"; -require_once "classes/model/Users.php"; -require_once "classes/model/GroupUser.php"; -require_once "classes/model/Task.php"; -require_once "classes/model/TaskUser.php"; -require_once "classes/model/Dynaform.php"; -require_once "classes/model/ProcessVariables.php"; -require_once "entities/SolrRequestData.php"; -require_once "entities/SolrUpdateDocument.php"; -require_once "entities/AppSolrQueue.php"; -require_once "classes/model/AppSolrQueue.php"; - - -/** - * Invalid search text for Solr exception - * - * @author Herbert Saal Gutierrez - * - */ -class InvalidIndexSearchTextException 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"; - } -} - -/** - * 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"; - } -} - -/** - * Dynaform file corrupt - * - * @author Herbert Saal Gutierrez - * - * @category Colosa - * @copyright Copyright (c) 2005-2012 Colosa Inc. (http://www.colosa.com) - */ -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); - } - - // custom string representation of object - public function __toString() - { - return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; - } -} - -/** - * Application APP_DATA could not be unserialized exception - * - * @author Herbert Saal Gutierrez - * - * @category Colosa - * @copyright Copyright (c) 2005-2012 Colosa Inc. (http://www.colosa.com) - */ -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); - } - - // 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 - * search service - * - * @author Herbert Saal Gutierrez - * @category Colosa - * @copyright Copyright (c) 2005-2011 Colosa Inc. (http://www.colosa.com) - * - */ -class AppSolr -{ - private $_solrIsEnabled = false; - private $_solrHost = ""; - private $_solrInstance = ""; - private $debug = false; //false - private $debugAppInfo = false; - private $trunkSizeAcumulated; - private $totalTimeAcumulated; - - 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() - { - $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."; - - 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' - );*/ - - $columsToInclude = array ( - 'APP_PRO_TITLE', - 'APP_TITLE', - 'APP_UID', - 'DEL_MAX_PRIORITY' - ); - - // 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_STATUS' : - $sortCols [0] = 'APP_STATUS'; //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); - - $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'; - } - } - // Paused, add condition - if ($userUid != null && $action == 'paused') { - $solrSearchText .= "APP_PAUSED_USERS:" . $userUid . ' AND '; - $delegationIndexes[] = "APP_PAUSED_USER_DEL_INDEX_" . trim ($userUid) . '_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 "; - } - - //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; - - //var_dump($solrQueryResult->aaData); die; - - //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 (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 - //$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 date('Y-m-d H:i:s:u') . " Delegation not defined\n"; - } - /* - elseif ($action == 'unassigned'){ - $delIndexes = $this->getApplicationDelegationsIndex ($appUID); - }*/ - } - //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 - } - - //var_dump($aRow); - - // 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 - )); - $row = ''; - foreach ($indexes as $index) { - $row = $aaappsDBData [$index]; - } - - if (empty($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']; - - $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; - } - - } - $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']; - $data = $this->getAppGridData ($userUid, 0, 0, 'paused', null, null, null, null, - null, null, null, null, null, null, null, true); - $casesCount ['paused'] = $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', TaskPeer::TAS_TITLE); - $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 ('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); - - $c->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID); - - $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); - - $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', TaskPeer::TAS_TITLE); - $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 ('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); - - $c->addJoin(AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID); - - $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); - - $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 - - $searchIndex = new BpmnEngine_Services_SearchIndex ($this->_solrIsEnabled, $this->_solrHost); - // execute query - $ListFieldsInfo = $searchIndex->getIndexFields ($this->_solrInstance); - - $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] - $result1 = strpos($searchText, '-'); - if ($result1 !== false) { - $result2 = strpos($searchText, 'TO'); - if ($result2 !== false) { - $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 != '*') { - $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 { - $searchText = str_replace( "[", "", $searchText ); - $searchText = str_replace( "]", "", $searchText ); - $searchText = str_replace( ":", "", $searchText ); - $searchText = ":[" . $searchText . "T00:00:00Z TO " . $searchText . "T23:59:59.999Z]"; - } - } - } - - // validate phrase in case of < and <= - $result1 = strpos($searchText, '<'); - if($result1 !== false) { - $result = strpos($searchText, '<='); - if($result !== false) { - $v1 = str_replace( '<=', '', $searchText ); - $v2 = str_replace( ':', '', $v1); - $v3 = str_replace( '<','' ,':[* TO '.$v2.']' ); - $searchText = $v3; - } else { - $v1 = str_replace( '<', '', $searchText ); - $v2 = str_replace( ':', '', $v1); - $v3 = (int) $v2-1; - $v4 = str_replace( '<','' ,':[* TO '.$v3.']' ); - $searchText = $v4; - } - } - // validate phrase in case of > and >= - $result2 = strpos($searchText, '>'); - if($result2 !== false) { - $result = strpos($searchText, '>='); - if($result !== false) { - $v1 = str_replace( '>=', '', $searchText ); - $v2 = str_replace( ':', '', $v1); - $v3 = str_replace( '>','' ,':['.$v2.' TO *]' ); - $searchText = $v3; - } else { - $v1 = str_replace( '>', '', $searchText ); - $v2 = str_replace( ':', '', $v1 ); - $v3 = (int) $v2+1; - $v4 = str_replace( '>','' ,':['.$v3.' TO *]' ); - $searchText = $v4; - } - } - $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 (); - } - - //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); - - $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{ - - $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]; - $pausedtUser = $result [14]; - - try { - - // create document - $xmlCurrentDoc = $this->buildSearchIndexDocumentPMOS2 ($documentInformation, $dynaformFieldTypes, - $lastUpdateDate, $maxPriority, $delLastIndex, $assignedUsers, $assignedUsersRead, $assignedUsersUnread, - $draftUser, $participatedUsers, $participatedUsersStartedByUser, $participatedUsersCompletedByUser, - $unassignedUsers, $unassignedGroups,$pausedtUser); - - //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,$pausedtUser) - { - // 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 (); - } - } - if (! empty ($pausedtUser)) { - foreach ($pausedtUser as $paused) { - $writer->startElement ("field"); - $writer->writeAttribute ('name', 'APP_PAUSED_USERS'); - $writer->text ($paused ['USR_UID']); - $writer->endElement (); - - $writer->startElement ("field"); - $writer->writeAttribute ('name', 'APP_PAUSED_USER_DEL_INDEX_' . trim ($paused ['USR_UID']) . '_txt'); - $writer->text ($paused ['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) { - //This validation is only for the 'checkbox' control for the BPMN forms, - //the request is not made to the database to obtain the control - //associated with the variable so as not to decrease the performance. - if (is_array($value) && count($value) === 1 && isset($value[0]) && !is_object($value[0]) && !is_array($value[0])) { - $value = $value[0]; - } - 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 = str_replace( ',', '', $value ); - $value = intval ($value); - } - break; - case 'Real' : - $typeSufix = '_td'; - $value = str_replace( ',', '', $value ); - $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 != '*') { - $value = trim($value); - $pairs = array( - "\x03" => "", - "\x04" => "", - "\x05" => "", - "\x06" => "", - "\x07" => "", - "\x08" => "", - "\x0E" => "", - "\x16" => "", - "\x00-" => "", - "\x09" => "", - "\x11" => "", - "\x12" => "", - "\x14-" => "", - "\x1f" => "", - "\x7f" => "", - ); - $value = strtr($value, $pairs); - $writer->startElement ("field"); - $writer->writeAttribute ('name', trim ($k) . $typeSufix); - $writer->startCData (); - $writer->text ($value); - $writer->endCData(); - $writer->endElement (); - } - } - else { - $value = trim($value); - $pairs = array( - "\x03" => "", - "\x04" => "", - "\x05" => "", - "\x06" => "", - "\x07" => "", - "\x08" => "", - "\x0E" => "", - "\x16" => "", - "\x00-" => "", - "\x09" => "", - "\x11" => "", - "\x12" => "", - "\x14-" => "", - "\x1f" => "", - "\x7f" => "", - ); - $value = strtr($value, $pairs); - $writer->startElement ("field"); - $writer->writeAttribute ('name', trim ($k) . '_t'); - $writer->startCData (); - $writer->text ($value); - $writer->endCData(); - $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) - { - // 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' - 'APP_TYPE' => '' - )); - 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'] - ); - } - - $pausedUsers = array (); - $indexes = $this->aaSearchRecords ($allAppDbData, array ( - 'APP_TYPE' => 'PAUSE' - )); - foreach ($indexes as $index) { - if ($allAppDbData [$index] ['APP_DISABLE_ACTION_USER'] == null || $allAppDbData [$index] ['APP_DISABLE_ACTION_USER'] == 0) { - $pausedUsers [] = 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) { - $dynaformFileNames = $this->getProcessDynaformFileNames ($documentInformation ['PRO_UID']); - $dynaformFields = array (); - foreach ($dynaformFileNames as $dynaformFileName) { - if (is_file(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') && - filesize(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') >0 ) { - $dyn = new DynaformHandler (PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml'); - $dynaformFields [] = $dyn->getFields (); - } - if (is_file(PATH_DYNAFORM . $dynaformFileName ['DYN_FILENAME'] . '.xml') && - filesize(PATH_DYNAFORM . $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'); - } - } - } - $dynaformFieldTypes = $this->getVariablesDynaform($documentInformation['PRO_UID'], $dynaformFieldTypes); - // 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, - $draftUser, - $participatedUsers, - $participatedUsersStartedByUser, - $participatedUsersCompletedByUser, - $unassignedUsers, - $unassignedGroups, - $pausedUsers - ); - - return $result; - } - - /** - * - * - * @param array $dynaformFieldTypes - * @return array - */ - public function getVariablesDynaform($processUid, $dynaformFieldTypes = array()) - { - $criteria = new Criteria(); - $criteria->add(ProcessVariablesPeer::PRJ_UID, $processUid); - $ds = ProcessVariablesPeer::doSelectRS($criteria); - $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($ds->next()) { - $row = $ds->getRow(); - $type = "text"; - if ($row["VAR_FIELD_TYPE"] === "datetime") { - $type = "date"; - } - $dynaformFieldTypes[$row["VAR_NAME"]] = $type; - } - return $dynaformFieldTypes; - } - - /** - * 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 (); - $isEqual = true; - foreach ($arr as $i => $row) { - $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; - } - } - 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_TITLE); - $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->addSelectColumn (ProcessPeer::PRO_TITLE); - - $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 ('ad', 'APP_DELEGATION'); - $c->addAlias ('at', 'APP_THREAD'); - - $c->addJoin (ApplicationPeer::PRO_UID, ProcessPeer::PRO_UID, 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 (); - } - - //Propel::close(); - - 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_TITLE); - $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->addSelectColumn ('pro.PRO_TITLE'); - - $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 ('ade.APP_DELAY_UID'); - $c->addSelectColumn ('ade.APP_TYPE'); - $c->addSelectColumn ('ade.APP_DISABLE_ACTION_USER'); - - $c->addAsColumn("PRO_CATEGORY_UID", "pro.PRO_CATEGORY"); - - $c->addAlias ('ad', 'APP_DELEGATION'); - $c->addAlias ('at', 'APP_THREAD'); - $c->addAlias ('ade', 'APP_DELAY'); - $c->addAlias ("pro", ProcessPeer::TABLE_NAME); - - $c->addJoin (ApplicationPeer::PRO_UID, ProcessPeer::PRO_UID, 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); - - $aConditions = array (); - $aConditions [] = array ( - 'ad.APP_UID', - 'ade.APP_UID' - ); - $aConditions [] = array ( - 'ad.DEL_INDEX', - 'ade.APP_DEL_INDEX' - ); - //$aConditions [] = array ( - // 'ade.APP_DISABLE_ACTION_USER', - // DBAdapter::getStringDelimiter () . 'null' . DBAdapter::getStringDelimiter () - //); - $aConditions [] = array ( - 'ade.APP_DISABLE_ACTION_USER', - DBAdapter::getStringDelimiter () . '0' . DBAdapter::getStringDelimiter () - ); - $aConditions [] = array ( - 'ade.APP_TYPE', - DBAdapter::getStringDelimiter () . 'PAUSE' . DBAdapter::getStringDelimiter () - ); - $c->addJoinMC($aConditions, 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); - - $rs->next (); - $row = $rs->getRow (); - - while (is_array ($row)) { - $allAppDbData [] = $row; - $rs->next (); - $row = $rs->getRow (); - } - //Propel::close(); - - 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(); - - 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(); - - 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); - - $oAppSolrQueue = new AppSolrQueue (); - - $oAppSolrQueue->createUpdate ($AppUid, $traceData, $updated); - } - - private function getCurrentTraceInfo() - { - $resultTraceString = ""; - $traceData = debug_backtrace(); - foreach ($traceData as $key => $value) { - if ($value['function'] != 'getCurrentTraceInfo' && $value['function'] != 'require_once') { - if (isset($value['file']) && isset($value['line']) && isset($value['function'])) { - $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 (); - - $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 ); - } - } - - $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); - - $this->updateApplicationSearchIndex ($trunkUpdatedApplications, true); - - /*foreach($trunkUpdatedApplications as $appUid){ - $this->applicationChangedUpdateSolrQueue ($appUid, 0); - }*/ - } - - $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); - - $this->deleteApplicationSearchIndex ($trunkDeleteddApplications, true); - - /*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() - { - $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() - { - $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 (); - } - - //Propel::close(); - - 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; - - 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"); - } - -} - diff --git a/workflow/engine/classes/class.archive.php b/workflow/engine/classes/class.archive.php deleted file mode 100644 index 48dbe6a85..000000000 --- a/workflow/engine/classes/class.archive.php +++ /dev/null @@ -1,746 +0,0 @@ -options = array ('basedir' => ".",'name' => $name,'prepend' => "",'inmemory' => 0,'overwrite' => 0,'recurse' => 1,'storepaths' => 1,'followlinks' => 0,'level' => 3,'method' => 1,'sfx' => "",'type' => "",'comment' => "" - ); - $this->files = array (); - $this->exclude = array (); - $this->storeonly = array (); - $this->error = array (); - } - - /** - * This function gives options to a archive - * - * @param array $options - * @return void - */ - public function set_options ($options) - { - foreach ($options as $key => $value) { - $this->options[$key] = $value; - } - if (! empty( $this->options['basedir'] )) { - $this->options['basedir'] = str_replace( "\\", "/", $this->options['basedir'] ); - $this->options['basedir'] = preg_replace( "/\/+/", "/", $this->options['basedir'] ); - $this->options['basedir'] = preg_replace( "/\/$/", "", $this->options['basedir'] ); - } - if (! empty( $this->options['name'] )) { - $this->options['name'] = str_replace( "\\", "/", $this->options['name'] ); - $this->options['name'] = preg_replace( "/\/+/", "/", $this->options['name'] ); - } - if (! empty( $this->options['prepend'] )) { - $this->options['prepend'] = str_replace( "\\", "/", $this->options['prepend'] ); - $this->options['prepend'] = preg_replace( "/^(\.*\/+)+/", "", $this->options['prepend'] ); - $this->options['prepend'] = preg_replace( "/\/+/", "/", $this->options['prepend'] ); - $this->options['prepend'] = preg_replace( "/\/$/", "", $this->options['prepend'] ) . "/"; - } - } - - /** - * This function is used to create a archive. - * - * @return boolean - */ - public function create_archive () - { - $this->make_list(); - if ($this->options['inmemory'] == 0) { - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - if ($this->options['overwrite'] == 0 && file_exists( $this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : "") )) { - $this->error[] = "File {$this->options['name']} already exist."; - chdir( $pwd ); - return 0; - } elseif ($this->archive = @fopen( $this->options['name'] . ($this->options['type'] == "gzip" || $this->options['type'] == "bzip" ? ".tmp" : ""), "wb+" )) { - chdir( $pwd ); - } else { - $this->error[] = "Could not open {$this->options['name']} for writing."; - chdir( $pwd ); - return 0; - } - } else { - $this->archive = ""; - } - switch ($this->options['type']) { - case "zip": - if (! $this->create_zip()) { - $this->error[] = "Could not create zip file."; - return 0; - } - break; - case "bzip": - if (! $this->create_tar()) { - $this->error[] = "Could not create tar file."; - return 0; - } - if (! $this->create_bzip()) { - $this->error[] = "Could not create bzip2 file."; - return 0; - } - break; - case "gzip": - if (! $this->create_tar()) { - $this->error[] = "Could not create tar file."; - return 0; - } - if (! $this->create_gzip()) { - $this->error[] = "Could not create gzip file."; - return 0; - } - break; - case "tar": - if (! $this->create_tar()) { - $this->error[] = "Could not create tar file."; - return 0; - } - } - if ($this->options['inmemory'] == 0) { - fclose( $this->archive ); - if ($this->options['type'] == "gzip" || $this->options['type'] == "bzip") { - unlink( $this->options['basedir'] . "/" . $this->options['name'] . ".tmp" ); - } - } - } - - /** - * This function is used for add data to a archive - * - * @param string $data - * @return void - */ - public function add_data ($data) - { - if ($this->options['inmemory'] == 0) { - fwrite( $this->archive, $data ); - } else { - $this->archive .= $data; - } - } - - /** - * This function make a list - * - * @return void - */ - public function make_list () - { - if (! empty( $this->exclude )) { - foreach ($this->files as $key => $value) { - foreach ($this->exclude as $current) { - if ($value['name'] == $current['name']) { - unset( $this->files[$key] ); - } - } - } - } - if (! empty( $this->storeonly )) { - foreach ($this->files as $key => $value) { - foreach ($this->storeonly as $current) { - if ($value['name'] == $current['name']) { - $this->files[$key]['method'] = 0; - } - } - } - } - unset( $this->exclude, $this->storeonly ); - } - - /** - * Add files a list - * - * @param array $list - * @return void - */ - public function add_files ($list) - { - $temp = $this->list_files( $list ); - foreach ($temp as $current) { - $this->files[] = $current; - } - } - - /** - * This function exclude files of a list - * - * @param array $list - * @return void - */ - public function exclude_files ($list) - { - $temp = $this->list_files( $list ); - foreach ($temp as $current) { - $this->exclude[] = $current; - } - } - - /** - * This function store files - * - * @param array $list - */ - public function store_files ($list) - { - $temp = $this->list_files( $list ); - foreach ($temp as $current) { - $this->storeonly[] = $current; - } - } - - /** - * List files gives a List - * - * @param array $list - * @return array - */ - public function list_files ($list) - { - if (! is_array( $list )) { - $temp = $list; - $list = array ($temp - ); - unset( $temp ); - } - $files = array (); - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - foreach ($list as $current) { - $current = str_replace( "\\", "/", $current ); - $current = preg_replace( "/\/+/", "/", $current ); - $current = preg_replace( "/\/$/", "", $current ); - if (strstr( $current, "*" )) { - $regex = preg_replace( "/([\\\^\$\.\[\]\|\(\)\?\+\{\}\/])/", "\\\\\\1", $current ); - $regex = str_replace( "*", ".*", $regex ); - $dir = strstr( $current, "/" ) ? substr( $current, 0, strrpos( $current, "/" ) ) : "."; - $temp = $this->parse_dir( $dir ); - foreach ($temp as $current2) { - if (preg_match( "/^{$regex}$/i", $current2['name'] )) { - $files[] = $current2; - } - } - unset( $regex, $dir, $temp, $current ); - } elseif (@is_dir( $current )) { - $temp = $this->parse_dir( $current ); - foreach ($temp as $file) { - $files[] = $file; - } - unset( $temp, $file ); - } elseif (@file_exists( $current )) { - $files[] = array ('name' => $current,'name2' => $this->options['prepend'] . preg_replace( "/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr( $current, "/" )) ? substr( $current, strrpos( $current, "/" ) + 1 ) : $current ),'type' => @is_link( $current ) && $this->options['followlinks'] == 0 ? 2 : 0,'ext' => substr( $current, strrpos( $current, "." ) ),'stat' => stat( $current ) - ); - } - } - chdir( $pwd ); - unset( $current, $pwd ); - usort( $files, array ("archive","sort_files" - ) ); - return $files; - } - - /** - * This function is for parse a directory name - * - * @param string $dirname - * @return array - */ - public function parse_dir ($dirname) - { - if ($this->options['storepaths'] == 1 && ! preg_match( "/^(\.+\/*)+$/", $dirname )) { - $files = array (array ('name' => $dirname,'name2' => $this->options['prepend'] . preg_replace( "/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr( $dirname, "/" )) ? substr( $dirname, strrpos( $dirname, "/" ) + 1 ) : $dirname ),'type' => 5,'stat' => stat( $dirname ) - ) - ); - } else { - $files = array (); - } - $dir = @opendir( $dirname ); - while ($file = @readdir( $dir )) { - $fullname = $dirname . "/" . $file; - if ($file == "." || $file == "..") { - continue; - } elseif (@is_dir( $fullname )) { - if (empty( $this->options['recurse'] )) { - continue; - } - $temp = $this->parse_dir( $fullname ); - foreach ($temp as $file2) { - $files[] = $file2; - } - } elseif (@file_exists( $fullname )) { - $files[] = array ('name' => $fullname,'name2' => $this->options['prepend'] . preg_replace( "/(\.+\/+)+/", "", ($this->options['storepaths'] == 0 && strstr( $fullname, "/" )) ? substr( $fullname, strrpos( $fullname, "/" ) + 1 ) : $fullname ),'type' => @is_link( $fullname ) && $this->options['followlinks'] == 0 ? 2 : 0,'ext' => substr( $file, strrpos( $file, "." ) ),'stat' => stat( $fullname ) - ); - } - } - @closedir( $dir ); - return $files; - } - - /** - * This function sort two files - * - * @param array $a - * @param array $b - * @return boolean - */ - public function sort_files ($a, $b) - { - if ($a['type'] != $b['type']) { - if ($a['type'] == 5 || $b['type'] == 2) { - return - 1; - } elseif ($a['type'] == 2 || $b['type'] == 5) { - return 1; - } elseif ($a['type'] == 5) { - return strcmp( strtolower( $a['name'] ), strtolower( $b['name'] ) ); - } elseif ($a['ext'] != $b['ext']) { - return strcmp( $a['ext'], $b['ext'] ); - } elseif ($a['stat'][7] != $b['stat'][7]) { - return $a['stat'][7] > $b['stat'][7] ? - 1 : 1; - } else { - return strcmp( strtolower( $a['name'] ), strtolower( $b['name'] ) ); - } - } - return 0; - } - - /** - * This function download a file - * - * @return void - */ - public function download_file () - { - if ($this->options['inmemory'] == 0) { - $this->error[] = "Can only use download_file() if archive is in memory. Redirect to file otherwise, it is faster."; - return; - } - switch ($this->options['type']) { - case "zip": - header( "Content-Type: application/zip" ); - break; - case "bzip": - header( "Content-Type: application/x-bzip2" ); - break; - case "gzip": - header( "Content-Type: application/x-gzip" ); - break; - case "tar": - header( "Content-Type: application/x-tar" ); - } - $header = "Content-Disposition: attachment; filename=\""; - $header .= strstr( $this->options['name'], "/" ) ? substr( $this->options['name'], strrpos( $this->options['name'], "/" ) + 1 ) : $this->options['name']; - $header .= "\""; - header( $header ); - header( "Content-Length: " . strlen( $this->archive ) ); - header( "Content-Transfer-Encoding: binary" ); - header( "Cache-Control: no-cache, must-revalidate, max-age=60" ); - header( "Expires: Sat, 01 Jan 2000 12:00:00 GMT" ); - print ($this->archive) ; - } -} - -/** - * This class is derived from the class archive, is imployed to use files . - * tar - * - * @package workflow.engine.classes - * - */ -class tar_file extends archive -{ - - /** - * This function is the constructor of the class tar_file - * - * @param string $name - */ - public function tar_file ($name) - { - $this->archive( $name ); - $this->options['type'] = "tar"; - } - - /** - * This function create a file . - * tar - * - * @return boolean - */ - public function create_tar () - { - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - foreach ($this->files as $current) { - if ($current['name'] == $this->options['name']) { - continue; - } - if (strlen( $current['name2'] ) > 99) { - $path = substr( $current['name2'], 0, strpos( $current['name2'], "/", strlen( $current['name2'] ) - 100 ) + 1 ); - $current['name2'] = substr( $current['name2'], strlen( $path ) ); - if (strlen( $path ) > 154 || strlen( $current['name2'] ) > 99) { - $this->error[] = "Could not add {$path}{$current['name2']} to archive because the filename is too long."; - continue; - } - } - $block = pack( "a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12", $current['name2'], sprintf( "%07o", $current['stat'][2] ), sprintf( "%07o", $current['stat'][4] ), sprintf( "%07o", $current['stat'][5] ), sprintf( "%011o", $current['type'] == 2 ? 0 : $current['stat'][7] ), sprintf( "%011o", $current['stat'][9] ), " ", $current['type'], $current['type'] == 2 ? @readlink( $current['name'] ) : "", "ustar ", " ", "Unknown", "Unknown", "", "", ! empty( $path ) ? $path : "", "" ); - $checksum = 0; - for ($i = 0; $i < 512; $i ++) { - $checksum += ord( substr( $block, $i, 1 ) ); - } - $checksum = pack( "a8", sprintf( "%07o", $checksum ) ); - $block = substr_replace( $block, $checksum, 148, 8 ); - if ($current['type'] == 2 || $current['stat'][7] == 0) { - $this->add_data( $block ); - } elseif ($fp = @fopen( $current['name'], "rb" )) { - $this->add_data( $block ); - while ($temp = fread( $fp, 1048576 )) { - $this->add_data( $temp ); - } - if ($current['stat'][7] % 512 > 0) { - $temp = ""; - for ($i = 0; $i < 512 - $current['stat'][7] % 512; $i ++) { - $temp .= "\0"; - } - $this->add_data( $temp ); - } - fclose( $fp ); - } else { - $this->error[] = "Could not open file {$current['name']} for reading. It was not added."; - } - } - $this->add_data( pack( "a1024", "" ) ); - chdir( $pwd ); - return 1; - } - - /** - * This function is used for extract files of the class tar_file - * - * @return void - */ - public function extract_files () - { - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - if ($fp = $this->open_archive()) { - if ($this->options['inmemory'] == 1) { - $this->files = array (); - } - while ($block = fread( $fp, 512 )) { - $temp = unpack( "a100name/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100symlink/a6magic/a2temp/a32temp/a32temp/a8temp/a8temp/a155prefix/a12temp", $block ); - $file = array ('name' => $this->options['basedir'] . '/' . $temp['prefix'] . $temp['name'],'stat' => array (2 => $temp['mode'],4 => octdec( $temp['uid'] ),5 => octdec( $temp['gid'] ),7 => octdec( $temp['size'] ),9 => octdec( $temp['mtime'] ) - ),'checksum' => octdec( $temp['checksum'] ),'type' => $temp['type'],'magic' => $temp['magic'] - ); - if ($file['checksum'] == 0x00000000) { - break; - } elseif (substr( $file['magic'], 0, 5 ) != "ustar") { - $this->error[] = "This script does not support extracting this type of tar file."; - break; - } - $block = substr_replace( $block, " ", 148, 8 ); - $checksum = 0; - for ($i = 0; $i < 512; $i ++) { - $checksum += ord( substr( $block, $i, 1 ) ); - } - if ($file['checksum'] != $checksum) { - $this->error[] = "Could not extract from {$this->options['name']}, it is corrupt."; - } - if ($this->options['inmemory'] == 1) { - $file['data'] = fread( $fp, $file['stat'][7] ); - fread( $fp, (512 - $file['stat'][7] % 512) == 512 ? 0 : (512 - $file['stat'][7] % 512) ); - unset( $file['checksum'], $file['magic'] ); - $this->files[] = $file; - } elseif ($file['type'] == 5) { - if (! is_dir( $file['name'] )) { - //mkdir($file['name'], $file['stat'][2]); - mkdir( $file['name'], 0775 ); - } - } elseif ($this->options['overwrite'] == 0 && file_exists( $file['name'] )) { - $this->error[] = "{$file['name']} already exist."; - continue; - } elseif ($file['type'] == 2) { - symlink( $temp['symlink'], $file['name'] ); - //chmod($file['name'], $file['stat'][2]); - } elseif ($new = @fopen( $file['name'], "wb" )) { - fwrite( $new, fread( $fp, $file['stat'][7] ) ); - if ((512 - $file['stat'][7] % 512) != 512) { - fread( $fp, (512 - $file['stat'][7] % 512) ); - } - //fread($fp, (512 - $file['stat'][7] % 512) == 512 ? 0 : (512 - $file['stat'][7] % 512)); - fclose( $new ); - //chmod($file['name'], $file['stat'][2]); - chmod( $file['name'], 0777 ); - $this->files[] = $file['name']; - } else { - $this->error[] = "Could not open {$file['name']} for writing."; - continue; - } - //chown($file['name'], $file['stat'][4]); - //chgrp($file['name'], $file['stat'][5]); - @touch( $file['name'], $file['stat'][9] ); - unset( $file ); - } - } else { - $this->error[] = "Could not open file {$this->options['name']}"; - } - chdir( $pwd ); - } - - /** - * This function open a archive of the class tar_file - * - * @return void - */ - public function open_archive () - { - return @fopen( $this->options['name'], "rb" ); - } -} - -/** - * This class is derived of the class archive, is employed to use archives . - * gzip - * - * @package workflow.engine.classes - * - */ -class gzip_file extends tar_file -{ - - /** - * This function is the constructor of the class gzip_file - * - * @param string $name - * @return void - */ - public function gzip_file ($name) - { - $this->tar_file( $name ); - $this->options['type'] = "gzip"; - } - - /** - * This function is employed to create files . - * gzip - * - * @return boolean - */ - public function create_gzip () - { - if ($this->options['inmemory'] == 0) { - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - if ($fp = gzopen( $this->options['name'], "wb{$this->options['level']}" )) { - fseek( $this->archive, 0 ); - while ($temp = fread( $this->archive, 1048576 )) { - gzwrite( $fp, $temp ); - } - gzclose( $fp ); - chdir( $pwd ); - } else { - $this->error[] = "Could not open {$this->options['name']} for writing."; - chdir( $pwd ); - return 0; - } - } else { - $this->archive = gzencode( $this->archive, $this->options['level'] ); - } - return 1; - } - - /** - * This function open a archive of the class gzip_file - * - * @return void - */ - public function open_archive () - { - return @gzopen( $this->options['name'], "rb" ); - } -} - -/** - * - * - * This class is derived from the class archive, is employed to use files .bzip - * - * @package workflow.engine.classes - * - */ -class bzip_file extends tar_file -{ - - /** - * This function is the constructor of the class bzip_file - * - * @param string $name - * @return void - */ - public function bzip_file ($name) - { - $this->tar_file( $name ); - $this->options['type'] = "bzip"; - } - - /** - * This function is employed to create files . - * bzip - * - * @return boolean - */ - public function create_bzip () - { - if ($this->options['inmemory'] == 0) { - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - if ($fp = bzopen( $this->options['name'], "wb" )) { - fseek( $this->archive, 0 ); - while ($temp = fread( $this->archive, 1048576 )) { - bzwrite( $fp, $temp ); - } - bzclose( $fp ); - chdir( $pwd ); - } else { - $this->error[] = "Could not open {$this->options['name']} for writing."; - chdir( $pwd ); - return 0; - } - } else { - $this->archive = bzcompress( $this->archive, $this->options['level'] ); - } - return 1; - } - - /** - * This function open a archive of the class bzip_file - * - * @return void - */ - public function open_archive () - { - return @bzopen( $this->options['name'], "rb" ); - } -} - -/** - * This class is derived from the class archive, is imployed to use files . - * zip - * - * @package workflow.engine.classes - */ - -class zip_file extends archive -{ - - public function zip_file ($name) - { - $this->archive( $name ); - $this->options['type'] = "zip"; - } - - /** - * This function is used to create archives . - * zip - * - * @return boolean - */ - public function create_zip () - { - $files = 0; - $offset = 0; - $central = ""; - if (! empty( $this->options['sfx'] )) { - if ($fp = @fopen( $this->options['sfx'], "rb" )) { - $temp = fread( $fp, filesize( $this->options['sfx'] ) ); - fclose( $fp ); - $this->add_data( $temp ); - $offset += strlen( $temp ); - unset( $temp ); - } else { - $this->error[] = "Could not open sfx module from {$this->options['sfx']}."; - } - } - $pwd = getcwd(); - chdir( $this->options['basedir'] ); - foreach ($this->files as $current) { - if ($current['name'] == $this->options['name']) { - continue; - } - $timedate = explode( " ", date( "Y n j G i s", $current['stat'][9] ) ); - $timedate = ($timedate[0] - 1980 << 25) | ($timedate[1] << 21) | ($timedate[2] << 16) | ($timedate[3] << 11) | ($timedate[4] << 5) | ($timedate[5]); - $block = pack( "VvvvV", 0x04034b50, 0x000A, 0x0000, (isset( $current['method'] ) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate ); - if ($current['stat'][7] == 0 && $current['type'] == 5) { - $block .= pack( "VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen( $current['name2'] ) + 1, 0x0000 ); - $block .= $current['name2'] . "/"; - $this->add_data( $block ); - $central .= pack( "VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset( $current['method'] ) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, 0x00000000, 0x00000000, 0x00000000, strlen( $current['name2'] ) + 1, 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset ); - $central .= $current['name2'] . "/"; - $files ++; - $offset += (31 + strlen( $current['name2'] )); - } elseif ($current['stat'][7] == 0) { - $block .= pack( "VVVvv", 0x00000000, 0x00000000, 0x00000000, strlen( $current['name2'] ), 0x0000 ); - $block .= $current['name2']; - $this->add_data( $block ); - $central .= pack( "VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset( $current['method'] ) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, 0x00000000, 0x00000000, 0x00000000, strlen( $current['name2'] ), 0x0000, 0x0000, 0x0000, 0x0000, $current['type'] == 5 ? 0x00000010 : 0x00000000, $offset ); - $central .= $current['name2']; - $files ++; - $offset += (30 + strlen( $current['name2'] )); - } elseif ($fp = @fopen( $current['name'], "rb" )) { - $temp = fread( $fp, $current['stat'][7] ); - fclose( $fp ); - $crc32 = G::encryptCrc32( $temp ); - if (! isset( $current['method'] ) && $this->options['method'] == 1) { - $temp = gzcompress( $temp, $this->options['level'] ); - $size = strlen( $temp ) - 6; - $temp = substr( $temp, 2, $size ); - } else { - $size = strlen( $temp ); - } - $block .= pack( "VVVvv", $crc32, $size, $current['stat'][7], strlen( $current['name2'] ), 0x0000 ); - $block .= $current['name2']; - $this->add_data( $block ); - $this->add_data( $temp ); - unset( $temp ); - $central .= pack( "VvvvvVVVVvvvvvVV", 0x02014b50, 0x0014, $this->options['method'] == 0 ? 0x0000 : 0x000A, 0x0000, (isset( $current['method'] ) || $this->options['method'] == 0) ? 0x0000 : 0x0008, $timedate, $crc32, $size, $current['stat'][7], strlen( $current['name2'] ), 0x0000, 0x0000, 0x0000, 0x0000, 0x00000000, $offset ); - $central .= $current['name2']; - $files ++; - $offset += (30 + strlen( $current['name2'] ) + $size); - } else { - $this->error[] = "Could not open file {$current['name']} for reading. It was not added."; - } - } - $this->add_data( $central ); - $this->add_data( pack( "VvvvvVVv", 0x06054b50, 0x0000, 0x0000, $files, $files, strlen( $central ), $offset, ! empty( $this->options['comment'] ) ? strlen( $this->options['comment'] ) : 0x0000 ) ); - if (! empty( $this->options['comment'] )) { - $this->add_data( $this->options['comment'] ); - } - chdir( $pwd ); - return 1; - } -} - diff --git a/workflow/engine/classes/class.multipleFilesBackup.php b/workflow/engine/classes/class.multipleFilesBackup.php deleted file mode 100644 index 0abedf4c2..000000000 --- a/workflow/engine/classes/class.multipleFilesBackup.php +++ /dev/null @@ -1,231 +0,0 @@ -filename = $filename; - } - if (! empty( $size ) && (int) $size > 0) { - $this->fileSize = $size; - } - } - - /* Gets workspace information enough to make its backup. - * @workspace contains the workspace to be add to the commpression process. - */ - public function addToBackup ($workspace) - { - //verifing if workspace exists. - if (! $workspace->workspaceExists()) { - echo "Workspace {$workspace->name} not found\n"; - return false; - } - //create destination path - if (! file_exists( PATH_DATA . "upgrade/" )) { - mkdir( PATH_DATA . "upgrade/" ); - } - $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); - mkdir( $tempDirectory ); - $metadata = $workspace->getMetadata(); - CLI::logging( "Creating temporary files on database...\n" ); - $metadata["databases"] = $workspace->exportDatabase( $tempDirectory ); - $metadata["directories"] = array ("{$workspace->name}"); - $metadata["version"] = 1; - $metaFilename = "$tempDirectory/{$workspace->name}.meta"; - if (! file_put_contents( $metaFilename, str_replace( array (",","{","}"), array (",\n ","{\n ","\n}\n"), G::json_encode( $metadata ) ) )) { - CLI::logging( "Could not create backup metadata" ); - } - CLI::logging( "Adding database to backup...\n" ); - $this->addDirToBackup( $tempDirectory ); - CLI::logging( "Adding files to backup...\n" ); - $this->addDirToBackup( $workspace->path ); - $this->tempDirectories[] = $tempDirectory; - } - - /* Add a directory containing Db files or info files to be commpressed - * @directory the name and path of the directory to be add to the commpression process. - */ - private function addDirToBackup ($directory) - { - if (! empty( $directory )) { - $this->dir_to_compress .= $directory . " "; - } - } - - // Commpress the DB and files into a single or several files with numerical series extentions - - public function letsBackup () - { - // creating command - $CommpressCommand = "tar czv "; - $CommpressCommand .= $this->dir_to_compress; - $CommpressCommand .= "| split -b "; - $CommpressCommand .= $this->fileSize; - $CommpressCommand .= "m -d - "; - $CommpressCommand .= $this->filename . "."; - //executing command to create the files - echo exec( $CommpressCommand ); - //Remove leftovers dirs. - foreach ($this->tempDirectories as $tempDirectory) { - CLI::logging( "Deleting: " . $tempDirectory . "\n" ); - G::rm_dir( $tempDirectory ); - } - } - /* Restore from file(s) commpressed by letsBackup function, into a temporary directory - * @ filename got the name and path of the compressed file(s), if there are many files with file extention as a numerical series, the extention should be discriminated. - * @ srcWorkspace contains the workspace to be restored. - * @ dstWorkspace contains the workspace to be overwriting. - * @ overwrite got the option true if the workspace will be overwrite. - */ - static public function letsRestore ($filename, $srcWorkspace, $dstWorkspace = null, $overwrite = true) - { - // Needed info: - // TEMPDIR /shared/workflow_data/upgrade/ - // BACKUPS /shared/workflow_data/backups/ - // Creating command cat myfiles_split.tgz_* | tar xz - $DecommpressCommand = "cat " . $filename . ".* "; - $DecommpressCommand .= " | tar xzv"; - - $tempDirectory = PATH_DATA . "upgrade/" . basename( tempnam( __FILE__, '' ) ); - $tempDirectoryHelp = $tempDirectory; - - $parentDirectory = PATH_DATA . "upgrade"; - if (is_writable( $parentDirectory )) { - mkdir( $tempDirectory ); - } else { - throw new Exception( "Could not create directory:" . $parentDirectory ); - } - //Extract all backup files, including database scripts and workspace files - CLI::logging( "Restoring into " . $tempDirectory . "\n" ); - chdir( $tempDirectory ); - echo exec( $DecommpressCommand ); - CLI::logging( "\nUncompressed into: " . $tempDirectory . "\n" ); - - //Search for metafiles in the new standard (the old standard would contain meta files. - $decommpressedfile = scandir($tempDirectoryHelp.dirname($tempDirectoryHelp), 1); - $tempDirectory = $tempDirectoryHelp.dirname($tempDirectoryHelp)."/".$decommpressedfile[0]; - - $metaFiles = glob( $tempDirectory . "/*.meta" ); - if (empty( $metaFiles )) { - $metaFiles = glob( $tempDirectory . "/*.txt" ); - if (! empty( $metaFiles )) { - return workspaceTools::restoreLegacy( $tempDirectory ); - } else { - throw new Exception( "No metadata found in backup" ); - } - } else { - CLI::logging( "Found " . count( $metaFiles ) . " workspaces in backup:\n" ); - foreach ($metaFiles as $metafile) { - CLI::logging( "-> " . basename( $metafile ) . "\n" ); - } - } - if (count( $metaFiles ) > 1 && (! isset( $srcWorkspace ))) { - throw new Exception( "Multiple workspaces in backup but no workspace specified to restore" ); - } - if (isset( $srcWorkspace ) && ! in_array( "$srcWorkspace.meta", array_map( basename, $metaFiles ) )) { - throw new Exception( "Workspace $srcWorkspace not found in backup" ); - } - foreach ($metaFiles as $metaFile) { - $metadata = G::json_decode( file_get_contents( $metaFile ) ); - if ($metadata->version != 1) { - throw new Exception( "Backup version {$metadata->version} not supported" ); - } - $backupWorkspace = $metadata->WORKSPACE_NAME; - if (isset( $dstWorkspace )) { - $workspaceName = $dstWorkspace; - $createWorkspace = true; - } else { - $workspaceName = $metadata->WORKSPACE_NAME; - $createWorkspace = false; - } - if (isset( $srcWorkspace ) && strcmp( $metadata->WORKSPACE_NAME, $srcWorkspace ) != 0) { - CLI::logging( CLI::warning( "> Workspace $backupWorkspace found, but not restoring." ) . "\n" ); - continue; - } else { - CLI::logging( "> Restoring " . CLI::info( $backupWorkspace ) . " to " . CLI::info( $workspaceName ) . "\n" ); - } - $workspace = new workspaceTools( $workspaceName ); - if ($workspace->workspaceExists()) { - if ($overwrite) { - CLI::logging( CLI::warning( "> Workspace $workspaceName already exist, overwriting!" ) . "\n" ); - } else { - throw new Exception( "Destination workspace already exist (use -o to overwrite)" ); - } - } - if (file_exists( $workspace->path )) { - G::rm_dir( $workspace->path ); - } - - $tempDirectorySite = $tempDirectoryHelp.dirname($workspace->path); - - foreach ($metadata->directories as $dir) { - CLI::logging( "+> Restoring directory '$dir'\n" ); - if (! rename( "$tempDirectorySite/$dir", $workspace->path )) { - throw new Exception( "There was an error copying the backup files ($tempDirectory/$dir) to the workspace directory {$workspace->path}." ); - } - } - - CLI::logging( "> Changing file permissions\n" ); - $shared_stat = stat( PATH_DATA ); - if ($shared_stat !== false) { - workspaceTools::dirPerms( $workspace->path, $shared_stat['uid'], $shared_stat['gid'], $shared_stat['mode'] ); - } else { - CLI::logging( CLI::error( "Could not get the shared folder permissions, not changing workspace permissions" ) . "\n" ); - } - - list ($dbHost, $dbUser, $dbPass) = @explode( SYSTEM_HASH, G::decrypt( HASH_INSTALLATION, SYSTEM_HASH ) ); - - CLI::logging( "> Connecting to system database in '$dbHost'\n" ); - $link = mysql_connect( $dbHost, $dbUser, $dbPass ); - @mysql_query( "SET NAMES 'utf8';" ); - @mysql_query( "SET FOREIGN_KEY_CHECKS=0;" ); - if (! $link) { - throw new Exception( 'Could not connect to system database: ' . mysql_error() ); - } - - if (strpos($metadata->DB_RBAC_NAME, 'rb_') === false) { - $onedb = true; - } else { - $onedb = false; - } - - $newDBNames = $workspace->resetDBInfo( $dbHost, $createWorkspace, $onedb ); - $aParameters = array('dbHost'=>$dbHost,'dbUser'=>$dbUser,'dbPass'=>$dbPass); - - foreach ($metadata->databases as $db) { - $dbName = $newDBNames[$db->name]; - CLI::logging( "+> Restoring database {$db->name} to $dbName\n" ); - $workspace->executeSQLScript( $dbName, "$tempDirectory/{$db->name}.sql", $aParameters ); - $workspace->createDBUser( $dbName, $db->pass, "localhost", $dbName ); - $workspace->createDBUser( $dbName, $db->pass, "%", $dbName ); - } - $workspace->upgradeCacheView( false ); - mysql_close( $link ); - - } - CLI::logging( "Removing temporary files\n" ); - G::rm_dir( $tempDirectory ); - CLI::logging( CLI::info( "Done restoring" ) . "\n" ); - } -} - diff --git a/workflow/engine/classes/class.plugin.php b/workflow/engine/classes/class.plugin.php index 3b70a555f..49affd971 100644 --- a/workflow/engine/classes/class.plugin.php +++ b/workflow/engine/classes/class.plugin.php @@ -25,7 +25,6 @@ use ProcessMaker\Plugins\PluginRegistry; -require_once 'class.pluginRegistry.php'; define('G_PLUGIN_CLASS', 1); define('PM_CREATE_CASE', 1001); diff --git a/workflow/engine/classes/class.pmFunctions.php b/workflow/engine/classes/class.pmFunctions.php index 84ddbd6b0..11cde69cd 100644 --- a/workflow/engine/classes/class.pmFunctions.php +++ b/workflow/engine/classes/class.pmFunctions.php @@ -28,6 +28,7 @@ // // License: LGPL, see LICENSE //////////////////////////////////////////////////// +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Util\ElementTranslation; @@ -242,7 +243,7 @@ function executeQuery ($SqlStatement, $DBConnectionUID = 'workflow', $aParameter $aContext = \Bootstrap::getDefaultContextLog(); $con = Propel::getConnection( $DBConnectionUID ); $con->begin(); - $blackList = PmSystem::getQueryBlackList(); + $blackList = System::getQueryBlackList(); $aListQueries = explode('|', $blackList['queries']); $aListAllTables = explode( '|', @@ -903,7 +904,7 @@ function WSProcessList () //private function to get current email configuration function getEmailConfiguration () { - return PmSystem::getEmailConfiguration(); + return System::getEmailConfiguration(); } /** @@ -960,7 +961,7 @@ function PMFSendMessage( } } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->sendMessage( $caseId, $sFrom, @@ -1558,7 +1559,7 @@ function WSAddCaseNote($caseUid, $processUid, $taskUid, $userUid, $note, $sendMa */ function PMFTaskCase ($caseId) //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->taskCase( $caseId ); $rows = Array (); $i = 1; @@ -1586,7 +1587,7 @@ function PMFTaskCase ($caseId) //its test was successfull */ function PMFTaskList ($userId) //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->taskList( $userId ); $rows = Array (); $i = 1; @@ -1613,7 +1614,7 @@ function PMFTaskList ($userId) //its test was successfull */ function PMFUserList () //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->userList(); $rows = Array (); $i = 1; @@ -1920,7 +1921,7 @@ function PMFGenerateOutputDocument ($outputID, $sApplication = null, $index = nu */ function PMFGroupList ($regex = null, $start = null, $limit = null) //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->groupList($regex, $start, $limit); $rows = array(); if ($result) { @@ -1944,7 +1945,7 @@ function PMFGroupList ($regex = null, $start = null, $limit = null) //its test w */ function PMFRoleList () //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->roleList(); $rows = Array (); $i = 1; @@ -1972,7 +1973,7 @@ function PMFRoleList () //its test was successfull */ function PMFCaseList ($userId) //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->caseList( $userId ); $rows = Array (); $i = 1; @@ -1999,7 +2000,7 @@ function PMFCaseList ($userId) //its test was successfull */ function PMFProcessList () //its test was successfull { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->processList(); $rows = Array (); $i = 1; @@ -2028,7 +2029,7 @@ function PMFProcessList () //its test was successfull */ function PMFSendVariables ($caseId, $variables) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->sendVariables( $caseId, $variables ); if ($result->status_code == 0) { @@ -2071,7 +2072,7 @@ function PMFDerivateCase ($caseId, $delIndex, $bExecuteTriggersBeforeAssignment $sUserLogged = $_SESSION['USER_LOGGED']; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->derivateCase( $sUserLogged, $caseId, $delIndex, $bExecuteTriggersBeforeAssignment ); if (is_array($result)) { $result = (object)$result; @@ -2103,7 +2104,7 @@ function PMFDerivateCase ($caseId, $delIndex, $bExecuteTriggersBeforeAssignment */ function PMFNewCaseImpersonate ($processId, $userId, $variables, $taskId = '') { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->newCaseImpersonate( $processId, $userId, $variables, $taskId); if ($result->status_code == 0) { @@ -2133,7 +2134,7 @@ function PMFNewCaseImpersonate ($processId, $userId, $variables, $taskId = '') */ function PMFNewCase ($processId, $userId, $taskId, $variables, $status = null) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->newCase($processId, $userId, $taskId, $variables, 0, $status); @@ -2163,7 +2164,7 @@ function PMFNewCase ($processId, $userId, $taskId, $variables, $status = null) */ function PMFAssignUserToGroup ($userId, $groupId) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->assignUserToGroup( $userId, $groupId ); if ($result->status_code == 0) { @@ -2196,7 +2197,7 @@ function PMFAssignUserToGroup ($userId, $groupId) */ function PMFCreateUser ($userId, $password, $firstname, $lastname, $email, $role, $dueDate = null, $status = null) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->createUser( $userId, $firstname, $lastname, $email, $role, $password, $dueDate, $status ); //When the user is created the $result parameter is an array, in other case is a object exception @@ -2235,7 +2236,7 @@ function PMFCreateUser ($userId, $password, $firstname, $lastname, $email, $role */ function PMFUpdateUser ($userUid, $userName, $firstName = null, $lastName = null, $email = null, $dueDate = null, $status = null, $role = null, $password = null) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->updateUser( $userUid, $userName, $firstName, $lastName, $email, $dueDate, $status, $role, $password ); if ($result->status_code == 0) { @@ -2261,7 +2262,7 @@ function PMFUpdateUser ($userUid, $userName, $firstName = null, $lastName = null */ function PMFInformationUser($userUid) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->informationUser($userUid); $info = array(); @@ -2387,7 +2388,7 @@ function PMFgetLabelOption ($PROCESS, $DYNAFORM_UID, $FIELD_NAME, $FIELD_SELECTE { $data = array(); $data["CURRENT_DYNAFORM"] = $DYNAFORM_UID; - $dynaform = new pmDynaform($data); + $dynaform = new PmDynaform($data); if ($dynaform->isResponsive()) { $json = $dynaform->searchFieldByName($DYNAFORM_UID, $FIELD_NAME); $options = $json->options + $json->optionsSql; @@ -2735,7 +2736,7 @@ function PMFGetCaseNotes ($applicationID, $type = 'array', $userUid = '') */ function PMFDeleteCase ($caseUid) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->deleteCase( $caseUid ); if ($result->status_code == 0) { @@ -2763,7 +2764,7 @@ function PMFDeleteCase ($caseUid) */ function PMFCancelCase ($caseUid, $delIndex, $userUid) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->cancelCase( $caseUid, $delIndex, $userUid ); if ($result->status_code == 0) { @@ -2773,7 +2774,7 @@ function PMFCancelCase ($caseUid, $delIndex, $userUid) G::header('Location: ../cases/casesListExtJsRedirector'); die(); } else { - die(__('ID_PM_FUNCTION_CHANGE_CASE', SYS_LANG, array('PMFCancelCase', G::LoadTranslation('ID_CANCELLED')))); + die(G::LoadTranslation('ID_PM_FUNCTION_CHANGE_CASE', SYS_LANG, array('PMFCancelCase', G::LoadTranslation('ID_CANCELLED')))); } } } @@ -2802,7 +2803,7 @@ function PMFCancelCase ($caseUid, $delIndex, $userUid) */ function PMFPauseCase ($caseUid, $delIndex, $userUid, $unpauseDate = null) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->pauseCase($caseUid, $delIndex, $userUid, $unpauseDate); if ($result->status_code == 0) { @@ -2812,7 +2813,7 @@ function PMFPauseCase ($caseUid, $delIndex, $userUid, $unpauseDate = null) G::header('Location: ../cases/casesListExtJsRedirector'); die(); } else { - die(__('ID_PM_FUNCTION_CHANGE_CASE', SYS_LANG, array('PMFPauseCase', G::LoadTranslation('ID_PAUSED')))); + die(G::LoadTranslation('ID_PM_FUNCTION_CHANGE_CASE', SYS_LANG, array('PMFPauseCase', G::LoadTranslation('ID_PAUSED')))); } } } @@ -2840,7 +2841,7 @@ function PMFPauseCase ($caseUid, $delIndex, $userUid, $unpauseDate = null) */ function PMFUnpauseCase ($caseUid, $delIndex, $userUid) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->unpauseCase( $caseUid, $delIndex, $userUid ); if ($result->status_code == 0) { @@ -2871,7 +2872,7 @@ function PMFUnpauseCase ($caseUid, $delIndex, $userUid) */ function PMFAddCaseNote($caseUid, $processUid, $taskUid, $userUid, $note, $sendMail = 1) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->addCaseNote($caseUid, $processUid, $taskUid, $userUid, $note, $sendMail); if ($result->status_code == 0) { @@ -2970,7 +2971,7 @@ function PMFSaveCurrentData () $response = 0; if (isset($_SESSION['APPLICATION']) && isset($oPMScript->aFields)) { - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->sendVariables($_SESSION['APPLICATION'], $oPMScript->aFields); $response = $result->status_code == 0 ? 1 : 0; } @@ -3127,7 +3128,7 @@ function PMFDynaFormFields($dynUid, $appUid = false, $delIndex = 0) } $data["CURRENT_DYNAFORM"] = $dynUid; - $dynaform = new pmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($data)); + $dynaform = new PmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($data)); $dynaform->onPropertyRead = function(&$json, $key, $value) { if (isset($json->data) && !isset($json->value)) { $json->value = $json->data->value; diff --git a/workflow/engine/classes/class.pmPhing.php b/workflow/engine/classes/class.pmPhing.php deleted file mode 100644 index 4f482e27a..000000000 --- a/workflow/engine/classes/class.pmPhing.php +++ /dev/null @@ -1,49 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * Phing Class Wrapper - * - * @author Erik Amaru Ortiz - */ - -include_once 'phing/Phing.php'; -set_include_path( PATH_THIRDPARTY . 'propel-generator/classes/' . PATH_SEPARATOR . get_include_path() ); - -if (! class_exists( 'Phing' )) { - throw new Exception( 'Fatal Error: Phing is not loaded!' ); -} - -class pmPhing extends Phing -{ - - public function getPhingVersion () - { - return 'pmPhing Ver 1.0'; - } -} - diff --git a/workflow/engine/classes/class.popupMenu.php b/workflow/engine/classes/class.popupMenu.php deleted file mode 100644 index 7739ddc89..000000000 --- a/workflow/engine/classes/class.popupMenu.php +++ /dev/null @@ -1,99 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * popupMenu - popupMenu class - * - * @package workflow.engine.ProcessMaker - * @copyright COLOSA - */ - -class popupMenu extends form -{ - var $type = 'popupMenu'; - var $theme = 'processmaker'; - - /** - * Print the popup - * - * @param string $tableId - * @param array $tableFields - * @return array - */ - function renderPopup ($tableId, $tableFields) - { - $this->name = $tableId; - $fields = array_keys( $tableFields ); - foreach ($fields as $f) { - switch (strtolower( $tableFields[$f]['Type'] )) { - case 'javascript': - case 'button': - case 'private': - case 'hidden': - case 'cellmark': - break; - default: - $label = ($tableFields[$f]['Label'] != '') ? $tableFields[$f]['Label'] : $f; - $label = str_replace( "\n", ' ', $label ); - $pmXmlNode = new Xml_Node( $f, 'complete', '', array ('label' => $label,'type' => 'popupOption','launch' => $tableId . '.showHideField("' . $f . '")' - ) ); - $this->fields[$f] = new XmlForm_Field_popupOption( $pmXmlNode ); - $this->values[$f] = ''; - } - } - $scTemp = ''; - $this->values['PAGED_TABLE_ID'] = $tableId; - print (parent::render( PATH_CORE . 'templates/popupMenu.html', $scTemp )) ; - $sc = ""; - return $sc; - } -} - -/** - * XmlForm_Field_popupOption - XmlForm_Field_popupOption class - * - * @package workflow.engine.ProcessMaker - * @copyright COLOSA - */ - -class XmlForm_Field_popupOption extends XmlForm_Field -{ - var $launch = ''; - - /** - * Get Events - * - * @return string - */ - function getEvents () - { - $script = '{name:"' . $this->name . '",text:"' . addcslashes( $this->label, '\\"' ) . '", launch:leimnud.closure({Function:function(target){' . $this->launch . '}, args:target})}'; - return $script; - } -} - diff --git a/workflow/engine/classes/class.report.php b/workflow/engine/classes/class.report.php deleted file mode 100644 index 9aafbe2fb..000000000 --- a/workflow/engine/classes/class.report.php +++ /dev/null @@ -1,855 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * Report - Report class - * - * @package workflow.engine.ProcessMaker - * @author Everth S. Berrios Morales - * @copyright 2008 COLOSA - */ - -class Report -{ - - /** - * This function does a sql statment to a report - * - * - * @name generatedReport1 - * - * param - * @return object - */ - public function generatedReport1 () - { - $this->reportsPatch(); - - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); - - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - while ($aRow = $oDataset->getRow()) { - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - - $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => ApplicationPeer::doCount( $oCriteria ),'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 ) - ); - $oDataset->next(); - } - - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function does a sql statment to a report wiht a condition - * or maybe when you're looking for some specials cases - * - * @name generatedReport1_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - public function generatedReport1_filter ($from, $to, $startedby) - { - $this->reportsPatch(); - - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( UsersPeer::USR_UID ); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addJoin (AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); - $oCriteria->addJoin( AppDelegationPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN ); - //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $from, Criteria::GREATER_EQUAL); - //$oCriteria->add(AppDelegationPeer::DEL_DURATION, $to, Criteria::LESS_EQUAL); - //$aAux1 = explode('-', $from); date('Y-m-d H:i:s', mktime(0, 0, 0, $aAux1[1], $aAux1[2], $aAux1[0])) - $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); - - if ($startedby != '') { - $oCriteria->add( ApplicationPeer::APP_INIT_USER, $startedby ); - } - - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); - - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - - $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - while ($aRow = $oDataset->getRow()) { - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - if ($startedby != '') { - $oCriteria->add( ApplicationPeer::APP_INIT_USER, $startedby ); - } - - $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => ApplicationPeer::doCount( $oCriteria ),'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 )); - $oDataset->next(); - } - - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function gets info about a report - * - * - * @name descriptionReport1 - * - * @param string $PRO_UID - * @return object - */ - public function descriptionReport1 ($PRO_UID) - { - $this->reportsPatch(); - - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Task.php'; - require_once 'classes/model/Content.php'; - - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn( TaskPeer::TAS_TITLE ); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - - $oCriteria->addJoin( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN ); - $oCriteria->add( AppDelegationPeer::PRO_UID, $PRO_UID ); - - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addGroupByColumn( TaskPeer::TAS_TITLE ); - - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - - $aProcess[] = array ('TAS_TITLE' => 'char','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - while ($aRow = $oDataset->getRow()) { - $aProcess[] = array ('TAS_TITLE' => $aRow['TAS_TITLE'],'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'TOTALDUR' => number_format( $aRow['TOTALDUR'], 2 ),'PROMEDIO' => number_format( $aRow['PROMEDIO'], 2 ) - ); - $oDataset->next(); - } - - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function generates a other kind of report - * - * - * @name generatedReport2 - * - * param - * @return object - */ - public function generatedReport2 () - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addJoin (AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - - $month = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 1, date( "d" ), date( "Y" ) ) ); - $lastmonth = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 2, date( "d" ), date( "Y" ) ) ); - - $day = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 1, date( "Y" ) ); - $lastday = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 2, date( "Y" ) ); - - $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','CASELASTMONTH' => 'integer','CASELASTDAY' => 'integer' - ); - - while ($aRow = $oDataset->getRow()) { - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL ); - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant1 = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL ); - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant2 = $aRow2['CANTCASES']; - - $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => $cant,'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'CASELASTMONTH' => number_format( $cant1, 2 ),'CASELASTDAY' => number_format( $cant2, 2 ) - ); - $oDataset->next(); - } - - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; - } - - /** - * This function generates the description about a report - * - * - * @name reports_Description_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @param string $PRO_UID - * @return object - */ - public function reports_Description_filter ($from, $to, $startedby, $PRO_UID) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Task.php'; - require_once 'classes/model/Content.php'; - require_once 'classes/model/Users.php'; - - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn( TaskPeer::TAS_TITLE ); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "TOTALDUR", "SUM(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "PROMEDIO", "AVG(" . AppDelegationPeer::DEL_DURATION . ")" ); - - $oCriteria->addJoin( AppDelegationPeer::TAS_UID, TaskPeer::TAS_UID, Criteria::LEFT_JOIN ); - $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); - - if ($startedby != '') { - $oCriteria->add( AppDelegationPeer::USR_UID, $startedby ); - } - - $oCriteria->add( AppDelegationPeer::PRO_UID, $PRO_UID ); - - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addGroupByColumn( TaskPeer::TAS_TITLE ); - - return $oCriteria; - } - - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport2_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - public function generatedReport2_filter ($from, $to, $startedby) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Users.php'; - - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addSelectColumn(ProcessPeer::PRO_TITLE); - $oCriteria->addAsColumn( "MIN", "MIN(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addAsColumn( "MAX", "MAX(" . AppDelegationPeer::DEL_DURATION . ")" ); - $oCriteria->addJoin(AppDelegationPeer::PRO_UID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); - $oCriteria->addGroupByColumn( AppDelegationPeer::PRO_UID ); - $oCriteria->addGroupByColumn(ProcessPeer::PRO_TITLE); - - $oCriteria->add( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $from . ' 00:00:00', Criteria::GREATER_EQUAL )->addAnd( $oCriteria->getNewCriterion( AppDelegationPeer::DEL_INIT_DATE, $to . ' 23:59:59', Criteria::LESS_EQUAL ) ) ); - - if ($startedby != '') { - $oCriteria->add( AppDelegationPeer::USR_UID, $startedby ); - } - - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - - $month = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 1, date( "d" ), date( "Y" ) ) ); - $lastmonth = date( 'Y-m-d', mktime( 0, 0, 0, date( "m" ) - 2, date( "d" ), date( "Y" ) ) ); - $day = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 1, date( "Y" ) ); - $lastday = mktime( 0, 0, 0, date( "m" ), date( "d" ) - 2, date( "Y" ) ); - $aProcess[] = array ('PRO_UID' => 'char','PRO_TITLE' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','CASELASTMONTH' => 'integer','CASELASTDAY' => 'integer'); - - while ($aRow = $oDataset->getRow()) { - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - if ($startedby != '') { - $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); - } - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastmonth, Criteria::GREATER_EQUAL ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $month, Criteria::LESS_EQUAL ); - if ($startedby != '') { - $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); - } - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant1 = $aRow2['CANTCASES']; - - $oCriteria2 = new Criteria( 'workflow' ); - $oCriteria2->addSelectColumn( ApplicationPeer::PRO_UID ); - $oCriteria2->addAsColumn( "CANTCASES", "COUNT(*)" ); - $oCriteria2->add( ApplicationPeer::PRO_UID, $aRow['PRO_UID'] ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $lastday, Criteria::GREATER_EQUAL ); - $oCriteria2->add( ApplicationPeer::APP_INIT_DATE, $day, Criteria::LESS_EQUAL ); - if ($startedby != '') { - $oCriteria2->add( ApplicationPeer::APP_INIT_USER, $startedby ); - } - $oCriteria2->addGroupByColumn( ApplicationPeer::PRO_UID ); - $oDataset2 = AppDelegationPeer::doSelectRS( $oCriteria2 ); - $oDataset2->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset2->next(); - $aRow2 = $oDataset2->getRow(); - $cant2 = $aRow2['CANTCASES']; - - /*$aProcess[] = array('PRO_UID' => $aRow['PRO_UID'], - 'PRO_TITLE' => $aRow['PRO_TITLE'], - 'CANTCASES' => $cant, - 'CASELASTMONTH' => $cant1, - 'CASELASTDAY' => $cant2 - );*/ - $aProcess[] = array ('PRO_UID' => $aRow['PRO_UID'],'PRO_TITLE' => $aRow['PRO_TITLE'],'CANTCASES' => $cant,'MIN' => number_format( $aRow['MIN'], 2 ),'MAX' => number_format( $aRow['MAX'], 2 ),'CASELASTMONTH' => number_format( $cant1, 2 ),'CASELASTDAY' => number_format( $cant2, 2 )); - $oDataset->next(); - } - - global $_DBArray; - $_DBArray['reports'] = $aProcess; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - return $oCriteria; - } - - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport2_filter - * - * @param string $from - * @param string $to - * @param string $startedby - * @return object - */ - public function generatedReport3 () - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, - COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APP_DELEGATION AS AD - LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) - WHERE AD.APP_UID<>'' AND P.PRO_STATUS<>'DISABLED' - GROUP BY FECHA"; - - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - - $ROW[] = array ('FECHA' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float'); - - while ($rs->next()) { - $ROW[] = array ('FECHA' => $rs->getString( 'FECHA' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 )); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - - } - - /** - * This function looks for an special case it has a condition - * - * - * @name generatedReport3_filter - * - * @param string $process - * @param string $task - * @return object - */ - public function generatedReport3_filter ($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - if ($process == '') { - $var = " WHERE P.PRO_STATUS<>'DISABLED'"; - } else { - if ($task == '') { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "'"; - } else { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE P.PRO_STATUS<>'DISABLED' AND AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; - } - } - $sql = "SELECT CONCAT(SUBSTRING(AD.DEL_INIT_DATE,6,2),'-', SUBSTRING(AD.DEL_INIT_DATE,1,4)) AS FECHA, - COUNT(DISTINCT(AD.APP_UID)) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APP_DELEGATION AS AD - LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) - " . $var . " - GROUP BY FECHA"; - - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - $ROW[] = array ('FECHA' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float'); - - while ($rs->next()) { - $ROW[] = array ('FECHA' => $rs->getString( 'FECHA' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 )); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function generates a report - * - * - * @name generatedReport4 - * - * param - * @return object - */ - public function generatedReport4 () - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, - COUNT(*) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APPLICATION AS A - LEFT JOIN APP_DELEGATION AS AD ON(A.APP_UID = AD.APP_UID AND AD.DEL_INDEX=1) - LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) - WHERE A.APP_UID<>'' - GROUP BY USER"; - // AND P.PRO_STATUS<>'DISABLED' that hapens when it is created to new version it exists at the moment to import - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - - $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - - while ($rs->next()) { - $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) - ); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - - } - - /** - * This function generates a filter to report 4 - * - * - * @name generatedReport4_filter - * - * @param string process - * @param string task - * @return object - */ - public function generatedReport4_filter ($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - if ($process == '') { - $var = " "; - } else { - if ($task == '') { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='" . $process . "'"; - } else { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; - } - } - - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, - COUNT(*) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APPLICATION AS A - LEFT JOIN APP_DELEGATION AS AD ON(A.APP_UID = AD.APP_UID AND AD.DEL_INDEX=1) - LEFT JOIN USERS AS U ON(U.USR_UID = A.APP_INIT_USER) - " . $var . " - GROUP BY USER"; - - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - - $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - - while ($rs->next()) { - $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) - ); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function generates a Report - * - * - * @name generatedReport4_filter - * - * @param string process - * @param string task - * @return object - */ - public function generatedReport5 () - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, - COUNT(*) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APP_DELEGATION AS AD - LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) - LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) - WHERE AD.APP_UID<>'' AND AD.DEL_FINISH_DATE IS NULL - GROUP BY USER"; - - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - - $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - - while ($rs->next()) { - $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) - ); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - - } - - /** - * This function generates a filter to report 5 - * - * - * @name generatedReport5_filter - * - * @param string process - * @param string task - * @return object - */ - public function generatedReport5_filter ($process, $task) - { - $this->reportsPatch(); - require_once 'classes/model/AppDelegation.php'; - require_once 'classes/model/Application.php'; - require_once 'classes/model/Process.php'; - require_once 'classes/model/Users.php'; - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - if ($process == '') { - $var = " WHERE AD.DEL_FINISH_DATE IS NULL"; - } else { - if ($task == '') { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='" . $process . "' AND AD.DEL_FINISH_DATE IS NULL"; - } else { - $var = " LEFT JOIN TASK AS T ON (AD.TAS_UID = T.TAS_UID) - WHERE AD.PRO_UID='" . $process . "' AND AD.TAS_UID='" . $task . "' "; - } - } - $sql = "SELECT CONCAT(U.USR_LASTNAME,' ',USR_FIRSTNAME) AS USER, - COUNT(*) AS CANTCASES, - MIN(AD.DEL_DURATION) AS MIN, - MAX(AD.DEL_DURATION) AS MAX, - SUM(AD.DEL_DURATION) AS TOTALDUR, - AVG(AD.DEL_DURATION) AS PROMEDIO - FROM APP_DELEGATION AS AD - LEFT JOIN PROCESS AS P ON (P.PRO_UID = AD.PRO_UID) - LEFT JOIN USERS AS U ON(U.USR_UID = AD.USR_UID) - " . $var . " - GROUP BY USER"; - - $con = Propel::getConnection( "workflow" ); - $stmt = $con->prepareStatement( $sql ); - $rs = $stmt->executeQuery(); - - $ROW[] = array ('USER' => 'char','CANTCASES' => 'integer','MIN' => 'float','MAX' => 'float','TOTALDUR' => 'float','PROMEDIO' => 'float' - ); - - while ($rs->next()) { - $ROW[] = array ('USER' => $rs->getString( 'USER' ),'CANTCASES' => $rs->getString( 'CANTCASES' ),'MIN' => number_format( $rs->getString( 'MIN' ), 2 ),'MAX' => number_format( $rs->getString( 'MAX' ), 2 ),'TOTALDUR' => number_format( $rs->getString( 'TOTALDUR' ), 2 ),'PROMEDIO' => number_format( $rs->getString( 'PROMEDIO' ), 2 ) - ); - } - - global $_DBArray; - $_DBArray['reports'] = $ROW; - $_SESSION['_DBArray'] = $_DBArray; - $oCriteria = new Criteria( 'dbarray' ); - $oCriteria->setDBArrayTable( 'reports' ); - - return $oCriteria; - } - - /** - * This function returns an array, it has the reports' names - * - * - * @name getAvailableReports - * - * param - * @return array - */ - public function getAvailableReports () - { - return array ('ID_REPORT1','ID_REPORT2','ID_REPORT3','ID_REPORT4','ID_REPORT5' - ); - } - - /** - * Patch for reports by The Answer (17-10-2k8) - * - * - * @name reportsPatch - * - * param - * @return void - */ - - public function reportsPatch () - { - require_once 'classes/model/AppDelegation.php'; - - $oCriteria = new Criteria( 'workflow' ); - $del = DBAdapter::getStringDelimiter(); - $oCriteria->addSelectColumn( AppDelegationPeer::APP_UID ); - $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INDEX ); - $oCriteria->addSelectColumn( AppDelegationPeer::TAS_UID ); - $oCriteria->addSelectColumn( AppDelegationPeer::DEL_DELEGATE_DATE ); - $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INIT_DATE ); - $oCriteria->addSelectColumn( AppDelegationPeer::DEL_FINISH_DATE ); - $oCriteria->addSelectColumn( AppDelegationPeer::DEL_DURATION ); - $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $oAppDelegation = new AppDelegation(); - - $aData['APP_UID'] = $aRow['APP_UID']; - $aData['DEL_INDEX'] = $aRow['DEL_INDEX']; - $aData['DEL_DELEGATE_DATE'] = $aRow['DEL_DELEGATE_DATE']; - - if ($aRow['DEL_INIT_DATE'] == null) { - $aData['DEL_INIT_DATE'] = $aRow['DEL_DELEGATE_DATE']; - } else { - $aData['DEL_INIT_DATE'] = $aRow['DEL_INIT_DATE']; - } - //$aData['DEL_FINISH_DATE']=$aRow['DEL_FINISH_DATE']; - if ($aRow['DEL_DURATION'] != 0) { - $oDates = new dates(); - $aData['DEL_DURATION'] = $oDates->calculateDuration( $aData['DEL_INIT_DATE'], $aRow['DEL_FINISH_DATE'], null, null, $aRow['TAS_UID'] ); - } - - $oAppDelegation->update( $aData ); - - $oDataset->next(); - } - return; - } -} - diff --git a/workflow/engine/classes/class.searchIndex.php b/workflow/engine/classes/class.searchIndex.php deleted file mode 100644 index 14bca73be..000000000 --- a/workflow/engine/classes/class.searchIndex.php +++ /dev/null @@ -1,447 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 5304 Ventura Drive, - * Delray Beach, FL, 33484, USA, or email info@colosa.com. - * - */ - - -/** - * Class used as interface to have access to the search index services - * - * @author Herbert Saal Gutierrez - * - */ -class BpmnEngine_Services_SearchIndex -{ - 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'); - - /** - * *************************************************************** - */ - // get array of selected facet groups - $facetRequestEntity->selectedFacetsString = str_replace (',,', ',', $facetRequestEntity->selectedFacetsString); - // remove descriptions of selected facet groups - - $aGroups = explode (',', $facetRequestEntity->selectedFacetsString); - - $aGroups = array_filter ($aGroups); // remove empty items - - $aSelectedFacetGroups = array (); - foreach ($aGroups as $i => $value) { - $gi = explode (':::', $value); - $gr = explode ('::', $gi [0]); - $it = explode ('::', $gi [1]); - - // create string for remove condition - $count = 0; - $removeCondition = str_replace ($value . ',', '', $facetRequestEntity->selectedFacetsString, $count); - if ($count == 0) { - $removeCondition = str_replace ($value, '', $facetRequestEntity->selectedFacetsString, $count); - } - $selectedFacetGroupData = array ( - 'selectedFacetGroupName' => $gr [0], - 'selectedFacetGroupPrintName' => $gr [1], - 'selectedFacetItemName' => $it [0], - 'selectedFacetItemPrintName' => $it [1], - 'selectedFacetRemoveCondition' => $removeCondition - ); - - $aSelectedFacetGroups [] = Entity_SelectedFacetGroupItem::createForRequest ($selectedFacetGroupData); - } - - /** - * *************************************************************** - */ - // convert request to index request - // create filters - $filters = array (); - if (! empty ($aSelectedFacetGroups)) { - // exclude facetFields and facetDates included in filter from the next - // list of facets - foreach ($aSelectedFacetGroups as $value) { - $facetRequestEntity->facetFields = array_diff ($facetRequestEntity->facetFields, array ( - $value->selectedFacetGroupName - )); - $facetRequestEntity->facetDates = array_diff ($facetRequestEntity->facetDates, array ( - $value->selectedFacetGroupName - )); - } - - // $facetFields = array_diff($facetFields, - // $facetInterfaceRequestEntity->selectedFacetGroups); - // $facetDates = array_diff($facetDates, - // $facetInterfaceRequestEntity->selectedFacetGroups); - foreach ($aSelectedFacetGroups as $group) { - $filters [] = $group->selectedFacetGroupName . ':' . urlencode ($group->selectedFacetItemName); - } - } - $facetRequestEntity->filters = $filters; - - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $facetsList = $solr->getFacetsList ($facetRequestEntity); - - $numFound = $facetsList->response->numFound; - - $facetCounts = $facetsList->facet_counts; - - $facetGroups = array (); - // convert facet fields result to objects - /** - * ********************************************************************* - */ - // include facet field results - $facetFieldsResult = $facetsList->facet_counts->facet_fields; - if (! empty ($facetFieldsResult)) { - foreach ($facetFieldsResult as $facetGroup => $facetvalues) { - if (count ($facetvalues) > 0) // if the group have facets included - { - $data = array ( - 'facetGroupName' => $facetGroup - ); - $data ['facetGroupPrintName'] = $facetGroup; - $data ['facetGroupType'] = 'field'; - $facetItems = array (); - for ($i = 0; $i < count ($facetvalues); $i += 2) { - $dataItem = array (); - $dataItem ['facetName'] = $facetvalues [$i]; - $dataItem ['facetPrintName'] = $facetvalues [$i]; - $dataItem ['facetCount'] = $facetvalues [$i + 1]; - $dataItem ['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty ($facetRequestEntity->selectedFacetsString) ? '' : ',') . $data ['facetGroupName'] . '::' . $data ['facetGroupPrintName'] . ':::' . $dataItem ['facetName'] . '::' . $dataItem ['facetPrintName']; - $newFacetItem = Entity_FacetItem::createForInsert ($dataItem); - $facetItems [] = $newFacetItem; - } - $data ['facetItems'] = $facetItems; - $newFacetGroup = Entity_FacetGroup::createForInsert ($data); - - $facetGroups [] = $newFacetGroup; - } - } - } - /** - * ********************************************************************* - */ - // include facet date ranges results - $facetDatesResult = $facetsList->facet_counts->facet_dates; - if (! empty ($facetDatesResult)) { - foreach ($facetDatesResult as $facetGroup => $facetvalues) { - if (count ((array)$facetvalues) > 3) // if the group have any facets included - // besides start, end and gap - { - $data = array ( - 'facetGroupName' => $facetGroup - ); - $data ['facetGroupPrintName'] = $facetGroup; - $data ['facetGroupType'] = 'daterange'; - $facetItems = array (); - $facetvalueskeys = array_keys ((array)$facetvalues); - foreach ($facetvalueskeys as $i => $k) { - if ($k != 'gap' && $k != 'start' && $k != 'end') { - $dataItem = array (); - if ($i < count ($facetvalueskeys) - 4) { - - $dataItem ['facetName'] = '[' . $k . '%20TO%20' . $facetvalueskeys [$i + 1] . ']'; - $dataItem ['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalueskeys [$i + 1] . ']'; - } - else { - // the last group - $dataItem ['facetName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; - $dataItem ['facetPrintName'] = '[' . $k . '%20TO%20' . $facetvalues->end . ']'; - } - - $dataItem ['facetCount'] = $facetvalues->$k; - $dataItem ['facetSelectCondition'] = $facetRequestEntity->selectedFacetsString . (empty ($facetRequestEntity->selectedFacetsString) ? '' : ',') . $data ['facetGroupName'] . '::' . $data ['facetGroupPrintName'] . ':::' . $dataItem ['facetName'] . '::' . $dataItem ['facetPrintName']; - $newFacetItem = Entity_FacetItem::createForInsert ($dataItem); - $facetItems [] = $newFacetItem; - } - } - - $data ['facetItems'] = $facetItems; - $newFacetGroup = Entity_FacetGroup::createForInsert ($data); - - $facetGroups [] = $newFacetGroup; - } - } - } - // TODO:convert facet queries - // ----- - /** - * *************************************************************** - */ - // Create a filter string used in the filter of results of a datatable - $filterText = ''; // the list of selected filters used for filtering result, - // send in ajax - foreach ($aSelectedFacetGroups as $selectedFacetGroup) { - $filterText .= $selectedFacetGroup->selectedFacetGroupName . ':' . urlencode ($selectedFacetGroup->selectedFacetItemName) . ','; - } - $filterText = substr_replace ($filterText, '', - 1); - // $filterText = ($filterText == '')?'':'&filterText='.$filterText; - - /** - * *************************************************************** - */ - // Create result - $dataFacetResult = array ( - 'aFacetGroups' => $facetGroups, - 'aSelectedFacetGroups' => $aSelectedFacetGroups, - 'sFilterText' => $filterText - ); - $facetResult = Entity_FacetResult::createForRequest ($dataFacetResult); - - return $facetResult; - } - - /** - * Get the total number of documents in search server - * @param string $workspace - * @return integer number of documents - * - */ - public function getNumberDocuments($workspace) - { - require_once ('class.solr.php'); - // require_once (ROOT_PATH . - // '/businessLogic/modules/SearchIndexAccess/Solr.php'); - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // create list of facets - $numberDocuments = $solr->getNumberDocuments ($workspace); - - return $numberDocuments; - } - - /** - * Update document Index - * @param SolrUpdateDocumentEntity $solrUpdateDocumentEntity - */ - public function updateIndexDocument($solrUpdateDocumentEntity) - { - $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) - { - $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) - { - $solr = new BpmnEngine_SearchIndexAccess_Solr ($this->_solrIsEnabled, $this->_solrHost); - - // commit - $solr->commitChanges ($workspace); - } - - /** - * Optimize index changes - * @param string $workspace - */ - public function optimizeIndexChanges($workspace) - { - $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 deleted file mode 100644 index 5e5698f67..000000000 --- a/workflow/engine/classes/class.solr.php +++ /dev/null @@ -1,666 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 5304 Ventura Drive, - * Delray Beach, FL, 33484, USA, or email info@colosa.com. - * - */ - - -/** - * Interface to the Solr Search server - * @author Herbert Saal Gutierrez - * - */ -class BpmnEngine_SearchIndexAccess_Solr -{ - const SOLR_VERSION = '&version=2.2'; - private $_solrIsEnabled = false; - private $_solrHost = ""; - - public function __construct($solrIsEnabled = false, $solrHost = "") - { - // 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 - * - * @return bool - */ - public function isEnabled($workspace) - { - $resultServerStatus = false; - - //if($this->_solrIsEnabled != true) - //return $resultServerStatus; - - // 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); - - //Apply proxy settings - $sysConf = PmSystem::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 (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); - - //Apply proxy settings - $sysConf = PmSystem::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 (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 - - //Apply proxy settings - $sysConf = PmSystem::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 (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 - - //Apply proxy settings - $sysConf = PmSystem::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 (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 - - //Apply proxy settings - $sysConf = PmSystem::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 (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 - - //Apply proxy settings - $sysConf = PmSystem::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 (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); - - //Apply proxy settings - $sysConf = PmSystem::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 (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); - - //there's no response - if(!$response) - return false; - - // 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; - } - - /** - * 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 = PmSystem::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 (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 - - //Apply proxy settings - $sysConf = PmSystem::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 (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);
-
-    //Apply proxy settings
-    $sysConf = PmSystem::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 (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/class.webdav.php b/workflow/engine/classes/class.webdav.php
index 6ba087c81..d02d0d86e 100644
--- a/workflow/engine/classes/class.webdav.php
+++ b/workflow/engine/classes/class.webdav.php
@@ -5,6 +5,9 @@
  *
  * @package workflow.engine.classes
  */
+
+use ProcessMaker\Core\System;
+
 require_once "HTTP/WebDAV/Server.php";
 require_once "System.php";
 
@@ -742,7 +745,7 @@ class ProcessMakerWebDav extends HTTP_WebDAV_Server
         if (is_dir($path)) {
             $query = "DELETE FROM properties WHERE path LIKE '" . $this->_slashify($options["path"]) . "%'";
             mysql_query($query);
-            PmSystem::rm("-rf $path");
+            System::rm("-rf $path");
         } else {
             unlink($path);
         }
@@ -845,7 +848,7 @@ class ProcessMakerWebDav extends HTTP_WebDAV_Server
             mysql_query($query);
         } else {
             if (is_dir($source)) {
-                $files = PmSystem::find($source);
+                $files = System::find($source);
                 $files = array_reverse($files);
             } else {
                 $files = array($source
diff --git a/workflow/engine/classes/class.wsResponse.php b/workflow/engine/classes/class.wsResponse.php
deleted file mode 100644
index f3c4ece35..000000000
--- a/workflow/engine/classes/class.wsResponse.php
+++ /dev/null
@@ -1,233 +0,0 @@
-.
- *
- * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
- * Coral Gables, FL, 33134, USA, or email info@colosa.com.
- */
-
-/**
- *
- * @package workflow.engine.classes
- */
-
-class wsResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @return void
-     */
-    function __construct ($status, $message)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-
-    /**
-     * Function getPayloadString
-     *
-     * @param string $operation
-     * @return string
-     */
-    function getPayloadString ($operation)
-    {
-        $res = "<$operation>\n";
-        $res .= "" . $this->status_code . "";
-        $res .= "" . $this->message . "";
-        $res .= "" . $this->timestamp . "";
-        //    $res .= "" . $this->timestamp . "";
-        $res .= "<$operation>";
-        return $res;
-    }
-
-    /**
-     * Function getPayloadArray
-     *
-     * @return array
-     */
-    function getPayloadArray ()
-    {
-        return array ("status_code" => $this->status_code,'message' => $this->message,'timestamp' => $this->timestamp
-        );
-    }
-}
-
-/**
- * Class wsCreateUserResponse
- *
- * @package workflow.engine.classes
- */
-class wsCreateUserResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $userUID = '';
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @param string $userUID
-     * @return void
-     */
-    function __construct ($status, $message, $userUID)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->userUID = $userUID;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-}
-
-/**
- * Class wsCreateGroupResponse
- *
- * @package workflow.engine.classes
- */
-class wsCreateGroupResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $groupUID = '';
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @param string $groupUID
-     * @return void
-     */
-    function __construct ($status, $message, $groupUID)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->groupUID = $groupUID;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-
-}
-
-/**
- * Class wsCreateDepartmentResponse
- *
- * @package workflow.engine.classes
- */
-class wsCreateDepartmentResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $departmentUID = '';
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @param string $departmentUID
-     * @return void
-     */
-    function __construct ($status, $message, $departmentUID)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->departmentUID = $departmentUID;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-}
-
-/**
- * Class wsGetVariableResponse
- *
- * @package workflow.engine.classes
- */
-class wsGetVariableResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $variables = null;
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @param string $variables
-     * @return void
-     */
-    function __construct ($status, $message, $variables)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->variables = $variables;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-}
-
-/**
- * Class wsGetCaseNotesResponse
- *
- * @package workflow.engine.classes
- */
-class wsGetCaseNotesResponse
-{
-    public $status_code = 0;
-    public $message = '';
-    public $notes = null;
-    public $timestamp = '';
-
-    /**
-     * Function __construct
-     * Constructor of the class
-     *
-     * @param string $status
-     * @param string $message
-     * @param array|object|string $notes
-     * @return void
-     */
-    function __construct ($status, $message, $notes)
-    {
-        $this->status_code = $status;
-        $this->message = $message;
-        $this->notes = $notes;
-        $this->timestamp = date( 'Y-m-d H:i:s' );
-    }
-}
-?>
\ No newline at end of file
diff --git a/workflow/engine/classes/class.xmlfield_InputPM.php b/workflow/engine/classes/class.xmlfield_InputPM.php
deleted file mode 100644
index 5bd2d3814..000000000
--- a/workflow/engine/classes/class.xmlfield_InputPM.php
+++ /dev/null
@@ -1,580 +0,0 @@
-.
- *
- * For more information, contact Colosa Inc, 2566 Le Jeune Rd.,
- * Coral Gables, FL, 33134, USA, or email info@colosa.com.
- *
- * @package workflow.engine.classes
- **/
-
-class XmlForm_Field_TextPM extends XmlForm_Field_SimpleText
-{
-    public $size = 15;
-    public $maxLength = 64;
-    public $validate = 'Any';
-    public $mask = '';
-    public $defaultValue = '';
-    public $required = false;
-    public $dependentFields = '';
-    public $linkField = '';
-    //Possible values:(-|UPPER|LOWER|CAPITALIZE)
-    public $strTo = '';
-    public $readOnly = false;
-    public $sqlConnection = 0;
-    public $sql = '';
-    public $sqlOption = array ();
-    //Atributes only for grids
-    public $formula = '';
-    public $function = '';
-    public $replaceTags = 0;
-    public $showVars = 0;
-    public $process = '';
-    public $symbol = '@@';
-
-    /**
-     * Function render
-     *
-     * @author Julio Cesar Laura Avendano 
-     * @access public
-     * @param eter string value
-     * @param eter string owner
-     * @return string
-     */
-    public function render ($value = null, $owner = null)
-    {
-        //$this->executeSQL();
-        //if (isset($this->sqlOption)) {
-        //  reset($this->sqlOption);
-        //  $firstElement=key($this->sqlOption);
-        //  if (isset($firstElement)) $value = $firstElement;
-        //}
-        //NOTE: string functions must be in G class
-        if ($this->strTo === 'UPPER') {
-            $value = strtoupper( $value );
-        }
-        if ($this->strTo === 'LOWER') {
-            $value = strtolower( $value );
-        }
-        //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value);
-        $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values );
-        if ($this->replaceTags == 1) {
-            $value = G::replaceDataField( $value, $owner->values );
-        }
-        if ($this->showVars == 1) {
-            $this->process = G::replaceDataField( $this->process, $owner->values );
-            //$sShowVars = ' ' . $this->symbol . '';
-            $sShowVars = ' ';
-        } else {
-            $sShowVars = '';
-        }
-        if ($this->mode === 'edit') {
-            if ($this->readOnly) {
-                return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly" style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars;
-            } else {
-                return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars;
-            }
-        } elseif ($this->mode === 'view') {
-            return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="display:none;' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $this->htmlentities( $value, ENT_COMPAT, 'utf-8' );
-        } else {
-            return $this->htmlentities( $value, ENT_COMPAT, 'utf-8' );
-        }
-    }
-
-    /**
-     * Function renderGrid
-     *
-     * @author Julio Cesar Laura Avendano 
-     * @access public
-     * @param eter array values
-     * @param eter string owner
-     * @return string
-     */
-    public function renderGrid ($values = array(), $owner)
-    {
-        $result = array ();
-        $r = 1;
-        foreach ($values as $v) {
-            if ($this->replaceTags == 1) {
-                $v = G::replaceDataField( $v, $owner->values );
-            }
-            if ($this->showVars == 1) {
-                $this->process = G::replaceDataField( $this->process, $owner->values );
-                //$sShowVars = ' ' . $this->symbol . '';
-                $sShowVars = ' ';
-            } else {
-                $sShowVars = '';
-            }
-            if ($this->mode === 'edit') {
-                if ($this->readOnly) {
-                    $result[] = '' . $sShowVars;
-                } else {
-                    $result[] = '' . $sShowVars;
-                }
-            } elseif ($this->mode === 'view') {
-                $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' );
-            } else {
-                $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' );
-            }
-            $r ++;
-        }
-        return $result;
-    }
-
-    /**
-     * Function attachEvents
-     *
-     * @access public
-     * @param eter string $element
-     * @return string
-     */
-    public function attachEvents ($element)
-    {
-        return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}');
-    myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");";
-    }
-}
-
-/**
- * Class XmlForm_Field_TextareaPM
- */
-class XmlForm_Field_TextareaPM extends XmlForm_Field
-{
-    public $rows = 12;
-    public $cols = 40;
-    public $required = false;
-    public $readOnly = false;
-    public $wrap = 'OFF';
-    public $showVars = 0;
-    public $process = '';
-    public $symbol = '@@';
-
-    /**
-     * Function render
-     *
-     * @author Julio Cesar Laura Avendao 
-     * @access public
-     * @param eter string value
-     * @param eter string owner
-     * @return string
-     */
-    public function render ($value = null, $owner)
-    {
-        if ($this->showVars == 1) {
-            $this->process = G::replaceDataField( $this->process, $owner->values );
-            $sShowVars = ' ';
-        } else {
-            $sShowVars = '';
-        }
-        if ($this->mode === 'edit') {
-            if ($this->readOnly) {
-                return '' . $sShowVars;
-            } else {
-                return '' . $sShowVars;
-            }
-        } elseif ($this->mode === 'view') {
-            return '';
-        } else {
-            return '';
-        }
-    }
-
-    /**
-     * Function renderGrid
-     *
-     * @author Julio Cesar Laura Avendano 
-     * @access public
-     * @param eter string values
-     * @param eter string owner
-     * @return string
-     */
-    public function renderGrid ($owner, $values = null)
-    {
-        $result = array ();
-        $r = 1;
-        foreach ($values as $v) {
-            if ($this->showVars == 1) {
-                $this->process = G::replaceDataField( $this->process, $owner->values );
-                //$sShowVars = ' ' . $this->symbol . '';
-                $sShowVars = ' ';
-            } else {
-                $sShowVars = '';
-            }
-            if ($this->mode === 'edit') {
-                if ($this->readOnly) {
-                    $result[] = 'htmlentities( $v, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly"/>' . $sShowVars;
-                } else {
-                    $result[] = 'htmlentities( $v, ENT_COMPAT, 'utf-8' ) . '\' />' . $sShowVars;
-                }
-            } elseif ($this->mode === 'view') {
-                if (stristr( $_SERVER['HTTP_USER_AGENT'], 'iPhone' )) {
-                    //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; - $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); - } else { - //$result[] = '
'.$this->htmlentities( $v , ENT_COMPAT, 'utf-8').'
'; - $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); - } - } else { - $result[] = $this->htmlentities( $v, ENT_COMPAT, 'utf-8' ); - } - $r ++; - } - return $result; - } -} - -/** - * Class XmlForm_Field_hours - */ -class XmlForm_Field_hours extends XmlForm_Field_SimpleText -{ - public $size = 15; - public $maxLength = 64; - public $validate = 'Any'; - public $mask = ''; - public $defaultValue = ''; - public $required = false; - public $dependentFields = ''; - public $linkField = ''; - //Possible values:(-|UPPER|LOWER|CAPITALIZE) - public $strTo = ''; - public $readOnly = false; - public $sqlConnection = 0; - public $sql = ''; - public $sqlOption = array (); - //Atributes only for grids - public $formula = ''; - public $function = ''; - public $replaceTags = 0; - public $showVars = 0; - public $process = ''; - public $symbol = '@@'; - - /** - * Function render - * - * @author Julio Cesar Laura Avendano - * @access public - * @param eter string value - * @param eter string owner - * @return string - */ - public function render ($value = null, $owner = null) - { - if ($this->strTo === 'UPPER') { - $value = strtoupper( $value ); - } - if ($this->strTo === 'LOWER') { - $value = strtolower( $value ); - } - //if ($this->strTo==='CAPITALIZE') $value = strtocapitalize($value); - $onkeypress = G::replaceDataField( $this->onkeypress, $owner->values ); - if ($this->replaceTags == 1) { - $value = G::replaceDataField( $value, $owner->values ); - } - if ($this->showVars == 1) { - $this->process = G::replaceDataField( $this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } else { - $sShowVars = ''; - } - if ($this->mode === 'edit') { - if ($this->readOnly) { - return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' readOnly="readOnly" style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; - } else { - return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $sShowVars; - } - } elseif ($this->mode === 'view') { - return 'htmlentities( $value, ENT_COMPAT, 'utf-8' ) . '\' style="display:none;' . htmlentities( $this->style, ENT_COMPAT, 'utf-8' ) . '" onkeypress="' . htmlentities( $onkeypress, ENT_COMPAT, 'utf-8' ) . '"/>' . $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); - } else { - return $this->htmlentities( $value, ENT_COMPAT, 'utf-8' ); - } - } - - /** - * Function renderGrid - * - * @author Julio Cesar Laura Avendano - * @access public - * @param eter array values - * @param eter string owner - * @return string - */ - public function renderGrid ($values = array(),$owner) - { - $result = array (); - $r = 1; - foreach ($values as $v) { - if ($this->replaceTags == 1) { - $v = G::replaceDataField( $v, $owner->values ); - } - if ($this->showVars == 1) { - $this->process = G::replaceDataField( $this->process, $owner->values ); - //$sShowVars = ' ' . $this->symbol . ''; - $sShowVars = ' '; - } else { - $sShowVars = ''; - } - if ($this->mode === 'edit') { - if ($this->readOnly) { - $result[] = '' . $sShowVars; - } else { - $result[] = '' . $sShowVars; - } - } elseif ($this->mode === 'view') { - $result[] = '

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

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

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

'; - } - $r ++; - } - return $result; - } - - /** - * Function attachEvents - * - * @access public - * @param eter string $element - * @return string - */ - public function attachEvents ($element) - { - return "myForm.aElements[i] = new G_Text(myForm, $element,'{$this->name}'); - myForm.aElements[i].setAttributes(" . $this->getAttributes() . ");"; - } -} - -/** - * Function getDynaformsVars - * - * @access public - * @param eter string $sProcessUID - * @param eter boolean $bSystemVars - * @return array - */ -function getDynaformsVars ($sProcessUID, $typeVars = 'all', $bIncMulSelFields = 0) -{ - $aFields = array (); - $aFieldsNames = array (); - if ($typeVars == 'system' || $typeVars == 'all') { - $aAux = G::getSystemConstants(); - foreach ($aAux as $sName => $sValue) { - $aFields[] = array ('sName' => $sName,'sType' => 'system','sLabel' => G::LoadTranslation('ID_TINY_SYSTEM_VARIABLES')); - } - //we're adding the pin variable to the system list - $aFields[] = array ('sName' => 'PIN','sType' => 'system','sLabel' => G::LoadTranslation('ID_TINY_SYSTEM_VARIABLES')); - - //we're adding the app_number variable to the system list - $aFields[] = array('sName' => 'APP_NUMBER', 'sType' => 'system', 'sLabel' => G::LoadTranslation('ID_TINY_SYSTEM_VARIABLE'), 'sUid' => ''); - } - - $aInvalidTypes = array("title", "subtitle", "file", "button", "reset", "submit", "javascript", "pmconnection"); - $aMultipleSelectionFields = array("listbox", "checkgroup"); - - if ($bIncMulSelFields != 0) { - $aInvalidTypes = array_merge( $aInvalidTypes, $aMultipleSelectionFields ); - } - // getting bpmn projects - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(BpmnProjectPeer::PRJ_UID); - $oCriteria->add(BpmnProjectPeer::PRJ_UID, $sProcessUID); - $oDataset = ProcessPeer::doSelectRS($oCriteria, Propel::getDbConnection('workflow_ro')); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - $row = $oDataset->getRow(); - if (isset($row["PRJ_UID"])) { - if($typeVars == 'process' || $typeVars == 'all') { - $oCriteria = new Criteria('workflow'); - $oCriteria->addSelectColumn(ProcessVariablesPeer::VAR_UID); - $oCriteria->addSelectColumn(ProcessVariablesPeer::VAR_NAME); - $oCriteria->addSelectColumn(ProcessVariablesPeer::VAR_FIELD_TYPE); - $oCriteria->add(ProcessVariablesPeer::PRJ_UID, $sProcessUID); - $oDataset = ProcessVariablesPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($oDataset->next()) { - $row = $oDataset->getRow(); - array_push($aFields, array( - "sName" => $row["VAR_NAME"], - "sType" => $row["VAR_FIELD_TYPE"], - "sLabel" => $row["VAR_FIELD_TYPE"] - )); - } - } - if($typeVars == 'grid' || $typeVars == 'all') { - $oC = new Criteria( 'workflow' ); - $oC->addSelectColumn( DynaformPeer::DYN_CONTENT ); - $oC->add( DynaformPeer::PRO_UID, $sProcessUID ); - $oC->add( DynaformPeer::DYN_TYPE, 'xmlform' ); - $oData = DynaformPeer::doSelectRS( $oC ); - $oData->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oData->next(); - while ($aRowd = $oData->getRow()) { - $dynaform = G::json_decode($aRowd['DYN_CONTENT'],true); - if(is_array($dynaform) && sizeof($dynaform)) { - $items = $dynaform['items'][0]['items']; - foreach($items as $key => $val){ - if(isset($val[0]['type']) && $val[0]['type'] == 'grid'){ - if(sizeof($val[0]['columns'])) { - $columns = $val[0]['columns']; - foreach($columns as $column) { - array_push($aFields, array( - "sName" => $column['name'], - "sType" => $column['type'], - "sLabel" => $column['type'] - )); - } - } - } - } - } - $oData->next(); - } - } - - } else { - require_once 'classes/model/Dynaform.php'; - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( DynaformPeer::DYN_FILENAME ); - $oCriteria->add( DynaformPeer::PRO_UID, $sProcessUID ); - $oCriteria->add( DynaformPeer::DYN_TYPE, 'xmlform' ); - $oDataset = DynaformPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - if (file_exists( PATH_DYNAFORM . PATH_SEP . $aRow['DYN_FILENAME'] . '.xml' )) { - $G_FORM = new Form( $aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG ); - if (($G_FORM->type == 'xmlform') || ($G_FORM->type == '')) { - foreach ($G_FORM->fields as $k => $v) { - if (! in_array( $v->type, $aInvalidTypes )) { - if (! in_array( $k, $aFieldsNames )) { - $aFields[] = array ('sName' => $k,'sType' => $v->type,'sLabel' => ($v->type != 'grid' ? $v->label : '[ ' . G::LoadTranslation( 'ID_GRID' ) . ' ]') - ); - $aFieldsNames[] = $k; - } - } - } - } - } - $oDataset->next(); - } - } - return $aFields; -} - -/** - * Function getGridsVars - * - * @access public - * @param eter string $sProcessUID - * @return array - */ -function getGridsVars ($sProcessUID) -{ - $aFields = array (); - $aFieldsNames = array (); - - require_once 'classes/model/Dynaform.php'; - $oCriteria = new Criteria( 'workflow' ); - $oCriteria->addSelectColumn( DynaformPeer::DYN_FILENAME ); - $oCriteria->add( DynaformPeer::PRO_UID, $sProcessUID ); - $oDataset = DynaformPeer::doSelectRS( $oCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $G_FORM = new Form( $aRow['DYN_FILENAME'], PATH_DYNAFORM, SYS_LANG ); - if ($G_FORM->type == 'xmlform') { - foreach ($G_FORM->fields as $k => $v) { - if ($v->type == 'grid') { - if (! in_array( $k, $aFieldsNames )) { - $aFields[] = array ('sName' => $k,'sXmlForm' => str_replace( $sProcessUID . '/', '', $v->xmlGrid )); - $aFieldsNames[] = $k; - } - } - } - } - $oDataset->next(); - } - return $aFields; -} -/** - * Function getVarsGrid returns all variables of Grid - * - * @access public - * @param string proUid process ID - * @param string dynUid dynaform ID - * @return array - */ - -function getVarsGrid ($proUid, $dynUid) -{ - $dynaformFields = array (); - - if (is_file( PATH_DATA . '/sites/'. SYS_SYS .'/xmlForms/'. $proUid .'/'.$dynUid. '.xml' ) && filesize( PATH_DATA . '/sites/'. SYS_SYS .'/xmlForms/'. $proUid .'/'. $dynUid .'.xml' ) > 0) { - $dyn = new DynaformHandler( PATH_DATA . '/sites/'. SYS_SYS .'/xmlForms/' .$proUid. '/' . $dynUid .'.xml' ); - $dynaformFields[] = $dyn->getFields(); - } - - $dynaformFieldTypes = array (); - - foreach ($dynaformFields as $aDynFormFields) { - foreach ($aDynFormFields as $field) { - - 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' ); - } - } - } - return $dynaformFieldTypes; -} - - -/** - * Class XmlForm_Field_CheckBoxTable - */ -class XmlForm_Field_CheckBoxTable extends XmlForm_Field_Checkbox -{ - - /** - * Function render - * - * @author The Answer - * @access public - * @param eter string value - * @param eter string owner - * @return string - */ - public function render ($value = null, $owner = null) - { - //$optionName = $owner->values['USR_UID']; - $optionName = $value; - $onclick = (($this->onclick) ? ' onclick="' . G::replaceDataField( $this->onclick, $owner->values ) . '" ' : ''); - $html = ' '; - return $html; - } -} - diff --git a/workflow/engine/classes/entities/AppSolrQueue.php b/workflow/engine/classes/entities/AppSolrQueue.php deleted file mode 100644 index 8df7933fa..000000000 --- a/workflow/engine/classes/entities/AppSolrQueue.php +++ /dev/null @@ -1,43 +0,0 @@ -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 deleted file mode 100644 index 5aa927469..000000000 --- a/workflow/engine/classes/entities/Base.php +++ /dev/null @@ -1,157 +0,0 @@ - $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; - } - } - - 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]]; - } - } - - /** - * - * - * - * 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/EntityAppSolrQueue.php b/workflow/engine/classes/entities/EntityAppSolrQueue.php new file mode 100644 index 000000000..95c54094e --- /dev/null +++ b/workflow/engine/classes/entities/EntityAppSolrQueue.php @@ -0,0 +1,37 @@ +initializeObject($data); + + $requiredFields = array( + "appUid", + "appChangeDate", + "appChangeTrace", + "appUpdated" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityBase.php b/workflow/engine/classes/entities/EntityBase.php new file mode 100644 index 000000000..55689d79a --- /dev/null +++ b/workflow/engine/classes/entities/EntityBase.php @@ -0,0 +1,148 @@ + $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' + )); + + 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; + } + + /** + * 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); + } +} diff --git a/workflow/engine/classes/entities/EntityFacetGroup.php b/workflow/engine/classes/entities/EntityFacetGroup.php new file mode 100644 index 000000000..045bc5284 --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetGroup.php @@ -0,0 +1,36 @@ +initializeObject($data); + + $requiredFields = array( + "facetGroupName", + "facetItems" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityFacetInterfaceRequest.php b/workflow/engine/classes/entities/EntityFacetInterfaceRequest.php new file mode 100644 index 000000000..f1d6a94ae --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetInterfaceRequest.php @@ -0,0 +1,40 @@ +initializeObject($data); + + $requiredFields = array( + "searchText", + "selectedFacetsString" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityFacetInterfaceResult.php b/workflow/engine/classes/entities/EntityFacetInterfaceResult.php new file mode 100644 index 000000000..651e54e3a --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetInterfaceResult.php @@ -0,0 +1,36 @@ +initializeObject($data); + + $requiredFields = array( + "aFacetGroup", + "aSelectedFacetGroupItem", + "sFilterText" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityFacetItem.php b/workflow/engine/classes/entities/EntityFacetItem.php new file mode 100644 index 000000000..84df00cf9 --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetItem.php @@ -0,0 +1,36 @@ +initializeObject($data); + + $requiredFields = array( + "facetName", + "facetCount" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityFacetRequest.php b/workflow/engine/classes/entities/EntityFacetRequest.php new file mode 100644 index 000000000..e8b38d989 --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetRequest.php @@ -0,0 +1,41 @@ +initializeObject($data); + + $requiredFields = array( + "workspace" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntityFacetResult.php b/workflow/engine/classes/entities/EntityFacetResult.php new file mode 100644 index 000000000..4ba58d9cb --- /dev/null +++ b/workflow/engine/classes/entities/EntityFacetResult.php @@ -0,0 +1,35 @@ +initializeObject($data); + + $requiredFields = array( + "aFacetGroups", + "aSelectedFacetGroups", + "sFilterText" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntitySelectedFacetGroupItem.php b/workflow/engine/classes/entities/EntitySelectedFacetGroupItem.php new file mode 100644 index 000000000..fcf6b5a14 --- /dev/null +++ b/workflow/engine/classes/entities/EntitySelectedFacetGroupItem.php @@ -0,0 +1,38 @@ +initializeObject($data); + + $requiredFields = array( + "selectedFacetGroupName", + "selectedFacetItemName" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntitySolrQueryResult.php b/workflow/engine/classes/entities/EntitySolrQueryResult.php new file mode 100644 index 000000000..355fb8f91 --- /dev/null +++ b/workflow/engine/classes/entities/EntitySolrQueryResult.php @@ -0,0 +1,38 @@ +initializeObject($data); + + $requiredFields = array( + 'sEcho', + 'iTotalRecords', + 'iTotalDisplayRecords', + 'aaData' + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntitySolrRequestData.php b/workflow/engine/classes/entities/EntitySolrRequestData.php new file mode 100644 index 000000000..9b3eea5b8 --- /dev/null +++ b/workflow/engine/classes/entities/EntitySolrRequestData.php @@ -0,0 +1,44 @@ +initializeObject($data); + + $requiredFields = array( + 'workspace' + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/EntitySolrUpdateDocument.php b/workflow/engine/classes/entities/EntitySolrUpdateDocument.php new file mode 100644 index 000000000..e132faf0a --- /dev/null +++ b/workflow/engine/classes/entities/EntitySolrUpdateDocument.php @@ -0,0 +1,33 @@ +initializeObject($data); + + $requiredFields = array( + "workspace", + "document" + ); + + $obj->validateRequiredFields($requiredFields); + + return $obj; + } +} diff --git a/workflow/engine/classes/entities/FacetGroup.php b/workflow/engine/classes/entities/FacetGroup.php deleted file mode 100644 index 4e3302d8d..000000000 --- a/workflow/engine/classes/entities/FacetGroup.php +++ /dev/null @@ -1,51 +0,0 @@ -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 deleted file mode 100644 index 2b074a2a5..000000000 --- a/workflow/engine/classes/entities/FacetInterfaceRequest.php +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 600581321..000000000 --- a/workflow/engine/classes/entities/FacetInterfaceResult.php +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index f710af459..000000000 --- a/workflow/engine/classes/entities/FacetItem.php +++ /dev/null @@ -1,47 +0,0 @@ -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 deleted file mode 100644 index cfd82ed40..000000000 --- a/workflow/engine/classes/entities/FacetRequest.php +++ /dev/null @@ -1,43 +0,0 @@ -initializeObject ($data); - - $requiredFields = array ( - "workspace" - ); - - $obj->validateRequiredFields ($requiredFields); - - return $obj; - } - -} \ No newline at end of file diff --git a/workflow/engine/classes/entities/FacetResult.php b/workflow/engine/classes/entities/FacetResult.php deleted file mode 100644 index c115a6220..000000000 --- a/workflow/engine/classes/entities/FacetResult.php +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 364ca2d74..000000000 --- a/workflow/engine/classes/entities/SelectedFacetGroupItem.php +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 7be7246b5..000000000 --- a/workflow/engine/classes/entities/SolrQueryResult.php +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index 931afbea4..000000000 --- a/workflow/engine/classes/entities/SolrRequestData.php +++ /dev/null @@ -1,46 +0,0 @@ -initializeObject ($data); - - $requiredFields = array ( - 'workspace' - ); - - $obj->validateRequiredFields ($requiredFields); - - return $obj; - } - -} \ No newline at end of file diff --git a/workflow/engine/classes/entities/SolrUpdateDocument.php b/workflow/engine/classes/entities/SolrUpdateDocument.php deleted file mode 100644 index 6ce732516..000000000 --- a/workflow/engine/classes/entities/SolrUpdateDocument.php +++ /dev/null @@ -1,35 +0,0 @@ -initializeObject ($data); - - $requiredFields = array ( - "workspace", - "document" - ); - - $obj->validateRequiredFields ($requiredFields); - - return $obj; - } - -} \ No newline at end of file diff --git a/workflow/engine/classes/interfaces/dashletInterface.php b/workflow/engine/classes/interfaces/DashletInterface.php similarity index 100% rename from workflow/engine/classes/interfaces/dashletInterface.php rename to workflow/engine/classes/interfaces/DashletInterface.php diff --git a/workflow/engine/classes/model/AddonsManager.php b/workflow/engine/classes/model/AddonsManager.php index 85a34f5ef..4549a981e 100644 --- a/workflow/engine/classes/model/AddonsManager.php +++ b/workflow/engine/classes/model/AddonsManager.php @@ -1,9 +1,9 @@ isCore()) { - return (EnterpriseUtils::pmVersion(PmSystem::getVersion())); + return (EnterpriseUtils::pmVersion(System::getVersion())); } else { if ($this->isPlugin()) { if (!$this->isInstalled()) { @@ -199,8 +199,6 @@ class AddonsManager extends BaseAddonsManager */ public function download() { - require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php'; - $this->setState("download"); /////// @@ -225,7 +223,7 @@ class AddonsManager extends BaseAddonsManager } /////// - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); $activeLicense = $licenseManager->getActiveLicense(); $data = $data . "Content-Disposition: form-data; name=\"licenseFile\"; filename=\"" . $licenseManager->file . "\"\n"; @@ -246,7 +244,7 @@ class AddonsManager extends BaseAddonsManager ); // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { if (!is_array($option['http'])) { $option['http'] = array(); @@ -388,7 +386,6 @@ class AddonsManager extends BaseAddonsManager $this->setState(); } else { if ($this->getAddonType() == "core") { - require_once PATH_CORE . 'classes' . PATH_SEP . 'class.Upgrade.php'; $upgrade = new Upgrade($this); $upgrade->install(); diff --git a/workflow/engine/classes/model/AddonsStore.php b/workflow/engine/classes/model/AddonsStore.php index 1c482f765..0a9fd1c30 100644 --- a/workflow/engine/classes/model/AddonsStore.php +++ b/workflow/engine/classes/model/AddonsStore.php @@ -1,5 +1,6 @@ id)) { //Remove any license store that is not the active license @@ -73,7 +72,7 @@ class AddonsStore extends BaseAddonsStore AddonsStore::checkLicenseStore(); - $licenseManager = &pmLicenseManager::getSingleton(); //Getting the licenseManager + $licenseManager = &PmLicenseManager::getSingleton(); //Getting the licenseManager $result["store_errors"] = array(); list($stores, $errors) = AddonsStore::updateAll(false, $type); @@ -185,7 +184,7 @@ class AddonsStore extends BaseAddonsStore AddonsStore::checkLicenseStore(); - $licenseManager = &pmLicenseManager::getSingleton(); //Getting the licenseManager + $licenseManager = &PmLicenseManager::getSingleton(); //Getting the licenseManager $result["store_errors"] = array(); list($stores, $errors) = AddonsStore::updateAll(false); @@ -331,12 +330,6 @@ class AddonsStore extends BaseAddonsStore */ public function update($force = false, $type = 'plugin') { - require_once PATH_CORE . 'classes' . PATH_SEP . 'class.pmLicenseManager.php'; - - if (!class_exists('AddonsManagerPeer')) { - require_once ('classes/model/AddonsManager.php'); - } - //If we have any addon that is installing or updating, don't update store $criteria = new Criteria(AddonsManagerPeer::DATABASE_NAME); $criteria->add(AddonsManagerPeer::ADDON_STATE, '', Criteria::NOT_EQUAL); @@ -358,7 +351,7 @@ class AddonsStore extends BaseAddonsStore $aPluginsPP = unserialize(trim(file_get_contents(PATH_DATA_SITE . 'ee'))); } - $pmLicenseManagerO = &pmLicenseManager::getSingleton(); + $pmLicenseManagerO = &PmLicenseManager::getSingleton(); $localPlugins = array(); if ($type == 'plugin') { @@ -497,7 +490,7 @@ class AddonsStore extends BaseAddonsStore "header" => "Content-type: application/x-www-form-urlencoded\r\n", "content" => http_build_query( array( - "pmVersion" => PmSystem::getVersion(), + "pmVersion" => System::getVersion(), "version" => STORE_VERSION ) ) @@ -505,7 +498,7 @@ class AddonsStore extends BaseAddonsStore ); // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if (isset($sysConf['proxy_host'])) { if ($sysConf['proxy_host'] != '') { if (!is_array($option['http'])) { diff --git a/workflow/engine/classes/model/AppDelegation.php b/workflow/engine/classes/model/AppDelegation.php index 46229d861..75beda41d 100644 --- a/workflow/engine/classes/model/AppDelegation.php +++ b/workflow/engine/classes/model/AppDelegation.php @@ -269,7 +269,7 @@ class AppDelegation extends BaseAppDelegation $dataAbe = $resultAbe->getRow(); $flagActionsByEmail = false; if($dataAbe['ABE_TYPE']!='' && $data->USR_UID!=''){ - $actionsByEmail = new actionsByEmailCoreClass(); + $actionsByEmail = new ActionsByEmailCoreClass(); $actionsByEmail->sendActionsByEmail($data, $dataAbe); } } @@ -281,7 +281,7 @@ class AppDelegation extends BaseAppDelegation $licensedFeatures = &PMLicensedFeatures::getSingleton (); if ($licensedFeatures->verifyfeature ( '7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09' )) { try{ - $pmGoogle = new PMGoogleApi (); + $pmGoogle = new PmGoogleApi (); if ($pmGoogle->getServiceGmailStatus()) { $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); $Pmgmail->gmailsForRouting($sUsrUid, $sTasUid, $sAppUid, $delIndex, $isSubprocess); diff --git a/workflow/engine/classes/model/AppNotes.php b/workflow/engine/classes/model/AppNotes.php index 8d72cc384..736173b36 100644 --- a/workflow/engine/classes/model/AppNotes.php +++ b/workflow/engine/classes/model/AppNotes.php @@ -1,6 +1,7 @@ load( $recipientUid ); $sTo = ((($aUser['USR_FIRSTNAME'] != '') || ($aUser['USR_LASTNAME'] != '')) ? $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME'] . ' ' : '') . '<' . $aUser['USR_EMAIL'] . '>'; - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aConfiguration); $oSpool->create( diff --git a/workflow/engine/classes/model/AppSolrQueue.php b/workflow/engine/classes/model/AppSolrQueue.php index 680481646..562b7b825 100644 --- a/workflow/engine/classes/model/AppSolrQueue.php +++ b/workflow/engine/classes/model/AppSolrQueue.php @@ -86,31 +86,31 @@ class AppSolrQueue extends BaseAppSolrQueue $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 - 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); + + //"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(); while (is_array( $row )) { - $appSolrQueue = Entity_AppSolrQueue::createEmpty(); + $appSolrQueue = EntityAppSolrQueue::createEmpty(); $appSolrQueue->appUid = $row["APP_UID"]; $appSolrQueue->appChangeDate = $row["APP_CHANGE_DATE"]; $appSolrQueue->appChangeTrace = $row["APP_CHANGE_TRACE"]; @@ -119,11 +119,11 @@ class AppSolrQueue extends BaseAppSolrQueue $rs->next(); $row = $rs->getRow(); } - + return $updatedApplications; } catch (Exception $e) { $con->rollback(); throw ($e); } } -} // AppSolrQueue +} // AppSolrQueue diff --git a/workflow/engine/classes/model/Content.php b/workflow/engine/classes/model/Content.php index 9d7e07c19..900b12d6d 100644 --- a/workflow/engine/classes/model/Content.php +++ b/workflow/engine/classes/model/Content.php @@ -361,7 +361,7 @@ class Content extends BaseContent FROM CONTENT ORDER BY CON_ID, CON_CATEGORY, CON_PARENT, CON_LANG"; - $workSpace = new workspaceTools( $workSpace ); + $workSpace = new WorkspaceTools( $workSpace ); $workSpace->getDBInfo(); $link = @mysql_pconnect( $workSpace->dbHost, $workSpace->dbUser, $workSpace->dbPass) or die( "Could not connect" ); diff --git a/workflow/engine/classes/model/Language.php b/workflow/engine/classes/model/Language.php index ceed78a4b..06e6a69e7 100644 --- a/workflow/engine/classes/model/Language.php +++ b/workflow/engine/classes/model/Language.php @@ -1,4 +1,7 @@ addHeader( 'Project-Id-Version', 'ProcessMaker ' . PmSystem::getVersion() ); + $poFile->addHeader( 'Project-Id-Version', 'ProcessMaker ' . System::getVersion() ); $poFile->addHeader( 'POT-Creation-Date', '' ); $poFile->addHeader( 'PO-Revision-Date', date( 'Y-m-d H:i:s' ) ); $poFile->addHeader( 'Last-Translator', '' ); diff --git a/workflow/engine/classes/model/OutputDocument.php b/workflow/engine/classes/model/OutputDocument.php index f11cab900..b30a14c60 100644 --- a/workflow/engine/classes/model/OutputDocument.php +++ b/workflow/engine/classes/model/OutputDocument.php @@ -885,7 +885,7 @@ class OutputDocument extends BaseOutputDocument $pdf->SetRightMargin($margins['right']); $pdf->SetAutoPageBreak(true, $margins['bottom']); - $oServerConf = &serverConf::getSingleton(); + $oServerConf = &ServerConf::getSingleton(); // set some language dependent data: $lg = array(); diff --git a/workflow/engine/classes/model/map/PluginsRegistryMapBuilder.php b/workflow/engine/classes/model/map/PluginsRegistryMapBuilder.php index 69733f7a6..7be2b32e9 100644 --- a/workflow/engine/classes/model/map/PluginsRegistryMapBuilder.php +++ b/workflow/engine/classes/model/map/PluginsRegistryMapBuilder.php @@ -63,9 +63,7 @@ class PluginsRegistryMapBuilder $tMap = $this->dbMap->addTable('PLUGINS_REGISTRY'); $tMap->setPhpName('PluginsRegistry'); - $tMap->setUseIdGenerator(true); - - $tMap->addColumn('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null); + $tMap->setUseIdGenerator(false); $tMap->addPrimaryKey('PR_UID', 'PrUid', 'string', CreoleTypes::VARCHAR, true, 32); @@ -89,9 +87,9 @@ class PluginsRegistryMapBuilder $tMap->addColumn('PLUGIN_VERSION', 'PluginVersion', 'string', CreoleTypes::VARCHAR, false, 50); - $tMap->addColumn('PLUGIN_ENABLE', 'PluginEnable', 'boolean', CreoleTypes::BOOLEAN, false, null); + $tMap->addColumn('PLUGIN_ENABLE', 'PluginEnable', 'int', CreoleTypes::TINYINT, false, null); - $tMap->addColumn('PLUGIN_PRIVATE', 'PluginPrivate', 'boolean', CreoleTypes::BOOLEAN, false, null); + $tMap->addColumn('PLUGIN_PRIVATE', 'PluginPrivate', 'int', CreoleTypes::TINYINT, false, null); $tMap->addColumn('PLUGIN_MENUS', 'PluginMenus', 'string', CreoleTypes::LONGVARCHAR, false, null); diff --git a/workflow/engine/classes/model/om/BasePluginsRegistry.php b/workflow/engine/classes/model/om/BasePluginsRegistry.php index 29d3abdd4..042361f6d 100644 --- a/workflow/engine/classes/model/om/BasePluginsRegistry.php +++ b/workflow/engine/classes/model/om/BasePluginsRegistry.php @@ -27,12 +27,6 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent */ protected static $peer; - /** - * The value for the id field. - * @var int - */ - protected $id; - /** * The value for the pr_uid field. * @var string @@ -101,15 +95,15 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent /** * The value for the plugin_enable field. - * @var boolean + * @var int */ - protected $plugin_enable = false; + protected $plugin_enable = 0; /** * The value for the plugin_private field. - * @var boolean + * @var int */ - protected $plugin_private = false; + protected $plugin_private = 0; /** * The value for the plugin_menus field. @@ -185,17 +179,6 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent */ protected $alreadyInValidation = false; - /** - * Get the [id] column value. - * - * @return int - */ - public function getId() - { - - return $this->id; - } - /** * Get the [pr_uid] column value. * @@ -320,7 +303,7 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent /** * Get the [plugin_enable] column value. * - * @return boolean + * @return int */ public function getPluginEnable() { @@ -331,7 +314,7 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent /** * Get the [plugin_private] column value. * - * @return boolean + * @return int */ public function getPluginPrivate() { @@ -449,28 +432,6 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent return $this->plugin_attributes; } - /** - * Set the value of [id] column. - * - * @param int $v new value - * @return void - */ - public function setId($v) - { - - // Since the native PHP type for this column is integer, - // we will cast the input value to an int (if it is not). - if ($v !== null && !is_int($v) && is_numeric($v)) { - $v = (int) $v; - } - - if ($this->id !== $v) { - $this->id = $v; - $this->modifiedColumns[] = PluginsRegistryPeer::ID; - } - - } // setId() - /** * Set the value of [pr_uid] column. * @@ -716,13 +677,19 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent /** * Set the value of [plugin_enable] column. * - * @param boolean $v new value + * @param int $v new value * @return void */ public function setPluginEnable($v) { - if ($this->plugin_enable !== $v || $v === false) { + // Since the native PHP type for this column is integer, + // we will cast the input value to an int (if it is not). + if ($v !== null && !is_int($v) && is_numeric($v)) { + $v = (int) $v; + } + + if ($this->plugin_enable !== $v || $v === 0) { $this->plugin_enable = $v; $this->modifiedColumns[] = PluginsRegistryPeer::PLUGIN_ENABLE; } @@ -732,13 +699,19 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent /** * Set the value of [plugin_private] column. * - * @param boolean $v new value + * @param int $v new value * @return void */ public function setPluginPrivate($v) { - if ($this->plugin_private !== $v || $v === false) { + // Since the native PHP type for this column is integer, + // we will cast the input value to an int (if it is not). + if ($v !== null && !is_int($v) && is_numeric($v)) { + $v = (int) $v; + } + + if ($this->plugin_private !== $v || $v === 0) { $this->plugin_private = $v; $this->modifiedColumns[] = PluginsRegistryPeer::PLUGIN_PRIVATE; } @@ -982,60 +955,58 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent { try { - $this->id = $rs->getInt($startcol + 0); + $this->pr_uid = $rs->getString($startcol + 0); - $this->pr_uid = $rs->getString($startcol + 1); + $this->plugin_namespace = $rs->getString($startcol + 1); - $this->plugin_namespace = $rs->getString($startcol + 2); + $this->plugin_description = $rs->getString($startcol + 2); - $this->plugin_description = $rs->getString($startcol + 3); + $this->plugin_class_name = $rs->getString($startcol + 3); - $this->plugin_class_name = $rs->getString($startcol + 4); + $this->plugin_friendly_name = $rs->getString($startcol + 4); - $this->plugin_friendly_name = $rs->getString($startcol + 5); + $this->plugin_file = $rs->getString($startcol + 5); - $this->plugin_file = $rs->getString($startcol + 6); + $this->plugin_folder = $rs->getString($startcol + 6); - $this->plugin_folder = $rs->getString($startcol + 7); + $this->plugin_setup_page = $rs->getString($startcol + 7); - $this->plugin_setup_page = $rs->getString($startcol + 8); + $this->plugin_company_logo = $rs->getString($startcol + 8); - $this->plugin_company_logo = $rs->getString($startcol + 9); + $this->plugin_workspaces = $rs->getString($startcol + 9); - $this->plugin_workspaces = $rs->getString($startcol + 10); + $this->plugin_version = $rs->getString($startcol + 10); - $this->plugin_version = $rs->getString($startcol + 11); + $this->plugin_enable = $rs->getInt($startcol + 11); - $this->plugin_enable = $rs->getBoolean($startcol + 12); + $this->plugin_private = $rs->getInt($startcol + 12); - $this->plugin_private = $rs->getBoolean($startcol + 13); + $this->plugin_menus = $rs->getString($startcol + 13); - $this->plugin_menus = $rs->getString($startcol + 14); + $this->plugin_folders = $rs->getString($startcol + 14); - $this->plugin_folders = $rs->getString($startcol + 15); + $this->plugin_triggers = $rs->getString($startcol + 15); - $this->plugin_triggers = $rs->getString($startcol + 16); + $this->plugin_pm_functions = $rs->getString($startcol + 16); - $this->plugin_pm_functions = $rs->getString($startcol + 17); + $this->plugin_redirect_login = $rs->getString($startcol + 17); - $this->plugin_redirect_login = $rs->getString($startcol + 18); + $this->plugin_steps = $rs->getString($startcol + 18); - $this->plugin_steps = $rs->getString($startcol + 19); + $this->plugin_css = $rs->getString($startcol + 19); - $this->plugin_css = $rs->getString($startcol + 20); + $this->plugin_js = $rs->getString($startcol + 20); - $this->plugin_js = $rs->getString($startcol + 21); + $this->plugin_rest_service = $rs->getString($startcol + 21); - $this->plugin_rest_service = $rs->getString($startcol + 22); - - $this->plugin_attributes = $rs->getString($startcol + 23); + $this->plugin_attributes = $rs->getString($startcol + 22); $this->resetModified(); $this->setNew(false); // FIXME - using NUM_COLUMNS may be clearer. - return $startcol + 24; // 24 = PluginsRegistryPeer::NUM_COLUMNS - PluginsRegistryPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 23; // 23 = PluginsRegistryPeer::NUM_COLUMNS - PluginsRegistryPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating PluginsRegistry object", $e); @@ -1240,75 +1211,72 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent { switch($pos) { case 0: - return $this->getId(); - break; - case 1: return $this->getPrUid(); break; - case 2: + case 1: return $this->getPluginNamespace(); break; - case 3: + case 2: return $this->getPluginDescription(); break; - case 4: + case 3: return $this->getPluginClassName(); break; - case 5: + case 4: return $this->getPluginFriendlyName(); break; - case 6: + case 5: return $this->getPluginFile(); break; - case 7: + case 6: return $this->getPluginFolder(); break; - case 8: + case 7: return $this->getPluginSetupPage(); break; - case 9: + case 8: return $this->getPluginCompanyLogo(); break; - case 10: + case 9: return $this->getPluginWorkspaces(); break; - case 11: + case 10: return $this->getPluginVersion(); break; - case 12: + case 11: return $this->getPluginEnable(); break; - case 13: + case 12: return $this->getPluginPrivate(); break; - case 14: + case 13: return $this->getPluginMenus(); break; - case 15: + case 14: return $this->getPluginFolders(); break; - case 16: + case 15: return $this->getPluginTriggers(); break; - case 17: + case 16: return $this->getPluginPmFunctions(); break; - case 18: + case 17: return $this->getPluginRedirectLogin(); break; - case 19: + case 18: return $this->getPluginSteps(); break; - case 20: + case 19: return $this->getPluginCss(); break; - case 21: + case 20: return $this->getPluginJs(); break; - case 22: + case 21: return $this->getPluginRestService(); break; - case 23: + case 22: return $this->getPluginAttributes(); break; default: @@ -1331,30 +1299,29 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent { $keys = PluginsRegistryPeer::getFieldNames($keyType); $result = array( - $keys[0] => $this->getId(), - $keys[1] => $this->getPrUid(), - $keys[2] => $this->getPluginNamespace(), - $keys[3] => $this->getPluginDescription(), - $keys[4] => $this->getPluginClassName(), - $keys[5] => $this->getPluginFriendlyName(), - $keys[6] => $this->getPluginFile(), - $keys[7] => $this->getPluginFolder(), - $keys[8] => $this->getPluginSetupPage(), - $keys[9] => $this->getPluginCompanyLogo(), - $keys[10] => $this->getPluginWorkspaces(), - $keys[11] => $this->getPluginVersion(), - $keys[12] => $this->getPluginEnable(), - $keys[13] => $this->getPluginPrivate(), - $keys[14] => $this->getPluginMenus(), - $keys[15] => $this->getPluginFolders(), - $keys[16] => $this->getPluginTriggers(), - $keys[17] => $this->getPluginPmFunctions(), - $keys[18] => $this->getPluginRedirectLogin(), - $keys[19] => $this->getPluginSteps(), - $keys[20] => $this->getPluginCss(), - $keys[21] => $this->getPluginJs(), - $keys[22] => $this->getPluginRestService(), - $keys[23] => $this->getPluginAttributes(), + $keys[0] => $this->getPrUid(), + $keys[1] => $this->getPluginNamespace(), + $keys[2] => $this->getPluginDescription(), + $keys[3] => $this->getPluginClassName(), + $keys[4] => $this->getPluginFriendlyName(), + $keys[5] => $this->getPluginFile(), + $keys[6] => $this->getPluginFolder(), + $keys[7] => $this->getPluginSetupPage(), + $keys[8] => $this->getPluginCompanyLogo(), + $keys[9] => $this->getPluginWorkspaces(), + $keys[10] => $this->getPluginVersion(), + $keys[11] => $this->getPluginEnable(), + $keys[12] => $this->getPluginPrivate(), + $keys[13] => $this->getPluginMenus(), + $keys[14] => $this->getPluginFolders(), + $keys[15] => $this->getPluginTriggers(), + $keys[16] => $this->getPluginPmFunctions(), + $keys[17] => $this->getPluginRedirectLogin(), + $keys[18] => $this->getPluginSteps(), + $keys[19] => $this->getPluginCss(), + $keys[20] => $this->getPluginJs(), + $keys[21] => $this->getPluginRestService(), + $keys[22] => $this->getPluginAttributes(), ); return $result; } @@ -1387,75 +1354,72 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent { switch($pos) { case 0: - $this->setId($value); - break; - case 1: $this->setPrUid($value); break; - case 2: + case 1: $this->setPluginNamespace($value); break; - case 3: + case 2: $this->setPluginDescription($value); break; - case 4: + case 3: $this->setPluginClassName($value); break; - case 5: + case 4: $this->setPluginFriendlyName($value); break; - case 6: + case 5: $this->setPluginFile($value); break; - case 7: + case 6: $this->setPluginFolder($value); break; - case 8: + case 7: $this->setPluginSetupPage($value); break; - case 9: + case 8: $this->setPluginCompanyLogo($value); break; - case 10: + case 9: $this->setPluginWorkspaces($value); break; - case 11: + case 10: $this->setPluginVersion($value); break; - case 12: + case 11: $this->setPluginEnable($value); break; - case 13: + case 12: $this->setPluginPrivate($value); break; - case 14: + case 13: $this->setPluginMenus($value); break; - case 15: + case 14: $this->setPluginFolders($value); break; - case 16: + case 15: $this->setPluginTriggers($value); break; - case 17: + case 16: $this->setPluginPmFunctions($value); break; - case 18: + case 17: $this->setPluginRedirectLogin($value); break; - case 19: + case 18: $this->setPluginSteps($value); break; - case 20: + case 19: $this->setPluginCss($value); break; - case 21: + case 20: $this->setPluginJs($value); break; - case 22: + case 21: $this->setPluginRestService($value); break; - case 23: + case 22: $this->setPluginAttributes($value); break; } // switch() @@ -1482,99 +1446,95 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent $keys = PluginsRegistryPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) { - $this->setId($arr[$keys[0]]); + $this->setPrUid($arr[$keys[0]]); } if (array_key_exists($keys[1], $arr)) { - $this->setPrUid($arr[$keys[1]]); + $this->setPluginNamespace($arr[$keys[1]]); } if (array_key_exists($keys[2], $arr)) { - $this->setPluginNamespace($arr[$keys[2]]); + $this->setPluginDescription($arr[$keys[2]]); } if (array_key_exists($keys[3], $arr)) { - $this->setPluginDescription($arr[$keys[3]]); + $this->setPluginClassName($arr[$keys[3]]); } if (array_key_exists($keys[4], $arr)) { - $this->setPluginClassName($arr[$keys[4]]); + $this->setPluginFriendlyName($arr[$keys[4]]); } if (array_key_exists($keys[5], $arr)) { - $this->setPluginFriendlyName($arr[$keys[5]]); + $this->setPluginFile($arr[$keys[5]]); } if (array_key_exists($keys[6], $arr)) { - $this->setPluginFile($arr[$keys[6]]); + $this->setPluginFolder($arr[$keys[6]]); } if (array_key_exists($keys[7], $arr)) { - $this->setPluginFolder($arr[$keys[7]]); + $this->setPluginSetupPage($arr[$keys[7]]); } if (array_key_exists($keys[8], $arr)) { - $this->setPluginSetupPage($arr[$keys[8]]); + $this->setPluginCompanyLogo($arr[$keys[8]]); } if (array_key_exists($keys[9], $arr)) { - $this->setPluginCompanyLogo($arr[$keys[9]]); + $this->setPluginWorkspaces($arr[$keys[9]]); } if (array_key_exists($keys[10], $arr)) { - $this->setPluginWorkspaces($arr[$keys[10]]); + $this->setPluginVersion($arr[$keys[10]]); } if (array_key_exists($keys[11], $arr)) { - $this->setPluginVersion($arr[$keys[11]]); + $this->setPluginEnable($arr[$keys[11]]); } if (array_key_exists($keys[12], $arr)) { - $this->setPluginEnable($arr[$keys[12]]); + $this->setPluginPrivate($arr[$keys[12]]); } if (array_key_exists($keys[13], $arr)) { - $this->setPluginPrivate($arr[$keys[13]]); + $this->setPluginMenus($arr[$keys[13]]); } if (array_key_exists($keys[14], $arr)) { - $this->setPluginMenus($arr[$keys[14]]); + $this->setPluginFolders($arr[$keys[14]]); } if (array_key_exists($keys[15], $arr)) { - $this->setPluginFolders($arr[$keys[15]]); + $this->setPluginTriggers($arr[$keys[15]]); } if (array_key_exists($keys[16], $arr)) { - $this->setPluginTriggers($arr[$keys[16]]); + $this->setPluginPmFunctions($arr[$keys[16]]); } if (array_key_exists($keys[17], $arr)) { - $this->setPluginPmFunctions($arr[$keys[17]]); + $this->setPluginRedirectLogin($arr[$keys[17]]); } if (array_key_exists($keys[18], $arr)) { - $this->setPluginRedirectLogin($arr[$keys[18]]); + $this->setPluginSteps($arr[$keys[18]]); } if (array_key_exists($keys[19], $arr)) { - $this->setPluginSteps($arr[$keys[19]]); + $this->setPluginCss($arr[$keys[19]]); } if (array_key_exists($keys[20], $arr)) { - $this->setPluginCss($arr[$keys[20]]); + $this->setPluginJs($arr[$keys[20]]); } if (array_key_exists($keys[21], $arr)) { - $this->setPluginJs($arr[$keys[21]]); + $this->setPluginRestService($arr[$keys[21]]); } if (array_key_exists($keys[22], $arr)) { - $this->setPluginRestService($arr[$keys[22]]); - } - - if (array_key_exists($keys[23], $arr)) { - $this->setPluginAttributes($arr[$keys[23]]); + $this->setPluginAttributes($arr[$keys[22]]); } } @@ -1588,10 +1548,6 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent { $criteria = new Criteria(PluginsRegistryPeer::DATABASE_NAME); - if ($this->isColumnModified(PluginsRegistryPeer::ID)) { - $criteria->add(PluginsRegistryPeer::ID, $this->id); - } - if ($this->isColumnModified(PluginsRegistryPeer::PR_UID)) { $criteria->add(PluginsRegistryPeer::PR_UID, $this->pr_uid); } @@ -1738,8 +1694,6 @@ abstract class BasePluginsRegistry extends BaseObject implements Persistent public function copyInto($copyObj, $deepCopy = false) { - $copyObj->setId($this->id); - $copyObj->setPluginNamespace($this->plugin_namespace); $copyObj->setPluginDescription($this->plugin_description); diff --git a/workflow/engine/classes/model/om/BasePluginsRegistryPeer.php b/workflow/engine/classes/model/om/BasePluginsRegistryPeer.php index 9623cb3cb..7b900ec09 100644 --- a/workflow/engine/classes/model/om/BasePluginsRegistryPeer.php +++ b/workflow/engine/classes/model/om/BasePluginsRegistryPeer.php @@ -25,15 +25,12 @@ abstract class BasePluginsRegistryPeer const CLASS_DEFAULT = 'classes.model.PluginsRegistry'; /** The total number of columns. */ - const NUM_COLUMNS = 24; + const NUM_COLUMNS = 23; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; - /** the column name for the ID field */ - const ID = 'PLUGINS_REGISTRY.ID'; - /** the column name for the PR_UID field */ const PR_UID = 'PLUGINS_REGISTRY.PR_UID'; @@ -114,10 +111,10 @@ abstract class BasePluginsRegistryPeer * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('Id', 'PrUid', 'PluginNamespace', 'PluginDescription', 'PluginClassName', 'PluginFriendlyName', 'PluginFile', 'PluginFolder', 'PluginSetupPage', 'PluginCompanyLogo', 'PluginWorkspaces', 'PluginVersion', 'PluginEnable', 'PluginPrivate', 'PluginMenus', 'PluginFolders', 'PluginTriggers', 'PluginPmFunctions', 'PluginRedirectLogin', 'PluginSteps', 'PluginCss', 'PluginJs', 'PluginRestService', 'PluginAttributes', ), - BasePeer::TYPE_COLNAME => array (PluginsRegistryPeer::ID, PluginsRegistryPeer::PR_UID, PluginsRegistryPeer::PLUGIN_NAMESPACE, PluginsRegistryPeer::PLUGIN_DESCRIPTION, PluginsRegistryPeer::PLUGIN_CLASS_NAME, PluginsRegistryPeer::PLUGIN_FRIENDLY_NAME, PluginsRegistryPeer::PLUGIN_FILE, PluginsRegistryPeer::PLUGIN_FOLDER, PluginsRegistryPeer::PLUGIN_SETUP_PAGE, PluginsRegistryPeer::PLUGIN_COMPANY_LOGO, PluginsRegistryPeer::PLUGIN_WORKSPACES, PluginsRegistryPeer::PLUGIN_VERSION, PluginsRegistryPeer::PLUGIN_ENABLE, PluginsRegistryPeer::PLUGIN_PRIVATE, PluginsRegistryPeer::PLUGIN_MENUS, PluginsRegistryPeer::PLUGIN_FOLDERS, PluginsRegistryPeer::PLUGIN_TRIGGERS, PluginsRegistryPeer::PLUGIN_PM_FUNCTIONS, PluginsRegistryPeer::PLUGIN_REDIRECT_LOGIN, PluginsRegistryPeer::PLUGIN_STEPS, PluginsRegistryPeer::PLUGIN_CSS, PluginsRegistryPeer::PLUGIN_JS, PluginsRegistryPeer::PLUGIN_REST_SERVICE, PluginsRegistryPeer::PLUGIN_ATTRIBUTES, ), - BasePeer::TYPE_FIELDNAME => array ('ID', 'PR_UID', 'PLUGIN_NAMESPACE', 'PLUGIN_DESCRIPTION', 'PLUGIN_CLASS_NAME', 'PLUGIN_FRIENDLY_NAME', 'PLUGIN_FILE', 'PLUGIN_FOLDER', 'PLUGIN_SETUP_PAGE', 'PLUGIN_COMPANY_LOGO', 'PLUGIN_WORKSPACES', 'PLUGIN_VERSION', 'PLUGIN_ENABLE', 'PLUGIN_PRIVATE', 'PLUGIN_MENUS', 'PLUGIN_FOLDERS', 'PLUGIN_TRIGGERS', 'PLUGIN_PM_FUNCTIONS', 'PLUGIN_REDIRECT_LOGIN', 'PLUGIN_STEPS', 'PLUGIN_CSS', 'PLUGIN_JS', 'PLUGIN_REST_SERVICE', 'PLUGIN_ATTRIBUTES', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, ) + BasePeer::TYPE_PHPNAME => array ('PrUid', 'PluginNamespace', 'PluginDescription', 'PluginClassName', 'PluginFriendlyName', 'PluginFile', 'PluginFolder', 'PluginSetupPage', 'PluginCompanyLogo', 'PluginWorkspaces', 'PluginVersion', 'PluginEnable', 'PluginPrivate', 'PluginMenus', 'PluginFolders', 'PluginTriggers', 'PluginPmFunctions', 'PluginRedirectLogin', 'PluginSteps', 'PluginCss', 'PluginJs', 'PluginRestService', 'PluginAttributes', ), + BasePeer::TYPE_COLNAME => array (PluginsRegistryPeer::PR_UID, PluginsRegistryPeer::PLUGIN_NAMESPACE, PluginsRegistryPeer::PLUGIN_DESCRIPTION, PluginsRegistryPeer::PLUGIN_CLASS_NAME, PluginsRegistryPeer::PLUGIN_FRIENDLY_NAME, PluginsRegistryPeer::PLUGIN_FILE, PluginsRegistryPeer::PLUGIN_FOLDER, PluginsRegistryPeer::PLUGIN_SETUP_PAGE, PluginsRegistryPeer::PLUGIN_COMPANY_LOGO, PluginsRegistryPeer::PLUGIN_WORKSPACES, PluginsRegistryPeer::PLUGIN_VERSION, PluginsRegistryPeer::PLUGIN_ENABLE, PluginsRegistryPeer::PLUGIN_PRIVATE, PluginsRegistryPeer::PLUGIN_MENUS, PluginsRegistryPeer::PLUGIN_FOLDERS, PluginsRegistryPeer::PLUGIN_TRIGGERS, PluginsRegistryPeer::PLUGIN_PM_FUNCTIONS, PluginsRegistryPeer::PLUGIN_REDIRECT_LOGIN, PluginsRegistryPeer::PLUGIN_STEPS, PluginsRegistryPeer::PLUGIN_CSS, PluginsRegistryPeer::PLUGIN_JS, PluginsRegistryPeer::PLUGIN_REST_SERVICE, PluginsRegistryPeer::PLUGIN_ATTRIBUTES, ), + BasePeer::TYPE_FIELDNAME => array ('PR_UID', 'PLUGIN_NAMESPACE', 'PLUGIN_DESCRIPTION', 'PLUGIN_CLASS_NAME', 'PLUGIN_FRIENDLY_NAME', 'PLUGIN_FILE', 'PLUGIN_FOLDER', 'PLUGIN_SETUP_PAGE', 'PLUGIN_COMPANY_LOGO', 'PLUGIN_WORKSPACES', 'PLUGIN_VERSION', 'PLUGIN_ENABLE', 'PLUGIN_PRIVATE', 'PLUGIN_MENUS', 'PLUGIN_FOLDERS', 'PLUGIN_TRIGGERS', 'PLUGIN_PM_FUNCTIONS', 'PLUGIN_REDIRECT_LOGIN', 'PLUGIN_STEPS', 'PLUGIN_CSS', 'PLUGIN_JS', 'PLUGIN_REST_SERVICE', 'PLUGIN_ATTRIBUTES', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, ) ); /** @@ -127,10 +124,10 @@ abstract class BasePluginsRegistryPeer * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'PrUid' => 1, 'PluginNamespace' => 2, 'PluginDescription' => 3, 'PluginClassName' => 4, 'PluginFriendlyName' => 5, 'PluginFile' => 6, 'PluginFolder' => 7, 'PluginSetupPage' => 8, 'PluginCompanyLogo' => 9, 'PluginWorkspaces' => 10, 'PluginVersion' => 11, 'PluginEnable' => 12, 'PluginPrivate' => 13, 'PluginMenus' => 14, 'PluginFolders' => 15, 'PluginTriggers' => 16, 'PluginPmFunctions' => 17, 'PluginRedirectLogin' => 18, 'PluginSteps' => 19, 'PluginCss' => 20, 'PluginJs' => 21, 'PluginRestService' => 22, 'PluginAttributes' => 23, ), - BasePeer::TYPE_COLNAME => array (PluginsRegistryPeer::ID => 0, PluginsRegistryPeer::PR_UID => 1, PluginsRegistryPeer::PLUGIN_NAMESPACE => 2, PluginsRegistryPeer::PLUGIN_DESCRIPTION => 3, PluginsRegistryPeer::PLUGIN_CLASS_NAME => 4, PluginsRegistryPeer::PLUGIN_FRIENDLY_NAME => 5, PluginsRegistryPeer::PLUGIN_FILE => 6, PluginsRegistryPeer::PLUGIN_FOLDER => 7, PluginsRegistryPeer::PLUGIN_SETUP_PAGE => 8, PluginsRegistryPeer::PLUGIN_COMPANY_LOGO => 9, PluginsRegistryPeer::PLUGIN_WORKSPACES => 10, PluginsRegistryPeer::PLUGIN_VERSION => 11, PluginsRegistryPeer::PLUGIN_ENABLE => 12, PluginsRegistryPeer::PLUGIN_PRIVATE => 13, PluginsRegistryPeer::PLUGIN_MENUS => 14, PluginsRegistryPeer::PLUGIN_FOLDERS => 15, PluginsRegistryPeer::PLUGIN_TRIGGERS => 16, PluginsRegistryPeer::PLUGIN_PM_FUNCTIONS => 17, PluginsRegistryPeer::PLUGIN_REDIRECT_LOGIN => 18, PluginsRegistryPeer::PLUGIN_STEPS => 19, PluginsRegistryPeer::PLUGIN_CSS => 20, PluginsRegistryPeer::PLUGIN_JS => 21, PluginsRegistryPeer::PLUGIN_REST_SERVICE => 22, PluginsRegistryPeer::PLUGIN_ATTRIBUTES => 23, ), - BasePeer::TYPE_FIELDNAME => array ('ID' => 0, 'PR_UID' => 1, 'PLUGIN_NAMESPACE' => 2, 'PLUGIN_DESCRIPTION' => 3, 'PLUGIN_CLASS_NAME' => 4, 'PLUGIN_FRIENDLY_NAME' => 5, 'PLUGIN_FILE' => 6, 'PLUGIN_FOLDER' => 7, 'PLUGIN_SETUP_PAGE' => 8, 'PLUGIN_COMPANY_LOGO' => 9, 'PLUGIN_WORKSPACES' => 10, 'PLUGIN_VERSION' => 11, 'PLUGIN_ENABLE' => 12, 'PLUGIN_PRIVATE' => 13, 'PLUGIN_MENUS' => 14, 'PLUGIN_FOLDERS' => 15, 'PLUGIN_TRIGGERS' => 16, 'PLUGIN_PM_FUNCTIONS' => 17, 'PLUGIN_REDIRECT_LOGIN' => 18, 'PLUGIN_STEPS' => 19, 'PLUGIN_CSS' => 20, 'PLUGIN_JS' => 21, 'PLUGIN_REST_SERVICE' => 22, 'PLUGIN_ATTRIBUTES' => 23, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, ) + BasePeer::TYPE_PHPNAME => array ('PrUid' => 0, 'PluginNamespace' => 1, 'PluginDescription' => 2, 'PluginClassName' => 3, 'PluginFriendlyName' => 4, 'PluginFile' => 5, 'PluginFolder' => 6, 'PluginSetupPage' => 7, 'PluginCompanyLogo' => 8, 'PluginWorkspaces' => 9, 'PluginVersion' => 10, 'PluginEnable' => 11, 'PluginPrivate' => 12, 'PluginMenus' => 13, 'PluginFolders' => 14, 'PluginTriggers' => 15, 'PluginPmFunctions' => 16, 'PluginRedirectLogin' => 17, 'PluginSteps' => 18, 'PluginCss' => 19, 'PluginJs' => 20, 'PluginRestService' => 21, 'PluginAttributes' => 22, ), + BasePeer::TYPE_COLNAME => array (PluginsRegistryPeer::PR_UID => 0, PluginsRegistryPeer::PLUGIN_NAMESPACE => 1, PluginsRegistryPeer::PLUGIN_DESCRIPTION => 2, PluginsRegistryPeer::PLUGIN_CLASS_NAME => 3, PluginsRegistryPeer::PLUGIN_FRIENDLY_NAME => 4, PluginsRegistryPeer::PLUGIN_FILE => 5, PluginsRegistryPeer::PLUGIN_FOLDER => 6, PluginsRegistryPeer::PLUGIN_SETUP_PAGE => 7, PluginsRegistryPeer::PLUGIN_COMPANY_LOGO => 8, PluginsRegistryPeer::PLUGIN_WORKSPACES => 9, PluginsRegistryPeer::PLUGIN_VERSION => 10, PluginsRegistryPeer::PLUGIN_ENABLE => 11, PluginsRegistryPeer::PLUGIN_PRIVATE => 12, PluginsRegistryPeer::PLUGIN_MENUS => 13, PluginsRegistryPeer::PLUGIN_FOLDERS => 14, PluginsRegistryPeer::PLUGIN_TRIGGERS => 15, PluginsRegistryPeer::PLUGIN_PM_FUNCTIONS => 16, PluginsRegistryPeer::PLUGIN_REDIRECT_LOGIN => 17, PluginsRegistryPeer::PLUGIN_STEPS => 18, PluginsRegistryPeer::PLUGIN_CSS => 19, PluginsRegistryPeer::PLUGIN_JS => 20, PluginsRegistryPeer::PLUGIN_REST_SERVICE => 21, PluginsRegistryPeer::PLUGIN_ATTRIBUTES => 22, ), + BasePeer::TYPE_FIELDNAME => array ('PR_UID' => 0, 'PLUGIN_NAMESPACE' => 1, 'PLUGIN_DESCRIPTION' => 2, 'PLUGIN_CLASS_NAME' => 3, 'PLUGIN_FRIENDLY_NAME' => 4, 'PLUGIN_FILE' => 5, 'PLUGIN_FOLDER' => 6, 'PLUGIN_SETUP_PAGE' => 7, 'PLUGIN_COMPANY_LOGO' => 8, 'PLUGIN_WORKSPACES' => 9, 'PLUGIN_VERSION' => 10, 'PLUGIN_ENABLE' => 11, 'PLUGIN_PRIVATE' => 12, 'PLUGIN_MENUS' => 13, 'PLUGIN_FOLDERS' => 14, 'PLUGIN_TRIGGERS' => 15, 'PLUGIN_PM_FUNCTIONS' => 16, 'PLUGIN_REDIRECT_LOGIN' => 17, 'PLUGIN_STEPS' => 18, 'PLUGIN_CSS' => 19, 'PLUGIN_JS' => 20, 'PLUGIN_REST_SERVICE' => 21, 'PLUGIN_ATTRIBUTES' => 22, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, ) ); /** @@ -231,8 +228,6 @@ abstract class BasePluginsRegistryPeer public static function addSelectColumns(Criteria $criteria) { - $criteria->addSelectColumn(PluginsRegistryPeer::ID); - $criteria->addSelectColumn(PluginsRegistryPeer::PR_UID); $criteria->addSelectColumn(PluginsRegistryPeer::PLUGIN_NAMESPACE); diff --git a/workflow/engine/classes/triggers/DestinationUrlCollection.php b/workflow/engine/classes/triggers/DestinationUrlCollection.php new file mode 100644 index 000000000..5ef24fa00 --- /dev/null +++ b/workflow/engine/classes/triggers/DestinationUrlCollection.php @@ -0,0 +1,12 @@ +- auth Setup"; - $this->auth = $auth; - } - - public function setwsdlurl($wsdl) - { - //print "
- wsdl Setup"; - $this->wsdlurl = $wsdl; - //var_dump($wsdl); - } - - public function loadSOAPClient() - { - try { - // we unregister the current HTTP wrapper - stream_wrapper_unregister('http'); - // we register the new HTTP wrapper - //$client = new PMServiceProviderNTLMStream($this->auth); - PMServiceProviderNTLMStream::setAuthStream($this->auth); - stream_wrapper_register('http', 'PMServiceProviderNTLMStream') or die("Failed to register protocol"); - - // $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1, 'auth' => $this->auth));// Hugo's code - $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1)); // Ankit's Code - $this->client->setAuthClient($this->auth); - return true; - } catch (Exception $e) { - echo $e; - exit(); - } - } - - public function callWsMethod($methodName, $paramArray) - { - - try { - if ($methodName == 'DeleteDws' || $methodName == 'GetListCollection') { - $strResult = ""; - $strResult = $this->client->$methodName($paramArray = ""); - return $strResult; - } else { - $strResult = ""; - $strResult = $this->client->$methodName($paramArray); - return $strResult; - } - } catch (SoapFault $fault) { - echo 'Fault code: ' . $fault->faultcode; - echo 'Fault string: ' . $fault->faultstring; - } - stream_wrapper_restore('http'); - } -} - -class DestinationUrlCollection -{ - public $string; -} - -; - -class FieldInformation -{ -} - -class FieldInformationCollection -{ - public $FieldInformation; -} - -class pmTrSharepointClass +class PmTrSharepointClass { public function __construct($server, $auth) @@ -443,4 +359,3 @@ class pmTrSharepointClass } } } - diff --git a/workflow/engine/classes/triggers/WsCaller.php b/workflow/engine/classes/triggers/WsCaller.php new file mode 100644 index 000000000..6e1b852df --- /dev/null +++ b/workflow/engine/classes/triggers/WsCaller.php @@ -0,0 +1,64 @@ +- auth Setup"; + $this->auth = $auth; + } + + public function setwsdlurl($wsdl) + { + //print "
- wsdl Setup"; + $this->wsdlurl = $wsdl; + //var_dump($wsdl); + } + + public function loadSOAPClient() + { + try { + // we unregister the current HTTP wrapper + stream_wrapper_unregister('http'); + // we register the new HTTP wrapper + //$client = new PMServiceProviderNTLMStream($this->auth); + PMServiceProviderNTLMStream::setAuthStream($this->auth); + stream_wrapper_register('http', 'PMServiceProviderNTLMStream') or die("Failed to register protocol"); + + // $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1, 'auth' => $this->auth));// Hugo's code + $this->client = new PMServiceNTLMSoapClient($this->wsdlurl, array('trace' => 1)); // Ankit's Code + $this->client->setAuthClient($this->auth); + return true; + } catch (Exception $e) { + echo $e; + exit(); + } + } + + public function callWsMethod($methodName, $paramArray) + { + + try { + if ($methodName == 'DeleteDws' || $methodName == 'GetListCollection') { + $strResult = ""; + $strResult = $this->client->$methodName($paramArray = ""); + return $strResult; + } else { + $strResult = ""; + $strResult = $this->client->$methodName($paramArray); + return $strResult; + } + } catch (SoapFault $fault) { + echo 'Fault code: ' . $fault->faultcode; + echo 'Fault string: ' . $fault->faultstring; + } + stream_wrapper_restore('http'); + } +} diff --git a/workflow/engine/classes/triggers/api/class.zimbraApi.php b/workflow/engine/classes/triggers/api/Zimbra.php similarity index 96% rename from workflow/engine/classes/triggers/api/class.zimbraApi.php rename to workflow/engine/classes/triggers/api/Zimbra.php index 0a564f8b7..dceac7d28 100644 --- a/workflow/engine/classes/triggers/api/class.zimbraApi.php +++ b/workflow/engine/classes/triggers/api/Zimbra.php @@ -1,5 +1,18 @@ + * @GPL 2007, Plymouth State University, ITS + */ + +use ProcessMaker\Core\System; + /** * zimbra.class.php * @@ -195,7 +208,7 @@ class Zimbra curl_setopt($this->_curl, CURLOPT_SSL_VERIFYHOST, false); //Apply proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt($this->_curl, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); if ($sysConf['proxy_port'] != '') { @@ -1296,66 +1309,3 @@ class Zimbra // end getDocId } - -// end Zimbra class -// annoying sorting functions for getTasks... -// I don't know how to make usort calls to internal OO functions -// if someone knows how, please fix this :) - -/** - * zimbra_startSort - * - * sort of zimbra elements - * - * @since version 1.0 - * @access public - * @param array $task_a - * @param array $task_b - * @return int (($task_a['dueDate']-$task_a['dur']) < ($task_b['dueDate']-$task_b['dur'])) ? -1 : 1 - */ -function zimbra_startSort($task_a, $task_b) -{ - if (($task_a['dueDate'] - $task_a['dur']) == ($task_b['dueDate'] - $task_b['dur'])) { - return ($task_a['name'] < $task_b['name']) ? - 1 : 1; - } - return (($task_a['dueDate'] - $task_a['dur']) < ($task_b['dueDate'] - $task_b['dur'])) ? - 1 : 1; -} - -/** - * zimbra_dueSort - * - * sort by dueDate - * - * @since version 1.0 - * @access public - * @param array $task_a - * @param array $task_b - * @return int ($task_a['dueDate'] < $task_b['dueDate']) ? -1 : 1 - */ -function zimbra_dueSort($task_a, $task_b) -{ - if ($task_a['dueDate'] == $task_b['dueDate']) { - return ($task_a['name'] < $task_b['name']) ? - 1 : 1; - } - return ($task_a['dueDate'] < $task_b['dueDate']) ? - 1 : 1; -} - -/** - * zimbra_nameSort - * - * sort by name - * - * @since version 1.0 - * @access public - * @param array $task_a - * @param array $task_b - * @return int ($task_a['name'] < $task_b['name']) ? -1 : 1 - */ -function zimbra_nameSort($task_a, $task_b) -{ - if ($task_a['name'] == $task_b['name']) { - return 0; - } - return ($task_a['name'] < $task_b['name']) ? - 1 : 1; -} - diff --git a/workflow/engine/classes/triggers/class.pmSharepointFunctions.php b/workflow/engine/classes/triggers/class.pmSharepointFunctions.php index 307520fcb..cb5ac56ed 100644 --- a/workflow/engine/classes/triggers/class.pmSharepointFunctions.php +++ b/workflow/engine/classes/triggers/class.pmSharepointFunctions.php @@ -48,7 +48,7 @@ function createDWS ($sharepointServer, $auth, $name = "", $users = "", $title = { //print "Trigger: createDWS"; require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $beforeResult = $pmTrSharepoint->createDWS( $name, $users, $title, $documents ); return $beforeResult; } @@ -72,7 +72,7 @@ function createDWS ($sharepointServer, $auth, $name = "", $users = "", $title = function deleteDWS ($sharepointServer, $auth, $dwsname) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $beforeResult = $pmTrSharepoint->deleteDWS( $dwsname ); $newResult = $beforeResult->DeleteDwsResult; if ($newResult == '') { @@ -103,7 +103,7 @@ function deleteDWS ($sharepointServer, $auth, $dwsname) function createFolderDWS ($sharepointServer, $auth, $dwsname, $dwsFolderName) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->createFolderDWS( $dwsname, $dwsFolderName ); var_dump( $result ); $newResult = $result->CreateFolderResult; @@ -138,7 +138,7 @@ function createFolderDWS ($sharepointServer, $auth, $dwsname, $dwsFolderName) function deleteFolderDWS ($sharepointServer, $auth, $dwsname, $folderName) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->deleteFolderDWS( $dwsname, $folderName ); $newResult = $result->DeleteFolderResult; if (isset( $newResult )) { @@ -171,7 +171,7 @@ function deleteFolderDWS ($sharepointServer, $auth, $dwsname, $folderName) function getDWSData ($sharepointServer, $auth, $newFileName, $dwsname, $lastUpdate) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $resultDWSData = $pmTrSharepoint->getDWSData( $newFileName, $dwsname, $lastUpdate ); if ($resultDWSData) { return $resultDWSData; @@ -202,7 +202,7 @@ function getDWSData ($sharepointServer, $auth, $newFileName, $dwsname, $lastUpda function getDWSMetaData ($sharepointServer, $auth, $newFileName, $dwsname, $id) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->getDWSMetaData( $newFileName, $dwsname, $id ); //$newResult = $result->GetDwsMetaDataResult; if (isset( $result )) { @@ -235,7 +235,7 @@ function getDWSMetaData ($sharepointServer, $auth, $newFileName, $dwsname, $id) function uploadDocumentDWS ($sharepointServer, $auth, $dwsname, $folderName, $sourceUrl, $filename) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $beforeResult = $pmTrSharepoint->uploadDocumentDWS( $dwsname, $folderName, $sourceUrl, $filename ); return $beforeResult; @@ -262,7 +262,7 @@ function uploadDocumentDWS ($sharepointServer, $auth, $dwsname, $folderName, $so function downloadDocumentDWS ($sharepointServer, $auth, $dwsname, $fileName, $fileLocation) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->downloadDocumentDWS( $dwsname, $fileName, $fileLocation ); if (isset( $result )) { return "Document downloaded"; @@ -291,7 +291,7 @@ function downloadDocumentDWS ($sharepointServer, $auth, $dwsname, $fileName, $fi function getDWSFolderItems ($sharepointServer, $auth, $dwsname, $strFolderUrl) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->getDWSFolderItems( $dwsname, $strFolderUrl ); if (isset( $result )) { return $result; @@ -320,7 +320,7 @@ function getDWSFolderItems ($sharepointServer, $auth, $dwsname, $strFolderUrl) function getDWSDocumentVersions ($sharepointServer, $auth, $newFileName, $dwsname) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->getDWSDocumentVersions( $newFileName, $dwsname ); if (isset( $result->GetVersionsResult )) { /* @@ -361,7 +361,7 @@ function getDWSDocumentVersions ($sharepointServer, $auth, $newFileName, $dwsnam function deleteDWSDocumentVersion ($sharepointServer, $auth, $newFileName, $dwsname, $versionNum) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->deleteDWSDocVersion( $newFileName, $dwsname, $versionNum ); return $result; } @@ -386,7 +386,7 @@ function deleteDWSDocumentVersion ($sharepointServer, $auth, $newFileName, $dwsn function deleteDWSAllDocumentVersion ($sharepointServer, $auth, $newFileName, $dwsname) { require_once (PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'class.pmTrSharepoint.php'); - $pmTrSharepoint = new pmTrSharepointClass( $sharepointServer, $auth ); + $pmTrSharepoint = new PmTrSharepointClass( $sharepointServer, $auth ); $result = $pmTrSharepoint->deleteAllDWSDocVersion( $newFileName, $dwsname ); return $result; } diff --git a/workflow/engine/classes/triggers/class.pmSugarFunctions.php b/workflow/engine/classes/triggers/class.pmSugarFunctions.php index 077883651..61ab24a34 100644 --- a/workflow/engine/classes/triggers/class.pmSugarFunctions.php +++ b/workflow/engine/classes/triggers/class.pmSugarFunctions.php @@ -1,5 +1,7 @@ 1); //Apply proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $options['proxy_host'] = $sysConf['proxy_host']; if ($sysConf['proxy_port'] != '') { diff --git a/workflow/engine/classes/triggers/class.pmTalendFunctions.php b/workflow/engine/classes/triggers/class.pmTalendFunctions.php index 340d9a1ed..0b0083618 100644 --- a/workflow/engine/classes/triggers/class.pmTalendFunctions.php +++ b/workflow/engine/classes/triggers/class.pmTalendFunctions.php @@ -15,6 +15,7 @@ // // License: LGPL, see LICENSE //////////////////////////////////////////////////// +use ProcessMaker\Core\System; /** @@ -47,7 +48,7 @@ function executeTalendWebservice ($wsdl, $message, $params = array()) ) ); //Apply proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt( $client, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); if ($sysConf['proxy_port'] != '') { diff --git a/workflow/engine/classes/triggers/class.pmTrZimbra.php b/workflow/engine/classes/triggers/class.pmTrZimbra.php index 2873a5258..6a7aed5c9 100644 --- a/workflow/engine/classes/triggers/class.pmTrZimbra.php +++ b/workflow/engine/classes/triggers/class.pmTrZimbra.php @@ -14,6 +14,7 @@ // // License: LGPL, see LICENSE //////////////////////////////////////////////////// +use ProcessMaker\Core\System; /** @@ -40,7 +41,6 @@ * @return string | $result | Response | * */ -include_once PATH_CORE . 'classes' . PATH_SEP . 'triggers' . PATH_SEP . 'api' . PATH_SEP . "class.zimbraApi.php"; function getZimbraFolder($ServerUrl, $username, $preAuthKey, $folderName, $protocol = 'http') { @@ -402,7 +402,7 @@ function uploadZimbraFile($ServerUrl, $username, $preAuthKey, $folderName, $file curl_setopt ($ch, CURLOPT_HTTPHEADER,$header_array); //Apply proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt($ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); if ($sysConf['proxy_port'] != '') { diff --git a/workflow/engine/config/paths.php b/workflow/engine/config/paths.php index 3a1b86dde..39b150708 100644 --- a/workflow/engine/config/paths.php +++ b/workflow/engine/config/paths.php @@ -142,3 +142,4 @@ define('PML_UPLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/uploadProcess'); define('PML_DOWNLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/download'); + G::defineConstants(); diff --git a/workflow/engine/config/schema.xml b/workflow/engine/config/schema.xml index 19cd4e063..a2036ea2f 100644 --- a/workflow/engine/config/schema.xml +++ b/workflow/engine/config/schema.xml @@ -5641,7 +5641,6 @@ - @@ -5653,8 +5652,8 @@ - - + + @@ -5666,8 +5665,5 @@ - - -
diff --git a/workflow/engine/controllers/admin.php b/workflow/engine/controllers/admin.php index bba49987b..aa87d89ca 100644 --- a/workflow/engine/controllers/admin.php +++ b/workflow/engine/controllers/admin.php @@ -1,5 +1,7 @@ requirePermissions( 'PM_SETUP' ); require_once PATH_CONTROLLERS . 'main.php'; - $skinsList = PmSystem::getSkingList(); + $skinsList = System::getSkingList(); foreach ($skinsList['skins'] as $key => $value) { if ($value['SKIN_WORKSPACE'] != 'Global') { unset( $skinsList['skins'][$key] ); @@ -29,7 +31,7 @@ class Admin extends Controller $mainController = new Main(); $languagesList = $mainController->getLanguagesList(); $languagesList[] = array ("", G::LoadTranslation("ID_USE_LANGUAGE_URL")); - $sysConf = PmSystem::getSystemConfiguration( PATH_CONFIG . 'env.ini' ); + $sysConf = System::getSystemConfiguration( PATH_CONFIG . 'env.ini' ); foreach ($skinsList['skins'] as $skin) { $skins[] = array ($skin['SKIN_FOLDER_ID'],$skin['SKIN_NAME']); @@ -230,7 +232,7 @@ class Admin extends Controller $redhat .= " (" . PHP_OS . ")"; if (defined( "DB_HOST" )) { - $dbNetView = new NET( DB_HOST ); + $dbNetView = new Net( DB_HOST ); $dbNetView->loginDbServer( DB_USER, DB_PASS ); $dbConns = new DbConnections( '' ); @@ -268,7 +270,7 @@ class Admin extends Controller if (defined('SYSTEM_NAME')) { $systemName = SYSTEM_NAME; } - $properties[] = array ($systemName. ' Ver.', PmSystem::getVersion() . $ee, $pmSection); + $properties[] = array ($systemName. ' Ver.', System::getVersion() . $ee, $pmSection); $properties[] = array("PMUI JS Lib. Ver.", $pmuiVer, $pmSection); $properties[] = array("MAFE JS Lib. Ver.", $mafeVer, $pmSection); $properties[] = array("PM Dynaform JS Lib. Ver.", $pmdynaformVer, $pmSection); diff --git a/workflow/engine/controllers/adminProxy.php b/workflow/engine/controllers/adminProxy.php index 17591826a..6c4aebb86 100644 --- a/workflow/engine/controllers/adminProxy.php +++ b/workflow/engine/controllers/adminProxy.php @@ -1,5 +1,6 @@ default_lang) { @@ -99,7 +100,7 @@ class adminProxy extends HttpProxyController } } - PmSystem::updateIndexFile(array( + System::updateIndexFile(array( 'lang' => $sysConf['default_lang'], 'skin' => $sysConf['default_skin'] )); @@ -433,7 +434,7 @@ class adminProxy extends HttpProxyController $Mailto = $_POST['eMailto']; $SMTPSecure = $_POST['UseSecureCon']; - $Server = new NET($server); + $Server = new Net($server); $smtp = new SMTP; $timeout = 10; @@ -614,12 +615,12 @@ class adminProxy extends HttpProxyController $sBodyPre->prepare(); $sBodyPre->assign('server', $_SERVER['SERVER_NAME']); $sBodyPre->assign('date', date('H:i:s')); - $sBodyPre->assign('ver', PmSystem::getVersion()); + $sBodyPre->assign('ver', System::getVersion()); $sBodyPre->assign('engine', $engine); $sBodyPre->assign('msg', $msg); $sBody = $sBodyPre->getOutputContent(); - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aConfiguration); @@ -790,7 +791,7 @@ class adminProxy extends HttpProxyController { $uplogo = PATH_TPL . 'setup' . PATH_SEP . 'uplogo.html'; $width = "100%"; - $upload = new replacementLogo(); + $upload = new ReplacementLogo(); $aPhotoSelect = $upload->getNameLogo($_SESSION['USER_LOGGED']); $sPhotoSelect = trim($aPhotoSelect['DEFAULT_LOGO_NAME']); $check = ''; @@ -1093,7 +1094,7 @@ class adminProxy extends HttpProxyController */ public function getNameCurrentLogo() { - $upload = new replacementLogo(); + $upload = new ReplacementLogo(); $aPhotoSelect = $upload->getNameLogo($_SESSION['USER_LOGGED']); $sPhotoSelect = trim($aPhotoSelect['DEFAULT_LOGO_NAME']); return $sPhotoSelect; @@ -1384,9 +1385,9 @@ class adminProxy extends HttpProxyController require_once (PATH_CONTROLLERS . "installer.php"); $params = array (); - $oServerConf = &serverConf::getSingleton(); + $oServerConf = &ServerConf::getSingleton(); $pluginRegistry = PluginRegistry::loadSingleton(); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); //License Information: $activeLicense = $licenseManager->getActiveLicense(); @@ -1418,7 +1419,7 @@ class adminProxy extends HttpProxyController $params['lt'] = isset($licInfo[SYS_SYS]) ? isset($licInfo[SYS_SYS]['TYPE'])? $licInfo[SYS_SYS]['TYPE'] : '' : ''; //ProcessMaker Version - $params['v'] = PmSystem::getVersion(); + $params['v'] = System::getVersion(); if (file_exists(PATH_DATA. 'log/upgrades.log')) { $params['pmu'] = serialize(file_get_contents(PATH_DATA. 'log/upgrades.log', 'r')); } else { @@ -1508,7 +1509,7 @@ class adminProxy extends HttpProxyController //Country/city (Timezone) $params['t'] = (defined('TIME_ZONE') && TIME_ZONE != "Unknown") ? TIME_ZONE : date_default_timezone_get(); - $params['w'] = count(PmSystem::listWorkspaces()); + $params['w'] = count(System::listWorkspaces()); $support = PATH_DATA_SITE . G::sanitizeString($licenseManager->info['FIRST_NAME'] . '-' . $licenseManager->info['LAST_NAME'] . '-' . SYS_SYS . '-' . date('YmdHis'), false, false) . '.spm'; file_put_contents($support, serialize($params)); diff --git a/workflow/engine/controllers/dashboard.php b/workflow/engine/controllers/dashboard.php index 1bb2f8e6f..84c0101fc 100644 --- a/workflow/engine/controllers/dashboard.php +++ b/workflow/engine/controllers/dashboard.php @@ -22,7 +22,7 @@ class Dashboard extends Controller G::header( 'location: login/login' ); exit(0); } - $this->pmDashlet = new PMDashlet(); + $this->pmDashlet = new PmDashlet(); } // Functions for the dashboards users module - Start @@ -244,14 +244,14 @@ class Dashboard extends Controller if ($data->DAS_INS_UID != '') { $this->pmDashlet->setup( $data->DAS_INS_UID ); $this->setJSVar( 'dashletInstance', $this->pmDashlet->getDashletInstance() ); - $this->setJSVar( 'additionalFields', PMDashlet::getAdditionalFields( get_class( $this->pmDashlet->getDashletObject() ) ) ); + $this->setJSVar( 'additionalFields', PmDashlet::getAdditionalFields( get_class( $this->pmDashlet->getDashletObject() ) ) ); } else { $dashletInstance = new stdclass(); $dashletInstance->DAS_UID = $dashlets[0][0]; $dashlet = new Dashlet(); $dashletFields = $dashlet->load( $dashletInstance->DAS_UID ); $this->setJSVar( 'dashletInstance', $dashletInstance ); - $this->setJSVar( 'additionalFields', PMDashlet::getAdditionalFields( $dashletFields['DAS_CLASS'] ) ); + $this->setJSVar( 'additionalFields', PmDashlet::getAdditionalFields( $dashletFields['DAS_CLASS'] ) ); } G::RenderPage( 'publish', 'extJs' ); return null; @@ -305,7 +305,7 @@ class Dashboard extends Controller $dashlet = new Dashlet(); $dashletFields = $dashlet->load( $data->DAS_UID ); if (! is_null( $dashletFields )) { - $result->additionalFields = PMDashlet::getAdditionalFields( $dashletFields['DAS_CLASS'] ); + $result->additionalFields = PmDashlet::getAdditionalFields( $dashletFields['DAS_CLASS'] ); } else { throw new Exception( 'Dashlet "' . $data->DAS_UID . '" does not exist.' ); } diff --git a/workflow/engine/controllers/designer.php b/workflow/engine/controllers/designer.php index 5b9b241da..efa0d8ccb 100644 --- a/workflow/engine/controllers/designer.php +++ b/workflow/engine/controllers/designer.php @@ -1,5 +1,6 @@ setVar("SYS_SYS", SYS_SYS); $this->setVar("SYS_LANG", SYS_LANG); $this->setVar("SYS_SKIN", SYS_SKIN); - $this->setVar('HTTP_SERVER_HOSTNAME', PmSystem::getHttpServerHostnameRequestsFrontEnd()); + $this->setVar('HTTP_SERVER_HOSTNAME', System::getHttpServerHostnameRequestsFrontEnd()); if ($debug) { if (!file_exists(PATH_HTML . "lib-dev/pmUI/build.cache")) { diff --git a/workflow/engine/controllers/home.php b/workflow/engine/controllers/home.php index 6e0f2e5c3..8633d6982 100644 --- a/workflow/engine/controllers/home.php +++ b/workflow/engine/controllers/home.php @@ -1,5 +1,7 @@ isRtl( SYS_LANG )) { $swRtl = 1; @@ -184,7 +186,7 @@ class Home extends Controller $solrEnabled = false; - if (($solrConf = PmSystem::solrEnv()) !== false) { + if (($solrConf = System::solrEnv()) !== false) { $ApplicationSolrIndex = new AppSolr( $solrConf["solr_enabled"], @@ -408,7 +410,7 @@ class Home extends Controller $type == "todo" || $type == "draft" || $type == "paused" || $type == "sent" || $type == "selfservice" || $type == "unassigned" || $type == "search" ) && - (($solrConf = PmSystem::solrEnv()) !== false) + (($solrConf = System::solrEnv()) !== false) ) { $ApplicationSolrIndex = new AppSolr( diff --git a/workflow/engine/controllers/installer.php b/workflow/engine/controllers/installer.php index e5fc7deac..634e28f07 100644 --- a/workflow/engine/controllers/installer.php +++ b/workflow/engine/controllers/installer.php @@ -1,12 +1,9 @@ - */ +use ProcessMaker\Core\System; global $translation; -include PATH_LANGUAGECONT."translation.".SYS_LANG; + +include PATH_LANGUAGECONT . "translation." . SYS_LANG; class Installer extends Controller { @@ -966,7 +963,7 @@ class Installer extends Controller $envFile = PATH_CONFIG . 'env.ini'; // getting configuration from env.ini - $sysConf = PmSystem::getSystemConfiguration( $envFile ); + $sysConf = System::getSystemConfiguration( $envFile ); $langUri = 'en'; if (isset($sysConf['default_lang'])) { @@ -1022,7 +1019,7 @@ class Installer extends Controller try { // update the main index file - $indexFileUpdated = PmSystem::updateIndexFile(array('lang' => 'en','skin' => $updatedConf['default_skin'])); + $indexFileUpdated = System::updateIndexFile(array('lang' => 'en','skin' => $updatedConf['default_skin'])); } catch (Exception $e) { $info->result = false; $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, Array(PATH_HTML . "index.html.")); diff --git a/workflow/engine/controllers/main.php b/workflow/engine/controllers/main.php index 4255bd3df..a7a35c9e8 100644 --- a/workflow/engine/controllers/main.php +++ b/workflow/engine/controllers/main.php @@ -1,5 +1,6 @@ getExpireIn(); $expireInLabel = $pmLicenseManager->getExpireInLabel(); @@ -199,7 +200,7 @@ class Main extends Controller if (($nextBeatDate = $this->memcache->get( 'nextBeatDate' )) === false) { //get the serverconf singleton, and check if we can send the heartbeat - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $sflag = $oServerConf->getHeartbeatProperty( 'HB_OPTION', 'HEART_BEAT_CONF' ); $sflag = (trim( $sflag ) != '') ? $sflag : '1'; //get date of next beat @@ -264,7 +265,7 @@ class Main extends Controller } $this->setVar( 'logo_company', $this->getCompanyLogo() ); - $this->setVar( 'pmos_version', PmSystem::getVersion() ); + $this->setVar( 'pmos_version', System::getVersion() ); $footerText = 'Copyright © 2003-' . date( 'Y' ) . ' Colosa, Inc. All rights reserved.'; $adviseText = 'Supplied free of charge with no support, certification, warranty, @@ -305,7 +306,7 @@ class Main extends Controller $aField['LOGIN_VERIFY_MSG'] = G::loadTranslation( 'LOGIN_VERIFY_MSG' ); //Get Server Configuration - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $availableLangArray = $this->getLanguagesList(); @@ -314,7 +315,7 @@ class Main extends Controller $this->includeExtJS( 'main/sysLogin' ); $this->setVar( 'logo_company', $this->getCompanyLogo() ); - $this->setVar( 'pmos_version', PmSystem::getVersion() ); + $this->setVar( 'pmos_version', System::getVersion() ); $footerText = G::LoadTranslation('ID_COPYRIGHT_FROM') . date( 'Y' ) . G::LoadTranslation('ID_COPYRIGHT_COL'); $adviseText = G::LoadTranslation('ID_COLOSA_AND_CERTIFIED_PARTNERS'); @@ -384,7 +385,7 @@ class Main extends Controller $template->assign( 'passwd', $newPass ); $template->assign( 'poweredBy', G::loadTranslation( 'ID_PROCESSMAKER_SLOGAN1' ) ); $template->assign( 'versionLabel', G::loadTranslation( 'ID_VERSION' ) ); - $template->assign( 'version', PmSystem::getVersion() ); + $template->assign( 'version', System::getVersion() ); $template->assign( 'visit', G::loadTranslation( 'ID_VISIT' ) ); $template->assign( 'footer', '' ); @@ -465,7 +466,7 @@ class Main extends Controller if (defined( "SYS_SYS" )) { if (($aFotoSelect = $this->memcache->get( 'aFotoSelect' )) === false) { - $oLogoR = new replacementLogo(); + $oLogoR = new ReplacementLogo(); $aFotoSelect = $oLogoR->getNameLogo( (isset( $_SESSION['USER_LOGGED'] )) ? $_SESSION['USER_LOGGED'] : '' ); $this->memcache->set( 'aFotoSelect', $aFotoSelect, 1 * 3600 ); } @@ -515,7 +516,7 @@ class Main extends Controller private function getWorkspacesAvailable () { - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $dir = PATH_DB; $filesArray = array (); if (file_exists( $dir )) { @@ -695,7 +696,7 @@ class Main extends Controller $redhat .= " (" . PHP_OS . ")"; if (defined( "DB_HOST" )) { - $dbNetView = new NET( DB_HOST ); + $dbNetView = new Net( DB_HOST ); $dbNetView->loginDbServer( DB_USER, DB_PASS ); $dbConns = new DbConnections( '' ); @@ -733,7 +734,7 @@ class Main extends Controller if (defined('SYSTEM_NAME')) { $systemName = SYSTEM_NAME; } - $properties[] = array ($systemName. ' Ver.', PmSystem::getVersion() . $ee, $pmSection); + $properties[] = array ($systemName. ' Ver.', System::getVersion() . $ee, $pmSection); $properties[] = array("PMUI JS Lib. Ver.", $pmuiVer, $pmSection); $properties[] = array("MAFE JS Lib. Ver.", $mafeVer, $pmSection); $properties[] = array("PM Dynaform JS Lib. Ver.", $pmdynaformVer, $pmSection); diff --git a/workflow/engine/controllers/newSiteProxy.php b/workflow/engine/controllers/newSiteProxy.php index e4951fe50..972b58c01 100644 --- a/workflow/engine/controllers/newSiteProxy.php +++ b/workflow/engine/controllers/newSiteProxy.php @@ -1,11 +1,7 @@ - */ +use ProcessMaker\Core\Installer; + class newSiteProxy extends HttpProxyController { @@ -15,7 +11,7 @@ class newSiteProxy extends HttpProxyController $ao_db_drop = (isset( $_POST['AO_DB_DROP'] )) ? true : false; $name = trim( $_POST['NW_TITLE'] ); - $inst = new PmInstaller(); + $inst = new Installer(); if ($inst->isset_site($name)) { if($ao_db_drop === true){ if(!file_exists(PATH_DATA . "sites/" . $name)){ diff --git a/workflow/engine/controllers/pmGmail.php b/workflow/engine/controllers/pmGmail.php index 6eea33ad7..49c4c3bfa 100644 --- a/workflow/engine/controllers/pmGmail.php +++ b/workflow/engine/controllers/pmGmail.php @@ -10,7 +10,7 @@ class pmGmail extends Controller { public function saveConfigPmGmail($httpData) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $result = new StdClass(); $result->success = true; @@ -62,7 +62,7 @@ class pmGmail extends Controller $this->setJSVar('__PMGMAIL_ERROR__', $_SESSION['__PMGMAIL_ERROR__']); unset($_SESSION['__PMGMAIL_ERROR__']); } - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $accountEmail = $pmGoogle->getServiceAccountEmail(); $googleCertificate = $pmGoogle->getServiceAccountCertificate(); $statusGmail = $pmGoogle->getServiceGmailStatus(); @@ -98,7 +98,7 @@ class pmGmail extends Controller */ public function testConfigPmGmail($httpData) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $result = new stdClass(); diff --git a/workflow/engine/controllers/pmTablesProxy.php b/workflow/engine/controllers/pmTablesProxy.php index 14f802cd8..41243e7f2 100644 --- a/workflow/engine/controllers/pmTablesProxy.php +++ b/workflow/engine/controllers/pmTablesProxy.php @@ -6,6 +6,9 @@ * @inherits HttpProxyController * @access public */ + +use ProcessMaker\Core\System; + header("Content-type: text/html;charset=utf-8"); require_once 'classes/model/AdditionalTables.php'; @@ -114,7 +117,7 @@ class pmTablesProxy extends HttpProxyController $dbConn = new DbConnections(); $dbConnections = $dbConn->getConnectionsProUid( $proUid, array('mysql') ); - $workSpace = new workspaceTools(SYS_SYS); + $workSpace = new WorkspaceTools(SYS_SYS); $workspaceDB = $workSpace->getDBInfo(); if ($workspaceDB['DB_NAME'] == $workspaceDB['DB_RBAC_NAME']) { @@ -267,7 +270,7 @@ class pmTablesProxy extends HttpProxyController } if ($row->type == 'CLASSIC') { - $rp = new reportTables(); + $rp = new ReportTables(); $rp->deleteReportTable( $row->id ); $count ++; } else { @@ -918,9 +921,9 @@ class pmTablesProxy extends HttpProxyController try { $result = new stdClass(); - $net = new NET( G::getIpAddress() ); + $net = new Net( G::getIpAddress() ); - $META = " \n-----== ProcessMaker Open Source Private Tables ==-----\n" . " @Ver: 1.0 Oct-2009\n" . " @Processmaker version: " . PmSystem::getVersion() . "\n" . " -------------------------------------------------------\n" . " @Export Date: " . date( "l jS \of F Y h:i:s A" ) . "\n" . " @Server address: " . getenv( 'SERVER_NAME' ) . " (" . getenv( 'SERVER_ADDR' ) . ")\n" . " @Client address: " . $net->hostname . "\n" . " @Workspace: " . SYS_SYS . "\n" . " @Export trace back:\n\n"; + $META = " \n-----== ProcessMaker Open Source Private Tables ==-----\n" . " @Ver: 1.0 Oct-2009\n" . " @Processmaker version: " . System::getVersion() . "\n" . " -------------------------------------------------------\n" . " @Export Date: " . date( "l jS \of F Y h:i:s A" ) . "\n" . " @Server address: " . getenv( 'SERVER_NAME' ) . " (" . getenv( 'SERVER_ADDR' ) . ")\n" . " @Client address: " . $net->hostname . "\n" . " @Workspace: " . SYS_SYS . "\n" . " @Export trace back:\n\n"; $EXPORT_TRACEBACK = Array (); $c = 0; @@ -1365,7 +1368,7 @@ class pmTablesProxy extends HttpProxyController $arrayDynaFormData = $dynaForm->getDynaFormRecordByPk($dynaFormUid, [], false); if ($arrayDynaFormData !== false) { - $arrayGrid = pmDynaform::getGridsAndFields($arrayDynaFormData['DYN_CONTENT']); + $arrayGrid = PmDynaform::getGridsAndFields($arrayDynaFormData['DYN_CONTENT']); if ($arrayGrid !== false && isset($arrayGrid[$gridId])) { $grid = $arrayGrid[$gridId]; @@ -1545,7 +1548,7 @@ class pmTablesProxy extends HttpProxyController $record = $rsCriteria->getRow(); if ($flagIsBpmn) { - $arrayGrid = pmDynaform::getGridsAndFields($record['DYN_CONTENT']); + $arrayGrid = PmDynaform::getGridsAndFields($record['DYN_CONTENT']); if ($arrayGrid !== false) { foreach ($arrayGrid as $value) { diff --git a/workflow/engine/controllers/processProxy.php b/workflow/engine/controllers/processProxy.php index 49d85ddab..bab5b3df8 100644 --- a/workflow/engine/controllers/processProxy.php +++ b/workflow/engine/controllers/processProxy.php @@ -147,15 +147,15 @@ class ProcessProxy extends HttpProxyController $this->success = true; if (! in_array( '-1', $res )) { if (count( $UIDS ) == 1) { - $this->msg = __( 'ID_ACTOR_ASSIGNED_SUCESSFULLY', SYS_LANG, Array ('tas_title' => $task->getTasTitle()) ); + $this->msg = G::LoadTranslation( 'ID_ACTOR_ASSIGNED_SUCESSFULLY', SYS_LANG, Array ('tas_title' => $task->getTasTitle()) ); } else { - $this->msg = __( 'ID_ACTORS_ASSIGNED_SUCESSFULLY', SYS_LANG, Array (count( $UIDS ),$task->getTasTitle()) ); + $this->msg = G::LoadTranslation( 'ID_ACTORS_ASSIGNED_SUCESSFULLY', SYS_LANG, Array (count( $UIDS ),$task->getTasTitle()) ); } } else { if (count( $UIDS ) == 1) { - $this->msg = __( 'ID_ACTOR_ALREADY_ASSIGNED', SYS_LANG, Array ($task->getTasTitle()) ); + $this->msg = G::LoadTranslation( 'ID_ACTOR_ALREADY_ASSIGNED', SYS_LANG, Array ($task->getTasTitle()) ); } else { - $this->msg = __( 'ID_SOME_ACTORS_ALREADY_ASSIGNED', SYS_LANG, Array ($task->getTasTitle()) ); + $this->msg = G::LoadTranslation( 'ID_SOME_ACTORS_ALREADY_ASSIGNED', SYS_LANG, Array ($task->getTasTitle()) ); } } } diff --git a/workflow/engine/controllers/strategicDashboard.php b/workflow/engine/controllers/strategicDashboard.php index 64c0d0810..0a39b6a24 100644 --- a/workflow/engine/controllers/strategicDashboard.php +++ b/workflow/engine/controllers/strategicDashboard.php @@ -1,5 +1,7 @@ load($RBAC->aUserInfo['USER_INFO']['USR_UID']); $this->usrUnitCost = $this->currencySymbolToShow($user); - $this->urlProxy = PmSystem::getHttpServerHostnameRequestsFrontEnd() . '/api/1.0/' . SYS_SYS . '/'; + $this->urlProxy = System::getHttpServerHostnameRequestsFrontEnd() . '/api/1.0/' . SYS_SYS . '/'; //change $clientId = 'x-pm-local-client'; $client = $this->getClientCredentials($clientId); diff --git a/workflow/engine/controllers/webEntryProxy.php b/workflow/engine/controllers/webEntryProxy.php index 4ac277da0..1b350e04e 100644 --- a/workflow/engine/controllers/webEntryProxy.php +++ b/workflow/engine/controllers/webEntryProxy.php @@ -1,5 +1,7 @@ assign( 'dynaform', $dynTitle ); $template->assign( 'timestamp', date( 'l jS \of F Y h:i:s A' ) ); $template->assign( 'ws', SYS_SYS ); - $template->assign( 'version', PmSystem::getVersion() ); + $template->assign( 'version', System::getVersion() ); $fileName = $pathProcess . $dynTitle . 'Post.php'; file_put_contents( $fileName, $template->getOutputContent() ); diff --git a/workflow/engine/data/mysql/schema.sql b/workflow/engine/data/mysql/schema.sql index ec7cbdb2b..156fdc2e4 100644 --- a/workflow/engine/data/mysql/schema.sql +++ b/workflow/engine/data/mysql/schema.sql @@ -3153,7 +3153,6 @@ DROP TABLE IF EXISTS `PLUGINS_REGISTRY`; CREATE TABLE `PLUGINS_REGISTRY` ( - `ID` INTEGER NOT NULL AUTO_INCREMENT, `PR_UID` VARCHAR(32) default '' NOT NULL, `PLUGIN_NAMESPACE` VARCHAR(100) NOT NULL, `PLUGIN_DESCRIPTION` VARCHAR(200) default '', @@ -3165,8 +3164,8 @@ CREATE TABLE `PLUGINS_REGISTRY` `PLUGIN_COMPANY_LOGO` VARCHAR(100) default '', `PLUGIN_WORKSPACES` VARCHAR(100) default '', `PLUGIN_VERSION` VARCHAR(50) default '', - `PLUGIN_ENABLE` INTEGER default 0, - `PLUGIN_PRIVATE` INTEGER default 0, + `PLUGIN_ENABLE` TINYINT default 0, + `PLUGIN_PRIVATE` TINYINT default 0, `PLUGIN_MENUS` MEDIUMTEXT, `PLUGIN_FOLDERS` MEDIUMTEXT, `PLUGIN_TRIGGERS` MEDIUMTEXT, @@ -3177,8 +3176,7 @@ CREATE TABLE `PLUGINS_REGISTRY` `PLUGIN_JS` MEDIUMTEXT, `PLUGIN_REST_SERVICE` MEDIUMTEXT, `PLUGIN_ATTRIBUTES` MEDIUMTEXT, - PRIMARY KEY (`PR_UID`), - UNIQUE KEY `INDEX_PLUGINS_REGISTRY_ID` (`ID`) + PRIMARY KEY (`PR_UID`) )ENGINE=InnoDB ; # This restores the fkey checks, after having unset them earlier SET FOREIGN_KEY_CHECKS = 1; diff --git a/workflow/engine/menus/setup.php b/workflow/engine/menus/setup.php index 989248d22..e057714f4 100644 --- a/workflow/engine/menus/setup.php +++ b/workflow/engine/menus/setup.php @@ -249,14 +249,13 @@ if ($RBAC->userCanAccess('PM_SETUP') === 1) { /*----------------------------------********---------------------------------*/ } /*----------------------------------********---------------------------------*/ -require_once 'classes/class.pmLicenseManager.php'; if (!file_exists(PATH_DATA_SITE . "plugin.singleton")) { require_once PATH_CORE . 'methods' . PATH_SEP . 'enterprise' . PATH_SEP . 'enterprise.php'; $enterprise = new enterprisePlugin('enterprise'); $enterprise->enable(); $enterprise->setup(); } -$pmLicenseManagerO = &pmLicenseManager::getSingleton(); +$pmLicenseManagerO = &PmLicenseManager::getSingleton(); $licenseStatusInfo = $pmLicenseManagerO->getCurrentLicenseStatus(); $licStatusMsg = null; diff --git a/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php b/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php index d1f5363fb..f97356c89 100644 --- a/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php +++ b/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php @@ -235,7 +235,7 @@ try { function getLDAPAdvanceInstance($authUid) { $RBAC = &RBAC::getSingleton(); - $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced = new LdapAdvanced(); $ldapAdvanced->sAuthSource = $authUid; $ldapAdvanced->sSystem = $RBAC->sSystem; diff --git a/workflow/engine/methods/authSources/ldapAdvancedProxy.php b/workflow/engine/methods/authSources/ldapAdvancedProxy.php index cd9d615a3..2800c8825 100644 --- a/workflow/engine/methods/authSources/ldapAdvancedProxy.php +++ b/workflow/engine/methods/authSources/ldapAdvancedProxy.php @@ -152,7 +152,7 @@ switch ($function) { $aFields['AUTH_SOURCE_DATA'] = $aData; //LDAP_PAGE_SIZE_LIMIT - $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced = new LdapAdvanced(); try { $arrayAuthenticationSourceData = $aFields; @@ -205,7 +205,7 @@ switch ($function) { //Get data $arrayData = array(); - $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced = new LdapAdvanced(); $ldapAdvanced->sAuthSource = $authenticationSourceUid; $result = $ldapAdvanced->searchUsers($keyword, $start, $limit); @@ -345,7 +345,7 @@ switch ($function) { $arrayAuthenticationSourceData['AUTH_SOURCE_VERSION'] = 3; //Test connection - $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced = new LdapAdvanced(); $ldapcnn = $ldapAdvanced->ldapConnection($arrayAuthenticationSourceData); diff --git a/workflow/engine/methods/cases/ajaxListener.php b/workflow/engine/methods/cases/ajaxListener.php index e5708129f..c8402914e 100644 --- a/workflow/engine/methods/cases/ajaxListener.php +++ b/workflow/engine/methods/cases/ajaxListener.php @@ -978,7 +978,7 @@ class Ajax $FieldsPmDynaform = $Fields; $FieldsPmDynaform["PRO_UID"] = $_SESSION['PROCESS']; $FieldsPmDynaform["CURRENT_DYNAFORM"] = $_REQUEST['DYN_UID']; - $a = new pmDynaform($FieldsPmDynaform); + $a = new PmDynaform($FieldsPmDynaform); if ($a->isResponsive()) { $a->printView(); } else { diff --git a/workflow/engine/methods/cases/caseConsolidated.php b/workflow/engine/methods/cases/caseConsolidated.php index 3b61d2f25..07e5aea99 100644 --- a/workflow/engine/methods/cases/caseConsolidated.php +++ b/workflow/engine/methods/cases/caseConsolidated.php @@ -127,7 +127,7 @@ if ($sStatus == "1" && $sDynUid != "") { if ($isBPMN) { - $pmDyna = new pmDynaform(array()); + $pmDyna = new PmDynaform(array()); $pmDyna->fields["CURRENT_DYNAFORM"] = $sDynUid; $dataDyna = $pmDyna->getDynaform(); $json = G::json_decode($dataDyna["DYN_CONTENT"]); diff --git a/workflow/engine/methods/cases/caseMessageHistory_Ajax.php b/workflow/engine/methods/cases/caseMessageHistory_Ajax.php index 32d71be76..a43f9b0eb 100644 --- a/workflow/engine/methods/cases/caseMessageHistory_Ajax.php +++ b/workflow/engine/methods/cases/caseMessageHistory_Ajax.php @@ -22,6 +22,8 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ +use ProcessMaker\Core\System; + $filter = new InputFilter(); $_POST = $filter->xssFilterHard($_POST); $_REQUEST = $filter->xssFilterHard($_REQUEST); @@ -192,9 +194,9 @@ if ($actionAjax == 'sendMailMessage_JXP') { $oCase = new Cases(); $data = $oCase->getHistoryMessagesTrackerView( $_POST['APP_UID'], $_POST['APP_MSG_UID'] ); - $aSetup = PmSystem::getEmailConfiguration(); + $aSetup = System::getEmailConfiguration(); - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aSetup); $oSpool->create( array ('msg_uid' => $data['MSG_UID'],'app_uid' => $data['APP_UID'],'del_index' => $data['DEL_INDEX'],'app_msg_type' => $data['APP_MSG_TYPE'],'app_msg_subject' => $data['APP_MSG_SUBJECT'],'app_msg_from' => $data['APP_MSG_FROM'],'app_msg_to' => $data['APP_MSG_TO'],'app_msg_body' => $data['APP_MSG_BODY'],'app_msg_cc' => $data['APP_MSG_CC'],'app_msg_bcc' => $data['APP_MSG_BCC'],'app_msg_attach' => $data['APP_MSG_ATTACH'],'app_msg_template' => $data['APP_MSG_TEMPLATE'],'app_msg_status' => 'pending' diff --git a/workflow/engine/methods/cases/casesConsolidatedListExtJs.php b/workflow/engine/methods/cases/casesConsolidatedListExtJs.php index 5ea1dbfc0..58d21dfa9 100644 --- a/workflow/engine/methods/cases/casesConsolidatedListExtJs.php +++ b/workflow/engine/methods/cases/casesConsolidatedListExtJs.php @@ -1,5 +1,7 @@ next()) { } if (count($arrayTabItem) > 0) { - $urlProxy = PmSystem::getHttpServerHostnameRequestsFrontEnd() . '/api/1.0/' . SYS_SYS . '/consolidated/'; + $urlProxy = System::getHttpServerHostnameRequestsFrontEnd() . '/api/1.0/' . SYS_SYS . '/consolidated/'; $clientId = 'x-pm-local-client'; $client = getClientCredentials($clientId); $authCode = getAuthorizationCode($client); diff --git a/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php b/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php index e6e0b9232..8a1f11255 100644 --- a/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php +++ b/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php @@ -390,7 +390,7 @@ if ($actionAjax == 'dynaformChangeLogViewHistory') { $FieldsPmDynaform = $Fields; $FieldsPmDynaform["PRO_UID"] = $_SESSION['PROCESS']; $FieldsPmDynaform["CURRENT_DYNAFORM"] = $_GET['DYN_UID']; - $a = new pmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); + $a = new PmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); if ($a->isResponsive()) { $a->printView(); } else { @@ -479,7 +479,7 @@ if ($actionAjax == 'historyDynaformGridPreview') { $FieldsPmDynaform = $Fields; $FieldsPmDynaform["CURRENT_DYNAFORM"] = $_GET['DYN_UID']; - $a = new pmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); + $a = new PmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); if ($a->isResponsive()) { $a->printView(); } else { diff --git a/workflow/engine/methods/cases/casesListExtJs.php b/workflow/engine/methods/cases/casesListExtJs.php index fe0cf9530..8ddadd997 100644 --- a/workflow/engine/methods/cases/casesListExtJs.php +++ b/workflow/engine/methods/cases/casesListExtJs.php @@ -1,5 +1,6 @@ confCasesList = $confCasesList; $solrEnabled = 0; if ($action == "todo" || $action == "draft" || $action == "sent" || $action == "selfservice" || $action == "unassigned" || $action == "search") { - $solrConfigured = ($solrConf = PmSystem::solrEnv()) !== false ? 1 : 0; + $solrConfigured = ($solrConf = System::solrEnv()) !== false ? 1 : 0; if ($solrConfigured == 1) { $applicationSolrIndex = new AppSolr( $solrConf['solr_enabled'], diff --git a/workflow/engine/methods/cases/casesListExtJsRedirector.php b/workflow/engine/methods/cases/casesListExtJsRedirector.php index 8465db24c..51d5b30a1 100644 --- a/workflow/engine/methods/cases/casesListExtJsRedirector.php +++ b/workflow/engine/methods/cases/casesListExtJsRedirector.php @@ -7,7 +7,7 @@ $statusPMGmail = false; $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); $statusPMGmail = $pmGoogle->getServiceGmailStatus(); } /*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/methods/cases/cases_Ajax.php b/workflow/engine/methods/cases/cases_Ajax.php index c0e0f6d14..140772f30 100644 --- a/workflow/engine/methods/cases/cases_Ajax.php +++ b/workflow/engine/methods/cases/cases_Ajax.php @@ -1,5 +1,7 @@ xssFilterHard($_GET); $_POST = $filter->xssFilterHard($_POST); @@ -785,7 +787,7 @@ switch (($_POST['action']) ? $_POST['action'] : $_REQUEST['action']) { $data = $oCase->getHistoryMessagesTrackerView( $_POST['APP_UID'], $_POST['APP_MSG_UID'] ); //print_r($data); - $aSetup = PmSystem::getEmailConfiguration(); + $aSetup = System::getEmailConfiguration(); $passwd = $aSetup['MESS_PASSWORD']; $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); @@ -805,7 +807,7 @@ switch (($_POST['action']) ? $_POST['action'] : $_REQUEST['action']) { $aSetup['MESS_RAUTH'] = 1; } - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig( array ( 'MESS_ENGINE' => $aSetup['MESS_ENGINE'], diff --git a/workflow/engine/methods/cases/cases_CatchExecute.php b/workflow/engine/methods/cases/cases_CatchExecute.php index e554c1512..5d1438597 100644 --- a/workflow/engine/methods/cases/cases_CatchExecute.php +++ b/workflow/engine/methods/cases/cases_CatchExecute.php @@ -64,7 +64,7 @@ if ($aDelegation['USR_UID'] == "") { $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.labelsGmail.php"); - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); if($pmGoogle->getServiceGmailStatus()) { $labGmail = new labelsGmail(); $labGmail->addRelabelingToQueue($sAppUid, $iDelIndex, -1, true); diff --git a/workflow/engine/methods/cases/cases_Derivate.php b/workflow/engine/methods/cases/cases_Derivate.php index 166d08fc4..ae6fbff44 100644 --- a/workflow/engine/methods/cases/cases_Derivate.php +++ b/workflow/engine/methods/cases/cases_Derivate.php @@ -190,7 +190,7 @@ try { /*----------------------------------********---------------------------------*/ $licensedFeatures = &PMLicensedFeatures::getSingleton (); if ($licensedFeatures->verifyfeature ( '7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09' )) { - $pmGoogle = new PMGoogleApi (); + $pmGoogle = new PmGoogleApi (); if ($pmGoogle->getServiceGmailStatus ()) { $flagGmail = true; diff --git a/workflow/engine/methods/cases/cases_SaveData.php b/workflow/engine/methods/cases/cases_SaveData.php index b8fe5b4ba..59ee9031c 100644 --- a/workflow/engine/methods/cases/cases_SaveData.php +++ b/workflow/engine/methods/cases/cases_SaveData.php @@ -141,7 +141,7 @@ try { $dataFields = $Fields["APP_DATA"]; $dataFields["CURRENT_DYNAFORM"] = $_GET['UID']; - $oPmDynaform = new pmDynaform($dataFields); + $oPmDynaform = new PmDynaform($dataFields); $pmdynaform = $oPmDynaform->validatePost($pmdynaform); $Fields["APP_DATA"] = array_merge( $Fields["APP_DATA"], $pmdynaform ); diff --git a/workflow/engine/methods/cases/cases_Step.php b/workflow/engine/methods/cases/cases_Step.php index 7b296b7e5..3762ddfe3 100644 --- a/workflow/engine/methods/cases/cases_Step.php +++ b/workflow/engine/methods/cases/cases_Step.php @@ -341,7 +341,7 @@ try { $FieldsPmDynaform["STEP_MODE"] = $oStep->getStepMode(); $FieldsPmDynaform["PRO_SHOW_MESSAGE"] = $noShowTitle; $FieldsPmDynaform["TRIGGER_DEBUG"] = $_SESSION['TRIGGER_DEBUG']['ISSET']; - $a = new pmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); + $a = new PmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); if ($a->isResponsive()) { $a->printEdit(); } else { diff --git a/workflow/engine/methods/cases/cases_StepToRevise.php b/workflow/engine/methods/cases/cases_StepToRevise.php index 4c94f1672..df72f5b7c 100644 --- a/workflow/engine/methods/cases/cases_StepToRevise.php +++ b/workflow/engine/methods/cases/cases_StepToRevise.php @@ -149,7 +149,7 @@ if ($_GET['DYN_UID'] != '') { $FieldsPmDynaform = $Fields; $FieldsPmDynaform["PRO_UID"] = $_SESSION['PROCESS']; $FieldsPmDynaform["CURRENT_DYNAFORM"] = $_GET['DYN_UID']; - $a = new pmDynaform($FieldsPmDynaform); + $a = new PmDynaform($FieldsPmDynaform); if ($a->isResponsive()) { $a->printEditSupervisor(); }else{ diff --git a/workflow/engine/methods/cases/derivatedGmail.php b/workflow/engine/methods/cases/derivatedGmail.php index 60729ed6f..43c6f571c 100644 --- a/workflow/engine/methods/cases/derivatedGmail.php +++ b/workflow/engine/methods/cases/derivatedGmail.php @@ -21,7 +21,7 @@ require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.la $oLabels = new labelsGmail(); $oLabels->addRelabelingToQueue($caseId, $actualIndex, $actualLastIndex, false); -$pmGoogle = new PMGoogleApi(); +$pmGoogle = new PmGoogleApi(); if(array_key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && $pmGoogle->getServiceGmailStatus() ){ $_SESSION['gmail'] = 0; unset($_SESSION['gmail']); //cleaning session diff --git a/workflow/engine/methods/cases/main_init.php b/workflow/engine/methods/cases/main_init.php index 73b590c11..f401a5239 100644 --- a/workflow/engine/methods/cases/main_init.php +++ b/workflow/engine/methods/cases/main_init.php @@ -122,7 +122,7 @@ if (isset($_SESSION['__OPEN_APPLICATION_UID__'])) { } } -$oServerConf = & serverConf::getSingleton(); +$oServerConf = & ServerConf::getSingleton(); if ($oServerConf->isRtl( SYS_LANG )) { $regionTreePanel = 'east'; $regionDebug = 'west'; diff --git a/workflow/engine/methods/cases/open.php b/workflow/engine/methods/cases/open.php index 3913ffdb2..ab2b7259c 100644 --- a/workflow/engine/methods/cases/open.php +++ b/workflow/engine/methods/cases/open.php @@ -72,7 +72,7 @@ $urlToRedirectAfterPause = 'casesListExtJs'; /*----------------------------------********---------------------------------*/ $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - $pmGoogle = new PMGoogleApi(); + $pmGoogle = new PmGoogleApi(); if (array_key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && $pmGoogle->getServiceGmailStatus()) { $_SESSION['gmail'] = 0; $urlToRedirectAfterPause = '/sys'. $_SESSION['WORKSPACE'] .'/en/neoclassic/cases/cases_Open?APP_UID='.$_SESSION['APPLICATION'].'&DEL_INDEX='.$_SESSION['INDEX'].'&action=sent'; diff --git a/workflow/engine/methods/cases/pmDynaform.php b/workflow/engine/methods/cases/pmDynaform.php index 2563062f2..598b1f6e1 100644 --- a/workflow/engine/methods/cases/pmDynaform.php +++ b/workflow/engine/methods/cases/pmDynaform.php @@ -2,6 +2,6 @@ $DYN_UID = $_GET["dyn_uid"]; $_SESSION['PROCESS'] = $_GET["prj_uid"]; -$a = new pmDynaform(array("CURRENT_DYNAFORM" => $DYN_UID)); +$a = new PmDynaform(array("CURRENT_DYNAFORM" => $DYN_UID)); $a->lang = null; $a->printPmDynaform(); diff --git a/workflow/engine/methods/cases/summary.php b/workflow/engine/methods/cases/summary.php index 9e2a1ba43..1a843ea22 100644 --- a/workflow/engine/methods/cases/summary.php +++ b/workflow/engine/methods/cases/summary.php @@ -70,7 +70,7 @@ try { if ($result->next()) { $FieldsPmDynaform = $applicationFields; $FieldsPmDynaform["CURRENT_DYNAFORM"] = $_REQUEST['DYN_UID']; - $a = new pmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); + $a = new PmDynaform(\ProcessMaker\Util\DateTime::convertUtcToTimeZone($FieldsPmDynaform)); $a->printView(); } if (file_exists( PATH_DYNAFORM . $applicationFields['PRO_UID'] . PATH_SEP . $_REQUEST['DYN_UID'] . '.xml' )) { diff --git a/workflow/engine/methods/dbConnections/dbConnectionsAjax.php b/workflow/engine/methods/dbConnections/dbConnectionsAjax.php index 44b1dbc84..3f6b043ae 100644 --- a/workflow/engine/methods/dbConnections/dbConnectionsAjax.php +++ b/workflow/engine/methods/dbConnections/dbConnectionsAjax.php @@ -240,7 +240,7 @@ switch ($action) { } } - $Server = new NET($server); + $Server = new Net($server); switch ($step) { case 1: @@ -305,7 +305,7 @@ switch ($action) { $connectionType = $_POST["connectionType"]; $tns = $_POST["tns"]; - $net = new NET(); + $net = new Net(); switch ($step) { case 1: diff --git a/workflow/engine/methods/dynaforms/dynaforms_Ajax.php b/workflow/engine/methods/dynaforms/dynaforms_Ajax.php index aee6ffcaa..a20026434 100644 --- a/workflow/engine/methods/dynaforms/dynaforms_Ajax.php +++ b/workflow/engine/methods/dynaforms/dynaforms_Ajax.php @@ -36,4 +36,4 @@ if (! isset( $_DBArray )) { $_DBArray = array (); } -$oDynaformEditorAjax = new dynaformEditorAjax( $_POST ); \ No newline at end of file +$oDynaformEditorAjax = new DynaformEditorAjax( $_POST ); \ No newline at end of file diff --git a/workflow/engine/methods/dynaforms/dynaforms_Editor.php b/workflow/engine/methods/dynaforms/dynaforms_Editor.php index 6021f5d7e..dc9a4d0f6 100644 --- a/workflow/engine/methods/dynaforms/dynaforms_Editor.php +++ b/workflow/engine/methods/dynaforms/dynaforms_Editor.php @@ -80,7 +80,7 @@ if (isset( $_GET['bpmn'] ) && $_GET['bpmn'] == '1') { $_SESSION['dynaform_editor'] = 'processmap'; } -$editor = new dynaformEditor( $_POST ); +$editor = new DynaformEditor( $_POST ); $editor->file = $dynaform->getDynFilename(); $editor->home = PATH_DYNAFORM; $editor->title = $dynaform->getDynTitle(); diff --git a/workflow/engine/methods/dynaforms/dynaforms_checkDependentFields.php b/workflow/engine/methods/dynaforms/dynaforms_checkDependentFields.php index c98467b09..6c1492387 100644 --- a/workflow/engine/methods/dynaforms/dynaforms_checkDependentFields.php +++ b/workflow/engine/methods/dynaforms/dynaforms_checkDependentFields.php @@ -73,7 +73,7 @@ $formValues = (Bootstrap::json_decode( $_POST['fields'] )); $sFieldName = $_POST['fieldName']; $sMasterField = ''; $sPath = PATH_DYNAFORM; -$G_FORM = new form( $sDynUid, $sPath ); +$G_FORM = new Form( $sDynUid, $sPath ); $aux = array (); $newValues = Bootstrap::json_decode( urlDecode( stripslashes( $_POST['form'] ) ) ); diff --git a/workflow/engine/methods/dynaforms/fields_Ajax.php b/workflow/engine/methods/dynaforms/fields_Ajax.php index 3bcd63bc8..ee098d1b6 100644 --- a/workflow/engine/methods/dynaforms/fields_Ajax.php +++ b/workflow/engine/methods/dynaforms/fields_Ajax.php @@ -47,7 +47,7 @@ if (isset( $_SESSION['CURRENT_PAGE_INITILIZATION'] )) { eval( $_SESSION['CURRENT_PAGE_INITILIZATION'] ); } -$G_FORM = new form( G::getUIDName( urlDecode( $_POST['form'] ) ) ); +$G_FORM = new Form( G::getUIDName( urlDecode( $_POST['form'] ) ) ); $G_FORM->id = urlDecode( $_POST['form'] ); $G_FORM->values = $_SESSION[$G_FORM->id]; diff --git a/workflow/engine/methods/dynaforms/fields_Save.php b/workflow/engine/methods/dynaforms/fields_Save.php index 3374708be..c7d874028 100644 --- a/workflow/engine/methods/dynaforms/fields_Save.php +++ b/workflow/engine/methods/dynaforms/fields_Save.php @@ -282,7 +282,7 @@ $_SESSION['_DBArray'] = $_DBArray; // Additions to javascript if (isset($sType) && $sType === 'javascript') { $sCode = urlencode($pmeCode); - $editor = new dynaformEditorAjax($_POST); + $editor = new DynaformEditorAjax($_POST); $editor->set_javascript($A, $fieldName, $sCode); } diff --git a/workflow/engine/methods/enterprise/addonsStore.php b/workflow/engine/methods/enterprise/addonsStore.php index c38805234..b078b4d23 100644 --- a/workflow/engine/methods/enterprise/addonsStore.php +++ b/workflow/engine/methods/enterprise/addonsStore.php @@ -1,12 +1,10 @@ date) && is_array($licenseManager->date)) { @@ -64,7 +62,7 @@ $oHeadPublisher->assign("SUPPORT_FLAG", ((isset($licenseManager->supportStartDat $oHeadPublisher->assign("supportStartDate", (isset($licenseManager->supportStartDate))? $licenseManager->supportStartDate : ''); $oHeadPublisher->assign("supportEndDate", (isset($licenseManager->supportEndDate))? $licenseManager->supportEndDate : ''); -$oHeadPublisher->assign("PROCESSMAKER_VERSION", PmSystem::getVersion()); +$oHeadPublisher->assign("PROCESSMAKER_VERSION", System::getVersion()); $oHeadPublisher->assign("PROCESSMAKER_URL", "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN ); $oHeadPublisher->assign("SYS_SKIN", SYS_SKIN); $oHeadPublisher->assign("URL_PART_LOGIN", ((substr(SYS_SKIN, 0, 2) == "ux" && SYS_SKIN != "uxs")? "main/login" : "login/login")); diff --git a/workflow/engine/methods/enterprise/addonsStoreAction.php b/workflow/engine/methods/enterprise/addonsStoreAction.php index a42344f79..36a95c0e7 100644 --- a/workflow/engine/methods/enterprise/addonsStoreAction.php +++ b/workflow/engine/methods/enterprise/addonsStoreAction.php @@ -1,9 +1,6 @@ installLicense($dir . $aInfoLoadFile["name"]); /////// //This command also find the following file "AddonsStore.php" - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); preg_match("/^license_(.*).dat$/", $licenseManager->file, $matches); $realId = urlencode($matches[1]); @@ -215,7 +212,7 @@ try { } /////// - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); $server = $licenseManager->server; $workspace = (isset($licenseManager->workspace)) ? $licenseManager->workspace : 'pmLicenseSrv'; $url = "http://$server/sys".$workspace."/en/green/services/rest"; @@ -254,7 +251,7 @@ try { ); // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { if (!is_array($option['http'])) { $option['http'] = array(); diff --git a/workflow/engine/methods/enterprise/enterprise.php b/workflow/engine/methods/enterprise/enterprise.php index 17343b26a..824b58bdc 100644 --- a/workflow/engine/methods/enterprise/enterprise.php +++ b/workflow/engine/methods/enterprise/enterprise.php @@ -1,5 +1,6 @@ sFriendlyName = "ProcessMaker Enterprise Core Edition"; @@ -133,7 +134,7 @@ class enterprisePlugin extends PMPlugin require_once (PATH_CORE . 'classes/model/AddonsStore.php'); AddonsStore::checkLicenseStore(); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); AddonsStore::updateAll(false); } diff --git a/workflow/engine/methods/enterprise/processMakerAjax.php b/workflow/engine/methods/enterprise/processMakerAjax.php index d5fb82be9..e034d2ae6 100644 --- a/workflow/engine/methods/enterprise/processMakerAjax.php +++ b/workflow/engine/methods/enterprise/processMakerAjax.php @@ -1,6 +1,6 @@ server) ? $licenseManager->server : ''; $workspace = (isset($licenseManager->workspace)) ? $licenseManager->workspace : 'pmLicenseSrv'; @@ -150,7 +150,7 @@ switch ($option) { ); // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if (isset($sysConf['proxy_host'])) { if ($sysConf['proxy_host'] != '') { if (!is_array($option['http'])) { @@ -295,7 +295,7 @@ switch ($option) { } /////// - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); $server = (isset($licenseManager->server)) ? $licenseManager->server : ''; $workspace = (isset($licenseManager->workspace)) ? $licenseManager->workspace : 'pmLicenseSrv'; @@ -319,7 +319,7 @@ switch ($option) { ); // Proxy settings - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if (isset($sysConf['proxy_host'])) { if ($sysConf['proxy_host'] != '') { if (!is_array($option['http'])) { diff --git a/workflow/engine/methods/install/autoinstallPlugins.php b/workflow/engine/methods/install/autoinstallPlugins.php index 02df8f7a8..4f164ec16 100644 --- a/workflow/engine/methods/install/autoinstallPlugins.php +++ b/workflow/engine/methods/install/autoinstallPlugins.php @@ -1,30 +1,9 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ +use ProcessMaker\Core\Installer; use ProcessMaker\Plugins\PluginRegistry; -$inst = new PmInstaller(); +$inst = new Installer(); $oProcess = new Processes(); diff --git a/workflow/engine/methods/install/autoinstallProcesses.php b/workflow/engine/methods/install/autoinstallProcesses.php index fd0adcbf0..149d48efe 100644 --- a/workflow/engine/methods/install/autoinstallProcesses.php +++ b/workflow/engine/methods/install/autoinstallProcesses.php @@ -1,27 +1,8 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ -$inst = new PmInstaller(); + +use ProcessMaker\Core\Installer; + +$inst = new Installer(); $oProcess = new Processes(); diff --git a/workflow/engine/methods/install/heartbeatStatus.php b/workflow/engine/methods/install/heartbeatStatus.php index a3c7fce25..dd79eaf13 100644 --- a/workflow/engine/methods/install/heartbeatStatus.php +++ b/workflow/engine/methods/install/heartbeatStatus.php @@ -2,7 +2,7 @@ try { if (isset( $_REQUEST['status'] )) { - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); /*you can use SYS_TEMP or SYS_SYS ON HEAR_BEAT_CONF to save for each workspace*/ if ($_REQUEST['status']) { echo "ACTIVE (Thanks!)"; diff --git a/workflow/engine/methods/install/newSite.php b/workflow/engine/methods/install/newSite.php index 03f4f65a1..9bc754583 100644 --- a/workflow/engine/methods/install/newSite.php +++ b/workflow/engine/methods/install/newSite.php @@ -1,12 +1,15 @@ allows(basename(__FILE__), basename(__FILE__)); if (isset( $_POST['form']['NW_TITLE'] )) { $action = (isset( $_POST['form']['ACTION'] )) ? trim( $_POST['form']['ACTION'] ) : 'test'; $name = trim( $_POST['form']['NW_TITLE'] ); - $inst = new PmInstaller(); + $inst = new Installer(); $isset = $inst->isset_site( $name ); diff --git a/workflow/engine/methods/login/authentication.php b/workflow/engine/methods/login/authentication.php index e445cf4c2..fa03f6b95 100644 --- a/workflow/engine/methods/login/authentication.php +++ b/workflow/engine/methods/login/authentication.php @@ -23,6 +23,7 @@ * */ +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; try { @@ -180,7 +181,7 @@ try { if ($oPluginRegistry->existsTrigger ( PM_LOGIN )) { $oPluginRegistry->executeTriggers ( PM_LOGIN , $loginInfo ); } - enterpriseClass::enterpriseSystemUpdate($loginInfo); + EnterpriseClass::enterpriseSystemUpdate($loginInfo); $_SESSION['USER_LOGGED'] = $uid; $_SESSION['USR_USERNAME'] = $usr; } else { @@ -247,7 +248,7 @@ try { $userTimeZone = $user->getUsrTimeZone(); if (trim($userTimeZone) == '') { - $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); $userTimeZone = $arraySystemConfiguration['time_zone']; } @@ -293,7 +294,7 @@ try { unset($_SESSION['FAILED_LOGINS']); // increment logins in heartbeat - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); $oServerConf->sucessfulLogin(); // Assign the uid of user to userloggedobj @@ -421,7 +422,7 @@ try { die; } - $configS = PmSystem::getSystemConfiguration('', '', SYS_SYS); + $configS = System::getSystemConfiguration('', '', SYS_SYS); $activeSession = isset($configS['session_block']) ? !(int)$configS['session_block']:true; if ($activeSession){ setcookie("PM-TabPrimary", 101010010, time() + (24 * 60 * 60), '/'); diff --git a/workflow/engine/methods/login/authenticationSso.php b/workflow/engine/methods/login/authenticationSso.php index 758b2258d..1d8a9cafb 100644 --- a/workflow/engine/methods/login/authenticationSso.php +++ b/workflow/engine/methods/login/authenticationSso.php @@ -1,6 +1,8 @@ singleSignOn) { $_SESSION['__USER_LOGGED_SSO__'] = $RBAC->userObj->fields['USR_UID']; @@ -38,7 +40,7 @@ try { } /*----------------------------------********---------------------------------*/ - $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); //Set User Time Zone $user = UsersPeer::retrieveByPK($userUid); diff --git a/workflow/engine/methods/login/licenseUpdate.php b/workflow/engine/methods/login/licenseUpdate.php index 26e4dcdab..c3b0cbe0c 100644 --- a/workflow/engine/methods/login/licenseUpdate.php +++ b/workflow/engine/methods/login/licenseUpdate.php @@ -15,11 +15,11 @@ if ($aux['extension'] != 'dat') { G::uploadFile($aInfoLoadFile["tmp_name"], $dir, $aInfoLoadFile["name"]); //reading the file that was uploaded - $licenseManager =& pmLicenseManager::getSingleton(); + $licenseManager =& PmLicenseManager::getSingleton(); $response = $licenseManager->installLicense($dir . $aInfoLoadFile["name"], false, false); if ($response) { - $licenseManager = new pmLicenseManager(); + $licenseManager = new PmLicenseManager(); preg_match("/^license_(.*).dat$/", $licenseManager->file, $matches); $realId = urlencode($matches[1]); $workspace = (isset($licenseManager->workspace)) ? $licenseManager->workspace : 'pmLicenseSrv'; diff --git a/workflow/engine/methods/login/login.php b/workflow/engine/methods/login/login.php index ab16993d0..8faa2997c 100644 --- a/workflow/engine/methods/login/login.php +++ b/workflow/engine/methods/login/login.php @@ -23,6 +23,7 @@ * */ +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; /*----------------------------------********---------------------------------*/ @@ -131,7 +132,7 @@ if (isset ($_SESSION['USER_LOGGED'])) { $licensedFeatures = & PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('x4TTzlISnp2K2tnSTJoMC8rTDRMTjlhMCtZeXV0QnNCLzU=')) { //Check in SSO class - $oSso = new pmSsoClass(); + $oSso = new PmSsoClass(); $res = $oSso->ssocVerifyUser(); if($res){ // Start new session @@ -208,7 +209,7 @@ $_SESSION['NW_PASSWORD2'] = $pass1; /*----------------------------------********---------------------------------*/ -$licenseManager =& pmLicenseManager::getSingleton(); +$licenseManager =& PmLicenseManager::getSingleton(); if (in_array(G::encryptOld($licenseManager->result), array('38afd7ae34bd5e3e6fc170d8b09178a3', 'ba2b45bdc11e2a4a6e86aab2ac693cbb'))) { $G_PUBLISH = new Publisher(); $version = explode('.', trim(file_get_contents(PATH_GULLIVER . 'VERSION'))); @@ -312,7 +313,7 @@ if ($version >= 3) { } //get the serverconf singleton, and check if we can send the heartbeat -$oServerConf = & serverConf::getSingleton(); +$oServerConf = & ServerConf::getSingleton(); $partnerFlag = (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false; if (!$partnerFlag) { $sflag = $oServerConf->getHeartbeatProperty('HB_OPTION', 'HEART_BEAT_CONF'); @@ -360,7 +361,7 @@ $flagForgotPassword = isset($oConf->aConfig['login_enableForgotPassword']) setcookie('PM-Warning', trim(G::LoadTranslation('ID_BLOCKER_MSG'), '*'), time() + (24 * 60 * 60), SYS_URI); -$configS = PmSystem::getSystemConfiguration('', '', SYS_SYS); +$configS = System::getSystemConfiguration('', '', SYS_SYS); $activeSession = isset($configS['session_block']) ? !(int)$configS['session_block'] : true; if ($activeSession) { setcookie("PM-TabPrimary", 101010010, time() + (24 * 60 * 60), '/'); diff --git a/workflow/engine/methods/login/retrivePassword.php b/workflow/engine/methods/login/retrivePassword.php index d3e2c9eff..842bc42f9 100644 --- a/workflow/engine/methods/login/retrivePassword.php +++ b/workflow/engine/methods/login/retrivePassword.php @@ -1,4 +1,7 @@ getByUsername($data['USR_USERNAME']); if ($userData['USR_EMAIL'] != '' && $userData['USR_EMAIL'] === $data['USR_EMAIL'] && ($userData['USR_AUTH_TYPE'] === '' || $userData['USR_AUTH_TYPE'] == 'MYSQL') ) { - $aSetup = PmSystem::getEmailConfiguration(); + $aSetup = System::getEmailConfiguration(); if (count($aSetup) == 0 || !isset($aSetup['MESS_ENGINE'])) { G::SendTemporalMessage ('ID_EMAIL_ENGINE_IS_NOT_ENABLED', "warning"); G::header('location: forgotPassword'); @@ -53,11 +56,11 @@ if ($userData['USR_EMAIL'] != '' && $userData['USR_EMAIL'] === $data['USR_EMAIL' $msg -

This Business Process is powered by ProcessMaker ver. ".PmSystem::getVersion().".
+

This Business Process is powered by ProcessMaker ver. ".System::getVersion().".
www.processmaker.com
"; - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aSetup); $oSpool->create(array( diff --git a/workflow/engine/methods/login/sysLogin.php b/workflow/engine/methods/login/sysLogin.php index 979995733..8fd4cd5c3 100644 --- a/workflow/engine/methods/login/sysLogin.php +++ b/workflow/engine/methods/login/sysLogin.php @@ -86,7 +86,7 @@ function getLangFiles() function getWorkspacesAvailable() { - $oServerConf = & serverConf::getSingleton (); + $oServerConf = & ServerConf::getSingleton (); $dir = PATH_DB; $filesArray = array (); if (file_exists ($dir)) { @@ -156,7 +156,7 @@ $version = isset($version[0]) ? intval($version[0]) : 0; switch (WS_IN_LOGIN) { case 'serverconf': //Get Server Configuration - $oServerConf = & serverConf::getSingleton (); + $oServerConf = & ServerConf::getSingleton (); if ($oServerConf->getProperty ('LOGIN_NO_WS')) { $fileLogin = $version >= 3 ? 'login/sysLoginNoWSpm3' : 'login/sysLoginNoWS'; } else { diff --git a/workflow/engine/methods/processes/ajaxListener.php b/workflow/engine/methods/processes/ajaxListener.php index 4fd2137ab..fadf2d975 100644 --- a/workflow/engine/methods/processes/ajaxListener.php +++ b/workflow/engine/methods/processes/ajaxListener.php @@ -205,9 +205,9 @@ class Ajax $result->success = true; if (count($UIDS) > 1) { - $result->msg = __('ID_ACTORS_ASSIGNED_SUCESSFULLY', SYS_LANG, Array(count($UIDS), $task->getTasTitle())); + $result->msg = G::LoadTranslation('ID_ACTORS_ASSIGNED_SUCESSFULLY', SYS_LANG, Array(count($UIDS), $task->getTasTitle())); } else { - $result->msg = __('ID_ACTOR_ASSIGNED_SUCESSFULLY', SYS_LANG, Array('tas_title' => $task->getTasTitle())); + $result->msg = G::LoadTranslation('ID_ACTOR_ASSIGNED_SUCESSFULLY', SYS_LANG, Array('tas_title' => $task->getTasTitle())); } } catch (Exception $e) { $result->success = false; diff --git a/workflow/engine/methods/processes/mainInit.php b/workflow/engine/methods/processes/mainInit.php index 415f09547..ef7697246 100644 --- a/workflow/engine/methods/processes/mainInit.php +++ b/workflow/engine/methods/processes/mainInit.php @@ -21,6 +21,8 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ + +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; //$oHeadPublisher = & headPublisher::getSingleton(); @@ -29,7 +31,7 @@ $RBAC->requirePermissions( 'PM_FACTORY' ); $conf = new Configurations(); -$pmVersion = (preg_match("/^([\d\.]+).*$/", PmSystem::getVersion(), $arrayMatch))? $arrayMatch[1] : ""; //Otherwise: Branch master +$pmVersion = (preg_match("/^([\d\.]+).*$/", System::getVersion(), $arrayMatch))? $arrayMatch[1] : ""; //Otherwise: Branch master /*----------------------------------********---------------------------------*/ if (true) { @@ -93,7 +95,7 @@ $designer = new Designer(); $oHeadPublisher->assign('SYS_SYS', SYS_SYS); $oHeadPublisher->assign('SYS_LANG', SYS_LANG); $oHeadPublisher->assign('SYS_SKIN', SYS_SKIN); -$oHeadPublisher->assign('HTTP_SERVER_HOSTNAME', PmSystem::getHttpServerHostnameRequestsFrontEnd()); +$oHeadPublisher->assign('HTTP_SERVER_HOSTNAME', System::getHttpServerHostnameRequestsFrontEnd()); $oHeadPublisher->assign('credentials', base64_encode(G::json_encode($designer->getCredentials()))); $deleteCasesFlag = false; diff --git a/workflow/engine/methods/processes/processes_webEntryGenerate.php b/workflow/engine/methods/processes/processes_webEntryGenerate.php index 6f92e759d..1767fcf2f 100644 --- a/workflow/engine/methods/processes/processes_webEntryGenerate.php +++ b/workflow/engine/methods/processes/processes_webEntryGenerate.php @@ -1,5 +1,8 @@ PRO_UID; $sTASKS = $oData->TASKS; $sDYNAFORM = $oData->DYNAFORM; @@ -86,7 +89,7 @@ try { $template->assign( 'dynaform', $dynTitle ); $template->assign( 'timestamp', date( 'l jS \of F Y h:i:s A' ) ); $template->assign( 'ws', SYS_SYS ); - $template->assign( 'version', PmSystem::getVersion() ); + $template->assign( 'version', System::getVersion() ); $fileName = $pathProcess . $dynTitle . 'Post.php'; file_put_contents( $fileName, $template->getOutputContent() ); diff --git a/workflow/engine/methods/reportTables/reportTables_Ajax.php b/workflow/engine/methods/reportTables/reportTables_Ajax.php index 49fd8abcd..31c06b2fa 100644 --- a/workflow/engine/methods/reportTables/reportTables_Ajax.php +++ b/workflow/engine/methods/reportTables/reportTables_Ajax.php @@ -267,7 +267,7 @@ switch ($action) { case 'delete': $rows = G::json_decode( $_REQUEST['rows'] ); - $rp = new reportTables(); + $rp = new ReportTables(); $at = new AdditionalTables(); try { diff --git a/workflow/engine/methods/services/ActionsByEmail.php b/workflow/engine/methods/services/ActionsByEmail.php index 7a250f3da..0b74dd7f2 100644 --- a/workflow/engine/methods/services/ActionsByEmail.php +++ b/workflow/engine/methods/services/ActionsByEmail.php @@ -1,4 +1,5 @@ verifyfeature('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0=')) { @@ -54,8 +55,6 @@ if (isset($_GET['BROWSER_TIME_ZONE_OFFSET'])) { $dataResponses['ABE_RES_MESSAGE'] = ''; try { - require_once 'classes/model/AbeResponses.php'; - $abeAbeResponsesInstance = new AbeResponses(); $dataResponses['ABE_RES_UID'] = $abeAbeResponsesInstance->createOrUpdate($dataResponses); } catch (Exception $e) { @@ -64,7 +63,7 @@ if (isset($_GET['BROWSER_TIME_ZONE_OFFSET'])) { $case->updateCase($_REQUEST['APP_UID'], $caseFieldsABE); - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->derivateCase( $caseFieldsABE['CURRENT_USER_UID'], $_REQUEST['APP_UID'], $_REQUEST['DEL_INDEX'], true diff --git a/workflow/engine/methods/services/ActionsByEmailDataForm.php b/workflow/engine/methods/services/ActionsByEmailDataForm.php index 0656eb5fc..3e54a488c 100644 --- a/workflow/engine/methods/services/ActionsByEmailDataForm.php +++ b/workflow/engine/methods/services/ActionsByEmailDataForm.php @@ -56,7 +56,7 @@ if (isset($_GET['BROWSER_TIME_ZONE_OFFSET'])) { $record['APP_DATA'] = $caseFields['APP_DATA']; if (is_null($caseFields['DEL_FINISH_DATE'])) { - $a = new pmDynaform($record); + $a = new PmDynaform($record); $a->printABE($action,$record); } else { diff --git a/workflow/engine/methods/services/ActionsByEmailDataFormPost.php b/workflow/engine/methods/services/ActionsByEmailDataFormPost.php index 5013ad775..0d5234973 100644 --- a/workflow/engine/methods/services/ActionsByEmailDataFormPost.php +++ b/workflow/engine/methods/services/ActionsByEmailDataFormPost.php @@ -101,7 +101,7 @@ if (PMLicensedFeatures //Update case info $case->updateCase($appUid, $casesFields); - $wsBaseInstance = new wsBase(); + $wsBaseInstance = new WsBase(); $result = $wsBaseInstance->derivateCase($casesFields['CURRENT_USER_UID'], $appUid, $delIndex, true); $code = (is_array($result) ? $result['status_code'] : $result->status_code); diff --git a/workflow/engine/methods/services/ldapadvanced.php b/workflow/engine/methods/services/ldapadvanced.php index 7ee2bb43c..a37594dd4 100644 --- a/workflow/engine/methods/services/ldapadvanced.php +++ b/workflow/engine/methods/services/ldapadvanced.php @@ -48,7 +48,7 @@ class ldapadvancedClassCron $rbac->authSourcesObj = new AuthenticationSource(); } - $plugin = new ldapAdvanced(); + $plugin = new LdapAdvanced(); $plugin->sSystem = $rbac->sSystem; $plugin->setFrontEnd(true); diff --git a/workflow/engine/methods/services/sessionPersists.php b/workflow/engine/methods/services/sessionPersists.php index 3a3128080..7b05bed07 100644 --- a/workflow/engine/methods/services/sessionPersists.php +++ b/workflow/engine/methods/services/sessionPersists.php @@ -15,7 +15,7 @@ if (isset($_REQUEST['dynaformEditorParams'])) { $dynaform = new Dynaform(); $dynaform->load($_REQUEST['DYN_UID']); - $editor = new dynaformEditor(array()); + $editor = new DynaformEditor(array()); $editor->file = $dynaform->getDynFilename(); $editor->home = PATH_DYNAFORM; $editor->title = $dynaform->getDynTitle(); diff --git a/workflow/engine/methods/services/soap2.php b/workflow/engine/methods/services/soap2.php index 603ebf596..d2fee0830 100644 --- a/workflow/engine/methods/services/soap2.php +++ b/workflow/engine/methods/services/soap2.php @@ -10,7 +10,7 @@ $wsdl = PATH_METHODS . "services" . PATH_SEP . "pmos2.wsdl"; function login ($params) { - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->login( $params->userid, $params->password ); return array ('status_code' => $res->status_code,'message' => $res->message,'version' => WEB_SERVICE_VERSION,'timestamp' => $res->timestamp @@ -30,7 +30,7 @@ function ProcessList ($params) } if (ifPermission( $params->sessionId, 'PM_CASES' ) != 0) { - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->processList(); return array ("processes" => $res @@ -54,14 +54,14 @@ function ProcessList ($params) $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->processListVerified( $userId ); return array ("processes" => $res ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->processList(); return array ("processes" => $res @@ -88,7 +88,7 @@ function RoleList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->roleList(); return array ("roles" => $res @@ -115,7 +115,7 @@ function GroupList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->groupList(); return array ("groups" => $res @@ -142,7 +142,7 @@ function DepartmentList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->departmentList(); return array ("departments" => $res @@ -179,7 +179,7 @@ function CaseList ($params) $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->caseList( $userId ); return array ("cases" => $res @@ -211,7 +211,7 @@ function UnassignedCaseList ($params) $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->unassignedCaseList( $userId ); return array ("cases" => $res @@ -238,7 +238,7 @@ function UserList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->userList(); return array ("users" => $res @@ -267,7 +267,7 @@ function triggerList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->triggerList(); return array ("triggers" => $res @@ -312,7 +312,7 @@ function outputDocumentList ($params) $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->outputDocumentList( $params->caseId, $userId ); return array ("documents" => $res @@ -357,7 +357,7 @@ function inputDocumentList ($params) $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->inputDocumentList( $params->caseId, $userId ); return array ("documents" => $res @@ -386,7 +386,7 @@ function inputDocumentProcessList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->inputDocumentProcessList( $params->processId ); return array ("documents" => $res @@ -407,7 +407,7 @@ function removeDocument ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->removeDocument( $params->appDocUid ); return $res; @@ -427,7 +427,7 @@ function SendMessage ($params) return $result->getPayloadArray(); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->sendMessage( $params->caseId, $params->from, $params->to, $params->cc, $params->bcc, $params->subject, $params->template ); return $res->getPayloadArray(); @@ -447,7 +447,7 @@ function getCaseInfo ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->getCaseInfo( $params->caseId, $params->delIndex ); return $res; @@ -467,7 +467,7 @@ function SendVariables ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $variables = $params->variables; $Fields = array (); @@ -506,7 +506,7 @@ function GetVariables ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->getVariables( $params->caseId, $params->variables ); @@ -528,7 +528,7 @@ function GetVariablesNames ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->getVariablesNames( $params->caseId ); @@ -556,7 +556,7 @@ function DerivateCase ($params) $oStd->stored_system_variables = true; $oStd->wsSessionId = $params->sessionId; - $ws = new wsBase( $oStd ); + $ws = new WsBase( $oStd ); $res = $ws->derivateCase($user["USR_UID"], $params->caseId, $params->delIndex, true); return $res; @@ -584,7 +584,7 @@ function RouteCase ($params) $oStd->stored_system_variables = true; $oStd->wsSessionId = $params->sessionId; - $ws = new wsBase( $oStd ); + $ws = new WsBase( $oStd ); $res = $ws->derivateCase($user["USR_UID"], $params->caseId, $params->delIndex, true); return $res; @@ -608,7 +608,7 @@ function executeTrigger ($params) $oSession = new Sessions(); $user = $oSession->getSessionUser( $params->sessionId ); - $ws = new wsBase(); + $ws = new WsBase(); $delIndex = (isset( $params->delIndex )) ? $params->delIndex : 1; $res = $ws->executeTrigger( $user['USR_UID'], $params->caseId, $params->triggerIndex, $delIndex ); @@ -649,7 +649,7 @@ function NewCaseImpersonate ($params) $params->variables = $field; /////// - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->newCaseImpersonate($params->processId, $params->userId, $params->variables, $params->taskId); return $res; @@ -712,7 +712,7 @@ function NewCase($params) $params->variables = $field; - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->newCase($params->processId, $userId, $params->taskId, $params->variables, (isset($params->executeTriggers)) ? (int) ($params->executeTriggers) : 0); @@ -743,7 +743,7 @@ function AssignUserToGroup ($params) return new wsResponse( 3, 'User not registered in the system' ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->assignUserToGroup( $params->userId, $params->groupId ); return $res->getPayloadArray(); @@ -770,7 +770,7 @@ function AssignUserToDepartment ($params) return new wsResponse( 3, G::LoadTranslation('ID_USER_NOT_REGISTERED_SYSTEM') ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->AssignUserToDepartment( $params->userId, $params->departmentId, $params->manager ); return $res->getPayloadArray(); @@ -790,7 +790,7 @@ function CreateUser ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); try { $res = $ws->createUser( $params->userId, $params->firstname, $params->lastname, $params->email, $params->role, $params->password, ((isset( $params->dueDate )) ? $params->dueDate : null), ((isset( $params->status )) ? $params->status : null) ); @@ -815,7 +815,7 @@ function updateUser ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->updateUser( $params->userUid, $params->userName, ((isset( $params->firstName )) ? $params->firstName : null), ((isset( $params->lastName )) ? $params->lastName : null), ((isset( $params->email )) ? $params->email : null), ((isset( $params->dueDate )) ? $params->dueDate : null), ((isset( $params->status )) ? $params->status : null), ((isset( $params->role )) ? $params->role : null), ((isset( $params->password )) ? $params->password : null) ); @@ -836,7 +836,7 @@ function informationUser($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->informationUser($params->userUid); return $result; @@ -847,18 +847,18 @@ function CreateGroup ($params) $vsResult = isValidSession( $params->sessionId ); if ($vsResult->status_code !== 0) { - $result = new wsCreateGroupResponse( $vsResult->status_code, $vsResult->message, '' ); + $result = new WsCreateGroupResponse( $vsResult->status_code, $vsResult->message, '' ); return $result; } if (ifPermission( $params->sessionId, 'PM_USERS' ) == 0) { - $result = new wsCreateGroupResponse( 2, G::LoadTranslation('ID_NOT_PRIVILEGES'), '' ); + $result = new WsCreateGroupResponse( 2, G::LoadTranslation('ID_NOT_PRIVILEGES'), '' ); return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->createGroup( $params->name ); return $res; @@ -878,7 +878,7 @@ function CreateDepartment ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->CreateDepartment( $params->name, $params->parentUID ); return $res; @@ -904,7 +904,7 @@ function TaskList ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $oSessions = new Sessions(); $session = $oSessions->getSessionUser( $params->sessionId ); $userId = $session['USR_UID']; @@ -934,7 +934,7 @@ function TaskCase ($params) ); } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->taskCase( $params->caseId ); return array ("taskCases" => $res @@ -948,7 +948,7 @@ function ReassignCase ($params) return $vsResult; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->reassignCase( $params->sessionId, $params->caseId, $params->delIndex, $params->userIdSource, $params->userIdTarget ); return $res; @@ -962,7 +962,7 @@ function systemInformation ($params) return $vsResult; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->systemInformation(); return $res; @@ -976,7 +976,7 @@ function getCaseNotes ($params) return $vsResult; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->getCaseNotes( $params->applicationID, $params->userUid ); return $res; @@ -1008,7 +1008,7 @@ function removeUserFromGroup ($params) return $vsResult; } - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->removeUserFromGroup( $params->userId, $params->groupId ); return $res; @@ -1052,7 +1052,7 @@ function deleteCase ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->deleteCase( $params->caseUid ); return $result; @@ -1072,7 +1072,7 @@ function cancelCase ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->cancelCase( $params->caseUid, $params->delIndex, $params->userUid ); return $result; @@ -1092,7 +1092,7 @@ function pauseCase ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->pauseCase( $params->caseUid, $params->delIndex, $params->userUid, ((isset( $params->unpauseDate )) ? $params->unpauseDate : null) ); @@ -1113,7 +1113,7 @@ function unpauseCase ($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->unpauseCase( $params->caseUid, $params->delIndex, $params->userUid ); return $result; @@ -1133,7 +1133,7 @@ function addCaseNote($params) return $result; } - $ws = new wsBase(); + $ws = new WsBase(); $result = $ws->addCaseNote( $params->caseUid, $params->processUid, @@ -1162,7 +1162,7 @@ function claimCase($params) $oSessions = new Sessions(); $session = $oSessions->getSessionUser($params->sessionId); - $ws = new wsBase(); + $ws = new WsBase(); $res = $ws->claimCase($session['USR_UID'], $params->guid, $params->delIndex); return $res; diff --git a/workflow/engine/methods/setup/appCacheViewAjax.php b/workflow/engine/methods/setup/appCacheViewAjax.php index 1e1f5042d..77c86bb6e 100644 --- a/workflow/engine/methods/setup/appCacheViewAjax.php +++ b/workflow/engine/methods/setup/appCacheViewAjax.php @@ -26,7 +26,7 @@ function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName } } - $Server = new NET($server); + $Server = new Net($server); $filter = new InputFilter(); if ($Server->getErrno() == 0) { diff --git a/workflow/engine/methods/setup/auditLogConfigAjax.php b/workflow/engine/methods/setup/auditLogConfigAjax.php index b2ea7d3f2..04f80123c 100644 --- a/workflow/engine/methods/setup/auditLogConfigAjax.php +++ b/workflow/engine/methods/setup/auditLogConfigAjax.php @@ -4,7 +4,7 @@ global $G_TMP_MENU; switch ($_GET['action']) { case 'saveOption': try { - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $response = new $oServerConf; $conf = new Configurations(); /*you can use SYS_TEMP or SYS_SYS ON AUDIT_LOG_CONF to save for each workspace*/ diff --git a/workflow/engine/methods/setup/cron.php b/workflow/engine/methods/setup/cron.php index 914881e70..2f4d7d211 100644 --- a/workflow/engine/methods/setup/cron.php +++ b/workflow/engine/methods/setup/cron.php @@ -2,6 +2,8 @@ global $RBAC; +use ProcessMaker\Core\System; + if ($RBAC->userCanAccess("PM_SETUP") != 1) { G::SendTemporalMessage("ID_USER_HAVENT_RIGHTS_PAGE", "error", "labels"); exit(0); @@ -62,7 +64,7 @@ $cronInfo["fileLogSize"] = $fileLogSize; $cronInfo["fileLogPath"] = $fileLog; //Workspaces -$workspaces = PmSystem::listWorkspaces(); +$workspaces = System::listWorkspaces(); $arrayAux = array (); foreach ($workspaces as $index => $workspace) { diff --git a/workflow/engine/methods/setup/emailSystemCron.php b/workflow/engine/methods/setup/emailSystemCron.php index 151faca82..6262a2dc0 100644 --- a/workflow/engine/methods/setup/emailSystemCron.php +++ b/workflow/engine/methods/setup/emailSystemCron.php @@ -26,7 +26,7 @@ $G_SUB_MENU = 'setup'; $G_ID_MENU_SELECTED = 'SETUP'; $G_ID_SUB_MENU_SELECTED = 'MAILSYSTEM'; -$run = new spoolRun(); +$run = new SpoolRun(); unset( $run ); $Fields['MESSAGE'] = 'Hello world, this is my first email ... '; diff --git a/workflow/engine/methods/setup/emails_Ajax.php b/workflow/engine/methods/setup/emails_Ajax.php index 1d5411532..f39be59e6 100644 --- a/workflow/engine/methods/setup/emails_Ajax.php +++ b/workflow/engine/methods/setup/emails_Ajax.php @@ -21,7 +21,9 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ - + + +use ProcessMaker\Core\System; $filter = new InputFilter(); $_POST = $filter->xssFilterHard($_POST); @@ -92,7 +94,7 @@ switch ($request) { $SMTPSecure = $_POST['SMTPSecure']; $timeout = 10; - $Server = new NET( $srv ); + $Server = new Net( $srv ); $smtp = new SMTP(); switch ($step) { @@ -252,11 +254,11 @@ function sendTestMail () $msg [" . date( 'H:i:s' ) . "] - $engine -

This Business Process is powered by ProcessMaker ver. " . PmSystem::getVersion() . ".
+

This Business Process is powered by ProcessMaker ver. " . System::getVersion() . ".
www.processmaker.com
"; - $oSpool = new spoolRun(); + $oSpool = new SpoolRun(); $passwd = $_POST['MESS_PASSWORD']; $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); diff --git a/workflow/engine/methods/setup/languages_Import.php b/workflow/engine/methods/setup/languages_Import.php index 2a8afb84d..fdda4812b 100644 --- a/workflow/engine/methods/setup/languages_Import.php +++ b/workflow/engine/methods/setup/languages_Import.php @@ -78,7 +78,7 @@ try { $configuration = new Configurations(); $importResults = $language->import( $languageFile ); - $renegerateContent = new workspaceTools( SYS_SYS ); + $renegerateContent = new WorkspaceTools( SYS_SYS ); $messs = $renegerateContent->upgradeContent(); $result->msg = G::LoadTranslation( 'IMPORT_LANGUAGE_SUCCESS' ) . "\n"; diff --git a/workflow/engine/methods/setup/loginSettings.php b/workflow/engine/methods/setup/loginSettings.php index 2f9322b21..1e6318038 100644 --- a/workflow/engine/methods/setup/loginSettings.php +++ b/workflow/engine/methods/setup/loginSettings.php @@ -27,7 +27,7 @@ $RBAC->requirePermissions( 'PM_SETUP' ); $oConf = new Configurations(); $oHeadPublisher = & headPublisher::getSingleton(); -$oServerConf = & serverConf::getSingleton(); +$oServerConf = & ServerConf::getSingleton(); $oHeadPublisher->addExtJsScript( 'setup/loginSettings', true ); //adding a javascript file .js $oHeadPublisher->addContent( 'setup/loginSettings' ); //adding a html file .html. diff --git a/workflow/engine/methods/setup/main_init.php b/workflow/engine/methods/setup/main_init.php index c63921d67..41ae62eef 100644 --- a/workflow/engine/methods/setup/main_init.php +++ b/workflow/engine/methods/setup/main_init.php @@ -93,7 +93,7 @@ $oHeadPublisher->assign( "tabActive", $tabActive ); $oHeadPublisher->assign( "tabItems", $tabItems ); $oHeadPublisher->assign( "_item_selected", (($adminSelected != null) ? $adminSelected : "") ); -$oServerConf = & serverConf::getSingleton(); +$oServerConf = & ServerConf::getSingleton(); if ($oServerConf->isRtl( SYS_LANG )) { $regionTreePanel = 'east'; $regionDebug = 'west'; diff --git a/workflow/engine/methods/setup/pluginsImportFile.php b/workflow/engine/methods/setup/pluginsImportFile.php index fcd0ca935..51f29c8ef 100644 --- a/workflow/engine/methods/setup/pluginsImportFile.php +++ b/workflow/engine/methods/setup/pluginsImportFile.php @@ -23,6 +23,8 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ + +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; global $RBAC; @@ -105,12 +107,12 @@ try { require_once ('classes/model/AddonsStore.php'); AddonsStore::checkLicenseStore(); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); AddonsStore::updateAll(false); $message = G::loadTranslation( 'ID_ENTERPRISE_INSTALLED') . ' ' . G::loadTranslation( 'ID_LOG_AGAIN'); G::SendMessageText($message, "INFO"); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); die(''); } } @@ -179,12 +181,12 @@ try { require_once ('classes/model/AddonsStore.php'); AddonsStore::checkLicenseStore(); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); AddonsStore::updateAll(false); $message = G::loadTranslation( 'ID_ENTERPRISE_INSTALLED') . ' ' . G::loadTranslation( 'ID_LOG_AGAIN'); G::SendMessageText($message, "INFO"); - $licenseManager = &pmLicenseManager::getSingleton(); + $licenseManager = &PmLicenseManager::getSingleton(); die(''); } } @@ -279,8 +281,8 @@ try { $oClass->iPMVersion = 0; } if ($oClass->iPMVersion > 0) { - if (PmSystem::getVersion() > 0) { - if ($oClass->iPMVersion > PmSystem::getVersion()) { + if (System::getVersion() > 0) { + if ($oClass->iPMVersion > System::getVersion()) { //throw new Exception('This plugin needs version ' . $oClass->iPMVersion . ' or higher of ProcessMaker'); } } diff --git a/workflow/engine/methods/setup/processHeartBeatAjax.php b/workflow/engine/methods/setup/processHeartBeatAjax.php index 7ede9389e..898a70f07 100644 --- a/workflow/engine/methods/setup/processHeartBeatAjax.php +++ b/workflow/engine/methods/setup/processHeartBeatAjax.php @@ -3,7 +3,7 @@ switch ($_GET['action']) { case 'saveOption': try { - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); $response = new stdclass(); /*you can use SYS_TEMP or SYS_SYS ON HEAR_BEAT_CONF to save for each workspace*/ $oServerConf->unsetHeartbeatProperty( 'HB_BEAT_TYPE', 'HEART_BEAT_CONF' ); diff --git a/workflow/engine/methods/setup/processHeartBeatConfig.php b/workflow/engine/methods/setup/processHeartBeatConfig.php index e57debd2e..9479daccb 100644 --- a/workflow/engine/methods/setup/processHeartBeatConfig.php +++ b/workflow/engine/methods/setup/processHeartBeatConfig.php @@ -25,7 +25,7 @@ global $RBAC; $RBAC->requirePermissions( 'PM_SETUP', 'PM_SETUP_HEART_BEAT'); $oHeadPublisher = & headPublisher::getSingleton(); -$oServerConf = & serverConf::getSingleton(); +$oServerConf = & ServerConf::getSingleton(); //you can use SYS_TEMP or SYS_SYS ON HEAR_BEAT_CONF to save for each workspace $sflag = $oServerConf->getHeartbeatProperty( 'HB_OPTION', 'HEART_BEAT_CONF' ); diff --git a/workflow/engine/methods/setup/processHeartBeatSave.php b/workflow/engine/methods/setup/processHeartBeatSave.php index eb4bad522..ef99d61c9 100644 --- a/workflow/engine/methods/setup/processHeartBeatSave.php +++ b/workflow/engine/methods/setup/processHeartBeatSave.php @@ -6,7 +6,7 @@ if ($RBAC->userCanAccess( 'PM_SETUP' ) != 1 && $RBAC->userCanAccess( 'PM_SETUP_A die(); } try { - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); /*you can use SYS_TEMP or SYS_SYS ON HEAR_BEAT_CONF to save for each workspace*/ $sflag = $_POST['HB_OPTION']; $oServerConf->unsetHeartbeatProperty( 'HB_BEAT_TYPE', 'HEART_BEAT_CONF' ); diff --git a/workflow/engine/methods/setup/replacementLogo.php b/workflow/engine/methods/setup/replacementLogo.php index 3ca46fffa..82b94d3a2 100644 --- a/workflow/engine/methods/setup/replacementLogo.php +++ b/workflow/engine/methods/setup/replacementLogo.php @@ -1,6 +1,6 @@ version; $fields['description'] = $oConf->description; -$fields['PMversion'] = PmSystem::getVersion(); +$fields['PMversion'] = System::getVersion(); savePluginFile( 'skinPluginMainClass', $pathHome . $id . '.php', $fields ); savePluginFile( 'skinPluginClass', $pathBase . 'class.' . $id . '.php', $fields ); diff --git a/workflow/engine/methods/setup/upgrade.php b/workflow/engine/methods/setup/upgrade.php index b3ae31211..8a41ecf50 100644 --- a/workflow/engine/methods/setup/upgrade.php +++ b/workflow/engine/methods/setup/upgrade.php @@ -1,27 +1,8 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ -global $RBAC; +use ProcessMaker\Core\System; + +global$RBAC; + $access = $RBAC->userCanAccess( 'PM_SETUP_ADVANCE' ); if ($access != 1) { switch ($access) { @@ -61,7 +42,7 @@ $G_SUB_MENU = 'setup'; $G_ID_MENU_SELECTED = 'SETUP'; $G_ID_SUB_MENU_SELECTED = 'UPGRADE'; -$Fields['PM_VERSION'] = PmSystem::getVersion(); +$Fields['PM_VERSION'] = System::getVersion(); $Fields['MAX_FILE_SIZE'] = $uploadMaxSize . " (" . $UPLOAD_MAX_SIZE . ") "; $G_PUBLISH = new Publisher(); diff --git a/workflow/engine/methods/setup/upgrade_System.php b/workflow/engine/methods/setup/upgrade_System.php index 3a51b97a1..bd2c1de01 100644 --- a/workflow/engine/methods/setup/upgrade_System.php +++ b/workflow/engine/methods/setup/upgrade_System.php @@ -22,6 +22,8 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ +use ProcessMaker\Core\System; + /** * New System Upgrade controller * @@ -49,7 +51,7 @@ $G_ID_MENU_SELECTED = 'SETUP'; $G_ID_SUB_MENU_SELECTED = 'UPGRADE'; require_once "classes/class.system.php"; -$oSystem = new PmSystem(); +$oSystem = new System(); try { if (! $oSystem->verifyFileForUpgrade()) { diff --git a/workflow/engine/methods/setup/webServicesAjax.php b/workflow/engine/methods/setup/webServicesAjax.php index 1a1910869..788e6518c 100644 --- a/workflow/engine/methods/setup/webServicesAjax.php +++ b/workflow/engine/methods/setup/webServicesAjax.php @@ -21,6 +21,9 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ + +use ProcessMaker\Core\System; + ini_set( "soap.wsdl_cache_enabled", "0" ); // enabling WSDL cache $filter = new InputFilter(); @@ -149,7 +152,7 @@ try { //Apply proxy settings $proxy = array (); - $sysConf = PmSystem::getSystemConfiguration(); + $sysConf = System::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { $proxy['proxy_host'] = $sysConf['proxy_host']; if ($sysConf['proxy_port'] != '') { diff --git a/workflow/engine/methods/tracker/tracker_Show.php b/workflow/engine/methods/tracker/tracker_Show.php index 15f12500a..294f91280 100644 --- a/workflow/engine/methods/tracker/tracker_Show.php +++ b/workflow/engine/methods/tracker/tracker_Show.php @@ -63,7 +63,7 @@ switch ($_GET['CTO_TYPE_OBJ']) { $Fields["PRO_UID"] = $_SESSION["PROCESS"]; $Fields["CURRENT_DYNAFORM"] = $_GET["CTO_UID_OBJ"]; - $pmDynaForm = new pmDynaform($Fields); + $pmDynaForm = new PmDynaform($Fields); if ($pmDynaForm->isResponsive()) { $pmDynaForm->printTracker(); diff --git a/workflow/engine/methods/users/myInfo_Edit.php b/workflow/engine/methods/users/myInfo_Edit.php index 81091d39c..a6b3f1642 100644 --- a/workflow/engine/methods/users/myInfo_Edit.php +++ b/workflow/engine/methods/users/myInfo_Edit.php @@ -25,7 +25,7 @@ try { global $RBAC; $RBAC->requirePermissions( 'PM_LOGIN' ); - // deprecated the class XmlForm_Field_Image is currently part of the class.xmlform.php package + // deprecated the class XmlFormFieldImage is currently part of the class.xmlform.php package // the use of the external xmlfield_Image is highly discouraged unset( $_SESSION['CURRENT_USER'] ); diff --git a/workflow/engine/methods/users/usersEdit.php b/workflow/engine/methods/users/usersEdit.php index 10601ece7..4148507e2 100644 --- a/workflow/engine/methods/users/usersEdit.php +++ b/workflow/engine/methods/users/usersEdit.php @@ -1,5 +1,7 @@ 0){ $expirationDate = abs($sysConf['expiration_year']); } @@ -31,7 +33,7 @@ if ($licensedFeatures->verifyfeature('w2LL3o4NFNiaDRXcFFCYVpJS3Jsall5dmh0ZWtBTkd } /*----------------------------------********---------------------------------*/ -$arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); +$arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'users/users', true ); //adding a javascript file .js diff --git a/workflow/engine/methods/users/usersInit.php b/workflow/engine/methods/users/usersInit.php index 9ee14d407..208d1197c 100644 --- a/workflow/engine/methods/users/usersInit.php +++ b/workflow/engine/methods/users/usersInit.php @@ -1,6 +1,8 @@ 0){ $expirationDate = abs($sysConf['expiration_year']); } @@ -46,7 +48,7 @@ if ($licensedFeatures->verifyfeature('w2LL3o4NFNiaDRXcFFCYVpJS3Jsall5dmh0ZWtBTkd } /*----------------------------------********---------------------------------*/ -$arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); +$arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'users/users', true ); //adding a javascript file .js diff --git a/workflow/engine/methods/users/usersNew.php b/workflow/engine/methods/users/usersNew.php index 1cbe900cf..b73bf00d3 100644 --- a/workflow/engine/methods/users/usersNew.php +++ b/workflow/engine/methods/users/usersNew.php @@ -1,5 +1,8 @@ requirePermissions( 'PM_USERS' ); //calculating the max upload file size; @@ -20,7 +23,7 @@ if ($postMaxSize < $uploadMaxSize) { $expirationDate = 1; $envFile = PATH_CONFIG . 'env.ini'; if (file_exists($envFile) ) { - $sysConf = PmSystem::getSystemConfiguration($envFile); + $sysConf = System::getSystemConfiguration($envFile); if(isset($sysConf['expiration_year']) && $sysConf['expiration_year']>0){ $expirationDate = abs($sysConf['expiration_year']); } @@ -35,7 +38,7 @@ if ($licensedFeatures->verifyfeature('w2LL3o4NFNiaDRXcFFCYVpJS3Jsall5dmh0ZWtBTkd } /*----------------------------------********---------------------------------*/ -$arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); +$arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'users/users', true ); //adding a javascript file .js diff --git a/workflow/engine/skinEngine/skinEngine.php b/workflow/engine/skinEngine/skinEngine.php index a6f40fc90..53cb9caf2 100644 --- a/workflow/engine/skinEngine/skinEngine.php +++ b/workflow/engine/skinEngine/skinEngine.php @@ -7,6 +7,7 @@ * @author Hugo Loza */ +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; define('SE_LAYOUT_NOT_FOUND', 6); @@ -44,7 +45,7 @@ class SkinEngine $this->content = $content; $this->skinVariants = array('blank','extjs','raw','tracker','submenu'); $this->skinsBasePath = G::ExpandPath("skinEngine"); - $sysConf = PmSystem::getSystemConfiguration( PATH_CONFIG . 'env.ini' ); + $sysConf = System::getSystemConfiguration( PATH_CONFIG . 'env.ini' ); $this->skinDefault = (isset($sysConf['default_skin']) && $sysConf['default_skin'] != '') ? $sysConf['default_skin'] : 'classic'; $this->_init(); } @@ -229,7 +230,7 @@ class SkinEngine private function _extjs() { - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); $oHeadPublisher =& headPublisher::getSingleton(); if( $oHeadPublisher->extJsInit === true){ @@ -303,7 +304,7 @@ class SkinEngine } } - $serverConf = &serverConf::getSingleton(); + $serverConf = &ServerConf::getSingleton(); if ($serverConf->isRtl(SYS_LANG)) { $dirBody = "dir=\"RTL\""; @@ -551,7 +552,7 @@ class SkinEngine private function _mvc() { - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); $oHeadPublisher =& headPublisher::getSingleton(); $smarty = new Smarty(); @@ -644,7 +645,7 @@ class SkinEngine //To setup en extJS Theme for this Skin - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); $extSkin = $oServerConf->getProperty("extSkin"); if(!$extSkin) { @@ -701,7 +702,7 @@ class SkinEngine $freeOfChargeText = ""; if (! defined('SKIP_FREE_OF_CHARGE_TEXT')) $freeOfChargeText = "Supplied free of charge with no support, certification, warranty, maintenance nor indemnity by ProcessMaker and its Certified Partners."; - if(file_exists(PATH_CLASSES."class.pmLicenseManager.php")) $freeOfChargeText=""; + if(file_exists(PATH_CLASSES."PmLicenseManager.php")) $freeOfChargeText=""; $fileFooter = PATH_SKINS . SYS_SKIN . PATH_SEP . 'footer.html'; if (file_exists($fileFooter)) { @@ -757,7 +758,7 @@ class SkinEngine } if (defined('SYS_SYS')) { - $pmLicenseManagerO = &pmLicenseManager::getSingleton(); + $pmLicenseManagerO = &PmLicenseManager::getSingleton(); $expireIn = $pmLicenseManagerO->getExpireIn(); $expireInLabel = $pmLicenseManagerO->getExpireInLabel(); @@ -782,7 +783,7 @@ class SkinEngine $smarty->assign('tpl_menu', PATH_TEMPLATE . 'menu.html'); $smarty->assign('tpl_submenu', PATH_TEMPLATE . 'submenu.html'); - $oLogoR = new replacementLogo(); + $oLogoR = new ReplacementLogo(); if(defined("SYS_SYS")){ $aFotoSelect = $oLogoR->getNameLogo((isset($_SESSION['USER_LOGGED']))?$_SESSION['USER_LOGGED']:''); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php b/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php index 4a66a77bd..fb0c7b3dd 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php @@ -2,7 +2,10 @@ namespace ProcessMaker\BusinessModel; +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; +use PmDynaform; +use SpoolRun; /** * Description of ActionsByEmailService @@ -406,9 +409,9 @@ class ActionsByEmail $arrayConfigAux = $row; $arrayConfigAux["SMTPSecure"] = $row["SMTPSECURE"]; } - $aSetup = (!empty($arrayConfigAux))? $arrayConfigAux : \PmSystem::getEmailConfiguration(); + $aSetup = (!empty($arrayConfigAux))? $arrayConfigAux : System::getEmailConfiguration(); - $spool = new \spoolRun(); + $spool = new SpoolRun(); $spool->setConfig($aSetup); $spool->create(array( @@ -579,7 +582,7 @@ class ActionsByEmail $configuration = $resultD->getRow(); $field = new \stdClass(); - $obj = new \pmDynaform($configuration); + $obj = new PmDynaform($configuration); if ($dataRes['ABE_RES_DATA'] !== '') { $value = unserialize($dataRes['ABE_RES_DATA']); @@ -670,7 +673,7 @@ class ActionsByEmail //SSO if (\PMLicensedFeatures::getSingleton()->verifyfeature('x4TTzlISnp2K2tnSTJoMC8rTDRMTjlhMCtZeXV0QnNCLzU=')) { - $sso = new \pmSsoClass(); + $sso = new \PmSsoClass(); if ($sso->ssocVerifyUser()) { global $RBAC; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php index 34b6c966e..78d510a65 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php @@ -5,16 +5,14 @@ use G; use UsersPeer; use CasesPeer; use AppDelegation; +use ProcessMaker\Core\System; use ProcessMaker\Plugins\PluginRegistry; use Exception; -use wsBase; +use WsBase; use RBAC; -use pmDynaform; +use Applications; +use PmDynaform; -/** - * @author Brayan Pereyra (Cochalo) - * @copyright Colosa - Bolivia - */ class Cases { private $formatFieldNameInUppercase = true; @@ -187,7 +185,7 @@ class Cases { try { $solrEnabled = false; - $solrConf = \PmSystem::solrEnv(); + $solrConf = System::solrEnv(); if ($solrConf !== false) { $ApplicationSolrIndex = new \AppSolr( @@ -262,7 +260,7 @@ class Cases $newerThan = (!empty($dataList['newerThan']))? $dataList['newerThan'] : ''; $oldestThan = (!empty($dataList['oldestthan']))? $dataList['oldestthan'] : ''; - $apps = new \Applications(); + $apps = new Applications(); $response = $apps->getAll( $userUid, $start, @@ -336,7 +334,7 @@ class Cases $dateTo = (!empty( $dataList["dateTo"] )) ? substr( $dataList["dateTo"], 0, 10 ) : ""; $filterStatus = isset( $dataList["filterStatus"] ) ? strtoupper( $dataList["filterStatus"] ) : ""; - $apps = new \Applications(); + $apps = new Applications(); $response = $apps->searchAll( $userId, $start, @@ -379,7 +377,7 @@ class Cases { try { $solrEnabled = 0; - if (($solrEnv = \PmSystem::solrEnv()) !== false) { + if (($solrEnv = System::solrEnv()) !== false) { $appSolr = new \AppSolr( $solrEnv["solr_enabled"], $solrEnv["solr_host"], @@ -406,7 +404,7 @@ class Cases $solrSearchText = "($solrSearchText)"; //Add del_index dynamic fields to list of resulting columns $columsToIncludeFinal = array_merge($columsToInclude, $delegationIndexes); - $solrRequestData = \Entity_SolrRequestData::createForRequestPagination( + $solrRequestData = \EntitySolrRequestData::createForRequestPagination( array( "workspace" => $solrEnv["solr_instance"], "startAfter" => 0, @@ -420,7 +418,7 @@ class Cases ) ); //Use search index to return list of cases - $searchIndex = new \BpmnEngine_Services_SearchIndex($appSolr->isSolrEnabled(), $solrEnv["solr_host"]); + $searchIndex = new \BpmnEngineServicesSearchIndex($appSolr->isSolrEnabled(), $solrEnv["solr_host"]); //Execute query $solrQueryResult = $searchIndex->getDataTablePaginatedList($solrRequestData); //Get the missing data from database @@ -467,7 +465,7 @@ class Cases if (!isset($row)) { continue; } - $ws = new wsBase(); + $ws = new WsBase(); $fields = $ws->getCaseInfo($applicationUid, $row["DEL_INDEX"]); $array = json_decode(json_encode($fields), true); if ($array ["status_code"] != 0) { @@ -534,7 +532,7 @@ class Cases throw (new Exception($arrayData)); } } else { - $ws = new wsBase(); + $ws = new WsBase(); $fields = $ws->getCaseInfo($applicationUid, 0); $array = json_decode(json_encode($fields), true); @@ -680,7 +678,7 @@ class Cases { try { - $ws = new wsBase(); + $ws = new WsBase(); if ($variables) { $variables = array_shift($variables); } @@ -724,7 +722,7 @@ class Cases { try { - $ws = new wsBase(); + $ws = new WsBase(); if ($variables) { $variables = array_shift($variables); } elseif ($variables == null) { @@ -779,7 +777,7 @@ class Cases $delIndex = AppDelegation::getCurrentIndex($applicationUid); } - $ws = new wsBase(); + $ws = new WsBase(); $fields = $ws->reassignCase($userUid, $applicationUid, $delIndex, $userUidSource, $userUidTarget); $array = json_decode(json_encode($fields), true); if (array_key_exists("status_code", $array)) { @@ -1010,7 +1008,7 @@ class Cases $RBAC->sSystem = 'PROCESSMAKER'; } - $case = new wsBase(); + $case = new WsBase(); $result = $case->executeTrigger($userUid, $appUid, $triUid, $delIndex); if ($result->status_code != 0) { @@ -1077,7 +1075,7 @@ class Cases } } - $ws = new wsBase(); + $ws = new WsBase(); $fields = $ws->derivateCase($userUid, $applicationUid, $delIndex, $bExecuteTriggersBeforeAssignment = false); $array = json_decode(json_encode($fields), true); if ($array ["status_code"] != 0) { @@ -1651,7 +1649,7 @@ class Cases } } return $caseVariable; - } catch (Exception $e) { + } catch (\Exception $e) { throw $e; } } @@ -1683,7 +1681,7 @@ class Cases if (!is_null($dynaFormUid)) { $data["CURRENT_DYNAFORM"] = $dynaFormUid; - $pmDynaForm = new \pmDynaform($data); + $pmDynaForm = new PmDynaform($data); $arrayDynaFormData = $pmDynaForm->getDynaform(); $arrayDynContent = \G::json_decode($arrayDynaFormData['DYN_CONTENT']); $pmDynaForm->jsonr($arrayDynContent); @@ -2302,7 +2300,7 @@ class Cases $tas_uid = $aCaseField["TAS_UID"]; $pro_uid = $aCaseField["PRO_UID"]; - $oApplication = new \Applications(); + $oApplication = new Applications(); $aField = $oApplication->getSteps($app_uid, $del_index, $tas_uid, $pro_uid); return $aField; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php index 7f79c3aed..8e34eb0d9 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php @@ -701,7 +701,7 @@ class InputDocument throw new \Exception(\G::LoadTranslation("ID_CASES_INPUT_DOES_NOT_EXIST", array($inputDocumentUid))); } - $ws = new \wsBase(); + $ws = new \WsBase(); $ws->removeDocument($inputDocumentUid); } catch (\Exception $e) { throw $e; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php b/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php index d626595a1..c53b794c0 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php @@ -1,18 +1,16 @@ - * @copyright Colosa - Bolivia - */ class Consolidated { /** @@ -69,7 +67,7 @@ class Consolidated */ public function postDerivate($app_uid, $app_number, $del_index, $usr_uid, $fieldName = '', $fieldValue = '') { - $ws = new \wsBase(); + $ws = new \WsBase(); $oCase = new \Cases(); if (!isset($Fields["DEL_INIT_DATE"])) { @@ -361,7 +359,7 @@ class Consolidated $filter = new \InputFilter(); if ($sort != "") { - $reportTable = new \ReportTables(); + $reportTable = new ReportTables(); $arrayReportTableVar = $reportTable->getTableVars($tableUid); $tableName = $filter->validateInput($tableName); $sort = $filter->validateInput($sort); @@ -468,7 +466,7 @@ class Consolidated $dataTask = $oDyna->load($dyn_uid); if ($dataTask['DYN_VERSION'] > 0) { $_SESSION['PROCESS'] = $pro_uid; - $pmDyna = new \pmDynaform(array('APP_DATA' => array(), "CURRENT_DYNAFORM" => $dyn_uid)); + $pmDyna = new PmDynaform(array('APP_DATA' => array(), "CURRENT_DYNAFORM" => $dyn_uid)); $json = G::json_decode($dataTask["DYN_CONTENT"]); $pmDyna->jsonr($json); $fieldsDyna = $json->items[0]->items; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php b/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php index 12dfb0afd..ec74705ca 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php @@ -271,7 +271,7 @@ class DataBaseConnection $flagTns = ($dataCon["DBS_TYPE"] == "oracle" && $dataCon["DBS_CONNECTION_TYPE"] == "TNS")? 1 : 0; if ($flagTns == 0) { - $Server = new \NET($dataCon['DBS_SERVER']); + $Server = new \Net($dataCon['DBS_SERVER']); // STEP 1 : Resolving Host Name $respTest['0'] = array(); @@ -356,7 +356,7 @@ class DataBaseConnection } } } else { - $net = new \NET(); + $net = new \Net(); //STEP 0: Trying to open database type TNS $respTest["0"] = array(); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/EmailServer.php b/workflow/engine/src/ProcessMaker/BusinessModel/EmailServer.php index 0946e163d..4fd3b5702 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/EmailServer.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/EmailServer.php @@ -1,8 +1,10 @@ prepare(); $sBodyPre->assign("server", $_SERVER["SERVER_NAME"]); $sBodyPre->assign("date", date("H:i:s")); - $sBodyPre->assign("ver", \PmSystem::getVersion()); + $sBodyPre->assign("ver", System::getVersion()); $sBodyPre->assign("engine", $engine); $sBodyPre->assign("msg", $msg); $sBody = $sBodyPre->getOutputContent(); - $oSpool = new \spoolRun(); + $oSpool = new SpoolRun(); $oSpool->setConfig($aConfiguration); @@ -316,7 +318,7 @@ class EmailServer $mailTo = $arrayData["MAIL_TO"]; $smtpSecure = $arrayData["SMTPSECURE"]; - $serverNet = new \NET($server); + $serverNet = new \Net($server); $smtp = new \SMTP(); $timeout = 10; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/InputDocument.php b/workflow/engine/src/ProcessMaker/BusinessModel/InputDocument.php index 9634740c2..62122e104 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/InputDocument.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/InputDocument.php @@ -1,6 +1,8 @@ update($arrayData); - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); $pmDynaform->synchronizeInputDocument($processUid, $arrayData); //Return diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light.php index 62030aac4..92a578e4c 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light.php @@ -7,7 +7,9 @@ use Criteria; use UsersPeer; use AppDelegationPeer; use AppDelayPeer; +use ProcessMaker\Core\System; use ProcessMaker\Util\DateTime; +use PmLicenseManager; class Light { @@ -524,7 +526,7 @@ class Light $delIndex = \AppDelegation::getCurrentIndex($applicationUid); } - $ws = new \wsBase(); + $ws = new \WsBase(); $fields = $ws->derivateCase($userUid, $applicationUid, $delIndex, $bExecuteTriggersBeforeAssignment = false, $tasks); $array = json_decode(json_encode($fields), true); $array['message'] = trim(strip_tags($array['message'])); @@ -779,7 +781,7 @@ class Light /*----------------------------------********---------------------------------*/ - $licenseManager =& \pmLicenseManager::getSingleton(); + $licenseManager =& PmLicenseManager::getSingleton(); if (in_array(md5($licenseManager->result), array('38afd7ae34bd5e3e6fc170d8b09178a3', 'ba2b45bdc11e2a4a6e86aab2ac693cbb'))) { $G_PUBLISH = new \Publisher(); $G_PUBLISH->AddContent('xmlform', 'xmlform', 'login/licenseExpired', '', array(), 'licenseUpdate'); @@ -1259,7 +1261,7 @@ class Light $offset = timezone_offset_get( new \DateTimeZone( $tz ), new \DateTime() ); $response['timeZone'] = sprintf( "GMT%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( ($offset % 3600) / 60 ) ); $response['multiTimeZone'] = $multiTimeZone; - $fields = \PmSystem::getSysInfo(); + $fields = System::getSysInfo(); $response['version'] = $fields['PM_VERSION']; $buildType = 'Community'; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php index 7aace44f0..ec282273e 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php @@ -2,6 +2,7 @@ namespace ProcessMaker\BusinessModel\Light; +use ProcessMaker\Core\System; use \ProcessMaker\Services\Api; use G; @@ -11,7 +12,7 @@ class NotificationDevice public function checkMobileNotifications() { - $conf = \PmSystem::getSystemConfiguration('', '', SYS_SYS); + $conf = System::getSystemConfiguration('', '', SYS_SYS); $activeNotifications = true; if (isset($conf['mobileNotifications'])) { $activeNotifications = $conf['mobileNotifications'] == 1 ? true : false; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageAndroid.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageAndroid.php index 667e61aae..98c02649d 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageAndroid.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageAndroid.php @@ -13,6 +13,8 @@ namespace ProcessMaker\BusinessModel\Light; +use ProcessMaker\Core\System; + class PushMessageAndroid { private $url = 'https://android.googleapis.com/gcm/send'; @@ -54,7 +56,7 @@ class PushMessageAndroid */ public function setSettingNotification() { - $conf = \PmSystem::getSystemConfiguration(PATH_CONFIG . 'mobile.ini'); + $conf = System::getSystemConfiguration(PATH_CONFIG . 'mobile.ini'); $this->setUrl($conf['android']['url']); $this->setKey($conf['android']['serverApiKey']); } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageIOS.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageIOS.php index 89647f707..d75ca9a15 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageIOS.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light/PushMessageIOS.php @@ -12,6 +12,8 @@ namespace ProcessMaker\BusinessModel\Light; +use ProcessMaker\Core\System; + class PushMessageIOS { private $url = 'ssl://gateway.sandbox.push.apple.com:2195'; @@ -67,7 +69,7 @@ class PushMessageIOS */ public function setSettingNotification() { - $conf = \PmSystem::getSystemConfiguration(PATH_CONFIG . 'mobile.ini'); + $conf = System::getSystemConfiguration(PATH_CONFIG . 'mobile.ini'); $this->setUrl($conf['apple']['url']); $this->setKey($conf['apple']['passphrase']); $this->setPemFile($conf['apple']['pemFile']); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light/Tracker.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light/Tracker.php index 66860e131..152aeb161 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light/Tracker.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light/Tracker.php @@ -2,6 +2,7 @@ namespace ProcessMaker\BusinessModel\Light; +use PmDynaform; class Tracker { @@ -266,7 +267,7 @@ class Tracker $Fields["PRO_UID"] = $pro_uid; $Fields["CURRENT_DYNAFORM"] = $obj_uid; - $pmDynaForm = new \pmDynaform($Fields); + $pmDynaForm = new PmDynaform($Fields); // if ($pmDynaForm->isResponsive()) { // $pmDynaForm->printTracker(); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/MessageApplication.php b/workflow/engine/src/ProcessMaker/BusinessModel/MessageApplication.php index 8f20fd727..de2e7614d 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/MessageApplication.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/MessageApplication.php @@ -368,7 +368,7 @@ class MessageApplication try { //Set variables - $ws = new \wsBase(); + $ws = new \WsBase(); $case = new \Cases(); $common = new \ProcessMaker\Util\Common(); $sysSys = (defined("SYS_SYS"))? SYS_SYS : "Undefined"; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Migrator/GranularExporter.php b/workflow/engine/src/ProcessMaker/BusinessModel/Migrator/GranularExporter.php index 09b5308f1..c3b670abc 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Migrator/GranularExporter.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Migrator/GranularExporter.php @@ -2,6 +2,7 @@ namespace ProcessMaker\BusinessModel\Migrator; +use ProcessMaker\Core\System; use ProcessMaker\Project; use ProcessMaker\Util\Common; @@ -134,7 +135,7 @@ class GranularExporter $data["version"] = "3.1"; $data["container"] = "ProcessMaker-Project"; $data["metadata"] = array( - "vendor_version" => \PmSystem::getVersion(), + "vendor_version" => System::getVersion(), "vendor_version_code" => "Michelangelo", "export_timestamp" => date("U"), "export_datetime" => date("Y-m-d\TH:i:sP"), diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php index fc3007b6a..397b5805a 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php @@ -1,12 +1,12 @@ getSystemConfiguration( PATH_CONFIG . 'env.ini' ); $response['enviroment'] = $responseSysConfig['default_skin']; @@ -357,7 +357,7 @@ class Pmgmail { return false; } - $ws = new \wsBase(); + $ws = new \WsBase(); $resultMail = $ws->sendMessage( $application['APP_UID'], $defaultEmail, //From, diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Process.php b/workflow/engine/src/ProcessMaker/BusinessModel/Process.php index d378b0765..429661919 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Process.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Process.php @@ -1617,7 +1617,7 @@ class Process $triggerWizard->setFormatFieldNameInUppercase($this->formatFieldNameInUppercase); $triggerWizard->setArrayFieldNameForException($this->arrayFieldNameForException); - $triggerLibrary = \triggerLibrary::getSingleton(); + $triggerLibrary = \TriggerLibrary::getSingleton(); $library = $triggerLibrary->getRegisteredClasses(); ksort($library); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Skins.php b/workflow/engine/src/ProcessMaker/BusinessModel/Skins.php index f9f17d759..a49bf9134 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Skins.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Skins.php @@ -1,7 +1,7 @@ library = \triggerLibrary::getSingleton(); + $this->library = \TriggerLibrary::getSingleton(); } catch (\Exception $e) { throw $e; } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php b/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php index a8cb0d838..abc80d5ef 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php @@ -4,6 +4,7 @@ namespace ProcessMaker\BusinessModel; use G; use Exception; use AdditionalTables; +use PmDynaform; class Variable { @@ -194,7 +195,7 @@ class Variable "VAR_ACCEPTED_VALUES" => $variable->getVarAcceptedValues() ); - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); $pmDynaform->synchronizeVariable($processUid, $newVariable, $oldVariable); } else { @@ -236,7 +237,7 @@ class Variable $this->throwExceptionIfVariableIsAssociatedAditionalTable($variableUid); $variable = $this->getVariable($processUid, $variableUid); - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); $isUsed = $pmDynaform->isUsed($processUid, $variable); if ($isUsed !== false) { $titleDynaform=$pmDynaform->getDynaformTitle($isUsed); @@ -783,7 +784,7 @@ class Variable //This value is required to be able to query the database. $_SESSION["PROCESS"] = $proUid; //The pmdynaform class is instantiated - $pmDynaform = new \pmDynaform(array("APP_DATA" => $params)); + $pmDynaform = new PmDynaform(array("APP_DATA" => $params)); //Get control from dynaform. //The parameters: queryFilter, queryStart, queryLimit, are only necessary diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/WebEntry.php b/workflow/engine/src/ProcessMaker/BusinessModel/WebEntry.php index aba48f509..e7c94d9f8 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/WebEntry.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/WebEntry.php @@ -1,6 +1,8 @@ assign("dynaform", empty($arrayDynaFormData) ? '' : $arrayDynaFormData["DYN_TITLE"]); $template->assign("timestamp", date("l jS \of F Y h:i:s A")); $template->assign("ws", $this->sysSys); - $template->assign("version", \PmSystem::getVersion()); + $template->assign("version", System::getVersion()); $fileName = $pathDataPublicProcess . PATH_SEP . $weTitle . "Post.php"; diff --git a/workflow/engine/classes/PmInstaller.php b/workflow/engine/src/ProcessMaker/Core/Installer.php similarity index 84% rename from workflow/engine/classes/PmInstaller.php rename to workflow/engine/src/ProcessMaker/Core/Installer.php index 23b9b082c..e912963c5 100644 --- a/workflow/engine/classes/PmInstaller.php +++ b/workflow/engine/src/ProcessMaker/Core/Installer.php @@ -1,46 +1,14 @@ . - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ -// -// It works with the table CONFIGURATION in a WF dataBase -// -// Copyright (C) 2007 COLOSA -// -// License: LGPL, see LICENSE -//////////////////////////////////////////////////// +namespace ProcessMaker\Core; -/** - * Processmaker Installer - * - * @package workflow.engine.ProcessMaker - * @author maborak - * @copyright 2008 COLOSA - */ -class PmInstaller +use AppCacheView; +use Archive_Tar; +use Configuration; +use Exception; +use G; + +class Installer { public $options = Array(); @@ -69,12 +37,12 @@ class PmInstaller public function create_site($config = Array(), $confirmed = false) { $this->options = G::array_concat(Array('isset' => false, 'password' => G::generate_password(15), 'path_data' => @PATH_DATA, 'path_compiled' => @PATH_C, 'name' => $config['name'], 'database' => Array(), 'admin' => Array('username' => 'admin', 'password' => 'admin' - ), 'advanced' => Array('ao_db_wf' => 'wf_' . $config['name'], 'ao_db_rb' => 'rb_' . $config['name'], 'ao_db_rp' => 'rp_' . $config['name'], 'ao_db_drop' => false - ) - ), $config); + ), 'advanced' => Array('ao_db_wf' => 'wf_' . $config['name'], 'ao_db_rb' => 'rb_' . $config['name'], 'ao_db_rp' => 'rp_' . $config['name'], 'ao_db_drop' => false + ) + ), $config); $a = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); $this->options['database'] = G::array_concat(Array('username' => @$a[1], 'password' => @$a[2], 'hostname' => @$a[0] - ), $this->options['database']); + ), $this->options['database']); return ($confirmed === true) ? $this->make_site() : $this->create_site_test(); } @@ -86,11 +54,11 @@ class PmInstaller */ public static function isset_site($name = "workflow") { - $pathSites = PATH_DATA . 'sites/'. '*'; + $pathSites = PATH_DATA . 'sites/' . '*'; $directories = glob($pathSites, GLOB_ONLYDIR); - foreach ($directories as $directory){ + foreach ($directories as $directory) { $site = basename($directory); - if(strtolower($site) === strtolower($name)){ + if (strtolower($site) === strtolower($name)) { return true; } } @@ -106,22 +74,22 @@ class PmInstaller { $name = (preg_match('/^[\w]+$/i', trim($this->options['name']))) ? true : false; $result = Array('path_data' => $this->is_dir_writable($this->options['path_data']), 'path_compiled' => $this->is_dir_writable($this->options['path_compiled']), 'database' => $this->check_connection(), 'access_level' => $this->cc_status, 'isset' => ($this->options['isset'] == true) ? $this->isset_site($this->options['name']) : false, 'microtime' => microtime(), 'workspace' => $this->options['name'], 'name' => array('status' => $name, 'message' => ($name) ? 'PASSED' : 'Workspace name invalid' - ), 'admin' => array('username' => (preg_match('/^[\w@\.-]+$/i', trim($this->options['admin']['username']))) ? true : false, 'password' => ((trim($this->options['admin']['password']) == '') ? false : true) - ) + ), 'admin' => array('username' => (preg_match('/^[\w@\.-]+$/i', trim($this->options['admin']['username']))) ? true : false, 'password' => ((trim($this->options['admin']['password']) == '') ? false : true) + ) ); $result['name']['message'] = ($result['isset']) ? 'Workspace already exist' : $result['name']['message']; $result['name']['status'] = ($result['isset']) ? false : $result['name']['status']; //print_r($result); return Array('created' => G::var_compare(true, - $result['path_data'], - $result['database']['connection'], - $result['name']['status'], - $result['database']['version'], - $result['database']['ao']['ao_db_wf']['status'], - $result['admin']['username'], - (($result['isset']) ? false : true), - $result['admin']['password']), - 'result' => $result + $result['path_data'], + $result['database']['connection'], + $result['name']['status'], + $result['database']['version'], + $result['database']['ao']['ao_db_wf']['status'], + $result['admin']['username'], + (($result['isset']) ? false : true), + $result['admin']['password']), + 'result' => $result ); } @@ -139,7 +107,7 @@ class PmInstaller $islocal = (strcmp(substr($this->options['database']['hostname'], 0, strlen('localhost')), 'localhost') === 0) || (strcmp(substr($this->options['database']['hostname'], 0, strlen('127.0.0.1')), '127.0.0.1') === 0); $this->wf_site_name = $wf = $this->options['advanced']['ao_db_wf']; - $this->wf_user_db = isset($this->options['advanced']['ao_user_wf'])?$this->options['advanced']['ao_user_wf']:uniqid('wf_'); + $this->wf_user_db = isset($this->options['advanced']['ao_user_wf']) ? $this->options['advanced']['ao_user_wf'] : uniqid('wf_'); $this->rbac_site_name = $rb = $this->options['advanced']['ao_db_rb']; $this->report_site_name = $rp = $this->options['advanced']['ao_db_rp']; @@ -178,23 +146,23 @@ class PmInstaller $this->log($qwv, isset($qwv['errors'])); $http = (G::is_https() == true) ? 'https' : 'http'; - $lang = defined( 'SYS_LANG' ) ? SYS_LANG : 'en'; + $lang = defined('SYS_LANG') ? SYS_LANG : 'en'; $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] != '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); $workspace = $this->options['name']; $endpoint = sprintf( - '%s://%s/sys%s/%s/%s/oauth2/grant', - $http, - $host, - $workspace, - $lang, - SYS_SKIN + '%s://%s/sys%s/%s/%s/oauth2/grant', + $http, + $host, + $workspace, + $lang, + SYS_SKIN ); // inserting the outh_client - $query = ( "INSERT INTO OAUTH_CLIENTS (CLIENT_ID,CLIENT_SECRET,CLIENT_NAME,CLIENT_DESCRIPTION,CLIENT_WEBSITE,REDIRECT_URI,USR_UID ) VALUES + $query = ("INSERT INTO OAUTH_CLIENTS (CLIENT_ID,CLIENT_SECRET,CLIENT_NAME,CLIENT_DESCRIPTION,CLIENT_WEBSITE,REDIRECT_URI,USR_UID ) VALUES ('x-pm-local-client','179ad45c6ce2cb97cf1029e212046e81','PM Web Designer','ProcessMaker Web Designer App','www.processmaker.com','" . $endpoint . "','00000000000000000000000000000001' )"); - $this->run_query( $query ); + $this->run_query($query); /* Dump schema rbac && data */ $pws = PATH_RBAC_MYSQL_DATA . $schema; @@ -206,8 +174,8 @@ class PmInstaller mysql_select_db($wf, $this->connection_database); - require_once ("propel/Propel.php"); - require_once ('classes/model/AppCacheView.php'); + require_once("propel/Propel.php"); + require_once('classes/model/AppCacheView.php'); $appCache = new AppCacheView(); $appCache->setPathToAppCacheFiles(PATH_METHODS . 'setup/setupSchemas/'); @@ -235,7 +203,7 @@ class PmInstaller $db_text .= " define ('SYSTEM_NAME', '" . SYSTEM_NAME . "');\n"; } } - $db_text .="?>"; + $db_text .= "?>"; $fp = @fopen($db_file, "w"); $this->log("Create: " . $db_file . " => " . ((!$fp) ? $fp : "OK") . "\n", $fp === false); @@ -249,9 +217,9 @@ class PmInstaller $content = 'system_utc_time_zone = 1' . "\n"; $fp = @fopen($envIniFile, 'w'); - $this->log('Create: ' . $envIniFile . ' => ' . ((!$fp)? $fp : 'OK') . "\n", $fp === false); + $this->log('Create: ' . $envIniFile . ' => ' . ((!$fp) ? $fp : 'OK') . "\n", $fp === false); $ff = @fputs($fp, $content, strlen($content)); - $this->log('Write: ' . $envIniFile . ' => ' . ((!$ff)? $ff : 'OK') . "\n", $ff === false); + $this->log('Write: ' . $envIniFile . ' => ' . ((!$ff) ? $ff : 'OK') . "\n", $ff === false); fclose($fp); /*----------------------------------********---------------------------------*/ @@ -294,16 +262,16 @@ class PmInstaller $dataFile = pathinfo($value); $nameSkinTmp = $dataFile['filename']; - $tar = new Archive_Tar( $value ); + $tar = new Archive_Tar($value); $pathSkinTmp = $pathSkinPartner . 'tmp' . PATH_SEP; G::rm_dir($pathSkinTmp); G::verifyPath($pathSkinTmp, true); - chmod( $pathSkinTmp, 0777); + chmod($pathSkinTmp, 0777); $tar->extract($pathSkinTmp); $pathSkinName = $pathSkinTmp . $nameSkinTmp . PATH_SEP; - chmod( $pathSkinName, 0777); + chmod($pathSkinName, 0777); G::verifyPath(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', true); $skinClassic = PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp' . PATH_SEP; @@ -334,7 +302,7 @@ class PmInstaller } // create session - $cookiefile = sys_get_temp_dir() . PATH_SEP . 'curl-session'; + $cookiefile = sys_get_temp_dir() . PATH_SEP . 'curl-session'; $fp = fopen($cookiefile, "w"); fclose($fp); @@ -365,7 +333,7 @@ class PmInstaller $ch = curl_init(); $postData = array(); // resolv the plugin name - $plugins = glob(PATH_CORE."plugins/*.tar"); + $plugins = glob(PATH_CORE . "plugins/*.tar"); if (count($plugins) > 0) { $pluginName = $plugins[0]; @@ -388,42 +356,42 @@ class PmInstaller } } - function copyFile($fromDir, $toDir, $chmod=0777) + function copyFile($fromDir, $toDir, $chmod = 0777) { $errors = array(); $messages = array(); - if (!is_writable($toDir)) { - $errors[]='target '.$toDir.' is not writable'; + if (!is_writable($toDir)) { + $errors[] = 'target ' . $toDir . ' is not writable'; } if (!is_dir($toDir)) { - $errors[]='target '.$toDir.' is not a directory'; + $errors[] = 'target ' . $toDir . ' is not a directory'; } if (!is_dir($fromDir)) { - $errors[]='source '.$fromDir.' is not a directory'; + $errors[] = 'source ' . $fromDir . ' is not a directory'; } if (!empty($errors)) { return false; } - $exceptions = array ('.','..'); + $exceptions = array('.', '..'); $handle = opendir($fromDir); - while (false !== ($item=readdir($handle))) { - if (!in_array($item,$exceptions)) { - $from = str_replace('//','/',$fromDir.'/'.$item); - $to = str_replace('//','/',$toDir.'/'.$item); + while (false !== ($item = readdir($handle))) { + if (!in_array($item, $exceptions)) { + $from = str_replace('//', '/', $fromDir . '/' . $item); + $to = str_replace('//', '/', $toDir . '/' . $item); if (is_file($from)) { - if (@copy($from,$to)) { - chmod($to,$chmod); - touch($to,filemtime($from)); + if (@copy($from, $to)) { + chmod($to, $chmod); + touch($to, filemtime($from)); } } if (is_dir($from)) { if (@mkdir($to)) { - chmod($to,$chmod); + chmod($to, $chmod); } - $this->copyFile($from,$to,$chmod); + $this->copyFile($from, $to, $chmod); } } } @@ -445,12 +413,12 @@ class PmInstaller if ($value['CFG_UID'] == 'ENVIRONMENT_SETTINGS') { $query = 'INSERT INTO CONFIGURATION (CFG_UID, OBJ_UID, CFG_VALUE, PRO_UID, USR_UID, APP_UID) VALUES'; $query .= "('" . - $value['CFG_UID'] . "', '". - $value['OBJ_UID'] . "', '". - $value['CFG_VALUE'] . "', '". - $value['PRO_UID'] . "', '". - $value['USR_UID'] . "', '". - $value['APP_UID'] . "')"; + $value['CFG_UID'] . "', '" . + $value['OBJ_UID'] . "', '" . + $value['CFG_VALUE'] . "', '" . + $value['PRO_UID'] . "', '" . + $value['USR_UID'] . "', '" . + $value['APP_UID'] . "')"; mysql_select_db($this->wf_site_name, $this->connection_database); $this->run_query($query, "Copy configuracion environment"); break; @@ -580,7 +548,7 @@ class PmInstaller if (PHP_OS == 'WINNT') { return $def; } else { - return (int) substr(sprintf('%o', @fileperms($file)), - 4); + return (int)substr(sprintf('%o', @fileperms($file)), -4); } } @@ -688,12 +656,12 @@ class PmInstaller if (!function_exists("mysql_connect")) { $this->cc_status = 0; $rt = Array('connection' => false, 'grant' => 0, 'version' => false, 'message' => "ERROR: Mysql Module for PHP is not enabled, try install php-mysql package.", 'ao' => Array('ao_db_wf' => false, 'ao_db_rb' => false, 'ao_db_rp' => false - ) + ) ); } else { $this->connection_database = @mysql_connect($this->options['database']['hostname'], $this->options['database']['username'], $this->options['database']['password']); $rt = Array('version' => false, 'ao' => Array('ao_db_wf' => false, 'ao_db_rb' => false, 'ao_db_rp' => false - ) + ) ); if (!$this->connection_database) { $this->cc_status = 0; @@ -750,7 +718,7 @@ class PmInstaller { array_push($this->report, $text); if ($failed) { - throw new Exception(is_string($text) ? $text : var_export($text, true) ); + throw new Exception(is_string($text) ? $text : var_export($text, true)); } } } diff --git a/workflow/engine/classes/PmSystem.php b/workflow/engine/src/ProcessMaker/Core/System.php similarity index 56% rename from workflow/engine/classes/PmSystem.php rename to workflow/engine/src/ProcessMaker/Core/System.php index 509d40e4e..e5b0e9837 100644 --- a/workflow/engine/classes/PmSystem.php +++ b/workflow/engine/src/ProcessMaker/Core/System.php @@ -1,15 +1,16 @@ * @access public * @return array of workspace tools objects */ - public static function listWorkspaces () + public static function listWorkspaces() { - $oDirectory = dir( PATH_DB ); - $aWorkspaces = array (); - foreach (glob( PATH_DB . "*" ) as $filename) { - if (is_dir( $filename ) && file_exists( $filename . "/db.php" )) { - $aWorkspaces[] = new workspaceTools( basename( $filename ) ); + $oDirectory = dir(PATH_DB); + $aWorkspaces = array(); + foreach (glob(PATH_DB . "*") as $filename) { + if (is_dir($filename) && file_exists($filename . "/db.php")) { + $aWorkspaces[] = new WorkspaceTools(basename($filename)); } } return $aWorkspaces; @@ -104,20 +104,19 @@ class PmSystem * If version-pmos.php is not found, try to * retrieve the version from git. * - * @author Alexandre Rosenfeld * @return string system */ - public static function getVersion () + public static function getVersion() { - if (! defined( 'PM_VERSION' )) { - if (file_exists( PATH_METHODS . 'login/version-pmos.php' )) { - include (PATH_METHODS . 'login/version-pmos.php'); + if (!defined('PM_VERSION')) { + if (file_exists(PATH_METHODS . 'login/version-pmos.php')) { + include(PATH_METHODS . 'login/version-pmos.php'); } else { $version = self::getVersionFromGit(); if ($version === false) { $version = 'Development Version'; } - define( 'PM_VERSION', $version ); + define('PM_VERSION', $version); } } return PM_VERSION; @@ -126,20 +125,19 @@ class PmSystem /** * Get the branch and tag information from a git repository. * - * @author Alexandre Rosenfeld * @return string branch and tag information */ - public static function getVersionFromGit ($dir = null) + public static function getVersionFromGit($dir = null) { if ($dir == null) { $dir = PATH_TRUNK; } - if (! file_exists( "$dir/.git" )) { + if (!file_exists("$dir/.git")) { return false; } - if (exec( "cd $dir && git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/^* \(.*\)$/(Branch \\1)/'", $target )) { + if (exec("cd $dir && git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/^* \(.*\)$/(Branch \\1)/'", $target)) { //exec( "cd $dir && git describe", $target ); ??? <-- thi is returning "fatal: No names found, cannot describe anything." on apache error log file - return implode( ' ', $target ); + return implode(' ', $target); } return false; } @@ -147,45 +145,44 @@ class PmSystem /** * Get system information * - * param * * @return array with system information */ - public static function getSysInfo () + public static function getSysInfo() { - $ipe = isset($_SERVER['SSH_CONNECTION']) ? explode( " ", $_SERVER['SSH_CONNECTION'] ) : array(); + $ipe = isset($_SERVER['SSH_CONNECTION']) ? explode(" ", $_SERVER['SSH_CONNECTION']) : array(); - if (getenv( 'HTTP_CLIENT_IP' )) { - $ip = getenv( 'HTTP_CLIENT_IP' ); - } elseif (getenv( 'HTTP_X_FORWARDED_FOR' )) { - $ip = getenv( 'HTTP_X_FORWARDED_FOR' ); + if (getenv('HTTP_CLIENT_IP')) { + $ip = getenv('HTTP_CLIENT_IP'); + } elseif (getenv('HTTP_X_FORWARDED_FOR')) { + $ip = getenv('HTTP_X_FORWARDED_FOR'); } else { - $ip = getenv( 'REMOTE_ADDR' ); + $ip = getenv('REMOTE_ADDR'); } /* For distros with the lsb_release, this returns a one-line description of * the distro name, such as "CentOS release 5.3 (Final)" or "Ubuntu 10.10" */ $distro = ''; - if (file_exists("/dev/")){ //Windows does not have this folder - $distro = exec( "lsb_release -d -s 2> /dev/null" ); + if (file_exists("/dev/")) { //Windows does not have this folder + $distro = exec("lsb_release -d -s 2> /dev/null"); } /* For distros without lsb_release, we look for *release (such as * redhat-release, gentoo-release, SuSE-release, etc) or *version (such as * debian_version, slackware-version, etc) */ - if (empty( $distro )) { - foreach (glob( "/etc/*release" ) as $filename) { - $distro = trim( file_get_contents( $filename ) ); - if (! empty( $distro )) { + if (empty($distro)) { + foreach (glob("/etc/*release") as $filename) { + $distro = trim(file_get_contents($filename)); + if (!empty($distro)) { break; } } - if (empty( $distro )) { - foreach (glob( "/etc/*version" ) as $filename) { - $distro = trim( file_get_contents( $filename ) ); - if (! empty( $distro )) { + if (empty($distro)) { + foreach (glob("/etc/*version") as $filename) { + $distro = trim(file_get_contents($filename)); + if (!empty($distro)) { break; } } @@ -195,9 +192,9 @@ class PmSystem /* CentOS returns a string with quotes, remove them and append * the OS name (such as LINUX, WINNT, DARWIN, etc) */ - $distro = trim( $distro, "\"" ) . " (" . PHP_OS . ")"; + $distro = trim($distro, "\"") . " (" . PHP_OS . ")"; - $Fields = array (); + $Fields = array(); $Fields['SYSTEM'] = $distro; $Fields['PHP'] = phpversion(); $Fields['PM_VERSION'] = self::getVersion(); @@ -205,45 +202,55 @@ class PmSystem $Fields['IP'] = isset($ipe[0]) ? $ipe[0] : ''; //lookup($ipe[0]); - $Fields['PLUGINS_LIST'] = PmSystem::getPlugins(); + $Fields['PLUGINS_LIST'] = System::getPlugins(); return $Fields; } - public static function listPoFiles () + /** + * Load the po files + * + * @return array $items + */ + public static function listPoFiles() { - $folders = glob( PATH_CORE . '/content/translations/*' ); + $folders = glob(PATH_CORE . '/content/translations/*'); - $items = glob( PATH_CORE . '/content/translations/*.po' ); + $items = glob(PATH_CORE . '/content/translations/*.po'); foreach ($folders as $folder) { - if (is_dir( $folder )) { - $add = glob( $folder . "/*.po" ); - $items = array_merge( $items, $add ); + if (is_dir($folder)) { + $add = glob($folder . "/*.po"); + $items = array_merge($items, $add); } } return $items; } - public static function verifyChecksum () + /** + * Review the checksum.txt + * + * @return array $result + */ + public static function verifyChecksum() { - if (! file_exists( PATH_TRUNK . "checksum.txt" )) { + if (!file_exists(PATH_TRUNK . "checksum.txt")) { return false; } - $lines = explode( "\n", file_get_contents( PATH_TRUNK . "checksum.txt" ) ); - $result = array ("diff" => array (),"missing" => array () + $lines = explode("\n", file_get_contents(PATH_TRUNK . "checksum.txt")); + $result = array("diff" => array(), "missing" => array() ); foreach ($lines as $line) { - if (empty( $line )) { + if (empty($line)) { continue; } - list ($checksum, $empty, $filename) = explode( " ", $line ); + list ($checksum, $empty, $filename) = explode(" ", $line); //Skip xmlform because these files always change. - if (strpos( $filename, "/xmlform/" ) !== false) { + if (strpos($filename, "/xmlform/") !== false) { continue; } - if (file_exists( realpath( $filename ) )) { - if (strcmp( $checksum, G::encryptFileOld( realpath( $filename ) ) ) != 0) { + if (file_exists(realpath($filename))) { + if (strcmp($checksum, G::encryptFileOld(realpath($filename))) != 0) { $result['diff'][] = $filename; } } else { @@ -256,26 +263,24 @@ class PmSystem /** * This function checks files to do updated to pm * - * * @name verifyFileForUpgrade * - * param * @return boolean */ - public function verifyFileForUpgrade () + public function verifyFileForUpgrade() { $filter = new InputFilter(); - $upgradeFilename = isset( $_FILES['form']['name']['UPGRADE_FILENAME'] ) ? $_FILES['form']['name']['UPGRADE_FILENAME'] : ''; - $tempFilename = isset( $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] ) ? $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] : ''; - $this->sRevision = str_replace( '.tar.gz', '', str_replace( 'pmos-patch-', '', $upgradeFilename ) ); + $upgradeFilename = isset($_FILES['form']['name']['UPGRADE_FILENAME']) ? $_FILES['form']['name']['UPGRADE_FILENAME'] : ''; + $tempFilename = isset($_FILES['form']['tmp_name']['UPGRADE_FILENAME']) ? $_FILES['form']['tmp_name']['UPGRADE_FILENAME'] : ''; + $this->sRevision = str_replace('.tar.gz', '', str_replace('pmos-patch-', '', $upgradeFilename)); $sTemFilename = $tempFilename; $sTemFilename = $filter->xssFilterHard($sTemFilename, 'path'); $pathFile = $filter->xssFilterHard(PATH_DATA . 'upgrade' . PATH_SEP . $upgradeFilename, 'path'); $this->sFilename = $pathFile; - $this->sPath = dirname( $this->sFilename ) . PATH_SEP; - G::mk_dir( PATH_DATA . 'upgrade' ); - if (! move_uploaded_file( $sTemFilename, $this->sFilename )) { + $this->sPath = dirname($this->sFilename) . PATH_SEP; + G::mk_dir(PATH_DATA . 'upgrade'); + if (!move_uploaded_file($sTemFilename, $this->sFilename)) { return false; } return true; @@ -284,43 +289,38 @@ class PmSystem /** * This function gets files to do updated to pm * - * * @name getUpgradedFilesList - * - * param * @return void + * @throws Exception */ - public function getUpgradedFilesList () + public function getUpgradedFilesList() { - $this->sFilesList = new gzip_file( $this->sFilename ); - $this->sFilesList->set_options( array ('basedir' => dirname( $this->sFilename ),'overwrite' => 1 - ) ); + $this->sFilesList = new GzipFile($this->sFilename); + $this->sFilesList->set_options(array('basedir' => dirname($this->sFilename), 'overwrite' => 1 + )); $this->sFilesList->extract_files(); - if (count( $this->sFilesList->error ) > 0) { + if (count($this->sFilesList->error) > 0) { $msg = ''; foreach ($this->sFilesList->error as $key => $val) { $msg .= $val . "\n"; } - throw new Exception( $msg ); + throw new Exception($msg); } - if (count( $this->sFilesList->files ) == 0) { - throw new Exception( 'The uploaded file is an invalid patch file.' ); + if (count($this->sFilesList->files) == 0) { + throw new Exception('The uploaded file is an invalid patch file.'); } } /** * This function checks to do updated for boot * - * * @name verifyForBootstrapUpgrade - * - * param * @return boolean */ - public function verifyForBootstrapUpgrade () + public function verifyForBootstrapUpgrade() { foreach ($this->sFilesList->files as $sFile) { - if (basename( $sFile ) == 'schema.xml') { + if (basename($sFile) == 'schema.xml') { $this->newSystemClass = $sFile; return true; } @@ -331,13 +331,12 @@ class PmSystem /** * This function updates to the files * - * * @name upgrade * - * param - * @return array + * @return object + * @throws Exception */ - public function upgrade () + public function upgrade() { //get special files $sListFile = ''; @@ -347,8 +346,8 @@ class PmSystem $sSchemaFile = ''; $sSchemaRBACFile = ''; foreach ($this->sFilesList->files as $sFile) { - if (basename( $sFile ) == 'schema.xml') { - if (strpos( $sFile, '/rbac/engine/' ) === false) { + if (basename($sFile) == 'schema.xml') { + if (strpos($sFile, '/rbac/engine/') === false) { $sOldSchema = ''; $sSchemaFile = $sFile; } else { @@ -358,105 +357,105 @@ class PmSystem } //files.lst - if (basename( $sFile ) == 'files.lst') { + if (basename($sFile) == 'files.lst') { $this->sUpgradeFileList = $sFile; } //files.lst - if (basename( $sFile ) == 'patch.version.txt') { + if (basename($sFile) == 'patch.version.txt') { $sPatchVersionFile = $sFile; } //files.rev.txt - if (substr( basename( $sFile ), 0, 6 ) == 'files.' && substr( basename( $sFile ), - 4 ) == '.txt') { + if (substr(basename($sFile), 0, 6) == 'files.' && substr(basename($sFile), -4) == '.txt') { $sCheckListFile = $sFile; } //po files - $sExtension = substr( $sFile, strrpos( $sFile, '.' ) + 1, strlen( $sFile ) ); + $sExtension = substr($sFile, strrpos($sFile, '.') + 1, strlen($sFile)); if ($sExtension == 'po') { $sPoFile = $sFile; } } - $pmVersion = explode( '-', self::getVersion() ); - array_shift( $pmVersion ); - $patchVersion = explode( '-', $this->sRevision ); + $pmVersion = explode('-', self::getVersion()); + array_shift($pmVersion); + $patchVersion = explode('-', $this->sRevision); - if ($sPatchVersionFile != '' && file_exists( $sPatchVersionFile )) { - $this->sRevision = file_get_contents( $sPatchVersionFile ); - $patchVersion = explode( '-', $this->sRevision ); + if ($sPatchVersionFile != '' && file_exists($sPatchVersionFile)) { + $this->sRevision = file_get_contents($sPatchVersionFile); + $patchVersion = explode('-', $this->sRevision); } - if (! file_exists( PATH_DATA . 'log' . PATH_SEP )) { - G::mk_dir( PATH_DATA . 'log' . PATH_SEP ); + if (!file_exists(PATH_DATA . 'log' . PATH_SEP)) { + G::mk_dir(PATH_DATA . 'log' . PATH_SEP); } //empty query log $sqlLog = PATH_DATA . 'log' . PATH_SEP . "query.log"; - $fp = fopen( $sqlLog, "w+" ); - fwrite( $fp, "" ); - fclose( $fp ); + $fp = fopen($sqlLog, "w+"); + fwrite($fp, ""); + fclose($fp); - $aEnvironmentsUpdated = array (); - $aEnvironmentsDiff = array (); - $aErrors = array (); + $aEnvironmentsUpdated = array(); + $aEnvironmentsDiff = array(); + $aErrors = array(); //now will verify each folder and file has permissions to write and add files. if ($this->sUpgradeFileList != '') { $bCopySchema = true; - $oFile = fopen( $this->sUpgradeFileList, 'r' ); - while ($sLine = trim( fgets( $oFile ) )) { - $sLine = substr( $sLine, 1 ); - $aAux = explode( PATH_SEP, $sLine ); - array_shift( $aAux ); - $sFilePath = implode( PATH_SEP, $aAux ); + $oFile = fopen($this->sUpgradeFileList, 'r'); + while ($sLine = trim(fgets($oFile))) { + $sLine = substr($sLine, 1); + $aAux = explode(PATH_SEP, $sLine); + array_shift($aAux); + $sFilePath = implode(PATH_SEP, $aAux); $targetFileName = PATH_TRUNK . $sFilePath; - if (! is_dir( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { + if (!is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath)) { //if we are updating or deleting a file - if (file_exists( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { - if (file_exists( $targetFileName )) { - if (! is_writable( $targetFileName )) { - throw (new Exception( "File $targetFileName is not writable." )); + if (file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath)) { + if (file_exists($targetFileName)) { + if (!is_writable($targetFileName)) { + throw (new Exception("File $targetFileName is not writable.")); } } else { //verify parent folder, and ask if that folder is writable - $auxDir = explode( '/', $targetFileName ); - array_pop( $auxDir ); - $parentDir = implode( '/', $auxDir ); - if (! is_dir( $parentDir )) { + $auxDir = explode('/', $targetFileName); + array_pop($auxDir); + $parentDir = implode('/', $auxDir); + if (!is_dir($parentDir)) { //throw (new Exception("File $parentDir is an invalid directory.")); - G::mk_dir( $parentDir ); + G::mk_dir($parentDir); } - if (! is_writable( $parentDir )) { - throw (new Exception( "Directory $parentDir is not writable." )); + if (!is_writable($parentDir)) { + throw (new Exception("Directory $parentDir is not writable.")); } } } else { //delete unused files - if (file_exists( $targetFileName ) && ! is_writable( $targetFileName )) { - throw (new Exception( "File $targetFileName is not writable." )); + if (file_exists($targetFileName) && !is_writable($targetFileName)) { + throw (new Exception("File $targetFileName is not writable.")); } } } else { $dirName = PATH_TRUNK . $sFilePath; - if ($dirName[strlen( $dirName ) - 1] == '/') { - $dirName = substr( $dirName, 0, strlen( $dirName ) - 1 ); + if ($dirName[strlen($dirName) - 1] == '/') { + $dirName = substr($dirName, 0, strlen($dirName) - 1); } - $auxDir = explode( '/', $dirName ); - array_pop( $auxDir ); - $parentDir = implode( '/', $auxDir ); - if (file_exists( $dirName )) { - if (is_writable( $dirName )) { + $auxDir = explode('/', $dirName); + array_pop($auxDir); + $parentDir = implode('/', $auxDir); + if (file_exists($dirName)) { + if (is_writable($dirName)) { //print "e. ok $dirName
"; } else { - throw (new Exception( "$dirName is not writable" )); + throw (new Exception("$dirName is not writable")); } } else { - if (is_writable( $parentDir )) { - mkdir( $dirName, 0777 ); + if (is_writable($parentDir)) { + mkdir($dirName, 0777); } else { - throw (new Exception( "$dirName does not exist and parent folder $parentDir is not writable" )); + throw (new Exception("$dirName does not exist and parent folder $parentDir is not writable")); } } } @@ -466,46 +465,46 @@ class PmSystem //processing list file files.lst if ($this->sUpgradeFileList != '') { $bCopySchema = true; - $oFile = fopen( $this->sUpgradeFileList, 'r' ); - while ($sLine = trim( fgets( $oFile ) )) { - $action = substr( $sLine, 0, 1 ); - $sLine = substr( $sLine, 1 ); - $aAux = explode( PATH_SEP, $sLine ); - array_shift( $aAux ); - $sFilePath = implode( PATH_SEP, $aAux ); + $oFile = fopen($this->sUpgradeFileList, 'r'); + while ($sLine = trim(fgets($oFile))) { + $action = substr($sLine, 0, 1); + $sLine = substr($sLine, 1); + $aAux = explode(PATH_SEP, $sLine); + array_shift($aAux); + $sFilePath = implode(PATH_SEP, $aAux); $targetFileName = PATH_TRUNK . $sFilePath; - if (strtoupper( $action ) != 'D') { - if (! is_dir( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { - if (file_exists( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath )) { - if (strpos( $sFilePath, 'schema.xml' ) !== false && $bCopySchema) { + if (strtoupper($action) != 'D') { + if (!is_dir($this->sPath . 'processmaker' . PATH_SEP . $sFilePath)) { + if (file_exists($this->sPath . 'processmaker' . PATH_SEP . $sFilePath)) { + if (strpos($sFilePath, 'schema.xml') !== false && $bCopySchema) { $bCopySchema = false; - $sOldSchema = str_replace( 'schema.xml', 'schema_' . date( 'Ymd' ) . '.xml', PATH_TRUNK . $sFilePath ); - $this->pm_copy( PATH_TRUNK . $sFilePath, $sOldSchema ); + $sOldSchema = str_replace('schema.xml', 'schema_' . date('Ymd') . '.xml', PATH_TRUNK . $sFilePath); + $this->pm_copy(PATH_TRUNK . $sFilePath, $sOldSchema); } - if (file_exists( $targetFileName )) { - if (is_writable( $targetFileName )) { - $this->pm_copy( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName ); - @chmod( $targetFileName, 0666 ); + if (file_exists($targetFileName)) { + if (is_writable($targetFileName)) { + $this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName); + @chmod($targetFileName, 0666); } else { - throw (new Exception( "Failed to open file: Permission denied in $targetFileName." )); + throw (new Exception("Failed to open file: Permission denied in $targetFileName.")); } } else { - $this->pm_copy( $this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName ); - @chmod( $targetFileName, 0666 ); + $this->pm_copy($this->sPath . 'processmaker' . PATH_SEP . $sFilePath, $targetFileName); + @chmod($targetFileName, 0666); } } else { //delete unused files - if (file_exists( $targetFileName )) { - @unlink( $targetFileName ); + if (file_exists($targetFileName)) { + @unlink($targetFileName); } } } else { - if (! file_exists( PATH_TRUNK . $sFilePath )) { - mkdir( PATH_TRUNK . $sFilePath, 0777 ); + if (!file_exists(PATH_TRUNK . $sFilePath)) { + mkdir(PATH_TRUNK . $sFilePath, 0777); } } - } elseif (file_exists( PATH_TRUNK . $sFilePath ) && $sFilePath != 'workflow/engine/gulliver') { - @unlink( PATH_TRUNK . $sFilePath ); + } elseif (file_exists(PATH_TRUNK . $sFilePath) && $sFilePath != 'workflow/engine/gulliver') { + @unlink(PATH_TRUNK . $sFilePath); } } } @@ -517,25 +516,25 @@ class PmSystem $distinct = 0; //checking files of this installation server with the files in Repository Code. if ($sCheckListFile != '') { - $fp = fopen( $sCheckListFile, 'r' ); - while (! feof( $fp )) { - $line = explode( ' ', fgets( $fp ) ); - if (count( $line ) == 3) { - $file = PATH_TRUNK . trim( $line[2] ); - if (is_readable( $file )) { - $size = sprintf( "%07d", filesize( $file ) ); - $checksum = sprintf( "%010u", G::encryptCrc32( file_get_contents( $file ) ) ); - if (! ($line[0] == $size && $line[1] == $checksum) && substr( $file, - 4 ) != '.xml') { + $fp = fopen($sCheckListFile, 'r'); + while (!feof($fp)) { + $line = explode(' ', fgets($fp)); + if (count($line) == 3) { + $file = PATH_TRUNK . trim($line[2]); + if (is_readable($file)) { + $size = sprintf("%07d", filesize($file)); + $checksum = sprintf("%010u", G::encryptCrc32(file_get_contents($file))); + if (!($line[0] == $size && $line[1] == $checksum) && substr($file, -4) != '.xml') { $distinctFiles .= $file . "\n"; - $distinct ++; + $distinct++; } } else { $missedFiles .= $file . "\n"; - $missed ++; + $missed++; } } } - fclose( $fp ); + fclose($fp); } if ($missed > 0) { @@ -555,47 +554,47 @@ class PmSystem $bForceXml = true; $bParseSchema = true; $bParseSchemaRBAC = true; - $oDirectory = dir( PATH_DB ); + $oDirectory = dir(PATH_DB); //count db.php files ( workspaces ) - $aWorkspaces = array (); + $aWorkspaces = array(); while (($sObject = $oDirectory->read())) { - if (is_dir( PATH_DB . $sObject ) && substr( $sObject, 0, 1 ) != '.' && file_exists( PATH_DB . $sObject . PATH_SEP . 'db.php' )) { + if (is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.' && file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php')) { $aWorkspaces[] = $sObject; } } - $aUpgradeData = array (); + $aUpgradeData = array(); $aUpgradeData['workspaces'] = $aWorkspaces; - $aUpgradeData['wsQuantity'] = count( $aWorkspaces ); + $aUpgradeData['wsQuantity'] = count($aWorkspaces); $aUpgradeData['sPoFile'] = $sPoFile; $aUpgradeData['bForceXmlPoFile'] = true; $aUpgradeData['sSchemaFile'] = $sSchemaFile; $aUpgradeData['sSchemaRBACFile'] = $sSchemaRBACFile; - file_put_contents( PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize( $aUpgradeData ) ); + file_put_contents(PATH_DATA . 'log' . PATH_SEP . "upgrade.data.bin", serialize($aUpgradeData)); $sSchemaFile = ''; $sPoFile = ''; $sSchemaRBACFile = ''; - $oDirectory = dir( PATH_DB ); + $oDirectory = dir(PATH_DB); while (($sObject = $oDirectory->read())) { - if (is_dir( PATH_DB . $sObject ) && substr( $sObject, 0, 1 ) != '.') { - if (file_exists( PATH_DB . $sObject . PATH_SEP . 'db.php' )) { - eval( $this->getDatabaseCredentials( PATH_DB . $sObject . PATH_SEP . 'db.php' ) ); + if (is_dir(PATH_DB . $sObject) && substr($sObject, 0, 1) != '.') { + if (file_exists(PATH_DB . $sObject . PATH_SEP . 'db.php')) { + eval($this->getDatabaseCredentials(PATH_DB . $sObject . PATH_SEP . 'db.php')); } $aEnvironmentsUpdated[] = $sObject; $aEnvironmentsDiff[] = $sObject; } } $oDirectory->close(); - @unlink( PATH_CORE . 'config/_databases_.php' ); + @unlink(PATH_CORE . 'config/_databases_.php'); //clean up smarty directory - $oDirectory = dir( PATH_SMARTY_C ); + $oDirectory = dir(PATH_SMARTY_C); while ($sFilename = $oDirectory->read()) { if (($sFilename != '.') && ($sFilename != '..')) { - @unlink( PATH_SMARTY_C . PATH_SEP . $sFilename ); + @unlink(PATH_SMARTY_C . PATH_SEP . $sFilename); } } @@ -605,12 +604,12 @@ class PmSystem //clean up xmlform folders $sDir = PATH_C . 'xmlform'; $sDir = $filter->xssFilterHard($sDir, 'path'); - if (file_exists( $sDir ) && is_dir( $sDir )) { - $oDirectory = dir( $sDir ); + if (file_exists($sDir) && is_dir($sDir)) { + $oDirectory = dir($sDir); while ($sObjectName = $oDirectory->read()) { if (($sObjectName != '.') && ($sObjectName != '..')) { - if (is_dir( $sDir . PATH_SEP . $sObjectName )) { - G::rm_dir( $sDir . PATH_SEP . $sObjectName ); + if (is_dir($sDir . PATH_SEP . $sObjectName)) { + G::rm_dir($sDir . PATH_SEP . $sObjectName); } } } @@ -618,14 +617,14 @@ class PmSystem } //changing the PM_VERSION according the patch file name - $oFile = fopen( PATH_METHODS . 'login/version-pmos.php', 'w+' ); - if (isset( $this->sRevision ) && $this->sRevision != '') { - fwrite( $oFile, "sRevision . "' ));\n?>" ); + $oFile = fopen(PATH_METHODS . 'login/version-pmos.php', 'w+'); + if (isset($this->sRevision) && $this->sRevision != '') { + fwrite($oFile, "sRevision . "' ));\n?>"); } else { - fwrite( $oFile, "" ); + fwrite($oFile, ""); } - fclose( $oFile ); - $ver = explode( "-", $this->sRevision ); + fclose($oFile); + $ver = explode("-", $this->sRevision); $this->aErrors = $aErrors; $this->aWorkspaces = $aWorkspaces; @@ -635,15 +634,13 @@ class PmSystem /** * This function does to clean up to the upgrate directory * - * * @name cleanupUpgradeDirectory * - * param * @return array */ - public function cleanupUpgradeDirectory () + public function cleanupUpgradeDirectory() { - G::rm_dir( PATH_DATA . "upgrade" . PATH_SEP . "processmaker" ); + G::rm_dir(PATH_DATA . "upgrade" . PATH_SEP . "processmaker"); } /** @@ -656,36 +653,35 @@ class PmSystem * @param string $target * @return void */ - public function pm_copy ($source, $target) + public function pm_copy($source, $target) { - if (! is_dir( dirname( $target ) )) { - G::mk_dir( dirname( $target ) ); + if (!is_dir(dirname($target))) { + G::mk_dir(dirname($target)); } - if (! copy( $source, $target )) { - krumo( $source ); - krumo( $target ); + if (!copy($source, $target)) { + krumo($source); + krumo($target); } } /** * This function gets info about db * - * * @name getDatabaseCredentials * * @param string $dbFile - * @return $sContent + * @return string $sContent */ - public function getDatabaseCredentials ($dbFile) + public function getDatabaseCredentials($dbFile) { - $sContent = file_get_contents( $dbFile ); - $sContent = str_replace( '', '', $sContent ); - $sContent = str_replace( 'define', '', $sContent ); - $sContent = str_replace( "('", '$', $sContent ); - $sContent = str_replace( "',", '=', $sContent ); - $sContent = str_replace( ");", ';', $sContent ); + $sContent = file_get_contents($dbFile); + $sContent = str_replace('', '', $sContent); + $sContent = str_replace('define', '', $sContent); + $sContent = str_replace("('", '$', $sContent); + $sContent = str_replace("',", '=', $sContent); + $sContent = str_replace(");", ';', $sContent); return $sContent; } @@ -694,9 +690,9 @@ class PmSystem * * @return schema content in an array */ - public static function getSystemSchema () + public static function getSystemSchema() { - return PmSystem::getSchema( PATH_TRUNK . "workflow/engine/config/schema.xml" ); + return System::getSchema(PATH_TRUNK . "workflow/engine/config/schema.xml"); } /** @@ -704,9 +700,9 @@ class PmSystem * * @return schema content in an array */ - public static function getSystemSchemaRbac () + public static function getSystemSchemaRbac() { - return PmSystem::getSchema( PATH_TRUNK . "rbac/engine/config/schema.xml" ); + return System::getSchema(PATH_TRUNK . "rbac/engine/config/schema.xml"); } /** @@ -715,13 +711,13 @@ class PmSystem * @param string $pluginName name of the plugin * @return $sContent */ - public static function getPluginSchema ($pluginName) + public static function getPluginSchema($pluginName) { $filter = new InputFilter(); $pathFile = $filter->xssFilterHard(PATH_PLUGINS . $pluginName . "/config/schema.xml", 'path'); - if (file_exists( $pathFile )) { - return PmSystem::getSchema( $pathFile ); + if (file_exists($pathFile)) { + return System::getSchema($pathFile); } else { return false; } @@ -731,7 +727,7 @@ class PmSystem * Retrieves a schema array from a file. * * @param string $sSchemaFile schema filename - * @return $sContent + * @return string $sContent */ public static function getSchema($sSchemaFile) { @@ -822,12 +818,12 @@ class PmSystem * @param array $aOldSchema original schema array * @return array with tablesToRename */ - public static function verifyRbacSchema ($aOldSchema) + public static function verifyRbacSchema($aOldSchema) { - $aChanges = array (); + $aChanges = array(); foreach ($aOldSchema as $sTableName => $aColumns) { - if(substr($sTableName, 0,4) != 'RBAC') { + if (substr($sTableName, 0, 4) != 'RBAC') { $aChanges[] = $sTableName; } } @@ -842,32 +838,25 @@ class PmSystem * @param array $aNewSchema new schema array * @return array with tablesToAdd, tablesToAlter, tablesWithNewIndex and tablesToAlterIndex */ - public static function compareSchema ($aOldSchema, $aNewSchema) + public static function compareSchema($aOldSchema, $aNewSchema) { - //$aChanges = array('tablesToDelete' => array(), 'tablesToAdd' => array(), 'tablesToAlter' => array()); - //Tables to delete, but this is disabled - //foreach ($aOldSchema as $sTableName => $aColumns) { - // if ( !isset($aNewSchema[$sTableName])) { - // if (!in_array($sTableName, array('KT_APPLICATION', 'KT_DOCUMENT', 'KT_PROCESS'))) { - // $aChanges['tablesToDelete'][] = $sTableName; - // } - // } - //} - - - $aChanges = array ('tablesToAdd' => array (),'tablesToAlter' => array (),'tablesWithNewIndex' => array (),'tablesToAlterIndex' => array () + $aChanges = array( + 'tablesToAdd' => array(), + 'tablesToAlter' => array(), + 'tablesWithNewIndex' => array(), + 'tablesToAlterIndex' => array() ); //new tables to create and alter foreach ($aNewSchema as $sTableName => $aColumns) { - if (! isset( $aOldSchema[$sTableName] )) { + if (!isset($aOldSchema[$sTableName])) { $aChanges['tablesToAdd'][$sTableName] = $aColumns; } else { //drop old columns foreach ($aOldSchema[$sTableName] as $sColumName => $aParameters) { - if (! isset( $aNewSchema[$sTableName][$sColumName] )) { - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () + if (!isset($aNewSchema[$sTableName][$sColumName])) { + if (!isset($aChanges['tablesToAlter'][$sTableName])) { + $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array() ); } $aChanges['tablesToAlter'][$sTableName]['DROP'][$sColumName] = $sColumName; @@ -878,10 +867,10 @@ class PmSystem //foreach ($aNewSchema[$sTableName] as $sColumName => $aParameters) { foreach ($aColumns as $sColumName => $aParameters) { if ($sColumName != 'INDEXES') { - if (! isset( $aOldSchema[$sTableName][$sColumName] )) { + if (!isset($aOldSchema[$sTableName][$sColumName])) { //this column doesnt exist in oldschema - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array () + if (!isset($aChanges['tablesToAlter'][$sTableName])) { + $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array() ); } $aChanges['tablesToAlter'][$sTableName]['ADD'][$sColumName] = $aParameters; @@ -890,18 +879,18 @@ class PmSystem $newField = $aNewSchema[$sTableName][$sColumName]; $oldField = $aOldSchema[$sTableName][$sColumName]; //both are null, no change is required - if (! isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) { + if (!isset($newField['Default']) && !isset($oldField['Default'])) { $changeDefaultAttr = false; //one of them is null, change IS required } - if (! isset( $newField['Default'] ) && isset( $oldField['Default'] ) && $oldField['Default'] != '') { + if (!isset($newField['Default']) && isset($oldField['Default']) && $oldField['Default'] != '') { $changeDefaultAttr = true; } - if (isset( $newField['Default'] ) && ! isset( $oldField['Default'] )) { + if (isset($newField['Default']) && !isset($oldField['Default'])) { $changeDefaultAttr = true; //both are defined and they are different. } - if (isset( $newField['Default'] ) && isset( $oldField['Default'] )) { + if (isset($newField['Default']) && isset($oldField['Default'])) { if ($newField['Default'] != $oldField['Default']) { $changeDefaultAttr = true; } else { @@ -910,28 +899,28 @@ class PmSystem } //special cases // BLOB and TEXT columns cannot have DEFAULT values. http://dev.mysql.com/doc/refman/5.0/en/blob.html - if (in_array( strtolower( $newField['Type'] ), array ('text','mediumtext') )) { + if (in_array(strtolower($newField['Type']), array('text', 'mediumtext'))) { $changeDefaultAttr = false; } - //#1067 - Invalid default value for datetime field - if (in_array( $newField['Type'], array ('datetime') ) && isset( $newField['Default'] ) && $newField['Default'] == '') { + //#1067 - Invalid default value for datetime field + if (in_array($newField['Type'], array('datetime')) && isset($newField['Default']) && $newField['Default'] == '') { $changeDefaultAttr = false; } //#1067 - Invalid default value for int field - if (substr( $newField['Type'], 0, 3 ) == "INT" && isset( $newField['Default'] ) && $newField['Default'] == '') { + if (substr($newField['Type'], 0, 3) == "INT" && isset($newField['Default']) && $newField['Default'] == '') { $changeDefaultAttr = false; } //if any difference exists, then insert the difference in aChanges - if (strcasecmp( $newField['Field'], $oldField['Field'] ) !== 0 || strcasecmp( $newField['Type'], $oldField['Type'] ) !== 0 || strcasecmp( $newField['Null'], $oldField['Null'] ) !== 0 || $changeDefaultAttr) { - if (! isset( $aChanges['tablesToAlter'][$sTableName] )) { - $aChanges['tablesToAlter'][$sTableName] = array ('DROP' => array (),'ADD' => array (),'CHANGE' => array ()); + if (strcasecmp($newField['Field'], $oldField['Field']) !== 0 || strcasecmp($newField['Type'], $oldField['Type']) !== 0 || strcasecmp($newField['Null'], $oldField['Null']) !== 0 || $changeDefaultAttr) { + if (!isset($aChanges['tablesToAlter'][$sTableName])) { + $aChanges['tablesToAlter'][$sTableName] = array('DROP' => array(), 'ADD' => array(), 'CHANGE' => array()); } $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Field'] = $newField['Field']; $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Type'] = $newField['Type']; $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Null'] = $newField['Null']; - if (isset( $newField['Default'] )) { + if (isset($newField['Default'])) { $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = $newField['Default']; } else { $aChanges['tablesToAlter'][$sTableName]['CHANGE'][$sColumName]['Default'] = null; @@ -942,19 +931,18 @@ class PmSystem //only columns, no the indexes column } //foreach $aColumns - //now check the indexes of table - if (isset( $aNewSchema[$sTableName]['INDEXES'] )) { + if (isset($aNewSchema[$sTableName]['INDEXES'])) { foreach ($aNewSchema[$sTableName]['INDEXES'] as $indexName => $indexFields) { - if (! isset( $aOldSchema[$sTableName]['INDEXES'][$indexName] )) { - if (! isset( $aChanges['tablesWithNewIndex'][$sTableName] )) { - $aChanges['tablesWithNewIndex'][$sTableName] = array (); + if (!isset($aOldSchema[$sTableName]['INDEXES'][$indexName])) { + if (!isset($aChanges['tablesWithNewIndex'][$sTableName])) { + $aChanges['tablesWithNewIndex'][$sTableName] = array(); } $aChanges['tablesWithNewIndex'][$sTableName][$indexName] = $indexFields; } else { if ($aOldSchema[$sTableName]['INDEXES'][$indexName] != $indexFields) { - if (! isset( $aChanges['tablesToAlterIndex'][$sTableName] )) { - $aChanges['tablesToAlterIndex'][$sTableName] = array (); + if (!isset($aChanges['tablesToAlterIndex'][$sTableName])) { + $aChanges['tablesToAlterIndex'][$sTableName] = array(); } $aChanges['tablesToAlterIndex'][$sTableName][$indexName] = $indexFields; } @@ -976,23 +964,23 @@ class PmSystem if (count($arrayEmailServerDefault) > 0) { $arrayDataEmailServerConfig = array( - "MESS_ENGINE" => $arrayEmailServerDefault["MESS_ENGINE"], - "MESS_SERVER" => $arrayEmailServerDefault["MESS_SERVER"], - "MESS_PORT" => (int)($arrayEmailServerDefault["MESS_PORT"]), - "MESS_RAUTH" => (int)($arrayEmailServerDefault["MESS_RAUTH"]), - "MESS_ACCOUNT" => $arrayEmailServerDefault["MESS_ACCOUNT"], - "MESS_PASSWORD" => $arrayEmailServerDefault["MESS_PASSWORD"], - "MESS_FROM_MAIL" => $arrayEmailServerDefault["MESS_FROM_MAIL"], - "MESS_FROM_NAME" => $arrayEmailServerDefault["MESS_FROM_NAME"], - "SMTPSecure" => $arrayEmailServerDefault["SMTPSECURE"], + "MESS_ENGINE" => $arrayEmailServerDefault["MESS_ENGINE"], + "MESS_SERVER" => $arrayEmailServerDefault["MESS_SERVER"], + "MESS_PORT" => (int)($arrayEmailServerDefault["MESS_PORT"]), + "MESS_RAUTH" => (int)($arrayEmailServerDefault["MESS_RAUTH"]), + "MESS_ACCOUNT" => $arrayEmailServerDefault["MESS_ACCOUNT"], + "MESS_PASSWORD" => $arrayEmailServerDefault["MESS_PASSWORD"], + "MESS_FROM_MAIL" => $arrayEmailServerDefault["MESS_FROM_MAIL"], + "MESS_FROM_NAME" => $arrayEmailServerDefault["MESS_FROM_NAME"], + "SMTPSecure" => $arrayEmailServerDefault["SMTPSECURE"], "MESS_TRY_SEND_INMEDIATLY" => (int)($arrayEmailServerDefault["MESS_TRY_SEND_INMEDIATLY"]), - "MAIL_TO" => $arrayEmailServerDefault["MAIL_TO"], - "MESS_DEFAULT" => (int)($arrayEmailServerDefault["MESS_DEFAULT"]), - "MESS_ENABLED" => 1, - "MESS_BACKGROUND" => "", - "MESS_PASSWORD_HIDDEN" => "", - "MESS_EXECUTE_EVERY" => "", - "MESS_SEND_MAX" => "" + "MAIL_TO" => $arrayEmailServerDefault["MAIL_TO"], + "MESS_DEFAULT" => (int)($arrayEmailServerDefault["MESS_DEFAULT"]), + "MESS_ENABLED" => 1, + "MESS_BACKGROUND" => "", + "MESS_PASSWORD_HIDDEN" => "", + "MESS_EXECUTE_EVERY" => "", + "MESS_SEND_MAX" => "" ); //Return @@ -1006,61 +994,66 @@ class PmSystem } } - public function getSkingList () + /** + * Get the list of skins + * + * @return array $skinListArray + */ + public function getSkingList() { //Create Skins custom folder if it doesn't exists - if (! is_dir( PATH_CUSTOM_SKINS )) { - G::verifyPath( PATH_CUSTOM_SKINS, true ); + if (!is_dir(PATH_CUSTOM_SKINS)) { + G::verifyPath(PATH_CUSTOM_SKINS, true); } //Get Skin Config files - $skinListArray = array (); - $customSkins = glob( PATH_CUSTOM_SKINS . "*/config.xml" ); + $skinListArray = array(); + $customSkins = glob(PATH_CUSTOM_SKINS . "*/config.xml"); if (!is_array($customSkins)) { $customSkins = array(); } // getting al base skins - $baseSkins = glob( G::ExpandPath( "skinEngine" ) . '*/config.xml' ); + $baseSkins = glob(G::ExpandPath("skinEngine") . '*/config.xml'); // filtering no public skins (uxs, simplified) foreach ($baseSkins as $i => $skinName) { - if (strpos( $skinName, 'simplified' ) !== false || strpos( $skinName, 'uxs' ) !== false || strpos( $skinName, 'uxmodern' ) !== false) { - unset( $baseSkins[$i] ); + if (strpos($skinName, 'simplified') !== false || strpos($skinName, 'uxs') !== false || strpos($skinName, 'uxmodern') !== false) { + unset($baseSkins[$i]); } } - $customSkins = array_merge( $baseSkins, $customSkins ); + $customSkins = array_merge($baseSkins, $customSkins); $global = G::LoadTranslation('ID_GLOBAL'); //Read and parse each Configuration File foreach ($customSkins as $key => $configInformation) { - $folderId = basename( dirname( $configInformation ) ); + $folderId = basename(dirname($configInformation)); if ($folderId == 'base') { $folderId = 'classic'; } $partnerFlag = (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false; - if ($partnerFlag && ($folderId == 'classic')){ + if ($partnerFlag && ($folderId == 'classic')) { continue; } - $xmlConfiguration = file_get_contents( $configInformation ); - $xmlConfigurationObj = G::xmlParser( $xmlConfiguration ); + $xmlConfiguration = file_get_contents($configInformation); + $xmlConfigurationObj = G::xmlParser($xmlConfiguration); - if (isset( $xmlConfigurationObj->result['skinConfiguration'] )) { + if (isset($xmlConfigurationObj->result['skinConfiguration'])) { $skinInformationArray = $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['information']['__CONTENT__']; - $res = array (); - $res['SKIN_FOLDER_ID'] = strtolower( $folderId ); + $res = array(); + $res['SKIN_FOLDER_ID'] = strtolower($folderId); foreach ($skinInformationArray as $keyInfo => $infoValue) { - $res['SKIN_' . strtoupper( $keyInfo )] = (isset($infoValue['__VALUE__'])) ? $infoValue['__VALUE__'] : ''; + $res['SKIN_' . strtoupper($keyInfo)] = (isset($infoValue['__VALUE__'])) ? $infoValue['__VALUE__'] : ''; } - $res['SKIN_CREATEDATE'] = (isset($res['SKIN_CREATEDATE'])) ? $res['SKIN_CREATEDATE']: ''; - $res['SKIN_MODIFIEDDATE'] = (isset($res['SKIN_MODIFIEDDATE'])) ? $res['SKIN_MODIFIEDDATE']: ''; - $res['SKIN_WORKSPACE'] = (isset($res['SKIN_WORKSPACE'])) ? ( ($res['SKIN_WORKSPACE'] != '')? $res['SKIN_WORKSPACE'] : $global): $global; + $res['SKIN_CREATEDATE'] = (isset($res['SKIN_CREATEDATE'])) ? $res['SKIN_CREATEDATE'] : ''; + $res['SKIN_MODIFIEDDATE'] = (isset($res['SKIN_MODIFIEDDATE'])) ? $res['SKIN_MODIFIEDDATE'] : ''; + $res['SKIN_WORKSPACE'] = (isset($res['SKIN_WORKSPACE'])) ? (($res['SKIN_WORKSPACE'] != '') ? $res['SKIN_WORKSPACE'] : $global) : $global; $swWS = true; if ($res['SKIN_WORKSPACE'] != $global) { @@ -1084,14 +1077,26 @@ class PmSystem return $skinListArray; } - public function getAllTimeZones () + /** + * Get all time zones + * + * @return array $skinListArray + * @throws Exception + * @deprecated this method is deprecated + */ + public function getAllTimeZones() { throw new Exception(__METHOD__ . ': The method is deprecated'); } - public static function getSystemConfiguration ($globalIniFile = '', $wsIniFile = '', $wsName = '') + /** + * Get the system configuration + * + * @return array $config + */ + public static function getSystemConfiguration($globalIniFile = '', $wsIniFile = '', $wsName = '') { - if (! is_null(self::$config)) { + if (!is_null(self::$config)) { return self::$config; } @@ -1118,8 +1123,8 @@ class PmSystem // default configuration for "error_reporting" conf if (empty(self::$defaultConfig["error_reporting"])) { - $errorReportingDefault = defined('E_DEPRECATED') ? E_ALL & ~E_DEPRECATED : E_ALL; - $errorReportingDefault = defined('E_STRICT') ? $errorReportingDefault & ~E_STRICT : $errorReportingDefault; + $errorReportingDefault = defined('E_DEPRECATED') ? E_ALL & ~E_DEPRECATED : E_ALL; + $errorReportingDefault = defined('E_STRICT') ? $errorReportingDefault & ~E_STRICT : $errorReportingDefault; self::$defaultConfig["error_reporting"] = $errorReportingDefault; } @@ -1131,7 +1136,7 @@ class PmSystem } // Workspace environment configuration - if (file_exists($wsIniFile) ) { + if (file_exists($wsIniFile)) { if (($wsConf = @parse_ini_file($wsIniFile)) !== false) { $config = array_merge($config, $wsConf); } @@ -1149,87 +1154,111 @@ class PmSystem return $config; } - /* - * Get information about the queries permitted and tables we can modified - * @access public - * @param string $globalIniFile - * @return array of execute query Black list - */ - public static function getQueryBlackList($globalIniFile = ''){ + /** + * Get information about the queries permitted and tables we can modified + * @access public + * @param string $globalIniFile + * @return array of execute query Black list + */ + public static function getQueryBlackList($globalIniFile = '') + { $config = array(); if (empty($globalIniFile)) { $blackListIniFile = PATH_CONFIG . 'execute-query-blacklist.ini'; $sysTablesIniFile = PATH_CONFIG . 'system-tables.ini'; } // read the global execute-query-blacklist.ini configuration file - if(file_exists($blackListIniFile)){ + if (file_exists($blackListIniFile)) { $config = @parse_ini_file($blackListIniFile); } - if(file_exists($sysTablesIniFile)){ + if (file_exists($sysTablesIniFile)) { $systemTables = @parse_ini_file($sysTablesIniFile); $config['tables'] = $systemTables['tables']; } return $config; } - public function updateIndexFile ($conf) + /** + * Update index file + * + * @param string $conf + * @return string $result + * @throws Exception + */ + public function updateIndexFile($conf) { - if (! file_exists( PATH_HTML . 'index.html' )) { - throw new Exception( 'The public index file "' . PATH_HTML . 'index.html" does not exist!' ); + if (!file_exists(PATH_HTML . 'index.html')) { + throw new Exception('The public index file "' . PATH_HTML . 'index.html" does not exist!'); } else { - if (! is_writable( PATH_HTML . 'index.html' )) { - throw new Exception( 'The index.html file is not writable on workflow/public_html directory.' ); + if (!is_writable(PATH_HTML . 'index.html')) { + throw new Exception('The index.html file is not writable on workflow/public_html directory.'); } } - $content = file_get_contents( PATH_HTML . 'index.html' ); + $content = file_get_contents(PATH_HTML . 'index.html'); $result = false; $patt = '//'; - @preg_match( $patt, $content, $match ); + @preg_match($patt, $content, $match); - if (is_array( $match ) && count( $match ) > 0 && isset( $match[1] )) { - $newUrl = "sys/" . (($conf["lang"] != "")? $conf["lang"] : ((defined("SYS_LANG") && SYS_LANG != "")? SYS_LANG : "en")) . "/" . $conf["skin"] . "/login/login"; + if (is_array($match) && count($match) > 0 && isset($match[1])) { + $newUrl = "sys/" . (($conf["lang"] != "") ? $conf["lang"] : ((defined("SYS_LANG") && SYS_LANG != "") ? SYS_LANG : "en")) . "/" . $conf["skin"] . "/login/login"; - $newMetaStr = str_replace( $match[1], $newUrl, $match[0] ); - $newContent = str_replace( $match[0], $newMetaStr, $content ); + $newMetaStr = str_replace($match[1], $newUrl, $match[0]); + $newContent = str_replace($match[0], $newMetaStr, $content); - $result = (@file_put_contents( PATH_HTML . 'index.html', $newContent ) !== false); + $result = (@file_put_contents(PATH_HTML . 'index.html', $newContent) !== false); } return $result; } - public static function solrEnv ($sysName = '') + /** + * Get the system configuration + * + * @param string $sysName + * @return array $config + */ + public static function solrEnv($sysName = '') { - if (empty( $sysName )) { - $conf = PmSystem::getSystemConfiguration(); + if (empty($sysName)) { + $conf = System::getSystemConfiguration(); } else { - $conf = PmSystem::getSystemConfiguration( '', '', $sysName ); + $conf = System::getSystemConfiguration('', '', $sysName); } - if (! isset( $conf['solr_enabled'] ) || ! isset( $conf['solr_host'] ) || ! isset( $conf['solr_instance'] )) { + if (!isset($conf['solr_enabled']) || !isset($conf['solr_host']) || !isset($conf['solr_instance'])) { return false; } if ($conf['solr_enabled']) { - return array ('solr_enabled' => $conf['solr_enabled'],'solr_host' => $conf['solr_host'],'solr_instance' => $conf['solr_instance'] + return array('solr_enabled' => $conf['solr_enabled'], 'solr_host' => $conf['solr_host'], 'solr_instance' => $conf['solr_instance'] ); } return false; } + /** + * Get the instance of the class + * + * @return array $instance + */ public static function getInstance() { if (is_null(self::$instance)) { - self::$instance = new PmSystem(); + self::$instance = new System(); } return self::$instance; } + /** + * Get if is debug mode + * + * @return array $debug + */ public static function isDebugMode() { if (is_null(self::$debug)) { @@ -1243,6 +1272,7 @@ class PmSystem * Get the complete name of the server host configured for requests Front-End (e.g. https://127.0.0.1:81) * * @return string Returns an string with the complete name of the server host configured for requests Front-End + * @throws Exception */ public static function getHttpServerHostnameRequestsFrontEnd() { @@ -1250,10 +1280,10 @@ class PmSystem $arraySystemConfiguration = self::getSystemConfiguration(); $serverProtocol = $arraySystemConfiguration['server_protocol']; - $serverProtocol = ($serverProtocol != '')? $serverProtocol : ((G::is_https())? 'https' : 'http'); + $serverProtocol = ($serverProtocol != '') ? $serverProtocol : ((G::is_https()) ? 'https' : 'http'); $serverHostname = $arraySystemConfiguration['server_hostname_requests_frontend']; - $serverHostname = ($serverHostname != '')? $serverHostname : $_SERVER['HTTP_HOST']; + $serverHostname = ($serverHostname != '') ? $serverHostname : $_SERVER['HTTP_HOST']; //Return return $serverProtocol . '://' . $serverHostname; diff --git a/workflow/engine/src/ProcessMaker/Exporter/Exporter.php b/workflow/engine/src/ProcessMaker/Exporter/Exporter.php index bf28ee0d5..22a5a6a46 100644 --- a/workflow/engine/src/ProcessMaker/Exporter/Exporter.php +++ b/workflow/engine/src/ProcessMaker/Exporter/Exporter.php @@ -1,6 +1,7 @@ projectData = $this->bpmnProject->getProject(); $this->metadata = array( - "vendor_version" => \PmSystem::getVersion(), + "vendor_version" => System::getVersion(), "vendor_version_code" => "Michelangelo", "export_timestamp" => date("U"), "export_datetime" => date("Y-m-d\TH:i:sP"), diff --git a/workflow/engine/src/ProcessMaker/Plugins/PluginRegistry.php b/workflow/engine/src/ProcessMaker/Plugins/PluginRegistry.php index 39f924f2f..c6fc39dd2 100644 --- a/workflow/engine/src/ProcessMaker/Plugins/PluginRegistry.php +++ b/workflow/engine/src/ProcessMaker/Plugins/PluginRegistry.php @@ -11,7 +11,7 @@ use InputFilter; use Language; use PEAR; use PluginsRegistry; -use PmSystem; +use ProcessMaker\Core\System; use ProcessMaker\Plugins\Adapters\PluginAdapter; use ProcessMaker\Plugins\Interfaces\CaseSchedulerPlugin; use ProcessMaker\Plugins\Interfaces\CronFile; @@ -34,7 +34,6 @@ use ProcessMaker\Plugins\Traits\Attributes; use ProcessMaker\Plugins\Traits\PluginStructure; use Publisher; use stdClass; -use System; /** * Class PluginRegistry @@ -450,7 +449,7 @@ class PluginRegistry */ public function uninstallPluginWorkspaces($arrayPlugin) { - $workspace = PmSystem::listWorkspaces(); + $workspace = System::listWorkspaces(); foreach ($workspace as $indexWS => $ws) { $pluginRegistry = PluginRegistry::loadSingleton(); diff --git a/workflow/engine/src/ProcessMaker/Project/Handler.php b/workflow/engine/src/ProcessMaker/Project/Handler.php index 0cb76b53e..ac3780ad0 100644 --- a/workflow/engine/src/ProcessMaker/Project/Handler.php +++ b/workflow/engine/src/ProcessMaker/Project/Handler.php @@ -1,6 +1,7 @@ setLog($str); } } public static function logInline() { - if (\PmSystem::isDebugMode()) { + if (System::isDebugMode()) { call_user_func_array(array(Logger::getInstance(), 'setLogInline'), func_get_args()); } } public static function log() { - if (\PmSystem::isDebugMode()) { + if (System::isDebugMode()) { $logger = Logger::getInstance(); call_user_func_array(array($logger, 'setLogLine'), func_get_args()); } diff --git a/workflow/engine/src/ProcessMaker/Project/Workflow.php b/workflow/engine/src/ProcessMaker/Project/Workflow.php index 2012b7226..028faa844 100644 --- a/workflow/engine/src/ProcessMaker/Project/Workflow.php +++ b/workflow/engine/src/ProcessMaker/Project/Workflow.php @@ -14,7 +14,7 @@ use \RoutePeer; use ProcessMaker\Util\Common; use ProcessMaker\Exception; use ProcessMaker\Util; - +use ReportTables; /** * Class Workflow * @@ -594,7 +594,7 @@ class Workflow extends Handler $oSwimlaneElement = new \SwimlanesElements(); $oConfiguration = new \Configuration(); $oDbSource = new \DbSource(); - $oReportTable = new \ReportTables(); + $oReportTable = new ReportTables(); $oCaseTracker = new \CaseTracker(); $oCaseTrackerObject = new \CaseTrackerObject(); diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Light.php b/workflow/engine/src/ProcessMaker/Services/Api/Light.php index 77784985c..afb607a32 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Light.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Light.php @@ -2,12 +2,13 @@ namespace ProcessMaker\Services\Api; -use \G; -use \ProcessMaker\Project\Adapter; -use \ProcessMaker\Services\Api; -use \Luracast\Restler\RestException; -use \ProcessMaker\BusinessModel\Validator; -use \ProcessMaker\Util\DateTime; +use G; +use ProcessMaker\Project\Adapter; +use ProcessMaker\Services\Api; +use Luracast\Restler\RestException; +use ProcessMaker\BusinessModel\Validator; +use ProcessMaker\Util\DateTime; +use PmDynaform; /** * @@ -867,7 +868,7 @@ class Light extends Api $response = $process->getDynaForms($prj_uid); $result = $this->parserDataDynaForm($response); - $pmDynaForm = new \pmDynaform(); + $pmDynaForm = new PmDynaform(); foreach ($result as $k => $form) { $result[$k]['formContent'] = (isset($form['formContent']) && $form['formContent'] != null)?json_decode($form['formContent']):""; $pmDynaForm->jsonr($result[$k]['formContent']); @@ -1009,7 +1010,7 @@ class Light extends Api $caseVariables = DateTime::convertUtcToTimeZone($caseVariables); } - $pmDynaform = new \pmDynaform(array("APP_DATA" => $caseVariables, "CURRENT_DYNAFORM" => $dyn_uid)); + $pmDynaform = new PmDynaform(array("APP_DATA" => $caseVariables, "CURRENT_DYNAFORM" => $dyn_uid)); $pmDynaform->jsonr($result['formContent']); return $result; } catch (\Exception $e) { @@ -1033,7 +1034,7 @@ class Light extends Api $result = $this->parserDataDynaForm($response); $result['formContent'] = (isset($result['formContent']) && $result['formContent'] != null) ? \G::json_decode($result['formContent']) : ""; - $pmDynaForm = new \pmDynaform(["CURRENT_DYNAFORM" => $dyn_uid]); + $pmDynaForm = new PmDynaform(["CURRENT_DYNAFORM" => $dyn_uid]); $pmDynaForm->jsonr($result['formContent']); return $result; } catch (\Exception $e) { @@ -1057,7 +1058,7 @@ class Light extends Api $return = array(); foreach ($request_data['formId'] as $dyn_uid) { $response = $dynaForm->getDynaForm($dyn_uid); - $pmDynaForm = new \pmDynaform(array("CURRENT_DYNAFORM" => $dyn_uid)); + $pmDynaForm = new PmDynaform(array("CURRENT_DYNAFORM" => $dyn_uid)); $result = $this->parserDataDynaForm($response); $result['formContent'] = (isset($result['formContent']) && $result['formContent'] != null)?json_decode($result['formContent']):""; $pmDynaForm->jsonr($result['formContent']); diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm.php b/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm.php index b544d7b4c..cd9dff8d6 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm.php @@ -1,9 +1,10 @@ downloadLanguage($dyn_uid, $lang); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); @@ -145,7 +146,7 @@ class DynaForm extends Api { try { - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); $pmDynaform->uploadLanguage($dyn_uid); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); @@ -162,7 +163,7 @@ class DynaForm extends Api { try { - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); $pmDynaform->deleteLanguage($dyn_uid, $lang); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); @@ -179,7 +180,7 @@ class DynaForm extends Api { try { - $pmDynaform = new \pmDynaform(); + $pmDynaform = new PmDynaform(); return $pmDynaform->listLanguage($dyn_uid); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); diff --git a/workflow/engine/src/ProcessMaker/Services/OAuth2/Server.php b/workflow/engine/src/ProcessMaker/Services/OAuth2/Server.php index b8c1c4d3f..efc47648a 100644 --- a/workflow/engine/src/ProcessMaker/Services/OAuth2/Server.php +++ b/workflow/engine/src/ProcessMaker/Services/OAuth2/Server.php @@ -3,15 +3,8 @@ namespace ProcessMaker\Services\OAuth2; use Luracast\Restler\iAuthenticate; use Luracast\Restler\RestException; +use ProcessMaker\Core\System; - -/** - * Class Server - * - * @package OAuth2 - * @author Erik Amaru Ortiz - * - */ class Server implements iAuthenticate { /** @@ -371,7 +364,7 @@ class Server implements iAuthenticate $userTimeZone = $user->getUsrTimeZone(); if (trim($userTimeZone) == '') { - $arraySystemConfiguration = \PmSystem::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = System::getSystemConfiguration('', '', SYS_SYS); $userTimeZone = $arraySystemConfiguration['time_zone']; } diff --git a/workflow/engine/src/ProcessMaker/Util/System.php b/workflow/engine/src/ProcessMaker/Util/System.php index 124b08d77..2ce9e4dcc 100644 --- a/workflow/engine/src/ProcessMaker/Util/System.php +++ b/workflow/engine/src/ProcessMaker/Util/System.php @@ -6,6 +6,7 @@ use Bootstrap; use Exception; use Maveriks\Util\ClassLoader; use PMPlugin; +use Processmaker\Core\System AS PmSystem; use ProcessMaker\Plugins\Interfaces\PluginDetail; use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Services\OAuth2\PmPdo; @@ -26,7 +27,7 @@ class System public static function getTimeZone() { try { - $arraySystemConfiguration = \PmSystem::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = PmSystem::getSystemConfiguration('', '', SYS_SYS); //Return return $arraySystemConfiguration['time_zone']; @@ -47,10 +48,10 @@ class System { $workspaces = array(); foreach ($args as $arg) { - $workspaces[] = new \workspaceTools($arg); + $workspaces[] = new \WorkspaceTools($arg); } if (empty($workspaces) && $includeAll) { - $workspaces = \System::listWorkspaces(); + $workspaces = PmSystem::listWorkspaces(); } return $workspaces; } diff --git a/workflow/engine/classes/class.actionsByEmailUtils.php b/workflow/engine/src/ProcessMaker/Util/helpers.php similarity index 73% rename from workflow/engine/classes/class.actionsByEmailUtils.php rename to workflow/engine/src/ProcessMaker/Util/helpers.php index ce242fc39..8896de766 100644 --- a/workflow/engine/classes/class.actionsByEmailUtils.php +++ b/workflow/engine/src/ProcessMaker/Util/helpers.php @@ -1,50 +1,44 @@ appUid))? $httpData->appUid : ''; - - $usrUid = (isset($httpData->usrUid))? $httpData->usrUid : '' ; - - require_once ( "classes/model/AppNotes.php" ); - + $appUid = (isset($httpData->appUid)) ? $httpData->appUid : ''; + $usrUid = (isset($httpData->usrUid)) ? $httpData->usrUid : ''; $appNotes = new AppNotes(); $noteContent = addslashes($httpData->noteText); - $result = $appNotes->postNewNote($appUid, $usrUid, $noteContent, false); - //return true; - //die(); //send the response to client @ini_set('implicit_flush', 1); ob_start(); - //echo G::json_encode($result); @ob_flush(); @flush(); @ob_end_flush(); ob_implicit_flush(1); - //return true; + //send notification in background $noteRecipientsList = array(); $oCase = new Cases(); - $p = $oCase->getUsersParticipatedInCase($appUid); - foreach ($p['array'] as $key => $userParticipated) { $noteRecipientsList[] = $key; } $noteRecipients = implode(",", $noteRecipientsList); - $appNotes->sendNoteNotification($appUid, $usrUid, $noteContent, $noteRecipients); - } +/** + * We will get to the abeRequest data from actions by email + * @param string $AbeRequestsUid + * @return array $abeRequests + */ function loadAbeRequest($AbeRequestsUid) { - require_once 'classes/model/AbeRequests.php'; - $criteria = new Criteria(); $criteria->add(AbeRequestsPeer::ABE_REQ_UID, $AbeRequestsUid); $resultRequests = AbeRequestsPeer::doSelectRS($criteria); @@ -55,10 +49,13 @@ function loadAbeRequest($AbeRequestsUid) return $abeRequests; } +/** + * We will get the AbeConfiguration by actions by email + * @param string $AbeConfigurationUid + * @return array $abeConfiguration + */ function loadAbeConfiguration($AbeConfigurationUid) { - require_once 'classes/model/AbeConfiguration.php'; - $criteria = new Criteria(); $criteria->add(AbeConfigurationPeer::ABE_UID, $AbeConfigurationUid); $result = AbeConfigurationPeer::doSelectRS($criteria); @@ -69,10 +66,14 @@ function loadAbeConfiguration($AbeConfigurationUid) return $abeConfiguration; } +/** + * We will update the request by actions by email + * @param array $data + * @return void + * @throws Exception + */ function uploadAbeRequest($data) { - require_once 'classes/model/AbeRequests.php'; - try { $abeRequestsInstance = new AbeRequests(); $abeRequestsInstance->createOrUpdate($data); diff --git a/workflow/engine/templates/dbConnections/dbConnections.php b/workflow/engine/templates/dbConnections/dbConnections.php index 185e31e4e..7febee44a 100644 --- a/workflow/engine/templates/dbConnections/dbConnections.php +++ b/workflow/engine/templates/dbConnections/dbConnections.php @@ -47,7 +47,7 @@ $html = ' $flagTns = ($_POST["type"] == "oracle" && $_POST["connectionType"] == "TNS")? 1 : 0; if ($flagTns == 0) { - $host = new NET($_POST["server"]); + $host = new Net($_POST["server"]); $port = $_POST["port"]; diff --git a/workflow/engine/templates/setup/mailConnectiontest.php b/workflow/engine/templates/setup/mailConnectiontest.php index 4d628bae7..6a98f350b 100644 --- a/workflow/engine/templates/setup/mailConnectiontest.php +++ b/workflow/engine/templates/setup/mailConnectiontest.php @@ -1,98 +1,98 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * @Description This is the View of all groups from a determinated user - * @author Erik Amaru Ortiz - * @Date 24/04/2008 - * @LastModification 30/05/2008 - * @Updated Nov 6th, 2009 bye Eriknyk - */ - - $host = new net($_POST['srv']); - $host = $filter->xssFilterHard($host); - $width_content = '550px'; - $filter = new InputFilter(); - $_POST = $filter->xssFilterHard($_POST); - $ID_SETUP_MAILCONF_TITLE = $filter->xssFilterHard(G::loadTranslation('ID_SETUP_MAILCONF_TITLE')); - - $html = ' -
-
- - - - -
'.$ID_SETUP_MAILCONF_TITLE.'
-
-
'; - - $tests = Array( - '', - 'Resolve host name '.$_POST['srv'], - 'Checking port '.$_POST['port'].'', - 'Establishing connection to host '.$host->hostname.'' - ); - $tests[] = 'Login as '.$_POST['account'].' on '.$host->hostname.' SMTP Server'; - - - if($_POST['send_test_mail'] == 'yes'){ - $tests[] = 'Sending a test mail from '.$_POST['account'].' to '.$_POST['mail_to'].'...'; - } - $tree->showSign = false; - $n = Array('','uno','dos','tres','cuatro','cinco'); - for($i=1; $i -
-
- - - - -
- '.$html.' -
-
-
- '; - print (""); +. + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * Coral Gables, FL, 33134, USA, or email info@colosa.com. + * + */ + +/** + * @Description This is the View of all groups from a determinated user + * @author Erik Amaru Ortiz + * @Date 24/04/2008 + * @LastModification 30/05/2008 + * @Updated Nov 6th, 2009 bye Eriknyk + */ + + $host = new Net($_POST['srv']); + $host = $filter->xssFilterHard($host); + $width_content = '550px'; + $filter = new InputFilter(); + $_POST = $filter->xssFilterHard($_POST); + $ID_SETUP_MAILCONF_TITLE = $filter->xssFilterHard(G::loadTranslation('ID_SETUP_MAILCONF_TITLE')); + + $html = ' +
+
+ + + + +
'.$ID_SETUP_MAILCONF_TITLE.'
+
+
'; + + $tests = Array( + '', + 'Resolve host name '.$_POST['srv'], + 'Checking port '.$_POST['port'].'', + 'Establishing connection to host '.$host->hostname.'' + ); + $tests[] = 'Login as '.$_POST['account'].' on '.$host->hostname.' SMTP Server'; + + + if($_POST['send_test_mail'] == 'yes'){ + $tests[] = 'Sending a test mail from '.$_POST['account'].' to '.$_POST['mail_to'].'...'; + } + $tree->showSign = false; + $n = Array('','uno','dos','tres','cuatro','cinco'); + for($i=1; $i +
+
+ + + + +
+ '.$html.' +
+
+
+ '; + print (""); diff --git a/workflow/engine/templates/setup/uplogo.php b/workflow/engine/templates/setup/uplogo.php index a19dbe42c..bc698c3a2 100644 --- a/workflow/engine/templates/setup/uplogo.php +++ b/workflow/engine/templates/setup/uplogo.php @@ -33,7 +33,7 @@ try { $template->assign ('WIDTH_PANEL' ,$width); $template->assign ('WIDTH_PANEL_20' ,$width-20); - $upload = new replacementLogo(); + $upload = new ReplacementLogo(); $aFotoSelect = $upload->getNameLogo($_SESSION['USER_LOGGED']); $sFotoSelect = trim($aFotoSelect['DEFAULT_LOGO_NAME']); $check =''; diff --git a/workflow/engine/templates/triggers/triggersTree.php b/workflow/engine/templates/triggers/triggersTree.php index 0b0bc71b3..3e190c8d7 100644 --- a/workflow/engine/templates/triggers/triggersTree.php +++ b/workflow/engine/templates/triggers/triggersTree.php @@ -25,7 +25,7 @@ try { - $triggerLibrary = triggerLibrary::getSingleton(); + $triggerLibrary = TriggerLibrary::getSingleton(); $triggerLibraryO = $triggerLibrary->getRegisteredClasses(); $oTree = new Tree(); diff --git a/workflow/engine/templates/triggers/triggers_CreateWizard.php b/workflow/engine/templates/triggers/triggers_CreateWizard.php index 600bb010e..2a2949669 100644 --- a/workflow/engine/templates/triggers/triggers_CreateWizard.php +++ b/workflow/engine/templates/triggers/triggers_CreateWizard.php @@ -25,7 +25,7 @@ try { - $triggerLibrary = triggerLibrary::getSingleton (); + $triggerLibrary = TriggerLibrary::getSingleton (); $libraryClassName = $_GET ['LIBRARY']; $libraryMethod = $_GET ['NAME_FUN']; $sProUid = $_GET ['PRO_UID']; diff --git a/workflow/engine/templates/triggers/triggers_EditWizard.php b/workflow/engine/templates/triggers/triggers_EditWizard.php index b206fa3a1..721b161de 100644 --- a/workflow/engine/templates/triggers/triggers_EditWizard.php +++ b/workflow/engine/templates/triggers/triggers_EditWizard.php @@ -25,7 +25,7 @@ try { - $triggerLibrary = triggerLibrary::getSingleton (); + $triggerLibrary = TriggerLibrary::getSingleton (); $libraryClassName = $_GET ['LIBRARY_CLASS']; $libraryMethod = $_GET ['PMFUNTION_NAME']; $sProUid = $_GET ['PRO_UID']; diff --git a/workflow/public_html/bootstrap.php b/workflow/public_html/bootstrap.php index ac472e9e5..9bc03c17d 100644 --- a/workflow/public_html/bootstrap.php +++ b/workflow/public_html/bootstrap.php @@ -247,7 +247,7 @@ use ProcessMaker\Plugins\PluginRegistry; // defining the serverConf singleton if (defined('PATH_DATA') && file_exists(PATH_DATA)) { //Instance Server Configuration Singleton - $oServerConf =& serverConf::getSingleton(); + $oServerConf =& ServerConf::getSingleton(); } // Call Gulliver Classes diff --git a/workflow/public_html/sysGeneric.php b/workflow/public_html/sysGeneric.php index 37608bb78..d7270015c 100644 --- a/workflow/public_html/sysGeneric.php +++ b/workflow/public_html/sysGeneric.php @@ -283,6 +283,8 @@ define( 'PML_WSDL_URL', PML_SERVER . '/syspmLibrary/en/green/services/wsdl' ); define( 'PML_UPLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/uploadProcess' ); define( 'PML_DOWNLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/download' ); +G::defineConstants(); + $config = Bootstrap::getSystemConfiguration(); // starting session @@ -504,7 +506,7 @@ define( 'SYS_URI', '/sys' . SYS_TEMP . '/' . SYS_LANG . '/' . SYS_SKIN . '/' ); // defining the serverConf singleton if (defined( 'PATH_DATA' ) && file_exists( PATH_DATA )) { //Instance Server Configuration Singleton - $oServerConf = & serverConf::getSingleton(); + $oServerConf = & ServerConf::getSingleton(); }