diff --git a/gulliver/system/class.g.php b/gulliver/system/class.g.php new file mode 100644 index 000000000..85dd96ca4 --- /dev/null +++ b/gulliver/system/class.g.php @@ -0,0 +1,5722 @@ +. + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * Coral Gables, FL, 33134, USA, or email info@colosa.com. + * + */ + +/** + * @package gulliver.system + */ + +class G +{ + public $sessionVar = array(); //SESSION temporary array store. + + /** + * is_https + * @return void + */ + public function is_https() + { + if (isset($_SERVER['HTTPS'])) { + if ($_SERVER['HTTPS']=='on') { + return true; + } else { + return false; + } + } else { + return false; + } + } + + /** + * Fill array values (recursive) + * @access public + * @param Array $arr + * @param Void $value + * @param Boolean $recursive + * @return Array + */ + public function array_fill_value ($arr = Array(), $value = '', $recursive = false) + { + if (is_array( $arr )) { + foreach ($arr as $key => $val) { + if (is_array( $arr[$key] )) { + $arr[$key] = ($recursive === true) ? G::array_fill_value( $arr[$key], $value, true ) : $val; + } else { + $arr[$key] = $value; + } + } + } else { + $arr = Array (); + } + return $arr; + } + + /** + * Generate Password Random + * @access public + * @param Int + * @return String + */ + public function generate_password($length = 8) + { + $password = ""; + $possible = "0123456789bcdfghjkmnpqrstvwxyz"; + $i = 0; + while ($i<$length) { + $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); + if (!strstr($password, $char)) { + $password .= $char; + $i++; + } + } + return $password; + } + + /** + * Array concat + * array_concat(ArrayToConcat,ArrayOriginal); + * + * @access public + * @param Array + * @return Array + */ + public function array_concat () + { + $nums = func_num_args(); + $vars = func_get_args(); + $ret = Array (); + for ($i = 0; $i < $nums; $i ++) { + if (is_array( $vars[$i] )) { + foreach ($vars[$i] as $key => $value) { + $ret[$key] = $value; + } + } + } + return $ret; + } + + /** + * Compare Variables + * var_compare(value,[var1,var2,varN]); + * @access public + * @param void $value + * @param void $var1-N + * @return Boolean + */ + public function var_compare ($value = true) + { + $nums = func_num_args(); + if ($nums < 2) { + return true; + } + $vars = func_get_args(); + $ret = Array (); + for ($i = 1; $i < $nums; $i ++) { + if ($vars[$i] !== $value) { + return false; + } + } + return true; + } + + /** + * Emulate variable selector + * @access public + * @param void + * @return void + */ + public function var_probe () + { + //return (!$variable)? + $nums = func_num_args(); + $vars = func_get_args(); + for ($i = 0; $i < $nums; $i ++) { + if ($vars[$i]) { + return $vars[$i]; + } + } + return 1; + } + + /** + * Get the current version of gulliver classes + * + * @author Fernando Ontiveros Lira + * @access public + * @return string + */ + public function &getVersion () + { + //majorVersion.minorVersion-SvnRevision + return '3.0-1'; + } + + /** + * getIpAddress + * @return string $ip + */ + public static function getIpAddress () + { + 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' ); + } + return $ip; + } + + /** + * getMacAddress + * + * @return string $mac + */ + public function getMacAddress () + { + if (strstr( getenv( 'OS' ), 'Windows' )) { + $ipconfig = `ipconfig /all`; + preg_match( '/[\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}/i', $ipconfig, $mac ); + } else { + $ifconfig = `/sbin/ifconfig`; + preg_match( '/[\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}[\:-][\dA-Z]{2,2}/i', $ifconfig, $mac ); + } + return isset( $mac[0] ) ? $mac[0] : '00:00:00:00:00:00'; + } + + /** + * microtime_float + * + * @return array_sum(explode(' ',microtime())) + */ + /*public static*/ + public function microtime_float () + { + return array_sum( explode( ' ', microtime() ) ); + } + + /** + * * Encrypt and decrypt functions *** + */ + /** + * Encrypt string + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $string + * @param string $key + * @return string + */ + public function encrypt ($string, $key) + { + //print $string; + // if ( defined ( 'ENABLE_ENCRYPT' ) && ENABLE_ENCRYPT == 'yes' ) { + if (strpos( $string, '|', 0 ) !== false) { + return $string; + } + $result = ''; + for ($i = 0; $i < strlen( $string ); $i ++) { + $char = substr( $string, $i, 1 ); + $keychar = substr( $key, ($i % strlen( $key )) - 1, 1 ); + $char = chr( ord( $char ) + ord( $keychar ) ); + $result .= $char; + } + + $result = base64_encode( $result ); + $result = str_replace( '/', '°', $result ); + $result = str_replace( '=', '', $result ); + return $result; + } + + /** + * Decrypt string + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $string + * @param string $key + * @return string + */ + public function decrypt ($string, $key) + { + // if ( defined ( 'ENABLE_ENCRYPT' ) && ENABLE_ENCRYPT == 'yes' ) { + //if (strpos($string, '|', 0) !== false) return $string; + $result = ''; + $string = str_replace( '°', '/', $string ); + $string_jhl = explode( "?", $string ); + $string = base64_decode( $string ); + $string = base64_decode( $string_jhl[0] ); + + for ($i = 0; $i < strlen( $string ); $i ++) { + $char = substr( $string, $i, 1 ); + $keychar = substr( $key, ($i % strlen( $key )) - 1, 1 ); + $char = chr( ord( $char ) - ord( $keychar ) ); + $result .= $char; + } + if (! empty( $string_jhl[1] )) { + $result .= '?' . $string_jhl[1]; + } + return $result; + } + + /** + * Look up an IP address direction + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $target + * @return void + */ + public function lookup ($target) + { + //Made compatible to PHP 5.3 + if (preg_match( "[a-zA-Z]", $target )) { + $ntarget = gethostbyname( $target ); + } else { + $ntarget = gethostbyaddr( $target ); + } + return ($ntarget); + } + + /** + * ************* path functions **************** + */ + public static function mk_dir ($strPath, $rights = 0770) + { + $folder_path = array ($strPath); + $oldumask = umask( 0 ); + while (! @is_dir( dirname( end( $folder_path ) ) ) && dirname( end( $folder_path ) ) != '/' && dirname( end( $folder_path ) ) != '.' && dirname( end( $folder_path ) ) != '') { + array_push( $folder_path, dirname( end( $folder_path ) ) ); //var_dump($folder_path); die; + } + + while ($parent_folder_path = array_pop( $folder_path )) { + if (! @is_dir( $parent_folder_path )) { + if (! @mkdir( $parent_folder_path, $rights)) { + error_log( "Can't create folder \"$parent_folder_path\""); + //umask( $oldumask ); + } + } + } + umask($oldumask); + } + + /** + * rm_dir + * + * @param string $dirName + * + * @return void + */ + public function rm_dir ($dirName) + { + if (! is_writable( $dirName )) { + return false; + } + + if (is_dir( $dirName )) { + foreach (glob( $dirName . '/{,.}*', GLOB_BRACE ) as $file) { + if ($file == $dirName . '/.' || $file == $dirName . '/..') { + continue; + } + + if (is_dir( $file )) { + G::rm_dir( $file ); + } else { + @unlink( $file ); + } + } + + if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") { + $dirName = str_replace("/", "\\", $dirName); + + exec("DEL /F /S /Q " . $dirName . "", $res); + exec("RD /S /Q " . $dirName . "", $res); + } else { + @rmdir($dirName); + } + } else { + @unlink( $dirName ); + } + } + + /** + * Delete all the directory tree cotents. + * @param string $dir + * @return void + */ + public function delTree($dir) + { + $files = glob( $dir . '*', GLOB_MARK ); + foreach ($files as $file ) { + if (substr( $file, -1 ) == '/' ) { + self::delTree( $file ); + } else { + unlink( $file ); + } + } + if (is_dir($dir)) { + rmdir( $dir ); + } + } + + /** + * Recursive copy + * @param string $source + * @param string $destination + * @return boolean + */ + function recursive_copy ($source, $destination) { + if ($source == $destination) { + return false; + } + $dir = opendir($source); + + if (!file_exists($destination)) { + G::mk_dir($destination, 0777); + } + + while (false !== ( $file = readdir($dir))) { + if (( $file != '.' ) && ( $file != '..' )) { + if ( is_dir($source . '/' . $file) ) { + self::recursive_copy($source . '/' . $file, $destination . '/' . $file); + } else { + copy($source . '/' . $file, $destination . '/' . $file); + } + } + } + closedir($dir); + return true; + } + + /** + * verify path + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strPath path + * @param boolean $createPath if true this public function will create the path + * @return boolean + */ + public function verifyPath ($strPath, $createPath = false) + { + $folder_path = strstr( $strPath, '.' ) ? dirname( $strPath ) : $strPath; + + if (file_exists( $strPath ) || @is_dir( $strPath )) { + return true; + } else { + if ($createPath) { + //TODO:: Define Environment constants: Devel (0777), Production (0770), ... + G::mk_dir( $strPath, 0777 ); + } else { + return false; + } + } + return false; + } + + /** + * Expand the path using the path constants + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strPath + * @return string + */ + public static function expandPath ($strPath = '') + { + $res = ""; + $res = PATH_CORE; + if ($strPath != "") { + $res .= $strPath . "/"; + } + return $res; + } + + /** + * Load Gulliver Classes + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strClass + * @return void + */ + public static function LoadSystem ($strClass) + { require_once (PATH_GULLIVER . 'class.inputfilter.php'); + $filter = new InputFilter(); + $path = PATH_GULLIVER . 'class.' . $strClass . '.php'; + $path = $filter->validateInput($path, 'path'); + require_once ($path); + } + + public function LoadSystemExist ($strClass) + { + if (file_exists( PATH_GULLIVER . 'class.' . $strClass . '.php' )) { + return true; + } else { + return false; + } + } + + /** + * Render Page + * + * @author Fernando Ontiveros Lira + * @access public + * @param object $objContent + * @param string $strTemplate + * @param string $strSkin + * @return void + */ + public function RenderPage ($strTemplate = "default", $strSkin = SYS_SKIN, $objContent = null, $layout = '') + { + global $G_CONTENT; + global $G_TEMPLATE; + global $G_SKIN; + global $G_PUBLISH; + + $G_CONTENT = $objContent; + $G_TEMPLATE = $strTemplate; + $G_SKIN = $strSkin; + + try { + $file = G::ExpandPath( 'skinEngine' ) . 'skinEngine.php'; + include $file; + $skinEngine = new SkinEngine( $G_TEMPLATE, $G_SKIN, $G_CONTENT ); + $skinEngine->setLayout( $layout ); + $skinEngine->dispatch(); + } catch (Exception $e) { + global $G_PUBLISH; + if (is_null( $G_PUBLISH )) { + $G_PUBLISH = new Publisher(); + } + if (count( $G_PUBLISH->Parts ) == 1) { + array_shift( $G_PUBLISH->Parts ); + } + global $oHeadPublisher; + $leimnudInitString = $oHeadPublisher->leimnudInitString; + $oHeadPublisher->clearScripts(); + $oHeadPublisher->leimnudInitString = $leimnudInitString; + $oHeadPublisher->addScriptFile( '/js/maborak/core/maborak.js' ); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', null, array ('MESSAGE' => $e->getMessage() + ) ); + if (class_exists( 'SkinEngine' )) { + $skinEngine = new SkinEngine( 'publish', 'blank', '' ); + $skinEngine->dispatch(); + } else { + die( $e->getMessage() ); + } + } + } + + /** + * Load a skin + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strSkinName + * @return void + */ + public function LoadSkin ($strSkinName) + { + //print $strSkinName; + //now, we are using the skin, a skin is a file in engine/skin directory + $file = G::ExpandPath( "skins" ) . $strSkinName . ".php"; + //G::pr($file); + if (file_exists( $file )) { + require_once ($file); + return; + } else { + if (file_exists( PATH_HTML . 'errors/error703.php' )) { + header( 'location: /errors/error703.php' ); + die(); + } else { + $text = "The Skin $file does not exist, please review the Skin Definition"; + throw (new Exception( $text )); + } + } + + } + + /** + * Include javascript files + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strInclude + * @return void + */ + public function LoadInclude ($strInclude) + { + $incfile = G::ExpandPath( "includes" ) . 'inc.' . $strInclude . '.php'; + if (! file_exists( $incfile )) { + $incfile = PATH_GULLIVER_HOME . 'includes' . PATH_SEP . 'inc.' . $strInclude . '.php'; + } + + if (file_exists( $incfile )) { + require_once ($incfile); + return true; + } else { + return false; + } + } + + /** + * Include all model files + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strInclude + * @return void + */ + public function LoadAllModelClasses () + { + $baseDir = PATH_CORE . 'classes' . PATH_SEP . 'model'; + if ($handle = opendir( $baseDir )) { + while (false !== ($file = readdir( $handle ))) { + if (strpos( $file, '.php', 1 ) && ! strpos( $file, 'Peer.php', 1 )) { + require_once ($baseDir . PATH_SEP . $file); + } + } + } + } + + /** + * Include all model plugin files + * + * LoadAllPluginModelClasses + * + * @author Hugo Loza + * @access public + * @return void + */ + public function LoadAllPluginModelClasses () + { + //Get the current Include path, where the plugins directories should be + if (! defined( 'PATH_SEPARATOR' )) { + define( 'PATH_SEPARATOR', (substr( PHP_OS, 0, 3 ) == 'WIN') ? ';' : ':' ); + } + $path = explode( PATH_SEPARATOR, get_include_path() ); + + foreach ($path as $possiblePath) { + if (strstr( $possiblePath, "plugins" )) { + $baseDir = $possiblePath . 'classes' . PATH_SEP . 'model'; + if (file_exists( $baseDir )) { + if ($handle = opendir( $baseDir )) { + while (false !== ($file = readdir( $handle ))) { + if (strpos( $file, '.php', 1 ) && ! strpos( $file, 'Peer.php', 1 )) { + require_once ($baseDir . PATH_SEP . $file); + } + } + } + //Include also the extendGulliverClass that could have some new definitions for fields + if (file_exists( $possiblePath . 'classes' . PATH_SEP . 'class.extendGulliver.php' )) { + include_once $possiblePath . 'classes' . PATH_SEP . 'class.extendGulliver.php'; + } + } + } + } + } + + /** + * Load a template + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strTemplateName + * @return void + */ + public function LoadTemplate ($strTemplateName) + { + if ($strTemplateName == '') { + return; + } + + $temp = $strTemplateName . ".php"; + $file = G::ExpandPath( 'templates' ) . $temp; + // Check if its a user template + if (file_exists( $file )) { + //require_once( $file ); + include ($file); + } else { + // Try to get the global system template + $file = PATH_TEMPLATE . PATH_SEP . $temp; + //require_once( $file ); + if (file_exists( $file )) { + include ($file); + } + } + } + + /** + * public function LoadClassRBAC + * + * @author David S. Callizaya S. + * @access public + * @param eter string strClass + * @return string + */ + public function LoadClassRBAC ($strClass) + { + $classfile = PATH_RBAC . "class.$strClass" . '.php'; + require_once ($classfile); + } + + /** + * If the class is not defined by the aplication, it + * attempt to load the class from gulliver.system + * + * @author Fernando Ontiveros Lira , David S. Callizaya + * @access public + * @param string $strClass + * @return void + */ + public static function LoadClass ($strClass) + { + $classfile = G::ExpandPath( "classes" ) . 'class.' . $strClass . '.php'; + if (! file_exists( $classfile )) { + if (file_exists( PATH_GULLIVER . 'class.' . $strClass . '.php' )) { + return require_once (PATH_GULLIVER . 'class.' . $strClass . '.php'); + } else { + return false; + } + } else { + return require_once ($classfile); + } + } + + /** + * Loads a Class. + * If the class is not defined by the aplication, it + * attempt to load the class from gulliver.system + * + * @author Fernando Ontiveros Lira , David S. Callizaya + * @access public + * @param string $strClass + * @return void + */ + public static function LoadThirdParty($sPath, $sFile) + { + $classfile = PATH_THIRDPARTY . $sPath . '/' . $sFile . ((substr( $sFile, 0, - 4 ) !== '.php') ? '.php' : ''); + return require_once ($classfile); + } + + /** + * Encrypt URL + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $urlLink + * @return string + */ + public function encryptlink ($url) + { + if (defined( 'ENABLE_ENCRYPT' ) && ENABLE_ENCRYPT == 'yes') { + return urlencode( G::encrypt( $url, URL_KEY ) ); + } else { + return $url; + } + } + + /** + * Parsing the URI + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $urlLink + * @return string + */ + static public function parseURI ($uri, $isRestRequest = false) + { + //*** process the $_POST with magic_quotes enabled + // The magic_quotes_gpc feature has been DEPRECATED as of PHP 5.3.0. + if (get_magic_quotes_gpc() === 1) { + $_POST = G::strip_slashes( $_POST ); + } + + $aRequestUri = explode( '/', $uri ); + if ($isRestRequest) { + $args = self::parseRestUri( $aRequestUri ); + } else { + $args = self::parseNormalUri( $aRequestUri ); + } + + define( "SYS_LANG", $args['SYS_LANG'] ); + define( "SYS_SKIN", $args['SYS_SKIN'] ); + define( 'SYS_COLLECTION', $args['SYS_COLLECTION'] ); + define( 'SYS_TARGET', $args['SYS_TARGET'] ); + + if ($args['SYS_COLLECTION'] == 'js2') { + print "ERROR"; + die(); + } + } + + public function parseNormalUri ($aRequestUri) + { + if (substr( $aRequestUri[1], 0, 3 ) == 'sys') { + define( 'SYS_TEMP', substr( $aRequestUri[1], 3 ) ); + } else { + define( "ENABLE_ENCRYPT", 'yes' ); + define( 'SYS_TEMP', $aRequestUri[1] ); + $plain = '/sys' . SYS_TEMP; + + for ($i = 2; $i < count( $aRequestUri ); $i ++) { + $decoded = G::decrypt( urldecode( $aRequestUri[$i] ), URL_KEY ); + if ($decoded == 'sWì›') { + $decoded = $VARS[$i]; //this is for the string "../" + } + $plain .= '/' . $decoded; + } + $_SERVER["REQUEST_URI"] = $plain; + } + + $work = explode( '?', $_SERVER["REQUEST_URI"] ); + + if (count( $work ) > 1) { + define( 'SYS_CURRENT_PARMS', $work[1] ); + } else { + define( 'SYS_CURRENT_PARMS', '' ); + } + + define( 'SYS_CURRENT_URI', $work[0] ); + + if (! defined( 'SYS_CURRENT_PARMS' )) { + define( 'SYS_CURRENT_PARMS', $work[1] ); + } + + $preArray = explode( '&', SYS_CURRENT_PARMS ); + $buffer = explode( '.', $work[0] ); + + if (count( $buffer ) == 1) { + $buffer[1] = ''; + } + + //request type + define( 'REQUEST_TYPE', ($buffer[1] != "" ? $buffer[1] : 'html') ); + + $toparse = substr( $buffer[0], 1, strlen( $buffer[0] ) - 1 ); + $uriVars = explode( '/', $toparse ); + + unset( $work ); + unset( $buffer ); + unset( $toparse ); + array_shift( $uriVars ); + + $args = array (); + $args['SYS_LANG'] = array_shift( $uriVars ); + $args['SYS_SKIN'] = array_shift( $uriVars ); + $args['SYS_COLLECTION'] = array_shift( $uriVars ); + $args['SYS_TARGET'] = array_shift( $uriVars ); + + //to enable more than 2 directories...in the methods structure + while (count( $uriVars ) > 0) { + $args['SYS_TARGET'] .= '/' . array_shift( $uriVars ); + } + + /* 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 = System::getSystemConfiguration(); + $args['SYS_SKIN'] = $config['default_skin']; + } + + return $args; + } + + public function parseRestUri ($requestUri) + { + $args = array (); + //$args['SYS_TEMP'] = $requestUri[1]; + define( 'SYS_TEMP', $requestUri[2] ); + $restUri = ''; + + for ($i = 3; $i < count( $requestUri ); $i ++) { + $restUri .= '/' . $requestUri[$i]; + } + + $args['SYS_LANG'] = 'en'; // TODO, this can be set from http header + $args['SYS_SKIN'] = ''; + $args['SYS_COLLECTION'] = ''; + $args['SYS_TARGET'] = $restUri; + + return $args; + } + + public function strip_slashes ($vVar) + { + if (is_array( $vVar )) { + foreach ($vVar as $sKey => $vValue) { + if (is_array( $vValue )) { + G::strip_slashes( $vVar[$sKey] ); + } else { + $vVar[$sKey] = stripslashes( $vVar[$sKey] ); + } + } + } else { + $vVar = stripslashes( $vVar ); + } + + return $vVar; + } + + /** + * function to calculate the time used to render a page + */ + public function logTimeByPage () + { + if (! defined( PATH_DATA )) { + return false; + } + + $serverAddr = $_SERVER['SERVER_ADDR']; + global $startingTime; + $endTime = microtime( true ); + $time = $endTime - $startingTime; + $fpt = fopen( PATH_DATA . 'log/time.log', 'a' ); + fwrite( $fpt, sprintf( "%s.%03d %15s %s %5.3f %s\n", date( 'Y-m-d H:i:s' ), $time, getenv( 'REMOTE_ADDR' ), substr( $serverAddr, - 4 ), $time, $_SERVER['REQUEST_URI'] ) ); + fclose( $fpt ); + } + + /** + * streaming a big JS file with small js files + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $file + * @return string + */ + public function streamCSSBigFile ($filename) + { + header( 'Content-Type: text/css' ); + + //First get Skin info + $filenameParts = explode( "-", $filename ); + $skinName = $filenameParts[0]; + $skinVariant = "skin"; + + if (isset( $filenameParts[1] )) { + $skinVariant = strtolower( $filenameParts[1] ); + } + + $configurationFile = ''; + if ($skinName == "jscolors") { + $skinName = "classic"; + } + if ($skinName == "xmlcolors") { + $skinName = "classic"; + } + if ($skinName == "classic") { + $configurationFile = G::ExpandPath( "skinEngine" ) . 'base' . PATH_SEP . 'config.xml'; + } else { + $configurationFile = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml'; + + if (! is_file( $configurationFile )) { + $configurationFile = G::ExpandPath( "skinEngine" ) . $skinName . PATH_SEP . 'config.xml'; + } + } + + //Read Configuration File + $xmlConfiguration = file_get_contents( $configurationFile ); + $xmlConfigurationObj = G::xmlParser( $xmlConfiguration ); + $baseSkinDirectory = dirname( $configurationFile ); + $directorySize = G::getDirectorySize( $baseSkinDirectory ); + $mtime = $directorySize['maxmtime']; + + $outputHeader = "/* Autogenerated CSS file by gulliver framework \n"; + $outputHeader .= " Skin: $filename\n"; + $outputHeader .= " Configuration: $configurationFile\n"; + $mtimeNow = date( 'U' ); + $gmt_mtimeNow = gmdate( "D, d M Y H:i:s", $mtimeNow ) . " GMT"; + $outputHeader .= " Date: $gmt_mtimeNow*/\n"; + $output = ""; + //Base files + switch (strtolower( $skinVariant )) { + case "extjs": + //Base + $baseCSSPath = PATH_SKIN_ENGINE . "base" . PATH_SEP . "baseCss" . PATH_SEP; + $output .= file_get_contents( $baseCSSPath . 'ext-all-notheme.css' ); + + //Classic Skin + $extJsSkin = 'xtheme-gray'; + break; + default: + break; + } + + //Get Browser Info + $infoBrowser = G::browser_detection( 'full_assoc' ); + $browserName = $infoBrowser['browser_working']; + if (isset( $infoBrowser[$browserName . '_data'] )) { + if ($infoBrowser[$browserName . '_data'][0] != "") { + $browserName = $infoBrowser[$browserName . '_data'][0]; + } + } + + //Read Configuration File + $xmlConfiguration = file_get_contents ( $configurationFile ); + $xmlConfigurationObj = G::xmlParser($xmlConfiguration); + + $skinFilesArray = $xmlConfigurationObj->result['skinConfiguration']['__CONTENT__']['cssFiles']['__CONTENT__'][$skinVariant]['__CONTENT__']['cssFile'] ; + foreach ($skinFilesArray as $keyFile => $cssFileInfo) { + $enabledBrowsers = explode(",", $cssFileInfo['__ATTRIBUTES__']['enabledBrowsers']); + $disabledBrowsers = explode(",", $cssFileInfo['__ATTRIBUTES__']['disabledBrowsers']); + + if (((in_array($browserName, $enabledBrowsers)) || (in_array('ALL', $enabledBrowsers)))&&(!(in_array($browserName, $disabledBrowsers)))) { + if ($cssFileInfo['__ATTRIBUTES__']['file'] == 'rtl.css') { + G::LoadClass('serverConfiguration'); + $oServerConf =& serverConf::getSingleton(); + if (!(defined('SYS_LANG'))) { + if (isset($_SERVER['HTTP_REFERER'])) { + $syss = explode('://', $_SERVER['HTTP_REFERER']); + $sysObjets = explode('/', $syss['1']); + $sysLang = $sysObjets['2']; + } else { + $sysLang = 'en'; + } + } else { + $sysLang = SYS_LANG; + } + if ($oServerConf->isRtl($sysLang)) { + $output .= file_get_contents ( $baseSkinDirectory . PATH_SEP.'css'.PATH_SEP.$cssFileInfo['__ATTRIBUTES__']['file'] ); + } + } else { + $output .= file_get_contents ( $baseSkinDirectory . PATH_SEP.'css'.PATH_SEP.$cssFileInfo['__ATTRIBUTES__']['file'] ); + } + } + } + + //Remove comments.. + $regex = array ("`^([\t\s]+)`ism" => '',"`^\/\*(.+?)\*\/`ism" => "","`([\n\A;]+)\/\*(.+?)\*\/`ism" => "$1","`([\n\A;\s]+)//(.+?)[\n\r]`ism" => "$1\n","`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism" => "\n" ); + $output = preg_replace( array_keys( $regex ), $regex, $output ); + $output = $outputHeader . $output; + + return $output; + } + + /** + * streaming the translation..js file + * take the WEB-INF/translation. file and append it to file js/widgets/lang/.js file + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $file + * @param boolean $download + * @param string $downloadFileName + * @return string + */ + public function streamJSTranslationFile ($filename, $locale = 'en') + { + $defaultTranslations = Array (); + $foreignTranslations = Array (); + + //if the default translations table doesn't exist we can't proceed + if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) { + return ; + } + //load the translations table + require_once (PATH_LANGUAGECONT . 'translation.en'); + $defaultTranslations = $translation; + + //if some foreign language was requested and its translation file exists + if ($locale != 'en' && file_exists( PATH_LANGUAGECONT . 'translation.' . $locale )) { + require_once (PATH_LANGUAGECONT . 'translation.' . $locale); //load the foreign translations table + $foreignTranslations = $translation; + } + + if (defined( "SHOW_UNTRANSLATED_AS_TAG" ) && SHOW_UNTRANSLATED_AS_TAG != 0) { + $translation = $foreignTranslations; + } else { + $translation = array_merge( $defaultTranslations, $foreignTranslations ); + } + + $calendarJs = ''; + $calendarJsFile = PATH_GULLIVER_HOME . "js/widgets/js-calendar/lang/" . $locale .".js"; + if (! file_exists($calendarJsFile)) { + $calendarJsFile = PATH_GULLIVER_HOME . "js/widgets/js-calendar/lang/en.js"; + } + $calendarJs = file_get_contents($calendarJsFile) . "\n"; + + return $calendarJs . 'var TRANSLATIONS = ' . G::json_encode( $translation ) . ';' ; + } + + /** + * streaming a file + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $file + * @param boolean $download + * @param string $downloadFileName + * @return string + */ + public static function streamFile ($file, $download = false, $downloadFileName = '') + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $file = $filter->xssFilterHard($file); + if(isset($_SERVER['REQUEST_URI'])) { + $_SERVER['REQUEST_URI'] = $filter->xssFilterHard($_SERVER['REQUEST_URI'],"url"); + } + require_once (PATH_THIRDPARTY . 'jsmin/jsmin.php'); + $folderarray = explode( '/', $file ); + $typearray = explode( '.', basename( $file ) ); + $typefile = $typearray[count( $typearray ) - 1]; + $filename = $file; + + //trick to generate the translation.language.js file , merging two files + if (strtolower( $typefile ) == 'js' && $typearray[0] == 'translation') { + $download = $filter->xssFilterHard($download); + $downloadFileName = $filter->xssFilterHard($downloadFileName); + G::sendHeaders( $filename, 'text/javascript', $download, $downloadFileName ); + $output = G::streamJSTranslationFile( $filename, $typearray[1] ); + $output = $filter->xssFilterHard($output); + print $output; + return; + } + + //trick to generate the big css file for ext style . + if (strtolower( $typefile ) == 'css' && $folderarray[count( $folderarray ) - 2] == 'css') { + G::sendHeaders( $filename, 'text/css', $download, $downloadFileName ); + $output = G::streamCSSBigFile( $typearray[0] ); + $output = $filter->xssFilterHard($output); + print $output; + return; + } + + if (file_exists( $filename )) { + switch (strtolower( $typefile )) { + case 'swf': + G::sendHeaders( $filename, 'application/x-shockwave-flash', $download, $downloadFileName ); + break; + case 'js': + G::sendHeaders( $filename, 'text/javascript', $download, $downloadFileName ); + break; + case 'htm': + case 'html': + G::sendHeaders( $filename, 'text/html', $download, $downloadFileName ); + break; + case 'htc': + G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName ); + break; + case 'json': + G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName ); + break; + case 'gif': + G::sendHeaders( $filename, 'image/gif', $download, $downloadFileName ); + break; + case 'png': + G::sendHeaders( $filename, 'image/png', $download, $downloadFileName ); + break; + case 'jpg': + G::sendHeaders( $filename, 'image/jpg', $download, $downloadFileName ); + break; + case 'css': + G::sendHeaders( $filename, 'text/css', $download, $downloadFileName ); + break; + case 'xml': + G::sendHeaders( $filename, 'text/xml', $download, $downloadFileName ); + break; + case 'txt': + G::sendHeaders( $filename, 'text/html', $download, $downloadFileName ); + break; + case 'doc': + case 'pdf': + case 'pm': + case 'po': + G::sendHeaders( $filename, 'application/octet-stream', $download, $downloadFileName ); + break; + case 'php': + if ($download) { + G::sendHeaders( $filename, 'text/plain', $download, $downloadFileName ); + } else { + require_once ($filename); + return; + } + break; + case 'tar': + G::sendHeaders( $filename, 'application/x-tar', $download, $downloadFileName ); + break; + default: + //throw new Exception ( "Unknown type of file '$file'. " ); + G::sendHeaders( $filename, 'application/octet-stream', $download, $downloadFileName ); + break; + } + } else { + if (strpos( $file, 'gulliver' ) !== false) { + list ($path, $filename) = explode( 'gulliver', $file ); + } + + $_SESSION['phpFileNotFound'] = $file; + G::header( "location: /errors/error404.php?l=" . $_SERVER['REQUEST_URI'] ); + } + + if ( substr($filename,-10) == "ext-all.js" ) { + $filename = PATH_GULLIVER_HOME . 'js/ext/min/ext-all.js'; + } + @readfile( $filename ); + } + + /** + * sendHeaders + * + * @param string $filename + * @param string $contentType default value '' + * @param boolean $download default value false + * @param string $downloadFileName default value '' + * + * @return void + */ + public function sendHeaders ($filename, $contentType = '', $download = false, $downloadFileName = '') + { + if ($download) { + if ($downloadFileName == '') { + $aAux = explode( '/', $filename ); + $downloadFileName = $aAux[count( $aAux ) - 1]; + } + header( 'Content-Disposition: attachment; filename="' . $downloadFileName . '"' ); + } + header( 'Content-Type: ' . $contentType ); + + //if userAgent (BROWSER) is MSIE we need special headers to avoid MSIE behaivor. + $userAgent = strtolower( $_SERVER['HTTP_USER_AGENT'] ); + if (preg_match( "/msie/i", $userAgent )) { + //if ( ereg("msie", $userAgent)) { + header( 'Pragma: cache' ); + + if (file_exists( $filename )) { + $mtime = filemtime( $filename ); + } else { + $mtime = date( 'U' ); + } + $gmt_mtime = gmdate( "D, d M Y H:i:s", $mtime ) . " GMT"; + header( 'ETag: "' . G::encryptOld( $mtime . $filename ) . '"' ); + header( "Last-Modified: " . $gmt_mtime ); + header( 'Cache-Control: public' ); + header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 60 * 10 ) . " GMT" ); //ten minutes + return; + } + + if (! $download) { + + header( 'Pragma: cache' ); + + if (file_exists( $filename )) { + $mtime = filemtime( $filename ); + } else { + $mtime = date( 'U' ); + } + $gmt_mtime = gmdate( "D, d M Y H:i:s", $mtime ) . " GMT"; + header( 'ETag: "' . G::encryptOld( $mtime . $filename ) . '"' ); + header( "Last-Modified: " . $gmt_mtime ); + header( 'Cache-Control: public' ); + header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + 90 * 60 * 60 * 24 ) . " GMT" ); + if (isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )) { + if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime) { + header( 'HTTP/1.1 304 Not Modified' ); + exit(); + } + } + + if (isset( $_SERVER['HTTP_IF_NONE_MATCH'] )) { + if (str_replace( '"', '', stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) == G::encryptOld( $mtime . $filename )) { + header( "HTTP/1.1 304 Not Modified" ); + exit(); + } + } + } + } + + /** + * Transform a public URL into a local path. + * + * @author David S. Callizaya S. + * @access public + * @param string $url + * @param string $corvertionTable + * @param string $realPath = local path + * @return boolean + */ + public function virtualURI ($url, $convertionTable, &$realPath) + { + foreach ($convertionTable as $urlPattern => $localPath) { + // $urlPattern = addcslashes( $urlPattern , '/'); + $urlPattern = addcslashes( $urlPattern, './' ); + $urlPattern = '/^' . str_replace( array ('*','?' + ), array ('.*','.?' + ), $urlPattern ) . '$/'; + if (preg_match( $urlPattern, $url, $match )) { + if ($localPath === false) { + $realPath = $url; + return false; + } + if ($localPath != 'jsMethod') { + $realPath = $localPath . $match[1]; + } else { + $realPath = $localPath; + } + return true; + } + } + $realPath = $url; + return false; + } + + /** + * Create an encrypted unique identifier based on $id and the selected scope id. + * + * @author David S. Callizaya S. + * @access public + * @param string $scope + * @param string $id + * @return string + */ + public function createUID ($scope, $id) + { + $e = $scope . $id; + $e = G::encrypt( $e, URL_KEY ); + $e = str_replace( array ('+','/','=' + ), array ('__','_','___' + ), base64_encode( $e ) ); + return $e; + } + + /** + * (Create an encrypted unique identificator based on $id and the selected scope id.) ^-1 + * getUIDName + * + * @author David S. Callizaya S. + * @access public + * @param string $id + * @param string $scope + * @return string + */ + public function getUIDName ($uid, $scope = '') + { + $e = str_replace( array ('=','+','/' + ), array ('___','__','_' + ), $uid ); + $e = base64_decode( $e ); + $e = G::decrypt( $e, URL_KEY ); + $e = substr( $e, strlen( $scope ) ); + return $e; + } + + /* formatNumber + * + * @author David Callizaya + * @param int/string $num + * @return string number + */ + public function formatNumber ($num, $language = 'latin') + { + switch ($language) { + default: + $snum = $num; + } + return $snum; + } + + /* Returns a date formatted according to the given format string + * @author David Callizaya + * @param string $format The format of the outputted date string + * @param string $datetime Date in the format YYYY-MM-DD HH:MM:SS + */ + public function formatDate ($datetime, $format = 'Y-m-d', $lang = '') + { + if ($lang === '') { + $lang = defined( SYS_LANG ) ? SYS_LANG : 'en'; + } + $aux = explode( ' ', $datetime ); //para dividir la fecha del dia + $date = explode( '-', isset( $aux[0] ) ? $aux[0] : '00-00-00' ); //para obtener los dias, el mes, y el año. + $time = explode( ':', isset( $aux[1] ) ? $aux[1] : '00:00:00' ); //para obtener las horas, minutos, segundos. + $date[0] = (int) ((isset( $date[0] )) ? $date[0] : '0'); + $date[1] = (int) ((isset( $date[1] )) ? $date[1] : '0'); + $date[2] = (int) ((isset( $date[2] )) ? $date[2] : '0'); + $time[0] = (int) ((isset( $time[0] )) ? $time[0] : '0'); + $time[1] = (int) ((isset( $time[1] )) ? $time[1] : '0'); + $time[2] = (int) ((isset( $time[2] )) ? $time[2] : '0'); + // Spanish months + $ARR_MONTHS['es'] = array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre" + ); + // English months + $ARR_MONTHS['en'] = array ("January","February","March","April","May","June","July","August","September","October","November","December" + ); + + // Spanish days + $ARR_WEEKDAYS['es'] = array ("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado" + ); + // English days + $ARR_WEEKDAYS['en'] = array ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" + ); + + if ($lang == 'fa') { + $number = 'persian'; + } else { + $number = 'latin'; + } + $d = '0' . $date[2]; + $d = G::formatNumber( substr( $d, strlen( $d ) - 2, 2 ), $number ); + $j = G::formatNumber( $date[2], $number ); + $F = isset( $ARR_MONTHS[$lang][$date[1] - 1] ) ? $ARR_MONTHS[$lang][$date[1] - 1] : ''; + $m = '0' . $date[1]; + $m = G::formatNumber( substr( $m, strlen( $m ) - 2, 2 ), $number ); + $n = G::formatNumber( $date[1], $number ); + $y = G::formatNumber( substr( $date[0], strlen( $date[0] ) - 2, 2 ), $number ); + $Y = '0000' . $date[0]; + $Y = G::formatNumber( substr( $Y, strlen( $Y ) - 4, 4 ), $number ); + $g = ($time[0] % 12); + if ($g === 0) { + $g = 12; + } + $G = $time[0]; + $h = '0' . $g; + $h = G::formatNumber( substr( $h, strlen( $h ) - 2, 2 ), $number ); + $H = '0' . $G; + $H = G::formatNumber( substr( $H, strlen( $H ) - 2, 2 ), $number ); + $i = '0' . $time[1]; + $i = G::formatNumber( substr( $i, strlen( $i ) - 2, 2 ), $number ); + $s = '0' . $time[2]; + $s = G::formatNumber( substr( $s, strlen( $s ) - 2, 2 ), $number ); + $names = array ('d','j','F','m','n','y','Y','g','G','h','H','i','s' + ); + $values = array ($d,$j,$F,$m,$n,$y,$Y,$g,$G,$h,$H,$i,$s + ); + $_formatedDate = str_replace( $names, $values, $format ); + return $_formatedDate; + } + + /** + * getformatedDate + * + * @param date $date + * @param string $format default value 'yyyy-mm-dd', + * @param string $lang default value '' + * + * @return string $ret + */ + public static function getformatedDate ($date, $format = 'yyyy-mm-dd', $lang = '') + { + /** + * ****************************************************************************************************** + * if the year is 2008 and the format is yy then -> 08 + * if the year is 2008 and the format is yyyy then -> 2008 + * + * if the month is 05 and the format is mm then -> 05 + * if the month is 05 and the format is m and the month is less than 10 then -> 5 else digit normal + * if the month is 05 and the format is MM or M then -> May + * + * if the day is 5 and the format is dd then -> 05 + * if the day is 5 and the format is d and the day is less than 10 then -> 5 else digit normal + * if the day is 5 and the format is DD or D then -> five + * ******************************************************************************************************* + */ + + //scape the literal + switch ($lang) { + case 'es': + $format = str_replace( ' del ', '[ofl]', $format ); + $format = str_replace( ' de ', '[of]', $format ); + break; + } + + //first we must formatted the string + $format = str_replace( 'h', '{h}', $format ); + $format = str_replace( 'i', '{i}', $format ); + $format = str_replace( 's', '{s}', $format ); + + $format = str_replace( 'yyyy', '{YEAR}', $format ); + $format = str_replace( 'yy', '{year}', $format ); + + $format = str_replace( 'mm', '{YONTH}', $format ); + $format = str_replace( 'm', '{month}', $format ); + $format = str_replace( 'M', '{XONTH}', $format ); + + $format = str_replace( 'dd', '{DAY}', $format ); + $format = str_replace( 'd', '{day}', $format ); + + if ($lang === '') { + $lang = defined( SYS_LANG ) ? SYS_LANG : 'en'; + } + + $aux = explode( ' ', $date ); //para dividir la fecha del dia + $date = explode( '-', isset( $aux[0] ) ? $aux[0] : '00-00-00' ); //para obtener los dias, el mes, y el año. + $time = explode( ':', isset( $aux[1] ) ? $aux[1] : '00:00:00' ); //para obtener las horas, minutos, segundos. + + $year = (int) ((isset( $date[0] )) ? $date[0] : '0'); //year + $month = (int) ((isset( $date[1] )) ? $date[1] : '0'); //month + $day = (int) ((isset( $date[2] )) ? $date[2] : '0'); //day + + $h = isset( $time[0] ) ? $time[0] : '00'; //hour + $i = isset( $time[1] ) ? $time[1] : '00'; //minute + $s = isset( $time[2] ) ? $time[2] : '00'; //second + + $MONTHS = Array (); + for ($j = 1; $j <= 12; $j ++) { + $MONTHS[$j] = G::LoadTranslation( "ID_MONTH_$j", $lang ); + } + + $d = (int) $day; + $dd = G::complete_field( $day, 2, 1 ); + + //missing D + + $M = $MONTHS[$month]; + $m = (int) $month; + $mm = G::complete_field( $month, 2, 1 ); + + $yy = substr( $year, strlen( $year ) - 2, 2 ); + $yyyy = $year; + + $names = array ('{day}','{DAY}','{month}','{YONTH}','{XONTH}','{year}','{YEAR}','{h}','{i}','{s}' + ); + $values = array ($d,$dd,$m,$mm,$M,$yy,$yyyy,$h,$i,$s + ); + + $ret = str_replace( $names, $values, $format ); + + //recovering the original literal + switch ($lang) { + case 'es': + $ret = str_replace( '[ofl]', ' del ', $ret ); + $ret = str_replace( '[of]', ' de ', $ret ); + break; + } + + return $ret; + } + + /** + * By + * Here's a little wrapper for array_diff - I found myself needing + * to iterate through the edited array, and I didn't need to original keys for anything. + */ + public function arrayDiff ($array1, $array2) + { + if (! is_array( $array1 )) { + $array1 = (array) $array1; + } + + if (! is_array( $array2 )) { + $array2 = (array) $array2; + } + + // This wrapper for array_diff rekeys the array returned + $valid_array = array_diff( $array1, $array2 ); + + // reinstantiate $array1 variable + $array1 = array (); + + // loop through the validated array and move elements to $array1 + // this is necessary because the array_diff function returns arrays that retain their original keys + foreach ($valid_array as $valid) { + $array1[] = $valid; + } + return $array1; + } + + /** + * + * @author Erik Amaru Ortiz + * @name complete_field($string, $lenght, $type={1:number/2:string/3:float}) + */ + public static function complete_field ($campo, $long, $tipo) + { + $campo = trim( $campo ); + switch ($tipo) { + case 1: //number + $long = $long - strlen( $campo ); + for ($i = 1; $i <= $long; $i ++) { + $campo = "0" . $campo; + } + break; + case 2: //string + $long = $long - strlen( $campo ); + for ($i = 1; $i <= $long; $i ++) { + $campo = " " . $campo; + } + break; + case 3: //float + if ($campo != "0") { + $vals = explode( ".", $long ); + $ints = $vals[0]; + + $decs = $vals[1]; + + $valscampo = explode( ".", $campo ); + + $intscampo = $valscampo[0]; + $decscampo = $valscampo[1]; + + $ints = $ints - strlen( $intscampo ); + + for ($i = 1; $i <= $ints; $i ++) { + $intscampo = "0" . $intscampo; + } + + //los decimales pueden ser 0 uno o dos + $decs = $decs - strlen( $decscampo ); + for ($i = 1; $i <= $decs; $i ++) { + $decscampo = $decscampo . "0"; + } + + $campo = $intscampo . "." . $decscampo; + } else { + $vals = explode( ".", $long ); + $ints = $vals[0]; + $decs = $vals[1]; + + $campo = ""; + for ($i = 1; $i <= $ints; $i ++) { + $campo = "0" . $campo; + } + $campod = ""; + for ($i = 1; $i <= $decs; $i ++) { + $campod = "0" . $campod; + } + + $campo = $campo . "." . $campod; + } + break; + } + return $campo; + } + + /* Escapes special characters in a string for use in a SQL statement + * @author David Callizaya + * @param string $sqlString The string to be escaped + * @param string $DBEngine Target DBMS + */ + public function sqlEscape ($sqlString, $DBEngine = DB_ADAPTER) + { + $DBEngine = DB_ADAPTER; + switch ($DBEngine) { + case 'mysql': + $con = Propel::getConnection( 'workflow' ); + return mysql_real_escape_string( stripslashes( $sqlString ), $con->getResource() ); + break; + case 'myxml': + $sqlString = str_replace( '"', '""', $sqlString ); + return str_replace( "'", "''", $sqlString ); + break; + default: + return addslashes( stripslashes( $sqlString ) ); + break; + } + } + + /** + * Function MySQLSintaxis + * + * @access public + * @return Boolean + * + */ + public function MySQLSintaxis () + { + $DBEngine = DB_ADAPTER; + switch ($DBEngine) { + case 'mysql': + return true; + break; + case 'mssql': + default: + return false; + break; + } + } + + /* Returns a sql string with @@parameters replaced with its values defined + * in array $result using the next notation: + * NOTATION: + * @@ Quoted parameter acording to the SYSTEM's Database + * @Q Double quoted parameter \\ \" + * @q Single quoted parameter \\ \' + * @% URL string + * @# Non-quoted parameter + * @! Evaluate string : Replace the parameters in value and then in the sql string + * @fn() Evaluate string with the function "fn" + * @author David Callizaya + */ + public function replaceDataField ($sqlString, $result, $DBEngine = 'mysql') + { + if (! is_array( $result )) { + $result = array (); + } + $result = $result + G::getSystemConstants(); + $__textoEval = ""; + $u = 0; + //$count=preg_match_all('/\@(?:([\@\%\#\!Qq])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))/',$sqlString,$match,PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); + $count = preg_match_all( '/\@(?:([\@\%\#\=\!Qq])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*?)*)\))/', $sqlString, $match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE ); + if ($count) { + for ($r = 0; $r < $count; $r ++) { + if (! isset( $result[$match[2][$r][0]] )) { + $result[$match[2][$r][0]] = ''; + } + if (! is_array( $result[$match[2][$r][0]] )) { + $__textoEval .= substr( $sqlString, $u, $match[0][$r][1] - $u ); + $u = $match[0][$r][1] + strlen( $match[0][$r][0] ); + //Mysql quotes scape + if (($match[1][$r][0] == '@') && (isset( $result[$match[2][$r][0]] ))) { + $__textoEval .= "\"" . G::sqlEscape( $result[$match[2][$r][0]], $DBEngine ) . "\""; + continue; + } + //URL encode + if (($match[1][$r][0]=='%')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.=urlencode($result[$match[2][$r][0]]); + continue; + } + //Double quoted parameter + if (($match[1][$r][0]=='Q')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.='"'.addcslashes($result[$match[2][$r][0]],'\\"').'"'; + continue; + } + //Single quoted parameter + if (($match[1][$r][0]=='q')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.="'".addcslashes($result[$match[2][$r][0]],'\\\'')."'"; + continue; + } + //Substring (Sub replaceDataField) + if (($match[1][$r][0]=='!')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result); + continue; + } + //Call function + if (($match[1][$r][0]==='')&&($match[2][$r][0]==='')&&($match[3][$r][0]!=='')) { + eval('$strAux = ' . $match[3][$r][0] . '(\'' . addcslashes(G::replaceDataField(stripslashes($match[4][$r][0]),$result),'\\\'') . '\');'); + + if ($match[3][$r][0] == "G::LoadTranslation") { + $arraySearch = array("'"); + $arrayReplace = array("\\'"); + $strAux = str_replace($arraySearch, $arrayReplace, $strAux); + } + + $__textoEval .= $strAux; + continue; + } + //Non-quoted + if (($match[1][$r][0]=='#')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result); + continue; + } + //Non-quoted = + if (($match[1][$r][0]=='=')&&(isset($result[$match[2][$r][0]]))) { + $__textoEval.=G::replaceDataField($result[$match[2][$r][0]],$result); + continue; + } + } + } + } + $__textoEval.=substr($sqlString,$u); + return $__textoEval; + } + + /** + * Replace Grid Values + * The tag @>GRID-NAME to open the grid and @])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*(?:[\\\\][\w\W])?)*)\))((?:\s*\[[\'"]?\w+[\'"]?\])+)?/', $strContentAux, $arrayMatch1, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); + + if ($iOcurrences) { + $arrayGrid = array(); + + for ($i = 0; $i <= $iOcurrences - 1; $i++) { + $arrayGrid[] = $arrayMatch1[2][$i][0]; + } + + $arrayGrid = array_unique($arrayGrid); + + foreach ($arrayGrid as $index => $value) { + if($value !== "") { + $grdName = $value; + + $strContentAux1 = $strContentAux; + $strContentAux = null; + + $ereg = "/^(.*)@>" . $grdName . "(.*)@<" . $grdName . "(.*)$/"; + + while (preg_match($ereg, $strContentAux1, $arrayMatch2)) { + $strData = null; + + if (isset($aFields[$grdName]) && is_array($aFields[$grdName])) { + foreach ($aFields[$grdName] as $aRow) { + if ($nl2brRecursive) { + foreach ($aRow as $sKey => $vValue) { + if (!is_array($vValue)) { + $aRow[$sKey] = str_replace($nrt, $nrthtml, nl2br($aRow[$sKey])); + } + } + } + $strData = $strData . G::replaceDataField($arrayMatch2[2], $aRow); + } + } + + $strContentAux1 = $arrayMatch2[1]; + $strContentAux = $strData . $arrayMatch2[3] . $strContentAux; + } + + $strContentAux = $strContentAux1 . $strContentAux; + + } + } + } + + $strContentAux = str_replace($nrthtml, $nrt, $strContentAux); + + $sContent = $strContentAux; + + if ($nl2brRecursive) { + foreach ($aFields as $sKey => $vValue) { + if (!is_array($vValue)) { + $aFields[$sKey] = nl2br($aFields[$sKey]); + } + } + } + + $sContent = G::replaceDataField($sContent, $aFields); + + return $sContent; + } + + /* Load strings from a XMLFile. + * @author David Callizaya + * @parameter $languageFile An xml language file. + * @parameter $languageId (es|en|...). + * @parameter $forceParse Force to read and parse the xml file. + */ + public function loadLanguageFile ($filename, $languageId = '', $forceParse = false) + { + global $arrayXmlMessages; + if ($languageId === '') { + $languageId = defined( 'SYS_LANG' ) ? SYS_LANG : 'en'; + } + $languageFile = basename( $filename, '.xml' ); + $cacheFile = substr( $filename, 0, - 3 ) . $languageId; + if (($forceParse) || (! file_exists( $cacheFile )) || (filemtime( $filename ) > filemtime( $cacheFile ))) { + $languageDocument = new Xml_document(); + $languageDocument->parseXmlFile( $filename ); + if (! is_array( $arrayXmlMessages )) { + $arrayXmlMessages = array (); + } + $arrayXmlMessages[$languageFile] = array (); + for ($r = 0; $r < sizeof( $languageDocument->children[0]->children ); $r ++) { + $n = $languageDocument->children[0]->children[$r]->findNode( $languageId ); + if ($n) { + $k = $languageDocument->children[0]->children[$r]->name; + $arrayXmlMessages[$languageFile][$k] = $n->value; + } + } + $f = fopen( $cacheFile, 'w' ); + fwrite( $f, "" ); + fclose( $f ); + } else { + require ($cacheFile); + } + } + + /* Funcion auxiliar Temporal: + * Registra en la base de datos los labels xml usados en el sistema + * @author David Callizaya + */ + public function registerLabel ($id, $label) + { + return 1; + $dbc = new DBConnection(); + $ses = new DBSession( $dbc ); + $ses->Execute( G::replaceDataField( + 'REPLACE INTO `TRANSLATION` (`TRN_CATEGORY`, `TRN_ID`, `TRN_LANG`, `TRN_VALUE`) VALUES + ("LABEL", @@ID, "' . SYS_LANG . '", @@LABEL);', array ('ID' => $id,'LABEL' => ($label !== null ? $label : '') + ) ) ); + } + + /** + * Function LoadMenuXml + * + * @author David S. Callizaya S. + * @access public + * @param eter string msgID + * @return string + */ + public function LoadMenuXml ($msgID) + { + global $arrayXmlMessages; + if (! isset( $arrayXmlMessages['menus'] )) { + G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/menus.xml' ); + } + G::registerLabel( $msgID, $arrayXmlMessages['menus'][$msgID] ); + return $arrayXmlMessages['menus'][$msgID]; + } + + /** + * Function SendMessageXml + * + * @author David S. Callizaya S. + * @access public + * @param eter string msgID + * @param eter string strType + * @param eter string file + * @return string + */ + public function SendMessageXml ($msgID, $strType, $file = "labels") + { + global $arrayXmlMessages; + if (! isset( $arrayXmlMessages[$file] )) { + G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/' . $file . '.xml' ); + } + $_SESSION['G_MESSAGE_TYPE'] = $strType; + G::registerLabel( $msgID, $arrayXmlMessages[$file][$msgID] ); + $_SESSION['G_MESSAGE'] = nl2br( $arrayXmlMessages[$file][$msgID] ); + } + + /** + * SendTemporalMessage + * + * @param string $msgID + * @param string $strType + * @param string $sType default value 'LABEL' + * @param date $time default value null + * @param integer $width default value null + * @param string $customLabels default value null + * + * @return void + */ + public function SendTemporalMessage ($msgID, $strType, $sType = 'LABEL', $time = null, $width = null, $customLabels = null) + { + if (isset( $width )) { + $_SESSION['G_MESSAGE_WIDTH'] = $width; + } + if (isset( $time )) { + $_SESSION['G_MESSAGE_TIME'] = $time; + } + switch (strtolower( $sType )) { + case 'label': + case 'labels': + $_SESSION['G_MESSAGE_TYPE'] = $strType; + $_SESSION['G_MESSAGE'] = nl2br( G::LoadTranslation( $msgID ) ); + break; + case 'string': + $_SESSION['G_MESSAGE_TYPE'] = $strType; + $_SESSION['G_MESSAGE'] = nl2br( $msgID ); + break; + } + if ($customLabels != null) { + $message = $_SESSION['G_MESSAGE']; + foreach ($customLabels as $key => $val) { + $message = str_replace( '{' . nl2br( $key ) . '}', nl2br( $val ), $message ); + } + $_SESSION['G_MESSAGE'] = $message; + } + } + + /** + * SendMessage + * + * @param string $msgID + * @param string $strType + * @param string $file default value "labels" + * + * @return void + */ + public function SendMessage ($msgID, $strType, $file = "labels") + { + global $arrayXmlMessages; + $_SESSION['G_MESSAGE_TYPE'] = $strType; + $_SESSION['G_MESSAGE'] = nl2br( G::LoadTranslation( $msgID ) ); + } + + /** + * SendMessageText + * Just put the $text in the message text + * + * @param string $text + * @param string $strType + * + * @return void + */ + public function SendMessageText ($text, $strType) + { + global $arrayXmlMessages; + $_SESSION['G_MESSAGE_TYPE'] = $strType; + $_SESSION['G_MESSAGE'] = nl2br( $text ); + } + + /** + * Render message from XML file + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $msgID + * @return void + */ + public function LoadMessage ($msgID, $file = "messages") + { + global $_SESSION; + global $arrayXmlMessages; + + if (! is_array( $arrayXmlMessages )) { + $arrayXmlMessages = G::LoadArrayFile( G::ExpandPath( 'content' ) . $file . "." . SYS_LANG ); + } + $aux = $arrayXmlMessages[$msgID]; + $msg = ""; + for ($i = 0; $i < strlen( $aux ); $i ++) { + if ($aux[$i] == "$") { + $token = ""; + $i ++; + while ($i < strlen( $aux ) && $aux[$i] != " " && $aux[$i] != "." && $aux[$i] != "'" && $aux[$i] != '"') { + $token .= $aux[$i ++]; + } + eval( "\$msg.= \$_SESSION['" . $token . "'] ; " ); + $msg .= $aux[$i]; + } else { + $msg = $msg . $aux[$i]; + } + } + return $msg; + } + + /** + * Function LoadXmlLabel + * deprecated + */ + public function LoadXmlLabel ($msgID, $file = 'labels') + { + return 'xxxxxx'; + } + + /** + * Function LoadMessageXml + * + * @author David S. Callizaya S. + * @access public + * @param eter string msgID + * @param eter string file + * @return string + */ + public function LoadMessageXml ($msgID, $file = 'labels') + { + global $arrayXmlMessages; + if (! isset( $arrayXmlMessages[$file] )) { + G::loadLanguageFile( G::ExpandPath( 'content' ) . 'languages/' . $file . '.xml' ); + } + if (isset( $arrayXmlMessages[$file][$msgID] )) { + G::registerLabel( $msgID, $arrayXmlMessages[$file][$msgID] ); + return $arrayXmlMessages[$file][$msgID]; + } else { + G::registerLabel( $msgID, '' ); + return null; + } + } + + /** + * Function LoadTranslationObject + * It generates a global Translation variable that will be used in all the system. + * this script check the file translation in folder shared/META-INF/ + * + * deprecated + * + * @access public + * @param string lang + * @return void + */ + public function LoadTranslationObject ($lang = SYS_LANG) + { + $defaultTranslations = Array (); + $foreignTranslations = Array (); + + //if the default translations table doesn't exist we can't proceed + if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) { + return null; + } + //load the translations table + require_once (PATH_LANGUAGECONT . 'translation.en'); + $defaultTranslations = $translation; + + //if some foreign language was requested and its translation file exists + if ($lang != 'en' && file_exists( PATH_LANGUAGECONT . 'translation.' . $lang )) { + require_once (PATH_LANGUAGECONT . 'translation.' . $lang); //load the foreign translations table + $foreignTranslations = $translation; + } + + global $translation; + if (defined( "SHOW_UNTRANSLATED_AS_TAG" ) && SHOW_UNTRANSLATED_AS_TAG != 0) { + $translation = $foreignTranslations; + } else { + $translation = array_merge( $defaultTranslations, $foreignTranslations ); + } + return true; + } + + /** + * Function LoadTranslation + * + * @author Aldo Mauricio Veliz Valenzuela. + * @access public + * @param eter string msgID + * @param eter string file + * @param eter array data // erik: associative array within data input to replace for formatted string i.e "any messsage {replaced_label} that contains a replace label" + * @return string + */ + public static function LoadTranslation ($msgID, $lang = SYS_LANG, $data = null) + { + global $translation; + + // if the second parameter ($lang) is an array, it was specified to use as data + if (is_array( $lang )) { + $data = $lang; + $lang = SYS_LANG; + } + + if (isset( $translation[$msgID] )) { + $translationString = preg_replace( "[\n|\r|\n\r]", ' ', $translation[$msgID] ); + + if (isset( $data ) && is_array( $data )) { + foreach ($data as $label => $value) { + $translationString = str_replace( '{' . $label . '}', $value, $translationString ); + } + } + + return $translationString; + } else { + if (defined( "UNTRANSLATED_MARK" )) { + $untranslatedMark = strip_tags( UNTRANSLATED_MARK ); + } else { + $untranslatedMark = "**"; + } + return $untranslatedMark . $msgID . $untranslatedMark; + } + } + + /** + * Function LoadTranslation + * + * @author Brayan Osmar Pereyra Suxo "Cochalo". + * @access public + * @param eter string name plugin + * @param eter string id msg + * @param eter array data + * @return string + */ + public function LoadTranslationPlugin ($namePlugin, $msgID, $data = null) + { + eval('global $translation' . $namePlugin . ';'); + + $existId = false; + eval('if (isset( $translation' . $namePlugin . '[$msgID])) { $existId = true; }'); + if ($existId) { + eval('$translationString = preg_replace( "[\n|\r|\n\r]", " ", $translation' . $namePlugin . '[$msgID] );'); + if (isset( $data ) && is_array( $data )) { + foreach ($data as $label => $value) { + $translationString = str_replace( '{' . $label . '}', $value, $translationString ); + } + } + + return $translationString; + } else { + if (defined( "UNTRANSLATED_MARK" )) { + $untranslatedMark = strip_tags( UNTRANSLATED_MARK ); + } else { + $untranslatedMark = "**"; + } + return $untranslatedMark . $msgID . $untranslatedMark; + } + } + + /** + * Function getTranslations + * + * @author Erik Amaru O. + * @access public + * @param eter array msgIDs + * @param eter string file + * @return string + */ + public function getTranslations ($msgIDs, $lang = SYS_LANG) + { + if (! is_array( $msgIDs )) { + return null; + } + $translations = Array (); + foreach ($msgIDs as $mID) { + $translations[$mID] = self::LoadTranslation( $mID, $lang ); + } + + return $translations; + } + + /** + * Load an array File Content + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $strFile + * @return void + */ + public function LoadArrayFile ($strFile = '') + { + $res = null; + if ($strFile != '') { + $src = file( $strFile ); + if (is_array( $src )) { + foreach ($src as $key => $val) { + $res[$key] = trim( $val ); + } + } + } + unset( $src ); + return $res; + } + + /** + * Expand an uri based in the current URI + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $methodPage the method directory and the page + * @return the expanded uri, later, will encryt the uri... + */ + public function expandUri ($methodPage) + { + $uri = explode( '/', getenv( 'REQUEST_URI' ) ); + $sw = 0; + $newUri = ''; + if (! defined( 'SYS_SKIN' )) { + for ($i = 0; $i < count( $uri ); $i ++) { + if ($sw == 0) { + $newUri .= $uri[$i] . PATH_SEP; + } + if ($uri[$i] == SYS_SKIN) { + $sw = 1; + } + } + } else { + for ($i = 0; $i < 4; $i ++) { + if ($sw == 0) { + $newUri .= $uri[$i] . PATH_SEP; + } + if ($uri[$i] == SYS_SKIN) { + $sw = 1; + } + } + } + $newUri .= $methodPage; + return $newUri; + } + + /** + * Forces login for generic applications + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $userid + * @param string $permission + * @param string $urlNoAccess + * @return void + */ + public function genericForceLogin ($permission, $urlNoAccess, $urlLogin = 'login/login') + { + global $RBAC; + + //the session is expired, go to login page, + //the login page is login/login.html + if (! isset( $_SESSION )) { + header( 'location: ' . G::expandUri( $urlLogin ) ); + die(); + } + + //$permission is an array, we'll verify all permission to allow access. + if (is_array( $permission )) { + $aux = $permission; + } else { + $aux[0] = $permission; + } + $sw = 0; + for ($i = 0; $i < count( $aux ); $i ++) { + $res = $RBAC->userCanAccess( $aux[$i] ); + if ($res == 1) { + $sw = 1; + } + } + + //you don't have access to this page + if ($sw == 0) { + header( 'location: ' . G::expandUri( $urlNoAccess ) ); + die(); + } + } + + /** + * capitalize + * + * @param string $string + * + * @return string $string + */ + public function capitalize ($string) + { + return ucfirst( $string ); + } + + /** + * toUpper + * + * @param string $sText + * + * @return string strtoupper($sText) + */ + public function toUpper ($sText) + { + return strtoupper( $sText ); + } + + /** + * toLower + * + * @param string $sText + * @return string strtolower($sText) + */ + public static function toLower ($sText) + { + return strtolower( $sText ); + } + + /** + * http_build_query + * + * @param string $formdata, + * @param string $numeric_prefix default value null, + * @param string $key default value null + * + * @return array $res + */ + public function http_build_query ($formdata, $numeric_prefix = null, $key = null) + { + $res = array (); + foreach ((array) $formdata as $k => $v) { + $tmp_key = rawurlencode( is_int( $k ) ? $numeric_prefix . $k : $k ); + if ($key) { + $tmp_key = $key . '[' . $tmp_key . ']'; + } + if (is_array( $v ) || is_object( $v )) { + $res[] = G::http_build_query( $v, null /* or $numeric_prefix if you want to add numeric_prefix to all indexes in array*/, $tmp_key ); + } else { + $res[] = $tmp_key . "=" . rawurlencode( $v ); + } + /* + If you want, you can write this as one string: + $res[] = ( ( is_array($v) || is_object($v) ) ? G::http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) ); + */ + } + $separator = ini_get( 'arg_separator.output' ); + return implode( $separator, $res ); + } + + /** + * Redirect URL + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $parameter + * @return string + */ + public static function header ($parameter) + { + if (defined( 'ENABLE_ENCRYPT' ) && (ENABLE_ENCRYPT == 'yes') && (substr( $parameter, 0, 9 ) == 'location:')) { + $url = G::encryptUrl( substr( $parameter, 10 ), URL_KEY ); + header( 'location:' . $url ); + } else { + header( $parameter ); + } + return; + } + + /** + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $permission + * @param string $urlNoAccess + * @return void + */ + public function forceLogin ($permission = "", $urlNoAccess = "") + { + global $RBAC; + + if (isset( $_SESSION['USER_LOGGED'] ) && $_SESSION['USER_LOGGED'] == '') { + $sys = (ENABLE_ENCRYPT == 'yes' ? SYS_SYS : "sys" . SYS_SYS); + $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG); + $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN); + $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login' ), URL_KEY ) : 'login'); + $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login.html' ), URL_KEY ) : 'login.html'); + $direction = "/$sys/$lang/$skin/$login/$loginhtml"; + die(); + } + + $Connection = new DBConnection(); + $ses = new DBSession( $Connection ); + $stQry = "SELECT LOG_STATUS FROM LOGIN WHERE LOG_SID = '" . session_id() . "'"; + $dset = $ses->Execute( $stQry ); + $row = $dset->read(); + $sessionPc = defined( 'SESSION_PC' ) ? SESSION_PC : ''; + $sessionBrowser = defined( 'SESSION_BROWSER' ) ? SESSION_BROWSER : ''; + if (($sessionPc == "1") or ($sessionBrowser == "1")) { + if ($row['LOG_STATUS'] == 'X') { + $sys = (ENABLE_ENCRYPT == 'yes' ? SYS_SYS : "sys" . SYS_SYS); + $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG); + $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN); + $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login' ), URL_KEY ) : 'login'); + $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( 'login.html' ), URL_KEY ) : 'login.html'); + $direction = "/$sys/$lang/$skin/$login/$loginhtml"; + G::SendMessageXml( 'ID_CLOSE_SESSION', "warning" ); + header( "location: $direction" ); + die(); + return; + } + } + if (defined( 'SIN_COMPATIBILIDAD_RBAC' ) and SIN_COMPATIBILIDAD_RBAC == 1) { + return; + } + + if ($permission == "") { + return; + } + + if (is_array( $permission )) { + $aux = $permission; + } else { + $aux[0] = $permission; + } + + $sw = 0; + for ($i = 0; $i < count( $aux ); $i ++) { + $res = $RBAC->userCanAccess( $aux[$i] ); + if ($res == 1) { + $sw = 1; + } + } + + if ($sw == 0 && $urlNoAccess != "") { + $aux = explode( '/', $urlNoAccess ); + $sys = (ENABLE_ENCRYPT == 'yes' ? SYS_SYS : "/sys" . SYS_LANG); + $lang = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_LANG ), URL_KEY ) : SYS_LANG); + $skin = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( SYS_SKIN ), URL_KEY ) : SYS_SKIN); + $login = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( $aux[0] ), URL_KEY ) : $aux[0]); + $loginhtml = (ENABLE_ENCRYPT == 'yes' ? G::encrypt( urldecode( $aux[1] ), URL_KEY ) : $aux[1]); + + //header ("location: /$sys/$lang/$skin/$login/$loginhtml"); + header( "location: /fluid/mNE/o9A/mNGm1aLiop3V4qU/dtij4J°gmaLPwKDU3qNn2qXanw" ); + die(); + } + + if ($sw == 0) { + header( "location: /fluid/mNE/o9A/mNGm1aLiop3V4qU/dtij4J°gmaLPwKDU3qNn2qXanw" ); + die(); + } + } + + /** + * Add slashes to a string + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $val_old + * @return string + */ + public function add_slashes ($val_old) + { + + if (! is_string( $val_old )) { + $val_old = "$val_old"; + } + + $tamano_cadena = strlen( $val_old ); + $contador_cadena = 0; + $new_val = ""; + + for ($contador_cadena = 0; $contador_cadena < $tamano_cadena; $contador_cadena ++) { + $car = $val_old[$contador_cadena]; + + if ($car != chr( 34 ) && $car != chr( 39 ) && $car != chr( 92 )) { + $new_val .= $car; + } else { + if ($car2 != chr( 92 )) { + //print " xmlvar: $new_val -- $car -- $car2
"; + $new_val .= chr( 92 ) . $car; + } else { + $new_val .= $car; + } + } + } + return $new_val; + } + + /** + * Extract the structure version value from serializated table field and check it. + * @return true if the version is bigger than 1 + */ + public function gotDirectoryStructureVer2() + { + G::LoadClass( "configuration" ); + $configuration = new Configurations(); + if (defined('SYS_SYS') && $configuration->exists("ENVIRONMENT_SETTINGS")) { + return ($configuration->getDirectoryStructureVer() > 1); + } + return false; + } + + /** + * Get the default blank directory 0 for external files + */ + public function getBlackHoleDir() + { + //len32:12345678901234567890123456789012 + return "00000000000000000000000000000000"; + } + + /** + * Funtion used to fix 32K issue related to ext3 max subdirectory storage, but checking Version first. + * @param string $uid + * @param int $splitSize + * @param int $pieces + * @return string xxx/xxx/xxx/xxxxxxxxxxxxxxxxxxxxx + */ + public function getPathFromUID($uid, $splitSize = 3, $pieces = 3) + { + if (! G::gotDirectoryStructureVer2()) { + return $uid; + } + return G::getPathFromUIDPlain($uid, $splitSize, $pieces); + } + + /** + * Funtion used to fix 32K issue related to ext3 max subdirectory storage. + * @param string $uid + * @param int $splitSize + * @param int $pieces + * @return string xxx/xxx/xxx/xxxxxxxxxxxxxxxxxxxxx + */ + public function getPathFromUIDPlain($uid, $splitSize = 3, $pieces = 3) + { + $dirArray = array(); + if (is_string($uid) && strlen($uid) >= 32 && $uid != G::getBlackHoleDir()) { + for ($i = 0; $i < $pieces; $i++) { + $dirArray[] = substr($uid, 0, $splitSize); + $len = strlen($uid); + $uid = substr($uid, $splitSize, $len); + } + } + $dirArray[] = $uid; + $newfileStructure = implode($dirArray, '/'); + return $newfileStructure; + } + + /** + * Get the uid from the splitted directory + filename. + * @param string $path + * @return string + */ + public function getUIDfromPath($path) + { + $uid = ''; + $item = explode($path, '/'); + $len = sizeof($item); + for ($i = 0; $i < $len; $i++) { + $uid .= $item[$i]; + } + if (strlen($uid) != 32){ + return "invalid"; + } + return $uid; + } + + /** + * Get the file stored in '0' dir as splitted, but checking version first. + * @param string $appUid + * @param string $fileUid + * @param int $splitSize + * @param int $pieces + * @return array index:0 got the path, index:1 got the filename + */ + public function getPathFromFileUID($appUid, $fileUid, $splitSize = 3, $pieces = 3) + { + if (! G::gotDirectoryStructureVer2()) { + $response = array(); + $response[] = ''; + $response[] = $fileUid; + return $response; + } + return G::getPathFromFileUIDPlain($appUid, $fileUid, $splitSize, $pieces); + } + + /** + * Get the file stored in '0' dir as splitted. + * @param string $appUid + * @param string $fileUid + * @param int $splitSize + * @param int $pieces + * @return array index:0 got the path, index:1 got the filename + */ + public function getPathFromFileUIDPlain($appUid, $fileUid, $splitSize = 3, $pieces = 3) + { + $response = array(); + if ($appUid == G::getBlackHoleDir()) { + $dirArray = array(); + if (is_string($fileUid) && strlen($fileUid) >= 32) { + for ($i = 0; $i < $pieces; $i++) { + $dirArray[] = substr($fileUid, 0, $splitSize); + $len = strlen($fileUid); + $fileUid = substr($fileUid, $splitSize, $len); + } + } + $response[] = implode($dirArray, '/') . '/'; + $response[] = $fileUid; + } else { + $response[] = ''; + $response[] = $fileUid; + } + return $response; + } + + /** + * Upload a file and then copy to path+ nameToSave + * + * @author Mauricio Veliz + * @access public + * @param string $file + * @param string $path + * @param string $nameToSave + * @param integer $permission + * @return void + */ + public static function uploadFile ($file, $path, $nameToSave, $permission = 0755) + { + try { + if ($file == '') { + throw new Exception( 'The filename is empty!' ); + } + if (filesize( $file ) > ((((ini_get( 'upload_max_filesize' ) + 0)) * 1024) * 1024)) { + throw new Exception( 'The size of upload file exceeds the allowed by the server!' ); + } + $oldumask = umask( 0 ); + if (! is_dir( $path )) { + G::verifyPath( $path, true ); + } + + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + $file = str_replace("\\\\","\\",$file,$count); + if(!$count) { + $winPath = explode("\\",$file); + $file = ""; + foreach($winPath as $k => $v){ + if($v != "") { + $file.= $v."\\"; + } + } + $file = substr($file,0,-1); + } + } + + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $file = $filter->validateInput($file, "path"); + $path = $filter->validateInput($path, "path"); + + move_uploaded_file( $file, $path . "/" . $nameToSave ); + @chmod( $path . "/" . $nameToSave, $permission ); + umask( $oldumask ); + + } catch (Exception $oException) { + throw $oException; + } + } + + /** + * resizeImage + * + * @param string $path, + * @param string $resWidth + * @param string $resHeight + * @param string $saveTo default value null + * + * @return void + */ + public function resizeImage ($path, $resWidth, $resHeight, $saveTo = null) + { + $imageInfo = @getimagesize( $path ); + + if (! $imageInfo) { + throw new Exception( "Could not get image information" ); + } + list ($width, $height) = $imageInfo; + $percentHeight = $resHeight / $height; + $percentWidth = $resWidth / $width; + $percent = ($percentWidth < $percentHeight) ? $percentWidth : $percentHeight; + $resWidth = $width * $percent; + $resHeight = $height * $percent; + + // Resample + $image_p = imagecreatetruecolor( $resWidth, $resHeight ); + imagealphablending( $image_p, false ); + imagesavealpha( $image_p, true ); + + $background = imagecolorallocate( $image_p, 0, 0, 0 ); + ImageColorTransparent( $image_p, $background ); // make the new temp image all transparent + + + //Assume 3 channels if we can't find that information + if (! array_key_exists( "channels", $imageInfo )) { + $imageInfo["channels"] = 3; + } + $memoryNeeded = Round( ($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] + Pow( 2, 16 )) * 1.95 ) / (1024 * 1024); + if ($memoryNeeded < 80) { + $memoryNeeded = 80; + } + ini_set( 'memory_limit', intval( $memoryNeeded ) . 'M' ); + + $functions = array (IMAGETYPE_GIF => array ('imagecreatefromgif','imagegif' + ),IMAGETYPE_JPEG => array ('imagecreatefromjpeg','imagejpeg'),IMAGETYPE_PNG => array ('imagecreatefrompng','imagepng')); + + if (! array_key_exists( $imageInfo[2], $functions )) { + throw new Exception( "Image format not supported" ); + } + list ($inputFn, $outputFn) = $functions[$imageInfo[2]]; + + $image = $inputFn( $path ); + imagecopyresampled( $image_p, $image, 0, 0, 0, 0, $resWidth, $resHeight, $width, $height ); + $outputFn( $image_p, $saveTo ); + + @chmod( $saveTo, 0666 ); + } + + /** + * Merge 2 arrays + * + * @author Fernando Ontiveros Lira + * @access public + * @return array + */ + public function array_merges () + { + $array = array (); + $arrays = & func_get_args(); + foreach ($arrays as $array_i) { + if (is_array( $array_i )) { + G::array_merge_2( $array, $array_i ); + } + } + return $array; + } + + /** + * Merge 2 arrays + * + * @author Fernando Ontiveros Lira + * @access public + * @param string $array + * @param string $array_i + * @return array + */ + public function array_merge_2 (&$array, &$array_i) + { + foreach ($array_i as $k => $v) { + if (is_array( $v )) { + if (! isset( $array[$k] )) { + $array[$k] = array (); + } + G::array_merge_2( $array[$k], $v ); + } else { + if (isset( $array[$k] ) && is_array( $array[$k] )) { + $array[$k][0] = $v; + } else { + if (isset( $array ) && ! is_array( $array )) { + $temp = $array; + $array = array(); + $array[0] = $temp; + } + $array[$k] = $v; + } + } + } + } + + /** + * Generate random number + * + * @author Fernando Ontiveros Lira + * @access public + * @return int + */ + public static function generateUniqueID () + { + do { + $sUID = str_replace( '.', '0', uniqid( rand( 0, 999999999 ), true ) ); + } while (strlen( $sUID ) != 32); + return $sUID; + //return strtoupper(substr(uniqid(rand(0, 9), false),0,14)); + } + + /** + * Generate a numeric or alphanumeric code + * + * @author Julio Cesar Laura Avendaힼjuliocesar@colosa.com> + * @access public + * @return string + */ + public function generateCode ($iDigits = 4, $sType = 'NUMERIC') + { + if (($iDigits < 4) || ($iDigits > 50)) { + $iDigits = 4; + } + if (($sType != 'NUMERIC') && ($sType != 'ALPHA') && ($sType != 'ALPHANUMERIC')) { + $sType = 'NUMERIC'; + } + $aValidCharacters = array ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' + ); + switch ($sType) { + case 'NUMERIC': + $iMin = 0; + $iMax = 9; + break; + case 'ALPHA': + $iMin = 10; + $iMax = 35; + break; + case 'ALPHANUMERIC': + $iMin = 0; + $iMax = 35; + break; + } + $sCode = ''; + for ($i = 0; $i < $iDigits; $i ++) { + $sCode .= $aValidCharacters[rand( $iMin, $iMax )]; + } + return $sCode; + } + + /** + * Verify if the input string is a valid UID + * + * @author David Callizaya + * @access public + * @return int + */ + public function verifyUniqueID ($uid) + { + return (bool) preg_match( '/^[0-9A-Za-z]{14,}/', $uid ); + } + + /** + * is_utf8 + * + * @param string $string + * + * @return string utf8_encode() + */ + public function is_utf8 ($string) + { + if (is_array( $string )) { + $enc = implode( '', $string ); + return @! ((ord( $enc[0] ) != 239) && (ord( $enc[1] ) != 187) && (ord( $enc[2] ) != 191)); + } else { + return (utf8_encode( utf8_decode( $string ) ) == $string); + } + } + + + /** + * Return date in Y-m-d format + * + * @author Fernando Ontiveros Lira + * @access public + * @return void + */ + public function CurDate($sFormat = '') + { + $sFormat = ($sFormat != '')? $sFormat : 'Y-m-d H:i:s'; + + return date($sFormat); + } + + /** + * Return the System defined constants and Application variables + * Constants: SYS_* + * Sessions : USER_* , URS_* + */ + public function getSystemConstants($params = null) + { + $t1 = G::microtime_float(); + $sysCon = array(); + + if (defined("SYS_LANG")) { + $sysCon["SYS_LANG"] = SYS_LANG; + } + + if (defined("SYS_SKIN")) { + $sysCon["SYS_SKIN"] = SYS_SKIN; + } + + if (defined("SYS_SYS")) { + $sysCon["SYS_SYS"] = SYS_SYS; + } + + $sysCon["APPLICATION"] = (isset($_SESSION["APPLICATION"]))? $_SESSION["APPLICATION"] : ""; + $sysCon["PROCESS"] = (isset($_SESSION["PROCESS"]))? $_SESSION["PROCESS"] : ""; + $sysCon["TASK"] = (isset($_SESSION["TASK"]))? $_SESSION["TASK"] : ""; + $sysCon["INDEX"] = (isset($_SESSION["INDEX"]))? $_SESSION["INDEX"] : ""; + $sysCon["USER_LOGGED"] = (isset($_SESSION["USER_LOGGED"]))? $_SESSION["USER_LOGGED"] : ""; + $sysCon["USR_USERNAME"] = (isset($_SESSION["USR_USERNAME"]))? $_SESSION["USR_USERNAME"] : ""; + + //############################################################################################### + // Added for compatibility betweek aplication called from web Entry that uses just WS functions + //############################################################################################### + + if ($params != null) { + if (isset($params->option)) { + switch ($params->option) { + case "STORED SESSION": + if (isset($params->SID)) { + G::LoadClass("sessions"); + + $oSessions = new Sessions($params->SID); + $sysCon = array_merge($sysCon, $oSessions->getGlobals()); + } + break; + } + } + + if (isset($params->appData) && is_array($params->appData)) { + $sysCon["APPLICATION"] = $params->appData["APPLICATION"]; + $sysCon["PROCESS"] = $params->appData["PROCESS"]; + $sysCon["TASK"] = $params->appData["TASK"]; + $sysCon["INDEX"] = $params->appData["INDEX"]; + + if (empty($sysCon["USER_LOGGED"])) { + $sysCon["USER_LOGGED"] = $params->appData["USER_LOGGED"]; + $sysCon["USR_USERNAME"] = $params->appData["USR_USERNAME"]; + } + } + } + + return $sysCon; + } + + /* + * Return the Friendly Title for a string, capitalize every word and remove spaces + * param : text string + */ + public function capitalizeWords($text) + { + return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8'); + } + + /** + * unhtmlentities + * + * @param string $string + * + * @return string substring + */ + public function unhtmlentities ($string) + { + if (version_compare(PHP_VERSION, '5.4.0', '<')) { + $trans_tbl = get_html_translation_table( HTML_ENTITIES ); + } else { + $trans_tbl = get_html_translation_table( HTML_ENTITIES, ENT_COMPAT, 'ISO-8859-1' ); + } + foreach ($trans_tbl as $k => $v) { + $ttr[$v] = utf8_encode( $k ); + } + return strtr( $string, $ttr ); + } + + /** + * ************************************* init ********************************************** + * Xml parse collection functions + * Returns a associative array within the xml structure and data + * + * @author Erik Amaru Ortiz + */ + public function xmlParser (&$string) + { + $parser = xml_parser_create(); + xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 ); + xml_parse_into_struct( $parser, $string, $vals, $index ); + + $mnary = array (); + $ary = &$mnary; + foreach ($vals as $r) { + $t = $r['tag']; + if ($r['type'] == 'open') { + if (isset( $ary[$t] )) { + if (isset( $ary[$t][0] )) { + $ary[$t][] = array (); + } else { + $ary[$t] = array ($ary[$t],array () ); + } + $cv = &$ary[$t][count( $ary[$t] ) - 1]; + } else { + $cv = &$ary[$t]; + } + if (isset( $r['attributes'] )) { + foreach ($r['attributes'] as $k => $v) { + $cv['__ATTRIBUTES__'][$k] = $v; + } + } + // note by gustavo cruz gustavo[at]colosa[dot]com + // minor adjustments to validate if an open node have a value attribute. + // for example a dropdown has many childs, but also can have a value attribute. + if (isset( $r['value'] ) && trim( $r['value'] ) != '') { + $cv['__VALUE__'] = $r['value']; + } + // end added code + $cv['__CONTENT__'] = array (); + $cv['__CONTENT__']['_p'] = &$ary; + $ary = &$cv['__CONTENT__']; + + } elseif ($r['type'] == 'complete') { + if (isset( $ary[$t] )) { + if (isset( $ary[$t][0] )) { + $ary[$t][] = array (); + } else { + $ary[$t] = array ($ary[$t],array ()); + } + $cv = &$ary[$t][count( $ary[$t] ) - 1]; + } else { + $cv = &$ary[$t]; + } + if (isset( $r['attributes'] )) { + foreach ($r['attributes'] as $k => $v) { + $cv['__ATTRIBUTES__'][$k] = $v; + } + } + $cv['__VALUE__'] = (isset( $r['value'] ) ? $r['value'] : ''); + + } elseif ($r['type'] == 'close') { + $ary = &$ary['_p']; + } + } + + self::_del_p( $mnary ); + + $obj_resp = new stdclass(); + $obj_resp->code = xml_get_error_code( $parser ); + $obj_resp->message = xml_error_string( $obj_resp->code ); + $obj_resp->result = $mnary; + xml_parser_free( $parser ); + + return $obj_resp; + } + + /** + * _del_p + * + * @param string &$ary + * + * @return void + */ + // _Internal: Remove recursion in result array + public function _del_p (&$ary) + { + foreach ($ary as $k => $v) { + if ($k === '_p') { + unset( $ary[$k] ); + } elseif (is_array( $ary[$k] )) { + self::_del_p( $ary[$k] ); + } + } + } + + /** + * ary2xml + * + * Array to XML + * + * @param string $cary + * @param string $d=0 + * @param string $forcetag default value '' + * + * @return void + */ + // Array to XML + public function ary2xml ($cary, $d = 0, $forcetag = '') + { + $res = array (); + foreach ($cary as $tag => $r) { + if (isset( $r[0] )) { + $res[] = self::ary2xml( $r, $d, $tag ); + } else { + if ($forcetag) { + $tag = $forcetag; + } + $sp = str_repeat( "\t", $d ); + $res[] = "$sp<$tag"; + if (isset( $r['_a'] )) { + foreach ($r['_a'] as $at => $av) { + $res[] = " $at=\"$av\""; + } + } + $res[] = ">" . ((isset( $r['_c'] )) ? "\n" : ''); + if (isset( $r['_c'] )) { + $res[] = ary2xml( $r['_c'], $d + 1 ); + } elseif (isset( $r['_v'] )) { + $res[] = $r['_v']; + } + $res[] = (isset( $r['_c'] ) ? $sp : '') . "\n"; + } + + } + return implode( '', $res ); + } + + /** + * ins2ary + * + * Insert element into array + * + * @param string &$ary + * @param string $element + * @param string $pos + * + * @return void + */ + // Insert element into array + public function ins2ary (&$ary, $element, $pos) + { + $ar1 = array_slice( $ary, 0, $pos ); + $ar1[] = $element; + $ary = array_merge( $ar1, array_slice( $ary, $pos ) ); + } + + /* + * Xml parse collection functions + **/ + + /** + * evalJScript + * + * @param string $c + * + * @return void + */ + public function evalJScript ($c) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $c = $filter->xssFilterHard($c); + print ("") ; + } + + /** + * Inflects a string with accented characters and other characteres not suitable for file names, by defaul replace with undescore + * + * @author Erik Amaru Ortiz + * @param (string) string to convert + * @param (string) character for replace + * @param (array) additional characteres map + * + */ + public function inflect ($string, $replacement = '_', $map = array()) + { + if (is_array( $replacement )) { + $map = $replacement; + $replacement = '_'; + } + + $quotedReplacement = preg_quote( $replacement, '/' ); + + $default = array ('/à|á|å|â/' => 'a','/è|é|ê|ẽ|ë/' => 'e','/ì|í|î/' => 'i','/ò|ó|ô|ø/' => 'o','/ù|ú|ů|û/' => 'u','/ç/' => 'c','/ñ/' => 'n','/ä|æ/' => 'ae','/ö/' => 'oe','/ü/' => 'ue','/Ä/' => 'Ae','/Ü/' => 'Ue','/Ö/' => 'Oe','/ß/' => 'ss','/\.|\,|\:|\-|\\|\//' => " ",'/\\s+/' => $replacement + ); + + $map = array_merge( $default, $map ); + return preg_replace( array_keys( $map ), array_values( $map ), $string ); + } + + /** + * pr + * + * @param string $var + * + * @return void + */ + public function pr ($var) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $var = $filter->xssFilterHard($var); + print ("
") ;
+        print_r( $var );
+        print ("
") ; + } + + /** + * dump + * + * @param string $var + * + * @return void + */ + public function dump ($var) + { + print ("
") ;
+        var_dump( $var );
+        print ("
") ; + } + + /** + * stripCDATA + * + * @param string $string + * + * @return string str_replace + */ + public function stripCDATA ($string) + { + preg_match_all( '//is', $string, $matches ); + return str_replace( $matches[0], $matches[1], $string ); + } + + /** + * Get the temporal directory path on differents O.S. + * i.e. /temp -> linux, C:/Temp -> win + * + * @author + */ + public function sys_get_temp_dir () + { + if (! function_exists( 'sys_get_temp_dir' )) { + // Based on http://www.phpit.net/ + // article/creating-zip-tar-archives-dynamically-php/2/ + // Try to get from environment variable + if (! empty( $_ENV['TMP'] )) { + return realpath( $_ENV['TMP'] ); + } elseif (! empty( $_ENV['TMPDIR'] )) { + return realpath( $_ENV['TMPDIR'] ); + } elseif (! empty( $_ENV['TEMP'] )) { + return realpath( $_ENV['TEMP'] ); + } else { + // Detect by creating a temporary file + // Try to use system's temporary directory as random name shouldn't exist + $temp_file = tempnam( G::encryptOld( uniqid( rand(), true ) ), '' ); + if ($temp_file) { + $temp_dir = realpath( dirname( $temp_file ) ); + unlink( $temp_file ); + return $temp_dir; + } else { + return false; + } + } + } else { + return sys_get_temp_dir(); + } + } + + /** + * Get the content of a compose pmos web service response + * Returns an array when has a valid reponse, if the response is invalid returns an object containing a status_code and message properties. + * + * @author + */ + public function PMWSCompositeResponse ($oResp, $prop) + { + $Resp = new stdClass(); + + if (is_object( $oResp ) && isset( $oResp->{$prop} )) { + $list = $oResp->{$prop}; + + if (is_object( $list )) { + $aList[0] = $list; + } else { + $aList = $list; + } + + $result = true; + if (is_array( $aList )) { + foreach ($aList as $item) { + if (! isset( $item->guid )) { + $result = false; + break; + } + } + } else { + $Resp->status_code = - 1; + $Resp->message = "Bad respose type for ({$prop})"; + } + + if ($result) { + //verifing if the response has a composite response into a guid value of the first row. + $tmp = explode( ' ', trim( $aList[0]->guid ) ); + if (sizeof( $tmp ) >= 2) { + //the guid can't has a space, so this should be a ws response + $Resp->status_code = $tmp[0]; + $Resp->message = substr( $aList[0]->guid, strpos( $aList[0]->guid, ' ' ) + 1 ); + } else { + return $aList; + } + + } else { + $Resp->status_code = - 2; + $Resp->message = "Bad respose, the response has not a uniform struct."; + } + } elseif (is_object( $oResp )) { + return Array (); + } else { + $Resp->status_code = - 1; + $Resp->message = "1 Bad respose type for ({$prop})"; + } + return $Resp; + } + + /** + * Validate and emai address in complete forms, + * + * @author Erik A.O. + * i.e. if the param. is 'erik a.o. ' + * -> returns a object within $o->email => erik@colosa.com and $o->name => erik A.O. in other case returns false + * + */ + public function emailAddress($sEmail) + { + $o = new stdClass(); + + if ( strpos($sEmail, '<') !== false ) { + preg_match('/([\"\w@\.-_\s]*\s*)?(<(\w+[\.-]?\w+]*@\w+([\.-]?\w+)*\.\w{2,3})+>)/', $sEmail, $matches); + + if ( isset($matches[1]) && $matches[3]) { + $o->email = $matches[3]; + $o->name = $matches[1]; + return $o; + } + return false; + } else { + preg_match('/\w+[\.-]?\w+]*@\w+([\.-]?\w+)*\.\w{2,3}+/', $sEmail, $matches); + if ( isset($matches[0]) ) { + $o->email = $matches[0]; + $o->name = ''; + return $o; + } + + return false; + } + } + + /** + * JSON encode + * + * @author Erik A.O. + */ + public static function json_encode($Json) + { + if ( function_exists('json_encode') ) { + return json_encode($Json); + } else { + G::LoadThirdParty('pear/json', 'class.json'); + $oJSON = new Services_JSON(); + return $oJSON->encode($Json); + } + } + + /** + * JSON decode + * + * @author Erik A.O. + */ + public function json_decode($Json, $assoc = false) + { + if (function_exists('json_decode')) { + return json_decode($Json, $assoc); + } else { + G::LoadThirdParty('pear/json', 'class.json'); + $oJSON = new Services_JSON(); + return $oJSON->decode($Json); + } + } + + /** + * isHttpRequest + * + * @return boolean true or false + */ + public static function isHttpRequest() + { + if (isset($_SERVER['SERVER_SOFTWARE']) && strpos(strtolower($_SERVER['SERVER_SOFTWARE']), 'apache') !== false) { + return true; + } + return false; + } + + /** + * Send a mail using phpmailer + * this method use the global smtp server connection stored on Configuration table + * this information is retrieved by the PMFunction getEmailConfiguration() + * + * @author Erik Amaru Ortiz + * @param string $from address that is sending the email + * @param string $fromName name of sender + * @param mixed $address the possibles values are: + * string + * array('email1', 'some name ') + * array('to'=>array('email1', 'some name '), 'cc'=>array(...), 'bcc'=>array(...)) + * @param string $subject contains the email subject + * @param string $body contains the email body (text plain or html) + * @return mixed boolean or string : if the email was sent successfully returns true, otherwise returns a string within error message + */ + public function sendMail ($from, $fromName, $address, $subject, $body) + { + // require_once "classes/class.pmFunctions.php"; + G::LoadClass("pmFunctions"); + G::LoadThirdParty('phpmailer', 'class.phpmailer'); + $setup = getEmailConfiguration(); + if ($setup['MESS_RAUTH'] == false || (is_string($setup['MESS_RAUTH']) && $setup['MESS_RAUTH'] == 'false')) { + $setup['MESS_RAUTH'] = 0; + } else { + $setup['MESS_RAUTH'] = 1; + } + + if (count($setup) == 0 || !isset($setup['MESS_ENGINE']) || !isset($setup['MESS_SERVER']) + || !isset($setup['MESS_ENABLED']) || !isset($setup['MESS_RAUTH']) || $setup['MESS_SERVER'] == '') { + return G::LoadTranslation('ID_EMAIL_ENGINE_IS_NOT_CONFIGURED'); + } + + if (!$setup['MESS_ENABLED']) { + return G::LoadTranslation('ID_EMAIL_ENGINE_IS_NOT_ENABLED'); + } + + $passwd = $setup['MESS_PASSWORD']; + $passwdDec = G::decrypt($passwd,'EMAILENCRYPT'); + $auxPass = explode('hash:', $passwdDec); + if (count($auxPass) > 1) { + if (count($auxPass) == 2) { + $passwd = $auxPass[1]; + } else { + array_shift($auxPass); + $passwd = implode('', $auxPass); + } + } + $setup['MESS_PASSWORD'] = $passwd; + $mail = new PHPMailer(true); + $mail->From = $from != '' && $from ? $from : $setup['MESS_ACCOUNT']; + $mail->FromName = $fromName; + $mail->Subject = $subject; + $mail->Body = $body; + $mail->IsHTML (true); + $mail->IsSMTP(); + $mail->Host = $setup['MESS_SERVER']; + $mail->Port = $setup['MESS_PORT']; + $mail->SMTPAuth = isset($setup['MESS_RAUTH']) && $setup['MESS_RAUTH'] ? true : false; + $mail->Username = $setup['MESS_ACCOUNT']; + $mail->Password = $setup['MESS_PASSWORD']; + $mail->SMTPSecure = $setup['SMTPSecure']; + + $emailAddressList = G::envelopEmailAddresses($address); + + foreach ($emailAddressList['to'] as $emails) { + $mail->AddAddress($emails[0], $emails[1]); + } + foreach ($emailAddressList['cc'] as $emails) { + $mail->AddCC($emails[0], $emails[1]); + } + foreach ($emailAddressList['bcc'] as $emails) { + $mail->AddBCC($emails[0], $emails[1]); + } + + return $mail->Send() ? true : $mail->ErrorInfo; + } + + /** + * Envelope a emails collection from a string or array + * @author Erik Amaru Ortiz + * @param mixed $address the possibles values are: + * string + * array('email1', 'some name ') + * array('to'=>array('email1', 'some name '), 'cc'=>array(...), 'bcc'=>array(...)) + * @return array contains: + * array( + * 'to' => array('email@host.com', 'some name or empty string', array('email@host.com', '..'), ...), + * 'cc' => array('email@host.com', 'some name or empty string', ...), + * 'bcc' => array('email@host.com', 'some name or empty string', ...) + * ) + */ + public function envelopEmailAddresses($address) + { + $emailAddressList = array(); + $emailAddressList['to'] = array(); + $emailAddressList['cc'] = array(); + $emailAddressList['bcc'] = array(); + $ereg = '/([\"\w\W\s]*\s*)?(<([\w\-\.]+@[\.-\w]+\.\w{2,3})+>)/'; + + if (!is_array($address)) { + if (preg_match($ereg, $address, $match)) { + $emailAddressList['to'][] = array($match[3], $match[1]); + } else { + $emailAddressList['to'][] = array($address, ''); + } + } else { + foreach ($address as $type => $emails) { + if (!is_array($emails)) { + if (preg_match($ereg, $emails, $match)) { + $emailAddressList['to'][] = array($match[3], $match[1]); + } else { + $emailAddressList['to'][] = array($emails, ''); + } + } else { + switch ($type) { + case 'cc': + foreach ($emails as $email) { + if (preg_match($ereg, $email, $match)) { + $emailAddressList['cc'][] = array($match[3], $match[1]); + } else { + $emailAddressList['cc'][] = array($email, ''); + } + } + break; + case 'bcc': + foreach ($emails as $email) { + if (preg_match($ereg, $email, $match)) { + $emailAddressList['bcc'][] = array($match[3], $match[1]); + } else { + $emailAddressList['bcc'][] = array($email, ''); + } + } + break; + case 'to': + default: + foreach ($emails as $email) { + if (preg_match($ereg, $email, $match)) { + $emailAddressList['to'][] = array($match[3], $match[1]); + } else { + $emailAddressList['to'][] = array($email, ''); + } + } + break; + } + } + } + } + return $emailAddressList; + } + + /** + * Get the type of a variable + * Returns the type of the PHP variable var. + * + * @author Erik A. Ortiz. + * @return (string) type of variable + */ + public function gettype($var) + { + switch ($var) { + case is_null($var): + $type='NULL'; + break; + case is_bool($var): + $type='boolean'; + break; + case is_float($var): + $type='double'; + break; + case is_int($var): + $type='integer'; + break; + case is_string($var): + $type='string'; + break; + case is_array($var): + $type='array'; + break; + case is_object($var): + $type='object'; + break; + case is_resource($var): + $type='resource'; + break; + default: + $type='unknown type'; + break; + } + return $type; + } + + public function removeComments($buffer) + { + /* remove comments */ + $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); + /* remove tabs, spaces, newlines, etc. */ + $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); + return $buffer; + } + + public function getMemoryUsage() + { + $size = memory_get_usage(true); + $unit=array('B','Kb','Mb','Gb','Tb','Pb'); + return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; + } + + public function getFormatUserList($format, $aUserInfo) + { + switch ($format) { + case '@firstName @lastName': + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $format); + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser); + break; + case '@firstName @lastName (@userName)': + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $format); + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser); + $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $infoUser); + break; + case '@userName': + $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $format); + break; + case '@userName (@firstName @lastName)': + $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $format); + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser); + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $infoUser); + break; + case '@lastName @firstName': + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format); + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser); + break; + case '@lastName, @firstName': + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format); + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser); + break; + case '@lastName, @firstName (@userName)': + $infoUser = str_replace('@lastName', $aUserInfo['USR_LASTNAME'], $format); + $infoUser = str_replace('@firstName', $aUserInfo['USR_FIRSTNAME'], $infoUser); + $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], $infoUser); + break; + default: + $infoUser = str_replace('@userName', $aUserInfo['USR_USERNAME'], '@userName'); + break; + } + return $infoUser; + } + + //public function getModel($model) + //{ + // require_once "classes/model/$model.php"; + // return new $model(); + //} + + /** + * Recursive Is writeable function + * + * @author Erik Amaru Ortiz + * + * @param $path path to scan recursively the write permission + * @param $pattern pattern to filter some specified files + * @return if the $path, assuming that is a directory -> all files in it are writeables or not + */ + public function is_rwritable($path, $pattern = '*') + { + $files = G::rglob($pattern, 0, $path); + foreach ($files as $file) { + if (! is_writable($file)) { + return false; + } + } + return true; + } + + /** + * Recursive version of glob php standard function + * + * @author Erik Amaru Ortiz + * + * @param $path path to scan recursively the write permission + * @param $flags to notive glob function + * @param $pattern pattern to filter some specified files + * @return array containing the recursive glob results + */ + public static function rglob($pattern = '*', $flags = 0, $path = '') + { + $paths = glob($path.'*', GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT); + $files = glob($path.$pattern, $flags); + foreach ($paths as $path) { + $files = array_merge($files, G::rglob($pattern, $flags, $path)); + } + return $files; + } + + public function browser_detection($which_test, $test_excludes = '', $external_ua_string = '') + { + G::script_time(); // set script timer to start timing + + static $a_full_assoc_data, $a_mobile_data, $a_moz_data, $a_webkit_data, $b_dom_browser, $b_repeat, $b_safe_browser, $browser_name, $browser_number, $browser_math_number, $browser_user_agent, $browser_working, $ie_version, $mobile_test, $moz_number, $moz_rv, $moz_rv_full, $moz_release_date, $moz_type, $os_number, $os_type, $true_ie_number, $ua_type, $webkit_type, $webkit_type_number; + + // switch off the optimization for external ua string testing. + if ( $external_ua_string ) { + $b_repeat = false; + } + + /* + this makes the test only run once no matter how many times you call it since + all the variables are filled on the first run through, it's only a matter of + returning the the right ones + */ + if ( !$b_repeat ) { + //initialize all variables with default values to prevent error + $a_browser_math_number = ''; + $a_full_assoc_data = ''; + $a_full_data = ''; + $a_mobile_data = ''; + $a_moz_data = ''; + $a_os_data = ''; + $a_unhandled_browser = ''; + $a_webkit_data = ''; + $b_dom_browser = false; + $b_os_test = true; + $b_mobile_test = true; + $b_safe_browser = false; + $b_success = false;// boolean for if browser found in main test + $browser_math_number = ''; + $browser_temp = ''; + $browser_working = ''; + $browser_number = ''; + $ie_version = ''; + $mobile_test = ''; + $moz_release_date = ''; + $moz_rv = ''; + $moz_rv_full = ''; + $moz_type = ''; + $moz_number = ''; + $os_number = ''; + $os_type = ''; + $run_time = ''; + $true_ie_number = ''; + $ua_type = 'bot';// default to bot since you never know with bots + $webkit_type = ''; + $webkit_type_number = ''; + + // set the excludes if required + if ( $test_excludes ) { + switch ( $test_excludes ){ + case '1': + $b_os_test = false; + break; + case '2': + $b_mobile_test = false; + break; + case '3': + $b_os_test = false; + $b_mobile_test = false; + break; + default: + die( 'Error: bad $test_excludes parameter 2 used: ' . $test_excludes ); + break; + } + } + + /* + make navigator user agent string lower case to make sure all versions get caught + isset protects against blank user agent failure. tolower also lets the script use + strstr instead of stristr, which drops overhead slightly. + */ + if ( $external_ua_string ) { + $browser_user_agent = strtolower( $external_ua_string ); + } elseif ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { + $browser_user_agent = strtolower( $_SERVER['HTTP_USER_AGENT'] ); + } else { + $browser_user_agent = ''; + } + + // known browsers, list will be updated routinely, check back now and then + $a_browser_types = array( + array( 'opera', true, 'op', 'bro' ), + array( 'msie', true, 'ie', 'bro' ), + // webkit before gecko because some webkit ua strings say: like gecko + array( 'webkit', true, 'webkit', 'bro' ), + // konq will be using webkit soon + array( 'konqueror', true, 'konq', 'bro' ), + // covers Netscape 6-7, K-Meleon, Most linux versions, uses moz array below + array( 'gecko', true, 'moz', 'bro' ), + array( 'netpositive', false, 'netp', 'bbro' ),// beos browser + array( 'lynx', false, 'lynx', 'bbro' ), // command line browser + array( 'elinks ', false, 'elinks', 'bbro' ), // new version of links + array( 'elinks', false, 'elinks', 'bbro' ), // alternate id for it + array( 'links2', false, 'links2', 'bbro' ), // alternate links version + array( 'links ', false, 'links', 'bbro' ), // old name for links + array( 'links', false, 'links', 'bbro' ), // alternate id for it + array( 'w3m', false, 'w3m', 'bbro' ), // open source browser, more features than lynx/links + array( 'webtv', false, 'webtv', 'bbro' ),// junk ms webtv + array( 'amaya', false, 'amaya', 'bbro' ),// w3c browser + array( 'dillo', false, 'dillo', 'bbro' ),// linux browser, basic table support + array( 'ibrowse', false, 'ibrowse', 'bbro' ),// amiga browser + array( 'icab', false, 'icab', 'bro' ),// mac browser + array( 'crazy browser', true, 'ie', 'bro' ),// uses ie rendering engine + + // search engine spider bots: + array( 'bingbot', false, 'bing', 'bot' ),// bing + array( 'exabot', false, 'exabot', 'bot' ),// exabot + array( 'googlebot', false, 'google', 'bot' ),// google + array( 'google web preview', false, 'googlewp', 'bot' ),// google preview + array( 'mediapartners-google', false, 'adsense', 'bot' ),// google adsense + array( 'yahoo-verticalcrawler', false, 'yahoo', 'bot' ),// old yahoo bot + array( 'yahoo! slurp', false, 'yahoo', 'bot' ), // new yahoo bot + array( 'yahoo-mm', false, 'yahoomm', 'bot' ), // gets Yahoo-MMCrawler and Yahoo-MMAudVid bots + array( 'inktomi', false, 'inktomi', 'bot' ), // inktomi bot + array( 'slurp', false, 'inktomi', 'bot' ), // inktomi bot + array( 'fast-webcrawler', false, 'fast', 'bot' ),// Fast AllTheWeb + array( 'msnbot', false, 'msn', 'bot' ),// msn search + array( 'ask jeeves', false, 'ask', 'bot' ), //jeeves/teoma + array( 'teoma', false, 'ask', 'bot' ),//jeeves teoma + array( 'scooter', false, 'scooter', 'bot' ),// altavista + array( 'openbot', false, 'openbot', 'bot' ),// openbot, from taiwan + array( 'ia_archiver', false, 'ia_archiver', 'bot' ),// ia archiver + array( 'zyborg', false, 'looksmart', 'bot' ),// looksmart + array( 'almaden', false, 'ibm', 'bot' ),// ibm almaden web crawler + array( 'baiduspider', false, 'baidu', 'bot' ),// Baiduspider asian search spider + array( 'psbot', false, 'psbot', 'bot' ),// psbot image crawler + array( 'gigabot', false, 'gigabot', 'bot' ),// gigabot crawler + array( 'naverbot', false, 'naverbot', 'bot' ),// naverbot crawler, bad bot, block + array( 'surveybot', false, 'surveybot', 'bot' ),// + array( 'boitho.com-dc', false, 'boitho', 'bot' ),//norwegian search engine + array( 'objectssearch', false, 'objectsearch', 'bot' ),// open source search engine + array( 'answerbus', false, 'answerbus', 'bot' ),// http://www.answerbus.com/, web questions + array( 'sohu-search', false, 'sohu', 'bot' ),// chinese media company, search component + array( 'iltrovatore-setaccio', false, 'il-set', 'bot' ), + + // various http utility libaries + array( 'w3c_validator', false, 'w3c', 'lib' ), // uses libperl, make first + array( 'wdg_validator', false, 'wdg', 'lib' ), // + array( 'libwww-perl', false, 'libwww-perl', 'lib' ), + array( 'jakarta commons-httpclient', false, 'jakarta', 'lib' ), + array( 'python-urllib', false, 'python-urllib', 'lib' ), + // download apps + array( 'getright', false, 'getright', 'dow' ), + array( 'wget', false, 'wget', 'dow' ),// open source downloader, obeys robots.txt + // netscape 4 and earlier tests, put last so spiders don't get caught + array( 'mozilla/4.', false, 'ns', 'bbro' ), + array( 'mozilla/3.', false, 'ns', 'bbro' ), + array( 'mozilla/2.', false, 'ns', 'bbro' ) + ); + + //array( '', false ); // browser array template + + /* + moz types array + note the order, netscape6 must come before netscape, which is how netscape 7 id's itself. + rv comes last in case it is plain old mozilla. firefox/netscape/seamonkey need to be later + Thanks to: http://www.zytrax.com/tech/web/firefox-history.html + */ + $a_moz_types = array( 'bonecho', 'camino', 'epiphany', 'firebird', 'flock', 'galeon', 'iceape', 'icecat', 'k-meleon', 'minimo', 'multizilla', 'phoenix', 'songbird', 'swiftfox', 'seamonkey', 'shiretoko', 'iceweasel', 'firefox', 'minefield', 'netscape6', 'netscape', 'rv' ); + + /* + webkit types, this is going to expand over time as webkit browsers spread + konqueror is probably going to move to webkit, so this is preparing for that + It will now default to khtml. gtklauncher is the temp id for epiphany, might + change. Defaults to applewebkit, and will all show the webkit number. + */ + $a_webkit_types = array( 'arora', 'chrome', 'epiphany', 'gtklauncher', 'konqueror', 'midori', 'omniweb', 'safari', 'uzbl', 'applewebkit', 'webkit' ); + + /* + run through the browser_types array, break if you hit a match, if no match, assume old browser + or non dom browser, assigns false value to $b_success. + */ + $i_count = count( $a_browser_types ); + for ($i = 0; $i < $i_count; $i++) { + //unpacks browser array, assigns to variables, need to not assign til found in string + $browser_temp = $a_browser_types[$i][0];// text string to id browser from array + + if ( strstr( $browser_user_agent, $browser_temp ) ) { + /* + it defaults to true, will become false below if needed + this keeps it easier to keep track of what is safe, only + explicit false assignment will make it false. + */ + $b_safe_browser = true; + $browser_name = $browser_temp;// text string to id browser from array + + // assign values based on match of user agent string + $b_dom_browser = $a_browser_types[$i][1];// hardcoded dom support from array + $browser_working = $a_browser_types[$i][2];// working name for browser + $ua_type = $a_browser_types[$i][3];// sets whether bot or browser + + switch ( $browser_working ) { + // this is modified quite a bit, now will return proper netscape version number + // check your implementation to make sure it works + case 'ns': + $b_safe_browser = false; + $browser_number = G::get_item_version( $browser_user_agent, 'mozilla' ); + break; + case 'moz': + /* + note: The 'rv' test is not absolute since the rv number is very different on + different versions, for example Galean doesn't use the same rv version as Mozilla, + neither do later Netscapes, like 7.x. For more on this, read the full mozilla + numbering conventions here: http://www.mozilla.org/releases/cvstags.html + */ + // this will return alpha and beta version numbers, if present + $moz_rv_full = G::get_item_version( $browser_user_agent, 'rv' ); + // this slices them back off for math comparisons + $moz_rv = substr( $moz_rv_full, 0, 3 ); + + // this is to pull out specific mozilla versions, firebird, netscape etc.. + $j_count = count( $a_moz_types ); + for ($j = 0; $j < $j_count; $j++) { + if ( strstr( $browser_user_agent, $a_moz_types[$j] ) ) { + $moz_type = $a_moz_types[$j]; + $moz_number = G::get_item_version( $browser_user_agent, $moz_type ); + break; + } + } + /* + this is necesary to protect against false id'ed moz'es and new moz'es. + this corrects for galeon, or any other moz browser without an rv number + */ + if ( !$moz_rv ) { + // you can use this if you are running php >= 4.2 + if ( function_exists( 'floatval' ) ) { + $moz_rv = floatval( $moz_number ); + } else { + $moz_rv = substr( $moz_number, 0, 3 ); + } + $moz_rv_full = $moz_number; + } + // this corrects the version name in case it went to the default 'rv' for the test + if ( $moz_type == 'rv' ) { + $moz_type = 'mozilla'; + } + + //the moz version will be taken from the rv number, see notes above for rv problems + $browser_number = $moz_rv; + // gets the actual release date, necessary if you need to do functionality tests + G::get_set_count( 'set', 0 ); + $moz_release_date = G::get_item_version( $browser_user_agent, 'gecko/' ); + /* + Test for mozilla 0.9.x / netscape 6.x + test your javascript/CSS to see if it works in these mozilla releases, if it + does, just default it to: $b_safe_browser = true; + */ + if ( ( $moz_release_date < 20020400 ) || ( $moz_rv < 1 ) ) { + $b_safe_browser = false; + } + break; + case 'ie': + /* + note we're adding in the trident/ search to return only first instance in case + of msie 8, and we're triggering the break last condition in the test, as well + as the test for a second search string, trident/ + */ + $browser_number = G::get_item_version( $browser_user_agent, $browser_name, true, 'trident/' ); + // construct the proper real number if it's in compat mode and msie 8.0/9.0 + if ( strstr( $browser_number, '7.' ) && strstr( $browser_user_agent, 'trident/5' ) ) { + // note that 7.0 becomes 9 when adding 1, but if it's 7.1 it will be 9.1 + $true_ie_number = $browser_number + 2; + } elseif ( strstr( $browser_number, '7.' ) && strstr( $browser_user_agent, 'trident/4' ) ) { + // note that 7.0 becomes 8 when adding 1, but if it's 7.1 it will be 8.1 + $true_ie_number = $browser_number + 1; + } + // the 9 series is finally standards compatible, html 5 etc, so worth a new id + if ( $browser_number >= 9 ) { + $ie_version = 'ie9x'; + } elseif ( $browser_number >= 7 ) { + $ie_version = 'ie7x'; + } elseif ( strstr( $browser_user_agent, 'mac') ) { + $ie_version = 'ieMac'; + } elseif ( $browser_number >= 5 ) { + $ie_version = 'ie5x'; + } elseif ( ( $browser_number > 3 ) && ( $browser_number < 5 ) ) { + $b_dom_browser = false; + $ie_version = 'ie4'; + // this depends on what you're using the script for, make sure this fits your needs + $b_safe_browser = true; + } else { + $ie_version = 'old'; + $b_dom_browser = false; + $b_safe_browser = false; + } + break; + case 'op': + $browser_number = G::get_item_version( $browser_user_agent, $browser_name ); + // opera is leaving version at 9.80 (or xx) for 10.x - see this for explanation + // http://dev.opera.com/articles/view/opera-ua-string-changes/ + if ( strstr( $browser_number, '9.' ) && strstr( $browser_user_agent, 'version/' ) ) { + G::get_set_count( 'set', 0 ); + $browser_number = G::get_item_version( $browser_user_agent, 'version/' ); + } + + if ( $browser_number < 5 ) { + $b_safe_browser = false; + } + break; + case 'webkit': + // note that this is the Webkit version number + $browser_number = G::get_item_version( $browser_user_agent, $browser_name ); + // this is to pull out specific webkit versions, safari, google-chrome etc.. + $j_count = count( $a_webkit_types ); + for ($j = 0; $j < $j_count; $j++) { + if (strstr( $browser_user_agent, $a_webkit_types[$j])) { + $webkit_type = $a_webkit_types[$j]; + if ( $webkit_type == 'omniweb' ) { + G::get_set_count( 'set', 2 ); + } + $webkit_type_number = G::get_item_version( $browser_user_agent, $webkit_type ); + // epiphany hack + if ( $a_webkit_types[$j] == 'gtklauncher' ) { + $browser_name = 'epiphany'; + } else { + $browser_name = $a_webkit_types[$j]; + } + break; + } + } + break; + default: + $browser_number = G::get_item_version( $browser_user_agent, $browser_name ); + break; + } + // the browser was id'ed + $b_success = true; + break; + } + } + + //assigns defaults if the browser was not found in the loop test + if ( !$b_success ) { + /* + this will return the first part of the browser string if the above id's failed + usually the first part of the browser string has the navigator useragent name/version in it. + This will usually correctly id the browser and the browser number if it didn't get + caught by the above routine. + If you want a '' to do a if browser == '' type test, just comment out all lines below + except for the last line, and uncomment the last line. If you want undefined values, + the browser_name is '', you can always test for that + */ + // delete this part if you want an unknown browser returned + $browser_name = substr( $browser_user_agent, 0, strcspn( $browser_user_agent , '();') ); + // this extracts just the browser name from the string, if something usable was found + if ( $browser_name && preg_match( '/[^0-9][a-z]*-*\ *[a-z]*\ *[a-z]*/', $browser_name, $a_unhandled_browser ) ) { + $browser_name = $a_unhandled_browser[0]; + if ( $browser_name == 'blackberry' ) { + G::get_set_count( 'set', 0 ); + } + $browser_number = G::get_item_version( $browser_user_agent, $browser_name ); + } else { + $browser_name = 'NA'; + $browser_number = 'NA'; + } + } + // get os data, mac os x test requires browser/version information, this is a change from older scripts + if ($b_os_test) { + $a_os_data = G::get_os_data( $browser_user_agent, $browser_working, $browser_number ); + $os_type = $a_os_data[0];// os name, abbreviated + $os_number = $a_os_data[1];// os number or version if available + } + /* + this ends the run through once if clause, set the boolean + to true so the function won't retest everything + */ + $b_repeat = true; + if ($browser_number && preg_match( '/[0-9]*\.*[0-9]*/', $browser_number, $a_browser_math_number ) ) { + $browser_math_number = $a_browser_math_number[0]; + } + if ( $b_mobile_test ) { + $mobile_test = G::check_is_mobile( $browser_user_agent ); + if ( $mobile_test ) { + $a_mobile_data = G::get_mobile_data( $browser_user_agent ); + $ua_type = 'mobile'; + } + } + } + + switch ($which_test) { + case 'math_number': + $which_test = 'browser_math_number'; + break; + case 'number': + $which_test = 'browser_number'; + break; + case 'browser': + $which_test = 'browser_working'; + break; + case 'moz_version': + $which_test = 'moz_data'; + break; + case 'true_msie_version': + $which_test = 'true_ie_number'; + break; + case 'type': + $which_test = 'ua_type'; + break; + case 'webkit_version': + $which_test = 'webkit_data'; + break; + } + /* + assemble these first so they can be included in full return data, using static variables + Note that there's no need to keep repacking these every time the script is called + */ + if (!$a_moz_data) { + $a_moz_data = array( $moz_type, $moz_number, $moz_rv, $moz_rv_full, $moz_release_date ); + } + if (!$a_webkit_data) { + $a_webkit_data = array( $webkit_type, $webkit_type_number, $browser_number ); + } + $run_time = G::script_time(); + + if ( !$a_full_assoc_data ) { + $a_full_assoc_data = array( + 'browser_working' => $browser_working, + 'browser_number' => $browser_number, + 'ie_version' => $ie_version, + 'dom' => $b_dom_browser, + 'safe' => $b_safe_browser, + 'os' => $os_type, + 'os_number' => $os_number, + 'browser_name' => $browser_name, + 'ua_type' => $ua_type, + 'browser_math_number' => $browser_math_number, + 'moz_data' => $a_moz_data, + 'webkit_data' => $a_webkit_data, + 'mobile_test' => $mobile_test, + 'mobile_data' => $a_mobile_data, + 'true_ie_number' => $true_ie_number, + 'run_time' => $run_time + ); + } + + // return parameters, either full data arrays, or by associative array index key + switch ($which_test) { + // returns all relevant browser information in an array with standard numberic indexes + case 'full': + $a_full_data = array( + $browser_working, + $browser_number, + $ie_version, + $b_dom_browser, + $b_safe_browser, + $os_type, + $os_number, + $browser_name, + $ua_type, + $browser_math_number, + $a_moz_data, + $a_webkit_data, + $mobile_test, + $a_mobile_data, + $true_ie_number, + $run_time + ); + return $a_full_data; + break; + case 'full_assoc': + return $a_full_assoc_data; + break; + default: + # check to see if the data is available, otherwise it's user typo of unsupported option + if (isset( $a_full_assoc_data[$which_test])) { + return $a_full_assoc_data[$which_test]; + } else { + die( "You passed the browser detector an unsupported option for parameter 1: " . $which_test ); + } + break; + } + } + + // gets which os from the browser string + public function get_os_data ($pv_browser_string, $pv_browser_name, $pv_version_number) + { + // initialize variables + $os_working_type = ''; + $os_working_number = ''; + /* + packs the os array. Use this order since some navigator user agents will put 'macintosh' + in the navigator user agent string which would make the nt test register true + */ + $a_mac = array( 'intel mac', 'ppc mac', 'mac68k' );// this is not used currently + // same logic, check in order to catch the os's in order, last is always default item + $a_unix_types = array( 'dragonfly', 'freebsd', 'openbsd', 'netbsd', 'bsd', 'unixware', 'solaris', 'sunos', 'sun4', 'sun5', 'suni86', 'sun', 'irix5', 'irix6', 'irix', 'hpux9', 'hpux10', 'hpux11', 'hpux', 'hp-ux', 'aix1', 'aix2', 'aix3', 'aix4', 'aix5', 'aix', 'sco', 'unixware', 'mpras', 'reliant', 'dec', 'sinix', 'unix' ); + // only sometimes will you get a linux distro to id itself... + $a_linux_distros = array( 'ubuntu', 'kubuntu', 'xubuntu', 'mepis', 'xandros', 'linspire', 'winspire', 'jolicloud', 'sidux', 'kanotix', 'debian', 'opensuse', 'suse', 'fedora', 'redhat', 'slackware', 'slax', 'mandrake', 'mandriva', 'gentoo', 'sabayon', 'linux' ); + $a_linux_process = array ( 'i386', 'i586', 'i686' );// not use currently + // note, order of os very important in os array, you will get failed ids if changed + $a_os_types = array( 'android', 'blackberry', 'iphone', 'palmos', 'palmsource', 'symbian', 'beos', 'os2', 'amiga', 'webtv', 'mac', 'nt', 'win', $a_unix_types, $a_linux_distros ); + + //os tester + $i_count = count( $a_os_types ); + for ($i = 0; $i < $i_count; $i++) { + // unpacks os array, assigns to variable $a_os_working + $os_working_data = $a_os_types[$i]; + /* + assign os to global os variable, os flag true on success + !strstr($pv_browser_string, "linux" ) corrects a linux detection bug + */ + if (!is_array($os_working_data) && strstr($pv_browser_string, $os_working_data ) && !strstr( $pv_browser_string, "linux")) { + $os_working_type = $os_working_data; + + switch ($os_working_type) { + // most windows now uses: NT X.Y syntax + case 'nt': + if (strstr( $pv_browser_string, 'nt 6.1' )) { + $os_working_number = 6.1; + } elseif (strstr( $pv_browser_string, 'nt 6.0')) { + $os_working_number = 6.0; + } elseif (strstr( $pv_browser_string, 'nt 5.2')) { + $os_working_number = 5.2; + } elseif (strstr( $pv_browser_string, 'nt 5.1') || strstr( $pv_browser_string, 'xp')) { + $os_working_number = 5.1;// + } elseif (strstr( $pv_browser_string, 'nt 5') || strstr( $pv_browser_string, '2000')) { + $os_working_number = 5.0; + } elseif (strstr( $pv_browser_string, 'nt 4')) { + $os_working_number = 4; + } elseif (strstr( $pv_browser_string, 'nt 3')) { + $os_working_number = 3; + } + break; + case 'win': + if (strstr( $pv_browser_string, 'vista')) { + $os_working_number = 6.0; + $os_working_type = 'nt'; + } elseif ( strstr( $pv_browser_string, 'xp')) { + $os_working_number = 5.1; + $os_working_type = 'nt'; + } elseif ( strstr( $pv_browser_string, '2003')) { + $os_working_number = 5.2; + $os_working_type = 'nt'; + } + elseif ( strstr( $pv_browser_string, 'windows ce' ) )// windows CE + { + $os_working_number = 'ce'; + $os_working_type = 'nt'; + } + elseif ( strstr( $pv_browser_string, '95' ) ) + { + $os_working_number = '95'; + } + elseif ( ( strstr( $pv_browser_string, '9x 4.9' ) ) || ( strstr( $pv_browser_string, ' me' ) ) ) + { + $os_working_number = 'me'; + } + elseif ( strstr( $pv_browser_string, '98' ) ) + { + $os_working_number = '98'; + } + elseif ( strstr( $pv_browser_string, '2000' ) )// windows 2000, for opera ID + { + $os_working_number = 5.0; + $os_working_type = 'nt'; + } + break; + case 'mac': + if (strstr($pv_browser_string, 'os x')) { + if (strstr($pv_browser_string, 'os x ')) { + $os_working_number = str_replace( '_', '.', G::get_item_version( $pv_browser_string, 'os x' ) ); + } else { + $os_working_number = 10; + } + } elseif ( ( $pv_browser_name == 'saf' ) || ( $pv_browser_name == 'cam' ) || + ( ( $pv_browser_name == 'moz' ) && ( $pv_version_number >= 1.3 ) ) || + ( ( $pv_browser_name == 'ie' ) && ( $pv_version_number >= 5.2 ) ) ) { + $os_working_number = 10; + } + break; + case 'iphone': + $os_working_number = 10; + break; + default: + break; + } + break; + } elseif ( is_array( $os_working_data ) && ( $i == ( $i_count - 2 ) ) ) { + $j_count = count($os_working_data); + for ($j = 0; $j < $j_count; $j++) { + if (strstr( $pv_browser_string, $os_working_data[$j])) { + $os_working_type = 'unix'; //if the os is in the unix array, it's unix, obviously... + $os_working_number = ( $os_working_data[$j] != 'unix' ) ? $os_working_data[$j] : '';// assign sub unix version from the unix array + break; + } + } + } elseif (is_array( $os_working_data ) && ( $i == ( $i_count - 1 ))) { + $j_count = count($os_working_data); + for ($j = 0; $j < $j_count; $j++) { + if ( strstr( $pv_browser_string, $os_working_data[$j] )) { + $os_working_type = 'lin'; + // assign linux distro from the linux array, there's a default + //search for 'lin', if it's that, set version to '' + $os_working_number = ( $os_working_data[$j] != 'linux' ) ? $os_working_data[$j] : ''; + break; + } + } + } + } + + // pack the os data array for return to main function + $a_os_data = array( $os_working_type, $os_working_number ); + + return $a_os_data; + } + + public function get_item_version($pv_browser_user_agent, $pv_search_string, $pv_b_break_last = '', $pv_extra_search = '') + { + $substring_length = 15; + $start_pos = 0; // set $start_pos to 0 for first iteration + $string_working_number = ''; + for ($i = 0; $i < 4; $i++) { + //start the search after the first string occurrence + if (strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) !== false) { + $start_pos = strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) + strlen( $pv_search_string ); + if (!$pv_b_break_last || ( $pv_extra_search && strstr( $pv_browser_user_agent, $pv_extra_search ) )) { + break; + } + } else { + break; + } + } + + $start_pos += G::get_set_count( 'get' ); + $string_working_number = substr( $pv_browser_user_agent, $start_pos, $substring_length ); + $string_working_number = substr( $string_working_number, 0, strcspn($string_working_number, ' );/') ); + if (!is_numeric( substr( $string_working_number, 0, 1 ))) { + $string_working_number = ''; + } + return $string_working_number; + } + + public function get_set_count($pv_type, $pv_value = '') + { + static $slice_increment; + $return_value = ''; + switch ( $pv_type ) { + case 'get': + if ( is_null( $slice_increment ) ) { + $slice_increment = 1; + } + $return_value = $slice_increment; + $slice_increment = 1; // reset to default + return $return_value; + break; + case 'set': + $slice_increment = $pv_value; + break; + } + } + + public function check_is_mobile($pv_browser_user_agent) + { + $mobile_working_test = ''; + $a_mobile_search = array( + 'android', 'epoc', 'linux armv', 'palmos', 'palmsource', 'windows ce', 'windows phone os', 'symbianos', 'symbian os', 'symbian', 'webos', + // devices - ipod before iphone or fails + 'benq', 'blackberry', 'danger hiptop', 'ddipocket', ' droid', 'ipad', 'ipod', 'iphone', 'kindle', 'lge-cx', 'lge-lx', 'lge-mx', 'lge vx', 'lge ', 'lge-', 'lg;lx', 'nintendo wii', 'nokia', 'palm', 'pdxgw', 'playstation', 'sagem', 'samsung', 'sec-sgh', 'sharp', 'sonyericsson', 'sprint', 'zune', 'j-phone', 'n410', 'mot 24', 'mot-', 'htc-', 'htc_', 'htc ', 'sec-', 'sie-m', 'sie-s', 'spv ', 'vodaphone', 'smartphone', 'armv', 'midp', 'mobilephone', + // browsers + 'avantgo', 'blazer', 'elaine', 'eudoraweb', 'iemobile', 'minimo', 'mobile safari', 'mobileexplorer', 'opera mobi', 'opera mini', 'netfront', 'opwv', 'polaris', 'semc-browser', 'up.browser', 'webpro', 'wms pie', 'xiino', + // services - astel out of business + 'astel', 'docomo', 'novarra-vision', 'portalmmm', 'reqwirelessweb', 'vodafone' + ); + + // then do basic mobile type search, this uses data from: get_mobile_data() + $j_count = count( $a_mobile_search ); + for ($j = 0; $j < $j_count; $j++) { + if (strstr( $pv_browser_user_agent, $a_mobile_search[$j] )) { + $mobile_working_test = $a_mobile_search[$j]; + break; + } + } + return $mobile_working_test; + } + + public function get_mobile_data ($pv_browser_user_agent) + { + $mobile_browser = ''; + $mobile_browser_number = ''; + $mobile_device = ''; + $mobile_device_number = ''; + $mobile_os = ''; // will usually be null, sorry + $mobile_os_number = ''; + $mobile_server = ''; + $mobile_server_number = ''; + + $a_mobile_browser = array( 'avantgo', 'blazer', 'elaine', 'eudoraweb', 'iemobile', 'minimo', 'mobile safari', 'mobileexplorer', 'opera mobi', 'opera mini', 'netfront', 'opwv', 'polaris', 'semc-browser', 'up.browser', 'webpro', 'wms pie', 'xiino' ); + $a_mobile_device = array( 'benq', 'blackberry', 'danger hiptop', 'ddipocket', ' droid', 'htc_dream', 'htc espresso', 'htc hero', 'htc halo', 'htc huangshan', 'htc legend', 'htc liberty', 'htc paradise', 'htc supersonic', 'htc tattoo', 'ipad', 'ipod', 'iphone', 'kindle', 'lge-cx', 'lge-lx', 'lge-mx', 'lge vx', 'lg;lx', 'nintendo wii', 'nokia', 'palm', 'pdxgw', 'playstation', 'sagem', 'samsung', 'sec-sgh', 'sharp', 'sonyericsson', 'sprint', 'zunehd', 'zune', 'j-phone', 'milestone', 'n410', 'mot 24', 'mot-', 'htc-', 'htc_', 'htc ', 'lge ', 'lge-', 'sec-', 'sie-m', 'sie-s', 'spv ', 'smartphone', 'armv', 'midp', 'mobilephone' ); + $a_mobile_os = array( 'android', 'epoc', 'cpu os', 'iphone os', 'palmos', 'palmsource', 'windows phone os', 'windows ce', 'symbianos', 'symbian os', 'symbian', 'webos', 'linux armv' ); + $a_mobile_server = array( 'astel', 'docomo', 'novarra-vision', 'portalmmm', 'reqwirelessweb', 'vodafone' ); + + $k_count = count( $a_mobile_browser ); + for ($k = 0; $k < $k_count; $k++) { + if (strstr( $pv_browser_user_agent, $a_mobile_browser[$k] )) { + $mobile_browser = $a_mobile_browser[$k]; + $mobile_browser_number = G::get_item_version( $pv_browser_user_agent, $mobile_browser ); + break; + } + } + $k_count = count( $a_mobile_device ); + for ($k = 0; $k < $k_count; $k++) { + if (strstr( $pv_browser_user_agent, $a_mobile_device[$k] )) { + $mobile_device = trim ( $a_mobile_device[$k], '-_' ); // but not space trims yet + if ($mobile_device == 'blackberry') { + G::get_set_count( 'set', 0 ); + } + $mobile_device_number = G::get_item_version( $pv_browser_user_agent, $mobile_device ); + $mobile_device = trim( $mobile_device ); // some of the id search strings have white space + break; + } + } + $k_count = count( $a_mobile_os ); + for ($k = 0; $k < $k_count; $k++) { + if (strstr( $pv_browser_user_agent, $a_mobile_os[$k] )) { + $mobile_os = $a_mobile_os[$k]; + $mobile_os_number = str_replace( '_', '.', G::get_item_version( $pv_browser_user_agent, $mobile_os ) ); + break; + } + } + $k_count = count( $a_mobile_server ); + for ($k = 0; $k < $k_count; $k++) { + if (strstr( $pv_browser_user_agent, $a_mobile_server[$k] )) { + $mobile_server = $a_mobile_server[$k]; + $mobile_server_number = G::get_item_version( $pv_browser_user_agent, $mobile_server ); + break; + } + } + // just for cases where we know it's a mobile device already + if (!$mobile_os && ( $mobile_browser || $mobile_device || $mobile_server ) && strstr( $pv_browser_user_agent, 'linux' ) ) { + $mobile_os = 'linux'; + $mobile_os_number = G::get_item_version( $pv_browser_user_agent, 'linux' ); + } + + $a_mobile_data = array( $mobile_device, $mobile_browser, $mobile_browser_number, $mobile_os, $mobile_os_number, $mobile_server, $mobile_server_number, $mobile_device_number ); + return $a_mobile_data; + } + + public function getBrowser () + { + $u_agent = $_SERVER['HTTP_USER_AGENT']; + $bname = 'Unknown'; + $platform = 'Unknown'; + $version = ""; + $ub = "other"; + + //First get the platform? + if (preg_match( '/linux/i', $u_agent )) { + $platform = 'linux'; + } elseif (preg_match( '/macintosh|mac os x/i', $u_agent )) { + $platform = 'mac'; + } elseif (preg_match( '/windows|win32/i', $u_agent )) { + $platform = 'windows'; + } + + // Next get the name of the useragent yes seperately and for good reason + if ((preg_match('~Trident/7.0; rv:11.0~', $u_agent) || preg_match( '/MSIE/i', $u_agent )) && ! preg_match( '/Opera/i', $u_agent )) { + $bname = 'Internet Explorer'; + $ub = "MSIE"; + } elseif (preg_match( '/Firefox/i', $u_agent )) { + $bname = 'Mozilla Firefox'; + $ub = "Firefox"; + } elseif ((preg_match( '/Opera/i', $u_agent )) || (preg_match( '/OPR/i', $u_agent ))) { + $bname = 'Opera'; + $ub = "Opera"; + } elseif (preg_match( '/Chrome/i', $u_agent )) { + $bname = 'Google Chrome'; + $ub = "Chrome"; + } elseif (preg_match( '/Safari/i', $u_agent )) { + $bname = 'Apple Safari'; + $ub = "Safari"; + } elseif (preg_match( '/Netscape/i', $u_agent )) { + $bname = 'Netscape'; + $ub = "Netscape"; + } elseif (preg_match( '/bingbot/i', $u_agent )) { + $bname = 'Bing Bot'; + $ub = "bingbot"; + } + + // finally get the correct version number + $known = array ('Version',$ub,'other'); + $pattern = '#(?P' . join( '|', $known ) . ')[/ ]+(?P[0-9.|a-zA-Z.]*)#'; + @preg_match_all( $pattern, $u_agent, $matches ); + + // see how many we have + $i = count( $matches['browser'] ); + if ($i != 1) { + //we will have two since we are not using 'other' argument yet + //see if version is before or after the name + if (strripos( $u_agent, "Version" ) < strripos( $u_agent, $ub )) { + $version = $matches['version'][0]; + } else { + $version = isset($matches['version'][1]) ? $matches['version'][1] : ''; + } + } else { + $version = $matches['version'][0]; + } + + // check if we have a number + if ($version == null || $version == "") { + if($ub == 'MSIE'){ + $parent = 'RV'; + } elseif ($ub == 'Opera'){ + $parent = 'OPR'; + } + if (isset($parent) && $parent != ""){ + $s = strpos(strtoupper($u_agent), $parent); + $f = $s + strlen($parent); + $version = substr($u_agent, $f, 15); + $version = preg_replace('/[^0-9,.]/','',$version); + }else { + $version = "?"; + } + } + + return array ('userAgent' => $u_agent,'name' => strtolower( $ub ),'longName' => $bname,'version' => $version,'platform' => $platform,'pattern' => $pattern + ); + } + + // track total script execution time + public function script_time () + { + static $script_time; + $elapsed_time = ''; + /* + note that microtime(true) requires php 5 or greater for microtime(true) + */ + if (sprintf( "%01.1f", phpversion() ) >= 5) { + if (is_null( $script_time )) { + $script_time = microtime( true ); + } else { + // note: (string)$var is same as strval($var) + // $elapsed_time = (string)( microtime(true) - $script_time ); + $elapsed_time = (microtime( true ) - $script_time); + $elapsed_time = sprintf( "%01.8f", $elapsed_time ); + $script_time = null; // can't unset a static variable + return $elapsed_time; + } + } + } + + public function getDirectorySize ($path, $maxmtime = 0) + { + $totalsize = 0; + $totalcount = 0; + $dircount = 0; + if ($handle = opendir( $path )) { + while (false !== ($file = readdir( $handle ))) { + $nextpath = $path . '/' . $file; + if ($file != '.' && $file != '..' && ! is_link( $nextpath ) && $file != '.svn') { + if (is_dir( $nextpath )) { + $dircount ++; + $result = G::getDirectorySize( $nextpath, $maxmtime ); + $totalsize += $result['size']; + $totalcount += $result['count']; + $dircount += $result['dircount']; + $maxmtime = $result['maxmtime'] > $maxmtime ? $result['maxmtime'] : $maxmtime; + } elseif (is_file( $nextpath )) { + $totalsize += filesize( $nextpath ); + $totalcount ++; + + $mtime = filemtime( $nextpath ); + if ($mtime > $maxmtime) { + $maxmtime = $mtime; + } + } + } + } + } + closedir( $handle ); + $total['size'] = $totalsize; + $total['count'] = $totalcount; + $total['dircount'] = $dircount; + $total['maxmtime'] = $maxmtime; + + return $total; + } + + /** + * Get checksum from multiple files + * + * @author erik amaru ortiz + */ + public function getCacheFileNameByPattern ($path, $pattern) + { + if ($file = glob( $path . $pattern )) { + preg_match( '/[a-f0-9]{32}/', $file[0], $match ); + } else { + $file[0] = ''; + } + return array ('filename' => $file[0],'checksum' => (isset( $match[0] ) ? $match[0] : '')); + } + + /** + * Get checksum from multiple files + * + * @author erik amaru ortiz + */ + public function getCheckSum ($files) + { + G::LoadClass( 'system' ); + $key = System::getVersion(); + + if (! is_array( $files )) { + $tmp = $files; + $files = array (); + $files[0] = $tmp; + } + + $checkSum = ''; + foreach ($files as $file) { + if (is_file( $file )) { + $checkSum .= G::encryptFileOld( $file ); + } + } + return G::encryptOld( $checkSum . $key ); + } + + /** + * parse_ini_string + * Define parse_ini_string if it doesn't exist. + * Does accept lines starting with ; as comments + * Does not accept comments after values + */ + public function parse_ini_string ($string) + { + if (function_exists( 'parse_ini_string' )) { + return parse_ini_string( $string ); + } else { + $array = Array (); + $lines = explode( "\n", $string ); + + foreach ($lines as $line) { + $statement = preg_match( "/^(?!;)(?P[\w+\.\-]+?)\s*=\s*(?P.+?)\s*$/", $line, $match ); + if ($statement) { + $key = $match['key']; + $value = $match['value']; + + //Remove quote + if (preg_match( "/^\".*\"$/", $value ) || preg_match( "/^'.*'$/", $value )) { + $value = mb_substr( $value, 1, mb_strlen( $value ) - 2 ); + } + $array[$key] = $value; + } + } + return $array; + } + } + + /** + * disableEnableINIvariable + * disable or enable a variable in ini file, this is useful for editing the env.ini file + * automatically get the value, and change to inverse value, I mean from true to false and viceversa + */ + public function disableEnableINIvariable ($inifile, $variable) + { + $enabled = 'false'; + if (file_exists( $inifile )) { + $fp = fopen( $inifile, 'r' ); + $line = fgets( $fp ); + $found = false; + $buffer = null; + + while (! feof( $fp )) { + $config = G::parse_ini_string( $line ); + if (isset( $config[$variable] )) { + $enabled = $config[$variable]; + $buffer .= sprintf( "%s = %d \n", $variable, 1 - $enabled ); + $found = true; + } else { + $buffer .= trim( $line ) . "\n"; + } + $line = fgets( $fp ); + } + fclose( $fp ); + if (! $found) { + $buffer .= sprintf( "\n%s = 1 \n", $variable ); + } + @file_put_contents( $inifile, $buffer ); + } else { + $contents = file_put_contents( $inifile, sprintf( "\n%s = 1\n", $variable ) ); + } + } + + /** + * set a variable in ini file + */ + public function setINIvariable ($inifile, $variable, $value) + { + if (file_exists( $inifile )) { + $fp = fopen( $inifile, 'r' ); + $line = fgets( $fp ); + $found = false; + $buffer = null; + + while (! feof( $fp )) { + $config = G::parse_ini_string( $line ); + if (isset( $config[$variable] )) { + $enabled = $config[$variable]; + $buffer .= sprintf( "%s = %s \n", $variable, $value ); + $found = true; + } else { + $buffer .= trim( $line ) . "\n"; + } + $line = fgets( $fp ); + } + fclose( $fp ); + if (! $found) { + $buffer .= sprintf( "\n%s = %s \n", $variable, $value ); + } + file_put_contents( $inifile, $buffer ); + } else { + $contents = file_put_contents( $inifile, sprintf( "\n%s = $s\n", $variable, $value ) ); + } + } + + public function write_php_ini ($file, $array) + { + $res = array (); + foreach ($array as $key => $val) { + if (is_array( $val )) { + $res[] = "[$key]"; + foreach ($val as $skey => $sval) { + $res[] = "$skey = " . (is_numeric( $sval ) ? $sval : '"' . $sval . '"'); + } + } else { + $res[] = "$key = " . (is_numeric( $val ) ? $val : '"' . $val . '"'); + } + } + file_put_contents( $file, implode( "\r\n", $res ) ); + } + + /** + * verify if all files & directories passed by param. + * are writable + * + * @author Erik Amaru Ortiz + * @param $resources array a list of files to verify write access + */ + public function verifyWriteAccess ($resources) + { + $noWritable = array (); + foreach ($resources as $i => $resource) { + if (! is_writable( $resource )) { + $noWritable[] = $resource; + } + } + + if (count( $noWritable ) > 0) { + $e = new Exception( "Write access not allowed for ProcessMaker resources" ); + $e->files = $noWritable; + throw $e; + } + } + + /** + * render a smarty template + * + * @author Erik Amaru Ortiz + * @param $template string containing the template filename on /gulliver/templates/ directory + * @param $data associative array containig the template data + */ + public function renderTemplate ($template, $data = array()) + { + if (! defined( 'PATH_THIRDPARTY' )) { + throw new Exception( 'System constant (PATH_THIRDPARTY) is not defined!' ); + } + + require_once PATH_THIRDPARTY . 'smarty/libs/Smarty.class.php'; + $fInfo = pathinfo( $template ); + + $tplExists = true; + + // file has absolute path + if (strpos($template, PATH_TRUNK) === false) { + $template = PATH_TPL . $template; + } + + // fix for template that have dot in its name but is not a valid extension + if (isset( $fInfo['extension'] ) && ($fInfo['extension'] != 'tpl' || $fInfo['extension'] != 'html')) { + unset( $fInfo['extension'] ); + } + + if (! isset( $fInfo['extension'] )) { + if (file_exists( $template . '.tpl' )) { + $template .= '.tpl'; + } elseif (file_exists( $template . '.html' )) { + $template .= '.html'; + } else { + $tplExists = false; + } + } else { + if (! file_exists( $template )) { + $tplExists = false; + } + } + + if (! $tplExists) { + throw new Exception( "Template: $template, doesn't exist!" ); + } + + $smarty = new Smarty(); + $smarty->compile_dir = G::sys_get_temp_dir(); + $smarty->cache_dir = G::sys_get_temp_dir(); + $smarty->config_dir = PATH_THIRDPARTY . 'smarty/configs'; + + $smarty->template_dir = PATH_TEMPLATE; + $smarty->force_compile = true; + + foreach ($data as $key => $value) { + $smarty->assign( $key, $value ); + } + + $smarty->display( $template ); + } + + /** + * parse a smarty template and return teh result as string + * + * @author Erik Amaru Ortiz + * @param $template string containing the template filename on /gulliver/templates/ directory + * @param $data associative array containig the template data + * @return $content string containing the parsed template content + */ + public function parseTemplate ($template, $data = array()) + { + $content = ''; + + ob_start(); + G::renderTemplate( $template, $data ); + $content = ob_get_contents(); + ob_get_clean(); + + return $content; + } + + /** + * Update a ini file passing a array values, this function don't remove the original comments + * + * @author Erik Amaru Ortiz + * @licence GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html) + * + * @param $file string containing the ini file to update + * @param $array associative array containing the config data + */ + public function update_php_ini ($file, $array) + { + $iniLines = array (); + $iniContent = array (); + + if (file_exists( $file ) && ! is_writable( $file )) { + throw new Exception( "File $file, is not writable." ); + } + + if (file_exists( $file )) { + $iniContent = file( $file ); + } + + foreach ($iniContent as $line) { + $line = trim( $line ); + $lineParts = explode( ';', $line ); + $setting = G::parse_ini_string( $lineParts[0] ); + + if (is_array( $setting ) && count( $setting ) > 0) { + list ($key, ) = array_keys( $setting ); + + if (isset( $array[$key] )) { + $value = $array[$key]; + $line = "$key = " . (is_numeric( $value ) ? $value : '"' . $value . '"'); + $line .= isset( $lineParts[1] ) ? ' ;' . $lineParts[1] : ''; + unset( $array[$key] ); + + $lastComment = array_pop( $iniLines ); + if (strpos( $lastComment, "Setting $key" ) === false) { + $iniLines[] = $lastComment; + } + + $iniLines[] = ";Setting $key - Updated by System on " . date( 'D d M, Y H:i:s' ); + } + } + $iniLines[] = $line; + } + + // inserting new values + foreach ($array as $key => $value) { + $line = "$key = " . (is_numeric( $value ) ? $value : '"' . $value . '"'); + $iniLines[] = ''; + $iniLines[] = ";Setting $key - Created by System on " . date( 'D d M, Y H:i:s' ); + $iniLines[] = $line; + } + + $content = implode( "\r\n", $iniLines ); + + if (@file_put_contents( $file, $content ) === false) { + throw new Exception( "G::update_php_ini() -> can't update file: $file" ); + } else { + //first a raw permission check + if(fileperms($file) != 33200) { + @chmod ($file, 0660); + } + } + } + + /** + * recursive file & directories write permission detect + * + * @author Erik Amaru Ortiz + * @licence GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html) + * + * @param $path string of directory or file to verify recursively + * @param $noWritableFiles (alternative) array passed by reference to store all no-writable files + * @return bool true if all files inside a directory path are writable, false in another case + */ + public function is_writable_r ($path, &$noWritableFiles = array()) + { + if (is_writable( $path )) { + if (! is_dir( $path )) { + return true; + } + $list = glob( rtrim( $path, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . '*' ); + + $sw = true; + foreach ($list as $f) { + if (! G::is_writable_r( $f, $noWritableFiles )) { + $sw = false; + } + } + + return $sw; + } else { + if (! in_array( $path, $noWritableFiles )) { + $noWritableFiles[] = $path; + } + return false; + } + } + + /** + * This method allow dispatch rest services using 'Restler' thirdparty library + * + * @author Erik Amaru Ortiz + */ + public function dispatchRestService ($uri, $config, $apiClassesPath = '') + { + require_once 'restler/restler.php'; + + $rest = new Restler(); + $rest->setSupportedFormats( 'JsonFormat', 'XmlFormat' ); + // getting all services class + $restClasses = array (); + $restClassesList = G::rglob( '*', 0, PATH_CORE . 'services/' ); + foreach ($restClassesList as $classFile) { + if (substr( $classFile, - 4 ) === '.php') { + $restClasses[str_replace( '.php', '', basename( $classFile ) )] = $classFile; + } + } + if (! empty( $apiClassesPath )) { + $pluginRestClasses = array (); + $restClassesList = G::rglob( '*', 0, $apiClassesPath . 'services/' ); + foreach ($restClassesList as $classFile) { + if (substr( $classFile, - 4 ) === '.php') { + $pluginRestClasses[str_replace( '.php', '', basename( $classFile ) )] = $classFile; + } + } + $restClasses = array_merge( $restClasses, $pluginRestClasses ); + } + // hook to get rest api classes from plugins + if (class_exists( 'PMPluginRegistry' )) { + $pluginRegistry = & PMPluginRegistry::getSingleton(); + $pluginClasses = $pluginRegistry->getRegisteredRestClassFiles(); + $restClasses = array_merge( $restClasses, $pluginClasses ); + } + foreach ($restClasses as $key => $classFile) { + if (! file_exists( $classFile )) { + unset( $restClasses[$key] ); + continue; + } + //load the file, and check if exist the class inside it. + require_once $classFile; + $namespace = 'Services_Rest_'; + $className = str_replace( '.php', '', basename( $classFile ) ); + + // if the core class does not exists try resolve the for a plugin + if (! class_exists( $namespace . $className )) { + $namespace = 'Plugin_Services_Rest_'; + // Couldn't resolve the class name, just skipp it + if (! class_exists( $namespace . $className )) { + unset( $restClasses[$key] ); + continue; + } + } + // verify if there is an auth class implementing 'iAuthenticate' + $classNameAuth = $namespace . $className; + $reflClass = new ReflectionClass( $classNameAuth ); + // that wasn't from plugin + if ($reflClass->implementsInterface( 'iAuthenticate' ) && $namespace != 'Plugin_Services_Rest_') { + // auth class found, set as restler authentication class handler + $rest->addAuthenticationClass( $classNameAuth ); + } else { + // add api class + $rest->addAPIClass( $classNameAuth ); + } + } + //end foreach rest class + // resolving the class for current request + $uriPart = explode( '/', $uri ); + $requestedClass = ''; + if (isset( $uriPart[1] )) { + $requestedClass = ucfirst( $uriPart[1] ); + } + if (class_exists( 'Services_Rest_' . $requestedClass )) { + $namespace = 'Services_Rest_'; + } elseif (class_exists( 'Plugin_Services_Rest_' . $requestedClass )) { + $namespace = 'Plugin_Services_Rest_'; + } else { + $namespace = ''; + } + // end resolv. + // Send additional headers (if exists) configured on rest-config.ini + if (array_key_exists( 'HEADERS', $config )) { + foreach ($config['HEADERS'] as $name => $value) { + header( "$name: $value" ); + } + } + // to handle a request with "OPTIONS" method + if (! empty( $namespace ) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') { + $reflClass = new ReflectionClass( $namespace . $requestedClass ); + // if the rest class has not a "options" method + if (! $reflClass->hasMethod( 'options' )) { + header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEADERS' ); + header( 'Access-Control-Allow-Headers: authorization, content-type' ); + header( "Access-Control-Allow-Credentials", "false" ); + header( 'Access-Control-Max-Age: 60' ); + exit(); + } + } + // override global REQUEST_URI to pass to Restler library + $_SERVER['REQUEST_URI'] = '/' . strtolower( $namespace ) . ltrim( $uri, '/' ); + // handle the rest request + $rest->handle(); + } + + public function reservedWordsSql () + { + //Reserved words SQL + $reservedWordsSql = array ("ACCESSIBLE","ACTION","ADD","ALL","ALTER","ANALYZE","AND","ANY","AS","ASC","ASENSITIVE","AUTHORIZATION","BACKUP","BEFORE","BEGIN","BETWEEN","BIGINT","BINARY","BIT","BLOB","BOTH","BREAK","BROWSE","BULK","BY","CALL","CASCADE","CASE","CHANGE","CHAR","CHARACTER","CHECK","CHECKPOINT","CLOSE","CLUSTERED","COALESCE","COLLATE","COLUMN","COMMIT","COMPUTE","CONDITION","CONSTRAINT","CONTAINS","CONTAINSTABLE","CONTINUE","CONVERT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DATE","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DBCC","DEALLOCATE","DEC","DECIMAL","DECLARE","DEFAULT","DELAYED","DELETE","DENY","DESC","DESCRIBE","DETERMINISTIC","DISK","DISTINCT","DISTINCTROW", + "DISTRIBUTED","DIV","DOUBLE","DROP","DUAL","DUMMY","DUMP","EACH","ELSE","ELSEIF","ENCLOSED","END","ENUM","ERRLVL","ESCAPE","ESCAPED","EXCEPT","EXEC","EXECUTE","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FILE","FILLFACTOR","FLOAT","FLOAT4","FLOAT8","FOR","FORCE","FOREIGN","FREETEXT","FREETEXTTABLE","FROM","FULL","FULLTEXT","FUNCTION","GENERAL","GOTO","GRANT","GROUP","HAVING","HIGH_PRIORITY","HOLDLOCK","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IDENTITY","IDENTITYCOL","IDENTITY_INSERT","IF","IGNORE","IGNORE_SERVER_IDS","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINENO","LINES", + "LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LONGBLOB","LONGTEXT","LOOP","LOW_PRIORITY","MASTER_HEARTBEAT_PERIOD","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATIONAL","NATURAL","NO","NOCHECK","NONCLUSTERED","NOT","NO_WRITE_TO_BINLOG","NULL","NULLIF","NUMERIC","OF","OFF","OFFSETS","ON","OPEN","OPENDATASOURCE","OPENQUERY","OPENROWSET","OPENXML","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PERCENT","PLAN","PRECISION","PRIMARY","PRINT","PROC","PROCEDURE","PUBLIC","PURGE","RAISERROR","RANGE","READ","READS","READTEXT","READ_WRITE","REAL","RECONFIGURE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE", + "REPLICATION","REQUIRE","RESIGNAL","RESTORE","RESTRICT","RETURN","REVOKE","RIGHT","RLIKE","ROLLBACK","ROWCOUNT","ROWGUIDCOL","RULE","SAVE","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SESSION_USER","SET","SETUSER","SHOW","SHUTDOWN","SIGNAL","SLOW","SMALLINT","SOME","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATISTICS","STRAIGHT_JOIN","SYSTEM_USER","TABLE","TERMINATED","TEXT","TEXTSIZE","THEN","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","TO","TOP","TRAILING","TRAN","TRANSACTION","TRIGGER","TRUE","TRUNCATE","TSEQUAL","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","UPDATETEXT","USAGE","USE","USER","USING","UTC_DATE","UTC_TIME", + "UTC_TIMESTAMP","VALUES","VARBINARY","VARCHAR","VARCHARACTER","VARYING","VIEW","WAITFOR","WHEN","WHERE","WHILE","WITH","WRITE","WRITETEXT","XOR","YEAR_MONTH","ZEROFILL"); + return $reservedWordsSql; + } + + /** + * isPMUnderUpdating, Used to set a file flag to check if PM is upgrading. + * + * @setFlag Contains the flag to set or unset the temporary file: + * 0 to delete the temporary file flag + * 1 to set the temporary file flag. + * 2 or bigger to check if the temporary file exists. + * return true if the file exists, otherwise false. + */ + public function isPMUnderUpdating($setFlag = 2) + { + if (!defined('PATH_DATA')) { + return false; + } + $fileCheck = PATH_DATA."UPDATE.dat"; + if ($setFlag == 0) { + if (file_exists($fileCheck)) { + unlink ($fileCheck); + } + } elseif ($setFlag == 1) { + $fp = fopen($fileCheck,'w'); + $line = fputs($fp,"true"); + } + //checking temporary file + if ($setFlag >= 1) { + if (file_exists($fileCheck)) { + return true; + } + } + return false; + } + + /** + * Save the $_SESSION variables into $sessionVar array, to unset them temporary. + * + */ + public function sessionVarSave() + { + //Unset any variable + $this->sessionVar = array(); + + if (isset($_SESSION["APPLICATION"])) { + $this->sessionVar["APPLICATION"] = $_SESSION["APPLICATION"]; + } + + if (isset($_SESSION["INDEX"])) { + $this->sessionVar["INDEX"] = $_SESSION["INDEX"]; + } + + if (isset($_SESSION["PROCESS"])) { + $this->sessionVar["PROCESS"] = $_SESSION["PROCESS"]; + } + + if (isset($_SESSION["TASK"])) { + $this->sessionVar["TASK"] = $_SESSION["TASK"]; + } + + if (isset($_SESSION["USER_LOGGED"])) { + $this->sessionVar["USER_LOGGED"] = $_SESSION["USER_LOGGED"]; + } + + if (isset($_SESSION["USR_USERNAME"])) { + $this->sessionVar["USR_USERNAME"] = $_SESSION["USR_USERNAME"]; + } + + if (isset($_SESSION["STEP_POSITION"])) { + $this->sessionVar["STEP_POSITION"] = $_SESSION["STEP_POSITION"]; + } + } + + /** + * Restore the session variables with values of $sessionVar array, if this is set. + * + */ + public function sessionVarRestore() + { + if (count($this->sessionVar) > 0) { + //Restore original values + unset($_SESSION["APPLICATION"]); + unset($_SESSION["INDEX"]); + unset($_SESSION["PROCESS"]); + unset($_SESSION["TASK"]); + unset($_SESSION["USER_LOGGED"]); + unset($_SESSION["USR_USERNAME"]); + unset($_SESSION["STEP_POSITION"]); + + if (isset($this->sessionVar["APPLICATION"])) { + $_SESSION["APPLICATION"] = $this->sessionVar["APPLICATION"]; + } + + if (isset($this->sessionVar["INDEX"])) { + $_SESSION["INDEX"] = $this->sessionVar["INDEX"]; + } + + if (isset($this->sessionVar["PROCESS"])) { + $_SESSION["PROCESS"] = $this->sessionVar["PROCESS"]; + } + + if (isset($this->sessionVar["TASK"])) { + $_SESSION["TASK"] = $this->sessionVar["TASK"]; + } + + if (isset($this->sessionVar["USER_LOGGED"])) { + $_SESSION["USER_LOGGED"] = $this->sessionVar["USER_LOGGED"]; + } + + if (isset($this->sessionVar["USR_USERNAME"])) { + $_SESSION["USR_USERNAME"] = $this->sessionVar["USR_USERNAME"]; + } + + if (isset($this->sessionVar["STEP_POSITION"])) { + $_SESSION["STEP_POSITION"] = $this->sessionVar["STEP_POSITION"]; + } + } + } + + public static function browserCacheFilesGetLibraryJs() + { + $arrayLibrary = array(); + + //Translations /js/ext/translation.en.js + //Translations /js/ext/translation.xxx.en.js //xxx is an plugin + $arrayLibrary["translation"] = 1; //Not use null + + //Translation environment /jscore/labels/en.js + if (file_exists(PATH_DATA . "META-INF" . PATH_SEP . "translations.env")) { + $arrayData = unserialize(file_get_contents(PATH_DATA . "META-INF" . PATH_SEP . "translations.env")); + + foreach ($arrayData as $index1 => $value1) { + foreach ($value1 as $index2 => $value2) { + $record = $value2; + + if (file_exists(PATH_CORE . "js" . PATH_SEP . "labels" . PATH_SEP . $record["LOCALE"] . ".js")) { + $arrayLibrary[$record["LOCALE"]] = 1; + } + } + } + } + + //Libraries + $library = G::json_decode(file_get_contents(PATH_HOME . "engine" . PATH_SEP . "bin" . PATH_SEP . "tasks" . PATH_SEP . "libraries.json")); + + foreach ($library as $index => $value) { + $lib = $value; + + if ($lib->build) { + if (substr($lib->build_js_to, -1) != "/") { + $lib->build_js_to = $lib->build_js_to . "/"; + } + + $arrayLibrary[$lib->name] = 1; + } + } + + return $arrayLibrary; + } + + public static function browserCacheFilesSetUid() + { + $uid = G::generateUniqueID(); + + $arrayData = array(); + $arrayData["browser_cache_files_uid"] = $uid; + + G::update_php_ini(PATH_CONFIG . "env.ini", $arrayData); + } + + public static function browserCacheFilesGetUid() + { + $sysConf = System::getSystemConfiguration(PATH_CONFIG . "env.ini"); + + return (isset($sysConf["browser_cache_files_uid"]))? $sysConf["browser_cache_files_uid"] : null; + } + + public static function browserCacheFilesUrl($url) + { + $browserCacheFilesUid = self::browserCacheFilesGetUid(); + + if ($browserCacheFilesUid != null) { + $arrayAux = explode("/", $url); + $n = count($arrayAux); + + if ($n > 0 && !empty($arrayAux[$n - 1])) { + $arrayAux = explode("?", $arrayAux[$n - 1]); + $name = $arrayAux[0]; + + if (preg_match("/^(.*)\.js$/i", $name, $arrayMatch)) { + $index = $arrayMatch[1]; + $index = (preg_match("/^translation\..*$/", $index))? "translation" : $index; + + $arrayLibrary = G::browserCacheFilesGetLibraryJs(); + + if (isset($arrayLibrary[$index])) { + $url = str_replace($name, $arrayMatch[1] . "." . $browserCacheFilesUid . ".js", $url); + } + } + } + } + + return $url; + } + + public static function skinGetPathToSrcByVirtualUri($option, $sysConf) + { + $path = ""; + $ereg = ""; + $strSearch = ""; + + switch ($option) { + case "errors": + $ereg = "/^\/errors\/.*$/"; + $strSearch = "/errors/"; + break; + case "update": + $ereg = "/^\/update\/.*$/"; + $strSearch = "/update/"; + break; + } + + if (preg_match($ereg, $_SERVER["REQUEST_URI"])) { + $strAux = str_replace($strSearch, null, $_SERVER["REQUEST_URI"]); + + if ($strAux != "") { + $skin = "base"; //classic + + if (isset($_SESSION["currentSkin"])) { + $skin = $_SESSION["currentSkin"]; + } else { + + if (isset($sysConf["default_skin"])) { + $skin = $sysConf["default_skin"]; + } + } + + $arrayAux = explode("?", $strAux); + $fileTemplate = $arrayAux[0]; + + if (file_exists(PATH_SKIN_ENGINE . "base" . PATH_SEP . $fileTemplate)) { + $path = PATH_SKIN_ENGINE . "base" . PATH_SEP; + } + + if (file_exists(PATH_SKIN_ENGINE . $skin . PATH_SEP . $fileTemplate)) { + $path = PATH_SKIN_ENGINE . $skin . PATH_SEP; + } + + if (file_exists(PATH_SKINS . $skin . PATH_SEP . $fileTemplate)) { + $path = PATH_SKINS . $skin . PATH_SEP; + } + + if (file_exists(PATH_CUSTOM_SKINS . $skin . PATH_SEP . $fileTemplate)) { + $path = PATH_CUSTOM_SKINS . $skin . PATH_SEP; + } + } + } + + return $path; + } + + public function isUserFunction($functionName) { + $allFunctions = get_defined_functions(); + if (!isset($allFunctions['user'])) { + $allFunctions['user'] = array(); + } + $allFunctions['user'][] = 'sort'; + return in_array(strtolower($functionName), $allFunctions['user']); + } + + /** + * Constructor for inputFilter class. Only first parameter is required. + * @access constructor + * @data Mixed - input string/array-of-string to be 'cleaned' + * @param Array $tagsArray - list of user-defined tags + * @param Array $attrArray - list of user-defined attributes + * @param int $tagsMethod - 0= allow just user-defined, 1= allow all but user-defined + * @param int $attrMethod - 0= allow just user-defined, 1= allow all but user-defined + * @param int $xssAuto - 0= only auto clean essentials, 1= allow clean blacklisted tags/attr + */ + public function sanitizeInput($data, $tagsArray = array(), $attrArray = array(), $tagsMethod = 0, $attrMethod = 0, $xssAuto = 1) + { + G::LoadSystem('inputfilter'); + $filtro = new InputFilter($tagsArray , $attrArray, $tagsMethod, $attrMethod, $xssAuto); + return $filtro->process($data); + } + + /** + * Stores a message in the log file, if the file size exceeds + * specified log file is renamed and a new one is created. + * + * @param type $message + * @param type $pathData + * @param type $file + */ + public static function log($message, $pathData = PATH_DATA, $file = 'cron.log') + { + $config = System::getSystemConfiguration(); + G::LoadSystem('logger'); + + $oLogger = Logger::getSingleton($pathData, PATH_SEP, $file); + $oLogger->limitFile = $config['number_log_file']; + $oLogger->limitSize = $config['size_log_file']; + $oLogger->write($message); + } + + /** + */ + public static function auditLog($actionToLog, $valueToLog = "") + { + $workspace = defined('SYS_SYS') ? SYS_SYS : 'Wokspace Undefined'; + $oServerConf = & serverConf::getSingleton(); + $sflagAudit = $oServerConf->getAuditLogProperty( 'AL_OPTION', $workspace ); + $ipClient = G::getIpAddress(); + + $licensedFeatures = PMLicensedFeatures::getSingleton(); + if ($sflagAudit && $licensedFeatures->verifyfeature('vtSeHNhT0JnSmo1bTluUVlTYUxUbUFSVStEeXVqc1pEUG5EeXc0MGd2Q3ErYz0=')) { + $username = isset($_SESSION['USER_LOGGED']) && $_SESSION['USER_LOGGED'] != '' ? $_SESSION['USER_LOGGED'] : 'Unknow User'; + $fullname = isset($_SESSION['USR_FULLNAME']) && $_SESSION['USR_FULLNAME'] != '' ? $_SESSION['USR_FULLNAME'] : '-'; + G::log("|". $workspace ."|". $ipClient ."|". $username . "|" . $fullname ."|" . $actionToLog . "|" . $valueToLog, PATH_DATA, "audit.log"); + } + } + + /** + * Changes all keys in an array and sub-arrays + * + * @param array $arrayData The array to work on + * @param int $case Either CASE_UPPER or CASE_LOWER (default) + * + * return array Returns an array with its keys lower or uppercased, or false if $arrayData is not an array + */ + public static function array_change_key_case2($arrayData, $case = CASE_LOWER) + { + $arrayData = array_change_key_case($arrayData, $case); + + foreach ($arrayData as $key => $value) { + if (is_array($value)) { + $arrayData[$key] = self::array_change_key_case2($value, $case); + } + } + + return $arrayData; + } + + public static function buildFrom($configuration, $from = '') { + if (!isset($configuration['MESS_FROM_NAME'])) { + $configuration['MESS_FROM_NAME'] = ''; + } + if (!isset($configuration['MESS_FROM_MAIL'])) { + $configuration['MESS_FROM_MAIL'] = ''; + } + if ($from != '') { + if (!preg_match('/(.+)@(.+)\.(.+)/', $from, $match)) { + if ($configuration['MESS_FROM_MAIL'] != '') { + $from .= ' <' . $configuration['MESS_FROM_MAIL'] . '>'; + } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) { + $from .= ' <' . $configuration['MESS_ACCOUNT'] . '>'; + } else { + $from .= ' '; + } + } + } else { + if ($configuration['MESS_FROM_NAME'] != '' && $configuration['MESS_FROM_MAIL'] != '') { + $from = $configuration['MESS_FROM_NAME'] . ' <' . $configuration['MESS_FROM_MAIL'] . '>'; + } else if ($configuration['MESS_FROM_NAME'] != '' && $configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) { + $from = $configuration['MESS_FROM_NAME'] . ' <' . $configuration['MESS_ACCOUNT'] . '>'; + } else if ($configuration['MESS_FROM_NAME'] != '') { + $from = $configuration['MESS_FROM_NAME'] . ' '; + } else if ($configuration['MESS_FROM_MAIL'] != '') { + $from = $configuration['MESS_FROM_MAIL']; + } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) { + $from = $configuration['MESS_ACCOUNT']; + } else if ($configuration['MESS_ENGINE'] == 'PHPMAILER' && $configuration['MESS_ACCOUNT'] != '' && !preg_match('/(.+)@(.+)\.(.+)/', $configuration['MESS_ACCOUNT'], $match)) { + $from = $configuration['MESS_ACCOUNT'] . ' '; + } else { + $from = 'info@' . ((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != '')? $_SERVER['HTTP_HOST'] : 'processmaker.com'); + } + } + return $from; + } + + public function getRealExtension($extensionInpDoc) { + $aux = explode('.', strtolower($extensionInpDoc)); + return isset($aux[1]) ? $aux[1] : ''; + } + + /** + * Verify the InputDoc extension, cheking the file name extension (.pdf, .ppt) and the file content. + * + * + * + */ + public function verifyInputDocExtension($InpDocAllowedFiles, $fileName, $filesTmpName) + { + // Initialize variables + $res = new stdclass(); + $allowedTypes = array_map('G::getRealExtension', explode(', ', $InpDocAllowedFiles)); + + // If required extension is *.* don't validate + if (in_array('*', $allowedTypes)) { + $res->status = true; + return $res; + } + + // Get the file extension + $aux = pathinfo($fileName); + $fileExtension = isset($aux['extension']) ? strtolower($aux['extension']) : ''; + + // If no valid extension finish (unnecesary check file content) + $validExtension = in_array($fileExtension, $allowedTypes); + if (!$validExtension) { + $res->status = false; + $res->message = G::LoadTranslation('ID_UPLOAD_ERR_NOT_ALLOWED_EXTENSION' ) . ' ' . $fileName; + return $res; + } + + // If not enabled fileinfo extension finish validation + if (!extension_loaded('fileinfo')) { + $res->status = true; + return $res; + } + + // If enabled fileinfo extension check the content + $finfo = new finfo(FILEINFO_MIME_TYPE); + $mimeType = $finfo->file($filesTmpName); + $docType = explode('/', $mimeType); + + // If is a empty file finish validation + if ($docType[1] == 'x-empty') { + $res->status = true; + return $res; + } + + // Check file content + foreach ($allowedTypes as $allowedType) { + switch ($allowedType) { + case 'xls': + if ($docType[1] == 'vnd.ms-excel' || ($fileExtension == 'xls' && $docType[1] == 'plain')) { + $res->status = true; + return $res; + } + break; + case 'doc': + if ($docType[1] == 'msword' || ($fileExtension == 'doc' && $docType[1] == 'html')) { + $res->status = true; + return $res; + } + break; + case 'ppt': + if ($docType[1] == 'vnd.ms-office') { + $res->status = true; + return $res; + } + break; + case 'docx': + case 'pptx': + case 'xlsx': + if ($docType[1] == 'zip') { + $res->status = true; + return $res; + } + break; + case 'exe': + case 'wmv': + if($docType[1] == 'octet-stream'){ + $res->status = true; + return $res; + } + break; + case 'jpg': + if ($docType[1] == 'jpeg'){ + $res->status = true; + return $res; + } + break; + case 'mp3': + if ($docType[1] == 'mpeg'){ + $res->status = true; + return $res; + } + break; + case 'rar': + if ($docType[1] == 'x-rar'){ + $res->status = true; + return $res; + } + break; + case 'txt': + case 'pm': + if ($docType[1] == 'plain'){ + $res->status = true; + return $res; + } + break; + case 'htm': + case 'html': + if ($docType[1] == 'html'){ + $res->status = true; + return $res; + } + break; + case 'po': + if ($docType[1] == 'x-po'){ + $res->status = true; + return $res; + } + break; + case 'pdf': + case 'png': + case 'jpeg': + case 'gif': + case 'zip': + case 'mp4': + if ($docType[1] == $allowedType){ + $res->status = true; + return $res; + } + break; + default: + if ($validExtension) { + $res->status = true; + return $res; + } + break; + } + } + + // If content don't match return error + $res->status = false; + $res->message = G::LoadTranslation('ID_UPLOAD_ERR_NOT_ALLOWED_EXTENSION' ) . ' ' . $fileName; + return $res; + + } + + /** + * Check the browser compativility + */ + public function checkBrowserCompatibility($browser = null, $version = null){ + if($browser == null || $version == null){ + $info = G::getBrowser(); + $browser = $info['name']; + $version = $info['version']; + } + if ((($browser== 'msie') && (($version >= 8) && ($version <= 11))) || + (($browser== 'chrome') && ($version >= 26)) || + (($browser== 'firefox') && ($version >= 20)) + ){ + return true; + } + return false; + } + + /* + * $string - The string to sanitize. + * $lowercase - Force the string to lowercase? + * $alpha - If set to *true*, will remove all non-alphanumeric characters. + */ + public function sanitizeString ($string, $lowercase = true, $alpha = false) + { + $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]", + "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—", + "—", "–", ",", "<", ".", ">", "/", "?"); + $clean = trim(str_replace($strip, "", strip_tags($string))); + $clean = preg_replace('/\s+/', "-", $clean); + $clean = ($alpha) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ; + $clean = ($lowercase) ? (function_exists('mb_strtolower')) ? mb_strtolower($clean, 'UTF-8') : strtolower($clean) : $clean; + return $clean; + } + /** + * encryptOld + * + * @param string $string + * + * @return md5($string) + */ + public function encryptOld ($string) + { + return md5($string); + } + /** + * encryptFileOld + * + * @param string $string + * + * @return md5_file($string) + */ + public function encryptFileOld ($string) + { + return md5_file($string); + } + /** + * crc32 + * + * @param string $string + * + * @return crc32($string) + */ + public function encryptCrc32 ($string) + { + return crc32($string); + } +} + +/** + * eprint + * + * @param string $s default value '' + * @param string $c default value null + * + * @return void + */ +function eprint ($s = "", $c = null) +{ + if (G::isHttpRequest()) { + if (isset( $c )) { + echo "
$s
"; + } else { + echo "
$s
"; + } + } else { + if (isset( $c )) { + switch ($c) { + case 'green': + printf( "\033[0;35;32m$s\033[0m" ); + return; + break; + case 'red': + printf( "\033[0;35;31m$s\033[0m" ); + return; + break; + case 'blue': + printf( "\033[0;35;34m$s\033[0m" ); + return; + break; + default: + print "$s"; + } + } else { + print "$s"; + } + } +} + +/** + * println + * + * @param string $s + * + * @return eprintln($s) + */ +function println ($s) +{ + return eprintln( $s ); +} + +/** + * eprintln + * + * @param string $s + * @param string $c + * + * @return void + */ +function eprintln ($s = "", $c = null) +{ + if (G::isHttpRequest()) { + if (isset( $c )) { + echo "
$s
"; + } else { + echo "
$s
"; + } + } else { + if (isset( $c ) && (PHP_OS != 'WINNT')) { + switch ($c) { + case 'green': + printf( "\033[0;35;32m$s\033[0m\n" ); + return; + break; + case 'red': + printf( "\033[0;35;31m$s\033[0m\n" ); + return; + break; + case 'blue': + printf( "\033[0;35;34m$s\033[0m\n" ); + return; + break; + } + } + print "$s\n"; + } +} + +function __ ($msgID, $lang = SYS_LANG, $data = null) +{ + return G::LoadTranslation( $msgID, $lang, $data ); +} diff --git a/workflow/engine/controllers/installer.php b/workflow/engine/controllers/installer.php new file mode 100644 index 000000000..e0248996e --- /dev/null +++ b/workflow/engine/controllers/installer.php @@ -0,0 +1,1704 @@ + + */ +global $translation; +include PATH_LANGUAGECONT."translation.".SYS_LANG; + +class Installer extends Controller +{ + public $path_config; + public $path_languages; + public $path_plugins; + public $path_xmlforms; + public $path_shared; + public $path_sep; + public $systemName; + + public $link; #resource for database connection + + + public function __construct () + { + $this->path_config = PATH_CORE . 'config/'; + $this->path_languages = PATH_CORE . 'content/languages/'; + $this->path_plugins = PATH_CORE . 'plugins/'; + $this->path_xmlforms = PATH_CORE . 'xmlform/'; + $this->path_public = PATH_HOME . 'public_html/index.html'; + $this->path_shared = PATH_TRUNK . 'shared/'; + $this->path_sep = PATH_SEP; + $this->systemName = ''; + //$this->path_documents = ; + $this->path_translations = PATH_CORE . 'js/labels/'; + $this->path_translationsMafe = PATH_HOME . 'public_html/translations/'; + } + + public function index ($httpData) + { + if ((strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') && (file_exists($this->path_shared . 'partner.info'))) { + $this->includeExtJS( 'installer/stopInstall'); + $this->setView( 'installer/mainStopInstall' ); + G::RenderPage( 'publish', 'extJs' ); + return; + } + + $licenseContent = file_get_contents( PATH_TRUNK . 'LICENSE.txt' ); + + $this->includeExtJS( 'installer/CardLayout', false ); + $this->includeExtJS( 'installer/Wizard', false ); + $this->includeExtJS( 'installer/Header', false ); + $this->includeExtJS( 'installer/Card', false ); + + $this->includeExtJS( 'installer/installer_cards' ); + $this->includeExtJS( 'installer/main', false ); + + $this->setJSVar( 'licenseTxt', $licenseContent ); + + $this->setJSVar( 'path_config', $this->path_config ); + $this->setJSVar( 'path_languages', $this->path_languages ); + $this->setJSVar( 'path_plugins', $this->path_plugins ); + $this->setJSVar( 'path_xmlforms', $this->path_xmlforms ); + $this->setJSVar( 'path_public', $this->path_public ); + $this->setJSVar( 'path_shared', $this->path_shared ); + $this->setJSVar( 'path_sep', $this->path_sep ); + $this->setJSVar( 'path_translations', $this->path_translations ); + $this->setJSVar( 'path_translationsMafe', $this->path_translationsMafe ); + + $this->setView( 'installer/main' ); + + G::RenderPage( 'publish', 'extJs' ); + } + + public function newSite () + { + $textStep1 = G::LoadTranslation('ID_PROCESSMAKER_REQUIREMENTS_DESCRIPTION_STEP4_1'); + $textStep2 = G::LoadTranslation('ID_PROCESSMAKER_REQUIREMENTS_DESCRIPTION_STEP5'); + + $this->includeExtJS( 'installer/CardLayout', false ); + $this->includeExtJS( 'installer/Wizard', false ); + $this->includeExtJS( 'installer/Header', false ); + $this->includeExtJS( 'installer/Card', false ); + $this->includeExtJS( 'installer/newSite', false ); + + $this->setJSVar( 'textStep1', $textStep1 ); + $this->setJSVar( 'textStep2', $textStep2 ); + + $this->setJSVar( 'DB_ADAPTER', DB_ADAPTER ); + $aux = explode( ':', DB_HOST ); + $this->setJSVar( 'DB_HOST', $aux[0] ); + $this->setJSVar( 'DB_PORT', isset( $aux[1] ) ? $aux[1] : (DB_ADAPTER == 'mssql' ? '1433' : '3306') ); + $this->setJSVar( 'DB_NAME', 'workflow' ); + $this->setJSVar( 'DB_USER', '' ); + $this->setJSVar( 'DB_PASS', '' ); + $this->setJSVar( 'pathConfig', PATH_CORE . 'config' . PATH_SEP ); + $this->setJSVar( 'pathLanguages', PATH_LANGUAGECONT ); + $this->setJSVar( 'pathPlugins', PATH_PLUGINS ); + $this->setJSVar( 'pathXmlforms', PATH_XMLFORM ); + $this->setJSVar( 'pathShared', PATH_DATA ); + + $this->setView( 'installer/newSite' ); + + G::RenderPage( 'publish', 'extJs' ); + } + + public function getSystemInfo () + { + //$echo ""; + //print_r ($valu);die(); + $this->setResponseType( 'json' ); + + // PHP info and verification + $phpVer = phpversion(); + preg_match( '/[0-9\.]+/', $phpVer, $match ); + $phpVerNum = (float) $match[0]; + + $info = new stdclass(); + $info->php = new stdclass(); + $info->mysql = new stdclass(); + $info->mssql = new stdclass(); + $info->openssl = new stdclass(); + $info->curl = new stdclass(); + $info->dom = new stdclass(); + $info->gd = new stdclass(); + $info->multibyte = new stdclass(); + $info->soap = new stdclass(); + $info->ldap = new stdclass(); + $info->mcrypt = new stdclass(); + $info->memory = new stdclass(); + + $info->php->version = phpversion(); + $info->php->result = version_compare(phpversion(), '5.2.10') >= 0 ? true : false; + + // MYSQL info and verification + $info->mysql->result = false; + if (function_exists( 'mysql_query' )) { + $mysqlVer = mysql_get_client_info(); + preg_match( '/[0-9\.]+/', $mysqlVer, $match ); + $mysqlNum = (float) $match[0]; + $info->mysql->version = 'Client API version ' . $mysqlVer; + $info->mysql->result = $mysqlNum >= 5.0 ? true : false; + } + + // MSSQL info and verification + $info->mssql->result = false; + $info->mssql->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'mssql_query' )) { + $info->mssql->result = true; + $info->mssql->version = G::LoadTranslation('ID_ENABLED'); + } + + // OpenSSL info + $info->openssl->result = false; + $info->openssl->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'openssl_open' )) { + $info->openssl->result = true; + $info->openssl->version = G::LoadTranslation('ID_ENABLED'); + } + + // Curl info + $info->curl->result = false; + $info->curl->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'curl_version' )) { + $info->curl->result = true; + $version = curl_version(); + $info->curl->version = 'cURL ' . $version['version']; + $info->openssl->version = $version['ssl_version']; + } + + // DOMDocument info + $info->dom->result = false; + $info->dom->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (class_exists( 'DOMDocument' )) { + $info->dom->result = true; + $info->dom->version = G::LoadTranslation('ID_ENABLED'); + } + + // GD info + $info->gd->result = false; + $info->gd->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'gd_info' )) { + $info->gd->result = true; + $gdinfo = gd_info(); + $info->gd->version = $gdinfo['GD Version']; + } + + // Multibyte info + $info->multibyte->result = false; + $info->multibyte->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'mb_check_encoding' )) { + $info->multibyte->result = true; + $info->multibyte->version = G::LoadTranslation('ID_ENABLED'); + } + + // soap info + $info->soap->result = false; + $info->soap->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (class_exists( 'SoapClient' )) { + $info->soap->result = true; + $info->soap->version = G::LoadTranslation('ID_ENABLED'); + } + + //mcrypt info + $info->mcrypt->result = extension_loaded("mcrypt"); + $info->mcrypt->version = ($info->mcrypt->result)? G::LoadTranslation("ID_ENABLED") : G::LoadTranslation("ID_NOT_ENABLED"); + + // ldap info + $info->ldap->result = false; + $info->ldap->version = G::LoadTranslation('ID_NOT_ENABLED'); + if (function_exists( 'ldap_connect' )) { + $info->ldap->result = true; + $info->ldap->version = G::LoadTranslation('ID_ENABLED'); + } + + // memory limit verification + $memory = (int) ini_get( "memory_limit" ); + $info->memory->version = $memory . 'M'; + if ($memory > 80) { + $info->memory->result = true; + } else { + $info->memory->result = false; + } + + return $info; + } + + public function is_dir_writable ($path) + { + return G::is_writable_r( $path ); + } + + public function getPermissionInfo () + { + $this->setResponseType( 'json' ); + $info = new StdClass(); + $info->success = true; + $noWritableFiles = array (); + // pathConfig + $info->pathConfig = new stdclass(); + $info->pathConfig->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathConfig->result = G::is_writable_r( $_REQUEST['pathConfig'], $noWritableFiles ); + if ($info->pathConfig->result) { + $info->pathConfig->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathLanguages = new stdclass(); + $info->pathLanguages->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathLanguages->result = G::is_writable_r( $_REQUEST['pathLanguages'], $noWritableFiles ); + if ($info->pathLanguages->result) { + $info->pathLanguages->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathPlugins = new stdclass(); + $info->pathPlugins->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathPlugins->result = G::is_writable_r( $_REQUEST['pathPlugins'], $noWritableFiles ); + if ($info->pathPlugins->result) { + $info->pathPlugins->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathXmlforms = new stdclass(); + $info->pathXmlforms->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathXmlforms->result = G::is_writable_r( $_REQUEST['pathXmlforms'], $noWritableFiles ); + if ($info->pathXmlforms->result) { + $info->pathXmlforms->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathTranslations = new stdclass(); + $info->pathTranslations->message = G::LoadTranslation('ID_TRANSLATION_NOT_WRITEABLE'); + $info->pathTranslations->result = G::is_writable_r( $_REQUEST['pathTranslations'], $noWritableFiles ); + if ($info->pathTranslations->result) { + $info->pathTranslations->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathTranslationsMafe = new stdclass(); + $info->pathTranslationsMafe->message = G::LoadTranslation('ID_MAFE_TRANSLATION_NOT_WRITEABLE'); + $info->pathTranslationsMafe->result = G::is_writable_r( $_REQUEST['pathTranslationsMafe'], $noWritableFiles ); + if ($info->pathTranslationsMafe->result) { + $info->pathTranslationsMafe->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathPublic = new stdclass(); + + $info->pathShared = new stdclass(); + $info->pathPublic->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathPublic->result = G::is_writable_r( $_REQUEST['pathPublic'], $noWritableFiles ); + if ($info->pathPublic->result) { + $info->pathShared->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + + $info->pathShared->message = G::LoadTranslation('ID_INDEX_NOT_WRITEABLE'); + $info->pathShared->result = G::is_writable_r( $_REQUEST['pathShared'], $noWritableFiles ); + if ($info->pathShared->result) { + $info->pathShared->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + G::verifyPath( $_REQUEST['pathShared'], true ); + $info->pathShared->result = G::is_writable_r( $_REQUEST['pathShared'], $noWritableFiles ); + if ($info->pathShared->result) { + $info->pathShared->message = G::LoadTranslation('ID_WRITEABLE'); + } else { + $info->success = false; + } + } + + if ($info->pathShared->result) { + $aux = pathinfo( $_REQUEST['pathLogFile'] ); + G::verifyPath( $aux['dirname'], true ); + if (is_dir( $aux['dirname'] )) { + if (! file_exists( $_REQUEST['pathLogFile'] )) { + @file_put_contents( $_REQUEST['pathLogFile'], '' ); + @chmod($_REQUEST['pathShared'], 0770); + } + } + } + + $info->pathLogFile = new stdclass(); + $info->pathLogFile->message = G::LoadTranslation('ID_CREATE_LOG_INSTALLATION'); + $info->pathLogFile->result = file_exists( $_REQUEST['pathLogFile'] ); + + if ($info->pathLogFile->result) { + $info->pathLogFile->message = G::LoadTranslation('ID_INSTALLATION_FILE_LOG'); + } + + if ($info->success) { + $info->notify = G::LoadTranslation('ID_SUCCESS_DIRECTORIES_WRITABLE'); + } else { + $info->notify = G::LoadTranslation('ID_DIRECTORIES_NOT_WRITABLE'); + } + + $info->noWritableFiles = $noWritableFiles; + + return $info; + } + + public function testConnection () + { + $this->setResponseType( 'json' ); + if (isset($_REQUEST["db_engine"]) && $_REQUEST["db_engine"] == "mysql") { + return $this->testMySQLconnection(); + } else { + return $this->testMSSQLconnection(); + } + } + + /** + * log the queries and other information to install.log, + * the install.log files should be placed in shared/logs + * for that reason we are using the $_REQUEST of pathShared + */ + public function installLog ($text) + { + $serverAddr = $_SERVER['SERVER_ADDR']; + //if this function is called outside the createWorkspace, just returns and do nothing + if (! isset( $_REQUEST['pathShared'] )) { + return; + } + //log file is in shared/logs + $pathShared = trim( $_REQUEST['pathShared'] ); + if (substr( $pathShared, - 1 ) != '/') { + $pathShared .= '/'; + } + $pathSharedLog = $pathShared . 'log/'; + G::verifyPath($pathSharedLog, true); + $logFile = $pathSharedLog . 'install.log'; + + if (! is_file( $logFile )) { + G::mk_dir( dirname( $pathShared ) ); + $fpt = fopen( $logFile, 'w' ); + if ($fpt !== null) { + fwrite( $fpt, sprintf( "%s %s\n", date( 'Y:m:d H:i:s' ), '----- '. G::LoadTranslation('ID_STARTING_LOG_FILE') .' ------' ) ); + fclose( $fpt ); + } else { + throw (new Exception( G::LoadTranslation('ID_FILE_NOT_WRITEABLE', SYS_LANG, Array($logFile) ) )); + return $false; + } + } + + $fpt = fopen( $logFile, 'a' ); + fwrite( $fpt, sprintf( "%s %s\n", date( 'Y:m:d H:i:s' ), trim( $text ) ) ); + fclose( $fpt ); + return true; + } + + /** + * function to create a workspace + * in fact this function is calling appropiate functions for mysql and mssql + */ + public function createWorkspace () + { + $pathSharedPartner = trim( $_REQUEST['pathShared'] ); + if (file_exists(trim($pathSharedPartner,PATH_SEP). PATH_SEP .'partner.info')) { + $this->systemName = $this->getSystemName($pathSharedPartner); + $_REQUEST["PARTNER_FLAG"] = true; + } + $this->setResponseType( 'json' ); + if ($_REQUEST['db_engine'] == 'mysql') { + $info = $this->createMySQLWorkspace(); + } else { + $info = $this->createMSSQLWorkspace(); + } + + return $info; + } + + public function forceTogenerateTranslationsFiles ($url) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, G::browserCacheFilesUrl((isset($_SERVER["HTTPS"])? (($_SERVER["HTTPS"] != "")? "https://" : "http://") : "http://") . $_SERVER["HTTP_HOST"] . "/js/ext/translation.en.js?r=" . rand(1, 10000))); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, 60); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); + curl_exec($ch); + curl_close($ch); + } + + /** + * send a query to MySQL and log the query + */ + public function mysqlQuery ($sql) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $sql = $filter->preventSqlInjection($sql, Array()); + $this->installLog( $sql ); + $query = @mysql_query( $sql, $this->link ); + if (! $query) { + $errorMessage = mysql_error( $this->link ); + $this->installLog( G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, Array($errorMessage) ) ); + throw new Exception( $errorMessage ); + return false; + } + @mysql_free_result( $query ); + return true; + } + + /** + * send a query to MSSQL and log the query + */ + public function mssqlQuery ($sql) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $sql = $filter->preventSqlInjection($sql, Array()); + $this->installLog( $sql ); + $query = @mssql_query( $sql, $this->link ); + if (! $query) { + $errorMessage = mssql_get_last_message(); + $this->installLog( G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, Array($errorMessage) )); + throw (new Exception( $errorMessage )); + return false; + } + @mssql_free_result( $query ); + return true; + } + + /** + * query_sql_file send many statements to server + * + * @param string $file + * @param string $connection + * @return array $report + */ + public function mysqlFileQuery ($file) + { + if (! is_file( $file )) { + throw (new Exception( G::LoadTranslation('ID_SQL_FILE_INVALID', SYS_LANG, Array($file) ) )); + return $false; + } + $this->installLog( G::LoadTranslation('ID_PROCESING', SYS_LANG, Array($file) )); + $startTime = microtime( true ); + // $content = file_get_contents($file); + // $queries = explode(';', $content); + + + // foreach( $queries as $sql) { + // if (trim($sql) != '') { + // $query = @mysql_query($sql, $this->link); + // if (!$query) { + // $errorMessage = mysql_error($this->link); + + + // $this->installLog ( sprintf ( 'MySQL error: %s Query: %s ', $errorMessage, $sql ) ); + // throw ( new Exception ( $errorMessage ) ); + // return false; + // } + // } + // } + + + //erik: New Update, to support more complex queries + + + $lines = file( $file ); + $previous = null; + $errors = ''; + @mysql_query( "SET NAMES 'utf8';" ); + foreach ($lines as $j => $line) { + $line = trim( $line ); // Remove comments from the script + + + if (strpos( $line, "--" ) === 0) { + $line = substr( $line, 0, strpos( $line, "--" ) ); + } + + if (empty( $line )) { + continue; + } + + if (strpos( $line, "#" ) === 0) { + $line = substr( $line, 0, strpos( $line, "#" ) ); + } + + if (empty( $line )) { + continue; + } + + // Concatenate the previous line, if any, with the current + if ($previous) { + $line = $previous . " " . $line; + } + $previous = null; + + // If the current line doesnt end with ; then put this line together + // with the next one, thus supporting multi-line statements. + if (strrpos( $line, ";" ) != strlen( $line ) - 1) { + $previous = $line; + continue; + } + + $line = substr( $line, 0, strrpos( $line, ";" ) ); + @mysql_query( $line, $this->link ); + } + + $endTime = microtime( true ); + $this->installLog( G::LoadTranslation('ID_FILE_PROCESSED', SYS_LANG, Array(basename( $file ), $endTime - $startTime )) ); + return true; + } + + /** + * query_sql_file send many statements to server + * + * @param string $file + * @param string $connection + * @return array $report + */ + public function mssqlFileQuery ($file) + { + if (! is_file( $file )) { + throw (new Exception( G::LoadTranslation('ID_SQL_FILE_INVALID', SYS_LANG, Array($file) ))); + return $false; + } + $this->installLog( G::LoadTranslation('ID_PROCESING', SYS_LANG, Array($file) )); + $startTime = microtime( true ); + $content = file_get_contents( $file ); + $queries = explode( ';', $content ); + + foreach ($queries as $sql) { + $query = @mssql_query( $sql, $this->link ); + if (! $query) { + $errorMessage = mssql_get_last_message(); + $this->installLog( G::LoadTranslation('ID_MYSQL_ERROR',SYS_LANG, Array( $errorMessage . G::LoadTranslation('ID_QUERY') .": ". $sql) )); + throw (new Exception( $errorMessage )); + return false; + } + } + $endTime = microtime( true ); + $this->installLog( G::LoadTranslation('ID_FILE_PROCESSED', SYS_LANG, Array(basename( $file ), $endTime - $startTime )) ); + return true; + } + + /** + * set Grant Privileges for MySQL + * + * @param string $psUser + * @param string $psPassword + * @param string $psDatabase + * @return void + */ + public function setGrantPrivilegesMySQL ($psUser, $psPassword, $psDatabase, $host) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $host = ($host == 'localhost' || $host == '127.0.0.1' ? 'localhost' : '%'); + + $query = "GRANT ALL PRIVILEGES ON `%s`.* TO %s@'%s' IDENTIFIED BY '%s' WITH GRANT OPTION"; + $sql = sprintf( $query, $psDatabase, $psUser, $host, $psPassword ); + $sql = $filter->preventSqlInjection($query, array($psDatabase, $psUser, $host, $psPassword )); + $query = @mysql_query( $sql, $this->link ); + + if (! $query) { + $errorMessage = mysql_error( $this->link ); + $this->installLog( G::LoadTranslation('ID_MYSQL_ERROR', SYS_LANG, Array($errorMessage) ) ); + if (mysql_errno( $this->link) == 1410 || mysql_errno( $this->link) == 1132) { + $errorMessage .= '. ' . G::LoadTranslation('ID_INSTALL_USE_CURRENT_USER'); + } + throw new Exception( $errorMessage ); + return false; + } + @mysql_free_result( $query ); + $this->installLog( $sql ); + } + + /** + * set Grant Privileges for SQLServer + * + * @param string $psUser + * @param string $psPassword + * @param string $psDatabase + * @return void + */ + public function setGrantPrivilegesMSSQL ($psUser, $psPassword, $psDatabase) + { + + $query = sprintf( "IF EXISTS (SELECT * FROM sys.server_principals WHERE name = N'%s') DROP LOGIN [%s]", $psUser, $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "CREATE LOGIN [%s] WITH PASSWORD=N'%s', DEFAULT_DATABASE=[%s], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF ", $psUser, $psPassword, $psDatabase ); + $this->mssqlQuery( $query ); + + $query = sprintf( "USE %s;", $psDatabase ); + $this->mssqlQuery( $query ); + + $query = sprintf( "IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'%s') DROP USER [%s]", $psUser, $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "CREATE USER %s FOR LOGIN %s;", $psUser, $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "sp_addrolemember 'db_owner', '%s' ", $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "sp_addrolemember 'db_ddladmin', '%s' ", $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "sp_addrolemember 'db_accessadmin', '%s' ", $psUser ); + $this->mssqlQuery( $query ); + + $query = sprintf( "use master " ); + $this->mssqlQuery( $query ); + + return true; + } + + public function createMySQLWorkspace () + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + ini_set( 'max_execution_time', '0' ); + $info = new StdClass(); + $info->result = false; + $info->message = ''; + $info->canRedirect = true; + + $db_hostname = trim( $_REQUEST['db_hostname'] ); + $db_port = trim( $_REQUEST['db_port'] ); + $db_port = $filter->validateInput($db_port); + $db_username = trim( $_REQUEST['db_username'] ); + $db_username = $filter->validateInput($db_username); + $db_password = trim( $_REQUEST['db_password'] ); + $db_password = $filter->validateInput($db_password); + $wf = trim( $_REQUEST['wfDatabase'] ); + $rb = trim( $_REQUEST['wfDatabase'] ); + $rp = trim( $_REQUEST['wfDatabase'] ); + $workspace = trim( $_REQUEST['workspace'] ); + $pathConfig = trim( $_REQUEST['pathConfig'] ); + $pathLanguages = trim( $_REQUEST['pathLanguages'] ); + $pathPlugins = trim( $_REQUEST['pathPlugins'] ); + $pathShared = trim( $_REQUEST['pathShared'] ); + $pathXmlforms = trim( $_REQUEST['pathXmlforms'] ); + $adminPassword = trim( $_REQUEST['adminPassword'] ); + $adminPassword = $filter->validateInput($adminPassword); + $adminUsername = trim( $_REQUEST['adminUsername'] ); + $adminUsername = $filter->validateInput($adminUsername); + $deleteDB = ($_REQUEST['deleteDB'] == 'true'); + $userLogged = (isset($_REQUEST['userLogged']) ? ($_REQUEST['userLogged'] == 'true') : false); + $userLogged = $filter->validateInput($userLogged); + + if (substr( $pathShared, - 1 ) != '/') { + $pathShared .= '/'; + } + + $this->installLog( '-------------------------------------------' ); + $this->installLog( G::LoadTranslation('ID_CREATING_WORKSPACE', SYS_LANG, Array($workspace))); + + try { + $db_host = ($db_port != '' && $db_port != 3306) ? $db_hostname . ':' . $db_port : $db_hostname; + $db_host = $filter->validateInput($db_host); + $db_username = $filter->validateInput($db_username); + $db_password = $filter->validateInput($db_password); + $this->link = @mysql_connect( $db_host, $db_username, $db_password ); + $this->installLog( G::LoadTranslation('ID_CONNECT_TO_SERVER', SYS_LANG, Array($db_hostname, $db_port, $db_username ) )); + + if ($deleteDB) { + $q = sprintf( 'DROP DATABASE IF EXISTS %s;', $wf, $wf ); + $this->mysqlQuery( $q ); + } + + // CREATE databases wf_workflow, rb_workflow and rp_workflow + $q = sprintf( 'CREATE DATABASE IF NOT EXISTS %s;', $wf, $wf ); + $this->mysqlQuery( $q ); + + // CREATE users and GRANT Privileges + $wf_workpace = $wf; + $rb_workpace = $wf; + $rp_workpace = $wf; + if (!$userLogged) { + $wfPass = G::generate_password( 12 ); + $this->setGrantPrivilegesMySQL( $wf, $wfPass, $wf, $db_hostname ); + $this->setGrantPrivilegesMySQL( $rb, $wfPass, $wf, $db_hostname ); + $this->setGrantPrivilegesMySQL( $rp, $wfPass, $wf, $db_hostname ); + } else { + $wfPass = $db_password; + $rbPass = $db_password; + $rpPass = $db_password; + $wf = $db_username; + $rb = $db_username; + $rp = $db_username; + } + + + // Generate the db.php file and folders + $pathSharedSites = $pathShared; + $path_site = $pathShared . "/sites/" . $workspace . "/"; + $db_file = $path_site . "db.php"; + @mkdir( $path_site, 0777, true ); + @mkdir( $path_site . "files/", 0777, true ); + @mkdir( $path_site . "mailTemplates/", 0777, true ); + @mkdir( $path_site . "public/", 0777, true ); + @mkdir( $path_site . "reports/", 0777, true ); + @mkdir( $path_site . "xmlForms", 0777, true ); + + $dbText = "systemName != '') { + $dbText .= " define ('SYSTEM_NAME', '" . $this->systemName . "');\n"; + } + } + + $this->installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array($db_file) )); + file_put_contents( $db_file, $dbText ); + + // Generate the databases.php file + $databases_file = $path_site . 'databases.php'; + $dbData = sprintf( "\$dbAdapter = '%s';\n", 'mysql' ); + $dbData .= sprintf( "\$dbHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbName = '%s';\n", $wf_workpace ); + $dbData .= sprintf( "\$dbUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbPass = '%s';\n", $wfPass ); + $dbData .= sprintf( "\$dbRbacHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbRbacName = '%s';\n", $wf_workpace ); + $dbData .= sprintf( "\$dbRbacUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbRbacPass = '%s';\n", $wfPass ); + $dbData .= sprintf( "\$dbReportHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbReportName = '%s';\n", $wf_workpace ); + $dbData .= sprintf( "\$dbReportUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbReportPass = '%s';\n", $wfPass ); + $databasesText = str_replace( '{dbData}', $dbData, @file_get_contents( PATH_HOME . 'engine/templates/installer/databases.tpl' ) ); + + $this->installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array($databases_file) )); + file_put_contents( $databases_file, $databasesText ); + + // Execute scripts to create and populates databases + $query = sprintf( "USE %s;", $wf_workpace ); + $this->mysqlQuery( $query ); + + $this->mysqlFileQuery( PATH_RBAC_HOME . 'engine/data/mysql/schema.sql' ); + $this->mysqlFileQuery( PATH_RBAC_HOME . 'engine/data/mysql/insert.sql' ); + + $query = sprintf( "USE %s;", $wf_workpace ); + $this->mysqlQuery( $query ); + $this->mysqlFileQuery( PATH_HOME . 'engine/data/mysql/schema.sql' ); + $this->mysqlFileQuery( PATH_HOME . 'engine/data/mysql/insert.sql' ); + + + if (defined('PARTNER_FLAG') || isset($_REQUEST['PARTNER_FLAG'])) { + $this->setPartner(); + //$this->setConfiguration(); + } + + // Create the triggers + if (file_exists( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql' ) && file_exists( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql' ) && file_exists( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql' ) && file_exists( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationDelete.sql' ) && file_exists( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerContentUpdate.sql' )) { + $this->mysqlQuery( @file_get_contents( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql' ) ); + $this->mysqlQuery( @file_get_contents( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql' ) ); + $this->mysqlQuery( @file_get_contents( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql' ) ); + $this->mysqlQuery( @file_get_contents( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerApplicationDelete.sql' ) ); + $this->mysqlQuery(@file_get_contents(PATH_HOME . "engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql")); + $this->mysqlQuery( @file_get_contents( PATH_HOME . 'engine/methods/setup/setupSchemas/triggerContentUpdate.sql' ) ); + + $this->mysqlQuery( "INSERT INTO `CONFIGURATION` ( + `CFG_UID`, + `CFG_VALUE` + ) + VALUES ( + 'APP_CACHE_VIEW_ENGINE', + '" . mysql_real_escape_string( serialize( array ('LANG' => 'en','STATUS' => 'active' + ) ) ) . "' + )" ); + + /*----------------------------------********---------------------------------*/ + if (true) { + // + } else { + /*----------------------------------********---------------------------------*/ + $this->mysqlQuery("INSERT INTO EMAIL_SERVER(MESS_ENGINE) VALUES('MAIL')"); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + } + + // Change admin user + $query = sprintf( "USE %s;", $wf_workpace ); + $this->mysqlQuery( $query ); + + $query = sprintf( "UPDATE USERS SET USR_USERNAME = '%s', USR_LASTNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, $adminUsername, md5( $adminPassword ) ); + $this->mysqlQuery( $query ); + + $query = sprintf( "UPDATE RBAC_USERS SET USR_USERNAME = '%s', USR_LASTNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, $adminUsername, md5( $adminPassword ) ); + $this->mysqlQuery( $query ); + + // Write the paths_installed.php file (contains all the information configured so far) + if (! file_exists( FILE_PATHS_INSTALLED )) { + $sh = G::encryptOld( filemtime( PATH_GULLIVER . '/class.g.php' ) ); + $h = G::encrypt( $db_hostname . $sh . $db_username . $sh . $db_password, $sh ); + $dbText = "installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array(FILE_PATHS_INSTALLED) )); + file_put_contents( FILE_PATHS_INSTALLED, $dbText ); + } + + /** + * AppCacheView Build + */ + define( 'HASH_INSTALLATION', $h ); + define( 'SYSTEM_HASH', $sh ); + define( 'PATH_DB', $pathShared . 'sites' . PATH_SEP ); + define( 'SYS_SYS', $workspace ); + + require_once ("propel/Propel.php"); + + Propel::init( PATH_CORE . "config/databases.php" ); + $con = Propel::getConnection( 'workflow' ); + + require_once ('classes/model/AppCacheView.php'); + $lang = 'en'; + + //setup the appcacheview object, and the path for the sql files + $appCache = new AppCacheView(); + + $appCache->setPathToAppCacheFiles( PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP ); + + //Update APP_DELEGATION.DEL_LAST_INDEX data + $res = $appCache->updateAppDelegationDelLastIndex($lang, true); + + //APP_DELEGATION INSERT + $res = $appCache->triggerAppDelegationInsert( $lang, true ); + + //APP_DELEGATION Update + $res = $appCache->triggerAppDelegationUpdate( $lang, true ); + + //APPLICATION UPDATE + $res = $appCache->triggerApplicationUpdate( $lang, true ); + + //APPLICATION DELETE + $res = $appCache->triggerApplicationDelete( $lang, true ); + + //SUB_APPLICATION INSERT + $res = $appCache->triggerSubApplicationInsert($lang, false); + + //CONTENT UPDATE + $res = $appCache->triggerContentUpdate( $lang, true ); + + //build using the method in AppCacheView Class + $res = $appCache->fillAppCacheView( $lang ); + + //end AppCacheView Build + + + //erik: for new env conf handling + G::loadClass( 'system' ); + $envFile = PATH_CONFIG . 'env.ini'; + + // getting configuration from env.ini + $sysConf = System::getSystemConfiguration( $envFile ); + + $langUri = 'en'; + if (isset($sysConf['default_lang'])) { + $langUri = $sysConf['default_lang']; + } + + $skinUri = 'neoclassic'; + if (isset($sysConf['default_skin'])) { + $skinUri = $sysConf['default_skin']; + } + + $updatedConf['default_lang'] = $langUri; + $updatedConf['default_skin'] = $skinUri; + $info->uri = PATH_SEP . 'sys' . $_REQUEST['workspace'] . PATH_SEP . $langUri . PATH_SEP . $skinUri . PATH_SEP . 'login' . PATH_SEP . 'login'; + + //register PMDesigner Client + $http = (G::is_https() == true) ? 'https' : 'http'; + $host = $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] != '80' ? ':' . $_SERVER['SERVER_PORT'] : ''); + + $endpoint = sprintf( + '%s://%s/sys%s/%s/%s/oauth2/grant', + $http, + $host, + $workspace, + $langUri, + $skinUri + ); + + // inserting the outh_client + if (!$userLogged) { + $query = sprintf( "USE %s;", $wf ); + } else { + $query = sprintf( "USE %s;", trim( $_REQUEST['wfDatabase']) ); + } + $this->mysqlQuery( $query ); + $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->mysqlQuery( $query ); + + $indexFileUpdated = true; + if (defined('PARTNER_FLAG') || isset($_REQUEST['PARTNER_FLAG'])) { + $this->buildParternExtras($adminUsername, $adminPassword, $_REQUEST['workspace'], $langUri, $skinUri); + } else { + try { + G::update_php_ini( $envFile, $updatedConf ); + } catch (Exception $e) { + $info->result = false; + $info->message = G::LoadTranslation('ID_PROCESSMAKER_WRITE_CONFIG_INDEX', SYS_LANG, Array($envFile)); + $info->message .= G::LoadTranslation('ID_PROCESSMAKER_UI_NOT_INSTALL'); + $this->installLog( G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, Array('env.ini'))); + return $info; + } + + try { + // update the main index file + $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.")); + $info->message .= G::LoadTranslation('ID_PROCESSMAKER_UI_NOT_INSTALL'); + $this->installLog( G::LoadTranslation('ID_INSTALL_BUT_ERROR', SYS_LANG, Array('index.html'))); + return $info; + } + } + + $this->installLog( G::LoadTranslation('ID_INDEX_FILE_UPDATED', SYS_LANG, Array($indexFileUpdated, $sysConf['default_lang'],$sysConf['default_skin']))); + $this->installLog( G::LoadTranslation('ID_INSTALL_SUCESS') ); + + $info->result = true; + $info->message = G::LoadTranslation('ID_INSTALL_SUCESS'); + $info->messageFinish = G::LoadTranslation('ID_PROCESSMAKER_SUCCESS_INSTALLED', SYS_LANG, Array($workspace));; + } catch (Exception $e) { + $info->canRedirect = false; + $info->result = false; + $info->message = $e->getMessage(); + } + return $info; + } + + public function createMSSQLWorkspace () + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + ini_set( 'max_execution_time', '0' ); + + $info = new stdClass(); + $info->result = false; + $info->message = ''; + + $db_hostname = trim( $_REQUEST['db_hostname'] ); + $db_hostname = $filter->validateInput($db_hostname); + $db_port = trim( $_REQUEST['db_port'] ); + $db_port = $filter->validateInput($db_port); + $db_username = trim( $_REQUEST['db_username'] ); + $db_username = $filter->validateInput($db_username); + $db_password = trim( $_REQUEST['db_password'] ); + $db_password = $filter->validateInput($db_password); + $wf = trim( $_REQUEST['wfDatabase'] ); + $rb = trim( $_REQUEST['wfDatabase'] ); + $rp = trim( $_REQUEST['wfDatabase'] ); + $workspace = trim( $_REQUEST['workspace'] ); + $pathConfig = trim( $_REQUEST['pathConfig'] ); + $pathLanguages = trim( $_REQUEST['pathLanguages'] ); + $pathPlugins = trim( $_REQUEST['pathPlugins'] ); + $pathShared = trim( $_REQUEST['pathShared'] ); + $pathXmlforms = trim( $_REQUEST['pathXmlforms'] ); + $adminPassword = trim( $_REQUEST['adminPassword'] ); + $adminUsername = trim( $_REQUEST['adminUsername'] ); + $deleteDB = ($_REQUEST['deleteDB'] == 'true'); + + if (substr( $pathShared, - 1 ) != '/') { + $pathShared .= '/'; + } + + $this->installLog( '-------------------------------------------' ); + $this->installLog( G::LoadTranslation('ID_CREATING_WORKSPACE', SYS_LANG, Array($workspace) ) ); + + try { + $db_host = ($db_port != '' && $db_port != 1433) ? $db_hostname . ':' . $db_port : $db_hostname; + $db_host = $filter->validateInput($db_host); + $db_username = $filter->validateInput($db_username); + $db_password = $filter->validateInput($db_password); + $this->link = @mssql_connect( $db_host, $db_username, $db_password ); + $this->installLog( G::LoadTranslation('ID_CONNECT_TO_SERVER', SYS_LANG, Array( $db_hostname, $db_port, $db_username )) ); + + $this->mssqlQuery( 'USE [master]' ); + + // DROP databases wf_workflow, rb_workflow and rp_workflow + if ($deleteDB) { + $q = sprintf( "IF EXISTS (SELECT name FROM sys.databases WHERE name='%s' ) DROP DATABASE %s", $wf, $wf ); + $this->mssqlQuery( $q ); + } + + // CREATE databases wf_workflow, rb_workflow and rp_workflow + $q = sprintf( "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name='%s' ) CREATE DATABASE %s", $wf, $wf ); + $this->mssqlQuery( $q ); + + //CREATE users and GRANT Privileges + $wfPass = G::generate_password( 12 ); + $this->setGrantPrivilegesMSSQL( $wf, $wfPass, $wf ); + + //Generate the db.php file and folders + $path_site = $pathShared . "/sites/" . $workspace . "/"; + $db_file = $path_site . "db.php"; + mkdir( $path_site, 0777, true ); + @mkdir( $path_site . "files/", 0777, true ); + @mkdir( $path_site . "mailTemplates/", 0777, true ); + @mkdir( $path_site . "public/", 0777, true ); + @mkdir( $path_site . "reports/", 0777, true ); + @mkdir( $path_site . "xmlForms", 0777, true ); + + $dbText = "systemName != '') { + $dbText .= " define ('SYSTEM_NAME', '" . $this->systemName . "');\n"; + } + } + + $this->installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array($db_file) )); + file_put_contents( $db_file, $dbText ); + + // Generate the databases.php file + $databases_file = $path_site . 'databases.php'; + $dbData = sprintf( "\$dbAdapter = '%s';\n", 'mssql' ); + $dbData .= sprintf( "\$dbHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbName = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbPass = '%s';\n", $wfPass ); + $dbData .= sprintf( "\$dbRbacHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbRbacName = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbRbacUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbRbacPass = '%s';\n", $wfPass ); + $dbData .= sprintf( "\$dbReportHost = '%s';\n", $db_host ); + $dbData .= sprintf( "\$dbReportName = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbReportUser = '%s';\n", $wf ); + $dbData .= sprintf( "\$dbReportPass = '%s';\n", $wfPass ); + $databasesText = str_replace( '{dbData}', $dbData, @file_get_contents( PATH_HOME . 'engine/templates/installer/databases.tpl' ) ); + + $this->installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array($databases_file) )); + file_put_contents( $databases_file, $databasesText ); + + //execute scripts to create and populates databases + $query = sprintf( "USE %s;", $wf ); + $this->mssqlQuery( $query ); + + $this->mssqlFileQuery( PATH_RBAC_HOME . 'engine/data/mssql/schema.sql' ); + $this->mssqlFileQuery( PATH_RBAC_HOME . 'engine/data/mssql/insert.sql' ); + + $query = sprintf( "USE %s;", $wf ); + $this->mssqlQuery( $query ); + $this->mssqlFileQuery( PATH_HOME . 'engine/data/mssql/schema.sql' ); + $this->mssqlFileQuery( PATH_HOME . 'engine/data/mssql/insert.sql' ); + + // Create the triggers + if (file_exists( PATH_HOME . 'engine/plugins/enterprise/data/triggerAppDelegationInsert.sql' ) && file_exists( PATH_HOME . 'engine/plugins/enterprise/data/triggerAppDelegationUpdate.sql' ) && file_exists( PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationUpdate.sql' ) && file_exists( PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationDelete.sql' ) && file_exists( PATH_HOME . 'engine/plugins/enterprise/data/triggerContentUpdate.sql' )) { + $this->mssqlQuery( @file_get_contents( PATH_HOME . 'engine/plugins/enterprise/data/triggerAppDelegationInsert.sql' ) ); + $this->mssqlQuery( @file_get_contents( PATH_HOME . 'engine/plugins/enterprise/data/triggerAppDelegationUpdate.sql' ) ); + $this->mssqlQuery( @file_get_contents( PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationUpdate.sql' ) ); + $this->mssqlQuery( @file_get_contents( PATH_HOME . 'engine/plugins/enterprise/data/triggerApplicationDelete.sql' ) ); + $this->mysqlQuery(@file_get_contents(PATH_HOME . "engine/methods/setup/setupSchemas/triggerSubApplicationInsert.sql")); + $this->mssqlQuery( @file_get_contents( PATH_HOME . 'engine/plugins/enterprise/data/triggerContentUpdate.sql' ) ); + $this->mssqlQuery( "INSERT INTO CONFIGURATION ( + CFG_UID, + CFG_VALUE + ) + VALUES ( + 'APP_CACHE_VIEW_ENGINE', + '" . addslashes( serialize( array ('LANG' => 'en','STATUS' => 'active' + ) ) ) . "' + )" ); + + /*----------------------------------********---------------------------------*/ + if (true) { + // + } else { + /*----------------------------------********---------------------------------*/ + $this->mssqlQuery("INSERT INTO EMAIL_SERVER(MESS_ENGINE) VALUES('MAIL')"); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + } + + //change admin user + $query = sprintf( "USE %s;", $wf ); + $this->mssqlQuery( $query ); + + $query = sprintf( "UPDATE USERS SET USR_USERNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, G::encryptOld( $adminPassword ) ); + $this->mssqlQuery( $query ); + + $query = sprintf( "USE %s;", $wf ); + $this->mssqlQuery( $query ); + + $query = sprintf( "UPDATE RBAC_USERS SET USR_USERNAME = '%s', USR_PASSWORD = '%s' WHERE USR_UID = '00000000000000000000000000000001' ", $adminUsername, G::encryptOld( $adminPassword ) ); + $this->mssqlQuery( $query ); + + // Write the paths_installed.php file (contains all the information configured so far) + if (! file_exists( FILE_PATHS_INSTALLED )) { + $sh = G::encryptOld( filemtime( PATH_GULLIVER . '/class.g.php' ) ); + $h = G::encrypt( $db_hostname . $sh . $db_username . $sh . $db_password . '1', $sh ); + $dbText = "installLog( G::LoadTranslation('ID_CREATING', SYS_LANG, Array(FILE_PATHS_INSTALLED) )); + file_put_contents( FILE_PATHS_INSTALLED, $dbText ); + } + $this->installLog( G::LoadTranslation('ID_INSTALL_SUCESS') ); + $info->result = true; + $info->message = G::LoadTranslation('ID_INSTALL_SUCESS'); + $info->url = '/sys' . $_REQUEST['workspace'] . '/en/neoclassic/login/login'; + $info->messageFinish = G::LoadTranslation('ID_PROCESSMAKER_SUCCESS_INSTALLED', SYS_LANG, Array($workspace));; + } catch (Exception $e) { + $info->result = false; + $info->message = $e->getMessage(); + } + return $info; + } + + public function getSystemName ($siteShared) + { + $systemName = ''; + if (substr( $siteShared, - 1 ) != '/') { + $siteShared .= '/'; + } + + if (file_exists($siteShared . 'partner.info')) { + $dataInfo = parse_ini_file($siteShared . 'partner.info'); + if (isset($dataInfo['system_name'])) { + $systemName = trim($dataInfo['system_name']); + } + } + return $systemName; + } + + public function getEngines () + { + $this->setResponseType( 'json' ); + $engines = array (); + if (function_exists( 'mysql_query' )) { + $engine = new stdclass(); + $engine->id = 'mysql'; + $engine->label = 'MySQL'; + $engines[] = $engine; + } + /** + * DISABLED TEMPORARELY + * if (function_exists('mssql_query')) { + * $engine = new stdclass(); + * $engine->id = 'mssql'; + * $engine->label = 'Microsoft SQL Server'; + * $engines[] = $engine; + * } + */ + return $engines; + } + + public function checkDatabases () + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $this->setResponseType( 'json' ); + $info = new stdclass(); + + if ($_REQUEST['db_engine'] == 'mysql') { + $_REQUEST['db_hostname'] = $filter->validateInput($_REQUEST['db_hostname']); + $_REQUEST['db_username'] = $filter->validateInput($_REQUEST['db_username']); + $_REQUEST['db_password'] = $filter->validateInput($_REQUEST['db_password']); + $link = @mysql_connect( $_REQUEST['db_hostname'], $_REQUEST['db_username'], $_REQUEST['db_password'] ); + $_REQUEST['wfDatabase'] = $filter->validateInput($_REQUEST['wfDatabase'], 'nosql'); + $query = "show databases like '%s' "; + $query = $filter->preventSqlInjection( $query, array($_REQUEST['wfDatabase']) ); + $dataset = @mysql_query( $query, $link ); + $info->wfDatabaseExists = (@mysql_num_rows( $dataset ) > 0); + } else if ($_REQUEST['db_engine'] == 'mssql') { + $link = @mssql_connect( $_REQUEST['db_hostname'], $_REQUEST['db_username'], $_REQUEST['db_password'] ); + $_REQUEST['wfDatabase'] = $filter->validateInput($_REQUEST['wfDatabase'], 'nosql'); + $query = "select * from sys.databases where name = '%s' "; + $query = $filter->preventSqlInjection( $query, array($_REQUEST['wfDatabase']) ); + $dataset = @mssql_query( $query , $link ); + $info->wfDatabaseExists = (@mssql_num_rows( $dataset ) > 0); + } else if ($_REQUEST['db_engine'] == 'sqlsrv') { + $arguments = array("UID" => $_REQUEST['db_username'], "PWD" => $_REQUEST['db_password']); + $link = @sqlsrv_connect( $_REQUEST['db_hostname'], $arguments); + $_REQUEST['wfDatabase'] = $filter->validateInput($_REQUEST['wfDatabase'], 'nosql'); + $query = "select * from sys.databases where name = '%s' "; + $query = $filter->preventSqlInjection( $query, array($_REQUEST['wfDatabase']) ); + $dataset = @sqlsrv_query( $link, $query ); + $info->wfDatabaseExists = (@sqlsrv_num_rows( $dataset ) > 0); + } else { + $link = @mssql_connect( $_REQUEST['db_hostname'], $_REQUEST['db_username'], $_REQUEST['db_password'] ); + $_REQUEST['wfDatabase'] = $filter->validateInput($_REQUEST['wfDatabase'], 'nosql'); + $query = "select * from sys.databases where name = '%s' "; + $query = $filter->preventSqlInjection( $query, array($_REQUEST['wfDatabase']) ); + $dataset = @mssql_query( $query , $link ); + $info->wfDatabaseExists = (@mssql_num_rows( $dataset ) > 0); + } + + $info->errMessage = G::LoadTranslation('ID_DATABASE_EXISTS_OVERWRITE'); + + return $info; + } + + /** + * Privates functions section, non callable by http request + */ + + private function testMySQLconnection () + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $info = new StdClass(); + $info->result = false; + $info->message = ''; + if (! function_exists( "mysql_connect" )) { + $info->message = G::LoadTranslation('ID_PHP_MYSQL_NOT _INSTALL'); + return $info; + } + $db_hostname = $_REQUEST['db_hostname']; + $db_hostname = $filter->validateInput($db_hostname); + $db_port = $_REQUEST['db_port']; + $db_port = $filter->validateInput($db_port); + $db_username = $_REQUEST['db_username']; + $db_username = $filter->validateInput($db_username); + $db_password = $_REQUEST['db_password']; + $db_password = $filter->validateInput($db_password); + $fp = @fsockopen( $db_hostname, $db_port, $errno, $errstr, 30 ); + if (! $fp) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR', SYS_LANG, Array("$errstr ($errno)")); + return $info; + } + + $db_host = ($db_port != '' && $db_port != 1433) ? $db_hostname . ':' . $db_port : $db_hostname; + + $link = @mysql_connect( $db_host, $db_username, $db_password ); + if (! $link) { + $info->message .= G::LoadTranslation('ID_MYSQL_CREDENTIALS_WRONG'); + return $info; + } + $db_username = $filter->validateInput($db_username, 'nosql'); + $db_hostname = $filter->validateInput($db_hostname, 'nosql'); + $query = "SELECT * FROM `information_schema`.`USER_PRIVILEGES` where (GRANTEE = \"'%s'@'%s'\" OR GRANTEE = \"'%s'@'%%'\") "; + $query = $filter->preventSqlInjection($query, array($db_username, $db_hostname, $db_username)); + $res = @mysql_query( $query, $link ); + $row = @mysql_fetch_array( $res ); + $hasSuper = is_array( $row ); + @mysql_free_result( $res ); + @mysql_close( $link ); + if (! $hasSuper) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR_PRIVILEGE', SYS_LANG, Array($db_username)); + return $info; + } + $info->message .= G::LoadTranslation('ID_MYSQL_SUCCESS_CONNECT'); + $info->result = true; + return $info; + } + + private function testMSSQLconnection () + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + $info = new stdClass(); + $info->result = false; + $info->message = ''; + + if (! function_exists( "mssql_connect" )) { + $info->message = G::LoadTranslation('ID_PHP_MSSQL_NOT_INSTALLED'); + return $info; + } + + $db_hostname = $_REQUEST['db_hostname']; + $db_hostname = $filter->validateInput($db_hostname); + $db_port = $_REQUEST['db_port']; + $db_port = $filter->validateInput($db_port); + $db_username = $_REQUEST['db_username']; + $db_username = $filter->validateInput($db_username); + $db_password = $_REQUEST['db_password']; + $db_password = $filter->validateInput($db_password); + + $fp = @fsockopen( $db_hostname, $db_port, $errno, $errstr, 30 ); + if (! $fp) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR', SYS_LANG, Array("$errstr ($errno)")); + return $info; + } + + $db_host = ($db_port != '' && $db_port != 1433) ? $db_hostname . ':' . $db_port : $db_hostname; + + $link = @mssql_connect( $db_host, $db_username, $db_password ); + if (! $link) { + $info->message .= G::LoadTranslation('ID_MYSQL_CREDENTIALS_WRONG'); + return $info; + } + + //checking if user has the dbcreator role + $hasDbCreator = false; + $hasSecurityAdmin = false; + $hasSysAdmin = false; + + $res = @mssql_query( "EXEC sp_helpsrvrolemember 'dbcreator' ", $link ); + $row = mssql_fetch_array( $res ); + while (is_array( $row )) { + if ($row['MemberName'] == $db_username) { + $hasDbCreator = true; + } + $row = mssql_fetch_array( $res ); + } + mssql_free_result( $res ); + + $res = @mssql_query( "EXEC sp_helpsrvrolemember 'sysadmin' ", $link ); + $row = mssql_fetch_array( $res ); + while (is_array( $row )) { + if ($row['MemberName'] == $db_username) { + $hasSysAdmin = true; + } + $row = mssql_fetch_array( $res ); + } + mssql_free_result( $res ); + + $res = @mssql_query( "EXEC sp_helpsrvrolemember 'SecurityAdmin' ", $link ); + $row = mssql_fetch_array( $res ); + while (is_array( $row )) { + if ($row['MemberName'] == $db_username) { + $hasSecurityAdmin = true; + } + $row = mssql_fetch_array( $res ); + } + mssql_free_result( $res ); + + if (! ($hasSysAdmin || ($hasSecurityAdmin && $hasDbCreator))) { + $info->message .= G::LoadTranslation('ID_CONNECTION_ERROR_SECURITYADMIN', SYS_LANG, Array($db_username) ); + return $info; + } + + $info->message .= G::LoadTranslation('ID_MSSQL_SUCCESS_CONNECT'); + $info->result = true; + return $info; + } + + public function setPartner() + { + if (defined('PARTNER_FLAG') || isset($_REQUEST['PARTNER_FLAG'])) { + // Execute sql for partner + $pathMysqlPartner = PATH_CORE . 'data' . PATH_SEP . 'partner' . PATH_SEP . 'mysql' . PATH_SEP; + if (G::verifyPath($pathMysqlPartner)) { + $res = array(); + $filesSlq = glob($pathMysqlPartner . '*.sql'); + foreach ($filesSlq as $value) { + $this->mysqlFileQuery($value); + } + } + + // Execute to change of skin + $pathSkinPartner = PATH_CORE . 'data' . PATH_SEP . 'partner' . PATH_SEP . 'skin' . PATH_SEP; + if (G::verifyPath($pathSkinPartner)) { + $res = array(); + $fileTar = glob($pathSkinPartner . '*.tar'); + foreach ($fileTar as $value) { + $dataFile = pathinfo($value); + $nameSkinTmp = $dataFile['filename']; + G::LoadThirdParty( 'pear/Archive', 'Tar' ); + $tar = new Archive_Tar( $value ); + + $pathSkinTmp = $pathSkinPartner . 'tmp' . PATH_SEP; + G::rm_dir($pathSkinTmp); + G::verifyPath($pathSkinTmp, true); + chmod( $pathSkinTmp, 0777); + $tar->extract($pathSkinTmp); + + $pathSkinName = $pathSkinTmp . $nameSkinTmp . PATH_SEP; + chmod( $pathSkinName, 0777); + G::verifyPath(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', true); + $skinClassic = PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp' . PATH_SEP; + + if (is_dir($pathSkinName)) { + $this->copyFile($pathSkinName, $skinClassic); + } + + G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'base'); + rename(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp', PATH_CORE . 'skinEngine' . PATH_SEP . 'base'); + G::rm_dir(PATH_CORE . 'skinEngine' . PATH_SEP . 'tmp'); + + break; + } + } + } + } + + function copyFile($fromDir, $toDir, $chmod=0777) + { + $errors = array(); + $messages = array(); + + if (!is_writable($toDir)) { + $errors[]='target '.$toDir.' is not writable'; + } + if (!is_dir($toDir)) { + $errors[]='target '.$toDir.' is not a directory'; + } + if (!is_dir($fromDir)) { + $errors[]='source '.$fromDir.' is not a directory'; + } + if (!empty($errors)) { + return false; + } + + $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); + if (is_file($from)) { + if (@copy($from,$to)) { + chmod($to,$chmod); + touch($to,filemtime($from)); + } + } + + if (is_dir($from)) { + if (@mkdir($to)) { + chmod($to,$chmod); + } + $this->copyFile($from,$to,$chmod); + } + } + } + + closedir($handle); + } + + public function setConfiguration() + { + //a:4:{s:26:"login_enableForgotPassword";b:0;s:27:"login_enableVirtualKeyboard";b:0;s:21:"login_defaultLanguage";s:5:"pt-BR";s:10:"dateFormat";s:15:"d \\d\\e F \\d\\e Y";} + $value = array( + 'login_defaultLanguage' => "pt-BR", + "dateFormat" => 'd \d\e F \d\e Y' + ); + + $value = serialize($value); + $query = "INSERT INTO CONFIGURATION (CFG_UID, CFG_VALUE) VALUES ('ENVIRONMENT_SETTINGS', '".mysql_real_escape_string($value)."')"; + + $this->mysqlQuery($query); + } + + public function buildParternExtras($username, $password, $workspace, $lang, $skinName) + { + G::LoadSystem('inputfilter'); + $filter = new InputFilter(); + ini_set('max_execution_time', '0'); + ini_set('memory_limit', '256M'); + + $serv = 'http://'; + if (isset($_SERVER['HTTPS']) && trim($_SERVER['HTTPS']) != '') { + $serv = 'https://'; + } + $serv .= $_SERVER['SERVER_NAME']; + if (isset($_SERVER['SERVER_PORT']) && trim($_SERVER['SERVER_PORT']) != '') { + $serv .= ':' . $_SERVER['SERVER_PORT']; + } + + // create session + $cookiefile = sys_get_temp_dir() . PATH_SEP . 'curl-session'; + + $fp = fopen($cookiefile, "w"); + fclose($fp); + chmod($cookiefile, 0777); + + $user = urlencode($username); + $user = $filter->validateInput($user); + $pass = urlencode($password); + $pass = $filter->validateInput($pass); + $lang = urlencode($lang); + $lang = $filter->validateInput($lang); + + $ch = curl_init(); + + // set URL and other appropriate options + curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/login/authentication"); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, "form[USR_USERNAME]=$user&form[USR_PASSWORD]=$pass&form[USER_LANG]=$lang"); + curl_setopt($ch, CURLOPT_TIMEOUT, 90); + + $output = curl_exec($ch); + curl_close($ch); + + /** + * Upload translation .po file + */ + + $ch = curl_init(); + $postData = array(); + // File to upload/post + + $postData['form[LANGUAGE_FILENAME]'] = "@".PATH_CORE."content/translations/processmaker.$lang.po"; + curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/languages_Import"); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_TIMEOUT, 90); + + $output = curl_exec($ch); + curl_close($ch); + + /** + * Upload skin file + */ + + $ch = curl_init(); + $postData = array(); + + $skins = glob(PATH_CORE."data/partner/*.tar"); + if (count($skins) > 0) { + $skin = $skins[0]; + + $postData['overwrite_files'] = "on"; + $postData['workspace'] = "global"; + $postData['option'] = "standardupload"; + $postData['action'] = "importSkin"; + // File to upload/post + $postData['uploadedFile'] = "@".$skin; + + curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/skin_Ajax"); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_TIMEOUT, 90); + + $output = curl_exec($ch); + curl_close($ch); + } + + /** + * Upload plugin file + */ + + $ch = curl_init(); + $postData = array(); + // resolv the plugin name + $plugins = glob(PATH_CORE."plugins/*.tar"); + if (count($plugins) > 0) { + $pluginName = $plugins[0]; + + // File to upload/post + $postData['form[PLUGIN_FILENAME]'] = "@{$pluginName}"; + curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/setup/pluginsImportFile"); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_TIMEOUT, 90); + + $output = curl_exec($ch); + curl_close($ch); + } + + /** + * Active plugins to enterprise + */ + + if (!defined("PATH_PM_ENTERPRISE")) { + define("PATH_PM_ENTERPRISE", PATH_CORE . "/plugins/enterprise/"); + } + set_include_path(PATH_PM_ENTERPRISE . PATH_SEPARATOR . get_include_path()); + require_once ('classes/model/AddonsManager.php'); + + $plugins = glob(PATH_CORE."plugins/*.php"); + foreach ($plugins as $value) { + $dataPlugin = pathinfo($value); + $namePlugin = $dataPlugin['filename']; + if ($value != 'enterprise') { + $db_hostname = trim( $_REQUEST['db_hostname'] ); + $db_hostname = $filter->validateInput($db_hostname); + $db_port = trim( $_REQUEST['db_port'] ); + $db_port = $filter->validateInput($db_port); + $db_username = trim( $_REQUEST['db_username'] ); + $db_username = $filter->validateInput($db_username); + $db_password = trim( $_REQUEST['db_password'] ); + $db_password = $filter->validateInput($db_password); + $wf = trim( $_REQUEST['wfDatabase'] ); + + $db_host = ($db_port != '' && $db_port != 3306) ? $db_hostname . ':' . $db_port : $db_hostname; + + $link = @mysql_connect( $db_host, $db_username, $db_password ); + @mysql_select_db($wf, $link); + $res = mysql_query( "SELECT STORE_ID FROM ADDONS_MANAGER WHERE ADDON_NAME = '" . $namePlugin . "'", $link ); + if ($row = mysql_fetch_array( $res )) { + $ch = curl_init(); + $postData = array(); + $postData['action'] = "enable"; + $postData['addon'] = $namePlugin; + $postData['store'] = $row['STORE_ID']; + + curl_setopt($ch, CURLOPT_URL, "$serv/sys{$workspace}/{$lang}/{$skinName}/enterprise/addonsStoreAction"); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_VERBOSE, 0); + curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); + curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); + curl_setopt($ch, CURLOPT_TIMEOUT, 90); + + $output = curl_exec($ch); + curl_close($ch); + } + } + } + } +} + diff --git a/workflow/engine/methods/cases/cases_Ajax.php b/workflow/engine/methods/cases/cases_Ajax.php new file mode 100644 index 000000000..a494ff921 --- /dev/null +++ b/workflow/engine/methods/cases/cases_Ajax.php @@ -0,0 +1,1028 @@ +xssFilterHard($_GET); +$_POST = $filter->xssFilterHard($_POST); +$_REQUEST = $filter->xssFilterHard($_REQUEST); +$_SESSION = $filter->xssFilterHard($_SESSION); + +if (!isset($_SESSION['USER_LOGGED'])) { + $response = new stdclass(); + $response->message = G::LoadTranslation('ID_LOGIN_AGAIN'); + $response->lostSession = true; + print G::json_encode( $response ); + die(); +} +/** + * cases_Ajax.php + * + * ProcessMaker Open Source Edition + * Copyright (C) 2004 - 2008 Colosa Inc.23 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * Coral Gables, FL, 33134, USA, or email info@colosa.com. + */ + +G::LoadClass( 'case' ); +$oCase = new Cases(); + +//if($RBAC->userCanAccess('PM_ALLCASES') < 0) { +// $oCase->thisIsTheCurrentUser( $_SESSION['APPLICATION'], +// $_SESSION['INDEX'], +// $_SESSION['USER_LOGGED'], +// 'SHOW_MESSAGE'); +//} + + +if (($RBAC_Response = $RBAC->userCanAccess( "PM_CASES" )) != 1) { + return $RBAC_Response; +} + +if (isset( $_POST['showWindow'] )) { + if ($_POST['showWindow'] == 'steps') { + $fn = 'showSteps();'; + } elseif ($_POST['showWindow'] == 'information') { + $fn = 'showInformation();'; + } elseif ($_POST['showWindow'] == 'actions') { + $fn = 'showActions();'; + } elseif ($_POST['showWindow'] == 'false') { + $fn = ''; + } else { + if ($_POST['showWindow'] != '') { + $fn = false; + } + } + $_SESSION['showCasesWindow'] = $fn; +} + +if (! isset( $_POST['action'] )) { + $_POST['action'] = ''; +} + +switch (($_POST['action']) ? $_POST['action'] : $_REQUEST['action']) { + case 'steps': + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'view', 'cases/cases_StepsTree' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'information': + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'view', 'cases/cases_InformationTree' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'actions': + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'view', 'cases/cases_ActionsTree' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showProcessMap': + G::LoadClass( 'processMap' ); + $oTemplatePower = new TemplatePower( PATH_TPL . 'processes/processes_Map.html' ); + $oTemplatePower->prepare(); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'template', '', '', '', $oTemplatePower ); + $oHeadPublisher = & headPublisher::getSingleton(); + $oHeadPublisher->addScriptCode( ' + var maximunX = ' . processMap::getMaximunTaskX( $_SESSION['PROCESS'] ) . '; + var pb=leimnud.dom.capture("tag.body 0"); + Pm=new processmap(); + + var params = "{\"uid\":\"' . $_SESSION['PROCESS'] . '\",\"mode\":false,\"ct\":false}"; + // maximun x and y position + var xPos = 0; + var yPos = 0; + + //obtaining the processmap object for the current process + var oRPC = new leimnud.module.rpc.xmlhttp({ + url : "../processes/processes_Ajax", + async : false, + method: "POST", + args : "action=load&data="+params + }); + + // make the ajax call + oRPC.make(); + var response = eval(\'(\' + oRPC.xmlhttp.responseText + \')\'); + //alert(response); + + for (var i in response) { + if (i==\'task\') { + elements = response[i]; + for (var j in elements) { + if (elements[j].uid!=undefined) { + if (elements[j].position.x > xPos) { + xPos = elements[j].position.x; + } + if (elements[j].position.y > yPos) { + yPos = elements[j].position.y; + } + } + } + } + } + + Pm.options = { + target : "pm_target", + dataServer: "../processes/processes_Ajax", + uid : "' . $_SESSION['PROCESS'] . '", + lang : "' . SYS_LANG . '", + theme : "processmaker", + size : {w:xPos+200,h:yPos+150}, + images_dir: "/jscore/processmap/core/images/", + rw : false, + hideMenu : false + } + Pm.make();' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showLeyends': + $aFields = array (); + $aFields['sLabel1'] = G::LoadTranslation( 'ID_TASK_IN_PROGRESS' ); + $aFields['sLabel2'] = G::LoadTranslation( 'ID_COMPLETED_TASK' ); + $aFields['sLabel3'] = G::LoadTranslation( 'ID_PENDING_TASK' ); + $aFields['sLabel4'] = G::LoadTranslation( 'ID_PARALLEL_TASK' ); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'smarty', 'cases/cases_Leyends', '', '', $aFields ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showProcessInformation': + //require_once 'classes/model/Process.php'; + $oProcess = new Process(); + $aFields = $oProcess->load( $_SESSION['PROCESS'] ); + require_once 'classes/model/Users.php'; + $oUser = new Users(); + try { + $aUser = $oUser->load( $aFields['PRO_CREATE_USER'] ); + $aFields['PRO_AUTHOR'] = $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME']; + } catch (Exception $oError) { + $aFields['PRO_AUTHOR'] = '(USER DELETED)'; + } + $aFields['PRO_CREATE_DATE'] = date( 'F j, Y', strtotime( $aFields['PRO_CREATE_DATE'] ) ); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_ProcessInformation', '', $aFields ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showTransferHistory': + G::LoadClass( "case" ); + $c = Cases::getTransferHistoryCriteria( $_SESSION['APPLICATION'] ); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_TransferHistory', $c, array () ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showDynaformListHistory': + //require_once 'classes/model/AppHistory.php'; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'view', 'cases/cases_DynaformHistory' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showTaskInformation': + //require_once 'classes/model/AppDelegation.php'; + //require_once 'classes/model/Task.php'; + $oTask = new Task(); + $aFields = $oTask->load( $_SESSION['TASK'] ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( AppDelegationPeer::APP_UID, $_SESSION['APPLICATION'] ); + $oCriteria->add( AppDelegationPeer::DEL_INDEX, $_SESSION['INDEX'] ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aDelegation = $oDataset->getRow(); + $iDiff = strtotime( $aDelegation['DEL_FINISH_DATE'] ) - strtotime( $aDelegation['DEL_INIT_DATE'] ); + $aFields['INIT_DATE'] = ($aDelegation['DEL_INIT_DATE'] != null ? $aDelegation['DEL_INIT_DATE'] : G::LoadTranslation( 'ID_CASE_NOT_YET_STARTED' )); + $aFields['DUE_DATE'] = ($aDelegation['DEL_TASK_DUE_DATE'] != null ? $aDelegation['DEL_TASK_DUE_DATE'] : G::LoadTranslation( 'ID_NOT_FINISHED' )); + $aFields['FINISH'] = ($aDelegation['DEL_FINISH_DATE'] != null ? $aDelegation['DEL_FINISH_DATE'] : G::LoadTranslation( 'ID_NOT_FINISHED' )); + $aFields['DURATION'] = ($aDelegation['DEL_FINISH_DATE'] != null ? (int) ($iDiff / 3600) . ' ' . ((int) ($iDiff / 3600) == 1 ? G::LoadTranslation( 'ID_HOUR' ) : G::LoadTranslation( 'ID_HOURS' )) . ' ' . (int) (($iDiff % 3600) / 60) . ' ' . ((int) (($iDiff % 3600) / 60) == 1 ? G::LoadTranslation( 'ID_MINUTE' ) : G::LoadTranslation( 'ID_MINUTES' )) . ' ' . (int) (($iDiff % 3600) % 60) . ' ' . ((int) (($iDiff % 3600) % 60) == 1 ? G::LoadTranslation( 'ID_SECOND' ) : G::LoadTranslation( 'ID_SECONDS' )) : G::LoadTranslation( 'ID_NOT_FINISHED' )); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_TaskInformation', '', $aFields ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showTaskDetails': + //require_once 'classes/model/AppDelegation.php'; + //require_once 'classes/model/Task.php'; + //require_once 'classes/model/Users.php'; + $oTask = new Task(); + $aRow = $oTask->load( $_POST['sTaskUID'] ); + $sTitle = $aRow['TAS_TITLE']; + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( UsersPeer::USR_UID ); + $oCriteria->addSelectColumn( UsersPeer::USR_FIRSTNAME ); + $oCriteria->addSelectColumn( UsersPeer::USR_LASTNAME ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_INIT_DATE ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_TASK_DUE_DATE ); + $oCriteria->addSelectColumn( AppDelegationPeer::DEL_FINISH_DATE ); + $oCriteria->addJoin( AppDelegationPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN ); + $oCriteria->add( AppDelegationPeer::APP_UID, $_SESSION['APPLICATION'] ); + $oCriteria->add( AppDelegationPeer::TAS_UID, $_POST['sTaskUID'] ); + $oCriteria->addDescendingOrderByColumn( AppDelegationPeer::DEL_INDEX ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + $iDiff = strtotime( $aRow['DEL_FINISH_DATE'] ) - strtotime( $aRow['DEL_INIT_DATE'] ); + $aFields = array (); + $aFields['TASK'] = $sTitle; + $aFields['USER'] = ($aRow['USR_UID'] != null ? $aRow['USR_FIRSTNAME'] . ' ' . $aRow['USR_LASTNAME'] : G::LoadTranslation( 'ID_NONE' )); + $aFields['INIT_DATE'] = ($aRow['DEL_INIT_DATE'] != null ? $aRow['DEL_INIT_DATE'] : G::LoadTranslation( 'ID_CASE_NOT_YET_STARTED' )); + $aFields['DUE_DATE'] = ($aRow['DEL_TASK_DUE_DATE'] != null ? $aRow['DEL_TASK_DUE_DATE'] : G::LoadTranslation( 'ID_CASE_NOT_YET_STARTED' )); + $aFields['FINISH'] = ($aRow['DEL_FINISH_DATE'] != null ? $aRow['DEL_FINISH_DATE'] : G::LoadTranslation( 'ID_NOT_FINISHED' )); + $aFields['DURATION'] = ($aRow['DEL_FINISH_DATE'] != null ? (int) ($iDiff / 3600) . ' ' . ((int) ($iDiff / 3600) == 1 ? G::LoadTranslation( 'ID_HOUR' ) : G::LoadTranslation( 'ID_HOURS' )) . ' ' . (int) (($iDiff % 3600) / 60) . ' ' . ((int) (($iDiff % 3600) / 60) == 1 ? G::LoadTranslation( 'ID_MINUTE' ) : G::LoadTranslation( 'ID_MINUTES' )) . ' ' . (int) (($iDiff % 3600) % 60) . ' ' . ((int) (($iDiff % 3600) % 60) == 1 ? G::LoadTranslation( 'ID_SECOND' ) : G::LoadTranslation( 'ID_SECONDS' )) : G::LoadTranslation( 'ID_NOT_FINISHED' )); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_TaskDetails', '', $aFields ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showUsers': + $_POST['TAS_ASSIGN_TYPE'] = $filter->xssFilterHard($_POST['TAS_ASSIGN_TYPE']); + switch ($_POST['TAS_ASSIGN_TYPE']) { + // switch verify $_POST['TAS_ASSIGN_TYPE'] + case 'BALANCED': + $_POST['USR_UID'] = $filter->xssFilterHard($_POST['USR_UID']); + G::LoadClass( 'user' ); + $oUser = new User( new DBConnection() ); + $oUser->load( $_POST['USR_UID'] ); + $oUser->Fields['USR_FIRSTNAME'] = $filter->xssFilterHard($oUser->Fields['USR_FIRSTNAME']); + $oUser->Fields['USR_LASTNAME'] = $filter->xssFilterHard($oUser->Fields['USR_LASTNAME']); + echo $oUser->Fields['USR_FIRSTNAME'] . ' ' . $oUser->Fields['USR_LASTNAME'] . ''; + break; + case 'MANUAL': + $sAux = ''; + echo $sAux; + break; + case 'EVALUATE': + $_POST['TAS_ASSIGN_VARIABLE'] = $filter->xssFilterHard($_POST['TAS_ASSIGN_VARIABLE']); + $_SESSION['APPLICATION'] = $filter->xssFilterHard($_SESSION['APPLICATION']); + G::LoadClass( 'application' ); + $oApplication = new Application( new DBConnection() ); + $oApplication->load( $_SESSION['APPLICATION'] ); + $sUser = ''; + if ($_POST['TAS_ASSIGN_VARIABLE'] != '') { + if (isset( $oApplication->Fields['APP_DATA'][str_replace( '@@', '', $_POST['TAS_ASSIGN_VARIABLE'] )] )) { + $sUser = $oApplication->Fields['APP_DATA'][str_replace( '@@', '', $_POST['TAS_ASSIGN_VARIABLE'] )]; + } + } + if ($sUser != '') { + G::LoadClass( 'user' ); + $oUser = new User( new DBConnection() ); + $oUser->load( $sUser ); + echo $oUser->Fields['USR_FIRSTNAME'] . ' ' . $oUser->Fields['USR_LASTNAME'] . ''; + } else { + $ID_EMPTY = $filter->xssFilterHard(G::LoadTranslation( 'ID_EMPTY' )); + echo 'Error: ' . $_POST['TAS_ASSIGN_VARIABLE'] . ' ' . $ID_EMPTY; + echo ''; + } + break; + case 'SELFSERVICE': + //Next release + break; + } + break; + case 'cancelCase': + $oCase = new Cases(); + $multiple = false; + + if (isset( $_POST['APP_UID'] ) && isset( $_POST['DEL_INDEX'] )) { + $APP_UID = $_POST['APP_UID']; + $DEL_INDEX = $_POST['DEL_INDEX']; + + $appUids = explode( ',', $APP_UID ); + $delIndexes = explode( ',', $DEL_INDEX ); + if (count( $appUids ) > 1 && count( $delIndexes ) > 1) { + $multiple = true; + } + } elseif (isset( $_POST['sApplicationUID'] ) && isset( $_POST['iIndex'] )) { + $APP_UID = $_POST['sApplicationUID']; + $DEL_INDEX = $_POST['iIndex']; + } else { + $APP_UID = $_SESSION['APPLICATION']; + $DEL_INDEX = $_SESSION['INDEX']; + } + + if ($multiple) { + foreach ($appUids as $i => $appUid) { + $oCase->cancelCase( $appUid, $delIndexes[$i], $_SESSION['USER_LOGGED'] ); + } + } else { + $oCase->cancelCase( $APP_UID, $DEL_INDEX, $_SESSION['USER_LOGGED'] ); + } + break; + case 'reactivateCase': + $sApplicationUID = isset( $_POST['sApplicationUID'] ) ? $_POST['sApplicationUID'] : $_SESSION['APPLICATION']; + $iIndex = (isset( $_POST['sApplicationUID'] )) ? $_POST['iIndex'] : $_SESSION['INDEX']; + $oCase = new Cases(); + $oCase->reactivateCase( $sApplicationUID, $iIndex, $_SESSION['USER_LOGGED'] ); + break; + case 'showPauseCaseInput': + //echo ''; + $aFields = Array (); + $G_PUBLISH = new Publisher(); + $aFields['TIME_STAMP'] = G::getformatedDate( date( 'Y-m-d' ), 'M d, yyyy', SYS_LANG ); + + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_UnpauseDateInput', '', $aFields ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'pauseCase': + // Save the note pause reason + if ($_POST['NOTE_REASON'] != '') { + require_once ("classes/model/AppNotes.php"); + $appNotes = new AppNotes(); + $noteContent = addslashes( $_POST['NOTE_REASON'] ); + $result = $appNotes->postNewNote( $_POST['APP_UID'], $_SESSION['USER_LOGGED'], $noteContent, $_POST['NOTIFY_PAUSE'] ); + } + // End save + + + $unpauseDate = $_POST['unpausedate'] . ' '. $_REQUEST['unpauseTime']; + $oCase = new Cases(); + if (isset( $_POST['APP_UID'] ) && isset( $_POST['DEL_INDEX'] )) { + $APP_UID = $_POST['APP_UID']; + $DEL_INDEX = $_POST['DEL_INDEX']; + } elseif (isset( $_POST['sApplicationUID'] ) && isset( $_POST['iIndex'] )) { + $APP_UID = $_POST['sApplicationUID']; + $DEL_INDEX = $_POST['iIndex']; + } else { + $APP_UID = $_SESSION['APPLICATION']; + $DEL_INDEX = $_SESSION['INDEX']; + } + + $oCase->pauseCase( $APP_UID, $DEL_INDEX, $_SESSION['USER_LOGGED'], $unpauseDate ); + break; + case 'unpauseCase': + $sApplicationUID = (isset( $_POST['sApplicationUID'] )) ? $_POST['sApplicationUID'] : $_SESSION['APPLICATION']; + $iIndex = (isset( $_POST['sApplicationUID'] )) ? $_POST['iIndex'] : $_SESSION['INDEX']; + $oCase = new Cases(); + $oCase->unpauseCase( $sApplicationUID, $iIndex, $_SESSION['USER_LOGGED'] ); + break; + case 'deleteCase': + $oCase = new Cases(); + $sApplicationUID = (isset( $_POST['sApplicationUID'] )) ? $_POST['sApplicationUID'] : $_SESSION['APPLICATION']; + $oCase->removeCase( $sApplicationUID ); + break; + case 'view_reassignCase': + G::LoadClass( 'groups' ); + G::LoadClass( 'tasks' ); + + $oTasks = new Tasks(); + $aAux = $oTasks->getGroupsOfTask( $_SESSION['TASK'], 1 ); + $row = array (); + + $groups = new Groups(); + foreach ($aAux as $aGroup) { + $aUsers = $groups->getUsersOfGroup( $aGroup['GRP_UID'] ); + foreach ($aUsers as $aUser) { + if ($aUser['USR_UID'] != $_SESSION['USER_LOGGED']) { + $row[] = $aUser['USR_UID']; + } + } + } + + $aAux = $oTasks->getUsersOfTask( $_SESSION['TASK'], 1 ); + foreach ($aAux as $aUser) { + if ($aUser['USR_UID'] != $_SESSION['USER_LOGGED']) { + $row[] = $aUser['USR_UID']; + } + } + + //require_once 'classes/model/Users.php'; + $c = new Criteria( 'workflow' ); + $c->addSelectColumn( UsersPeer::USR_UID ); + $c->addSelectColumn( UsersPeer::USR_FIRSTNAME ); + $c->addSelectColumn( UsersPeer::USR_LASTNAME ); + $c->add( UsersPeer::USR_UID, $row, Criteria::IN ); + + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'processes/processes_viewreassignCase', $c ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'reassignCase': + $cases = new Cases(); + $cases->reassignCase( $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['USER_LOGGED'], $_POST['USR_UID'], $_POST['THETYPE'] ); + break; + case 'toRevisePanel': + $_POST['APP_UID'] = $filter->xssFilterHard($_POST['APP_UID']); + $_POST['DEL_INDEX'] = $filter->xssFilterHard($_POST['DEL_INDEX']); + + $_GET['APP_UID'] = $_POST['APP_UID']; + $_GET['DEL_INDEX'] = $_POST['DEL_INDEX']; + $G_PUBLISH = new Publisher(); + + echo ""; + // $G_PUBLISH->AddContent( 'smarty', 'cases/cases_toRevise' ); + // $G_PUBLISH->AddContent('smarty', 'cases/cases_toReviseIn', '', '', array()); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showUploadedDocuments': + $oCase = new Cases(); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_AllInputdocsList', $oCase->getAllUploadedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ) ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showUploadedDocument': + //require_once 'classes/model/AppDocument.php'; + //require_once 'classes/model/AppDelegation.php'; + //require_once 'classes/model/InputDocument.php'; + //require_once 'classes/model/Users.php'; + $oAppDocument = new AppDocument(); + $oAppDocument->Fields = $oAppDocument->load( $_POST['APP_DOC_UID'] ); + $oInputDocument = new InputDocument(); + if ($oAppDocument->Fields['DOC_UID'] != - 1) { + $Fields = $oInputDocument->load( $oAppDocument->Fields['DOC_UID'] ); + } else { + $Fields = array ('INP_DOC_FORM_NEEDED' => '','FILENAME' => $oAppDocument->Fields['APP_DOC_FILENAME']); + } + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( AppDelegationPeer::APP_UID, $oAppDocument->Fields['APP_UID'] ); + $oCriteria->add( AppDelegationPeer::DEL_INDEX, $oAppDocument->Fields['DEL_INDEX'] ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + $oTask = new Task(); + try { + $aTask = $oTask->load( $aRow['TAS_UID'] ); + $Fields['ORIGIN'] = $aTask['TAS_TITLE']; + $oAppDocument->Fields['VIEW'] = G::LoadTranslation( 'ID_OPEN' ); + } catch (Exception $oException) { + $Fields['ORIGIN'] = '(TASK DELETED)'; + } + + try { + $oUser = new Users(); + $aUser = $oUser->load( $oAppDocument->Fields['USR_UID'] ); + $Fields['CREATOR'] = $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME']; + } catch (Exception $e) { + $Fields['CREATOR'] = '***'; + } + switch ($Fields['INP_DOC_FORM_NEEDED']) { + // switch verify $Fields['INP_DOC_FORM_NEEDED'] + case 'REAL': + $sXmlForm = 'cases/cases_ViewAnyInputDocument2'; + break; + case 'VIRTUAL': + $sXmlForm = 'cases/cases_ViewAnyInputDocument1'; + break; + case 'VREAL': + $sXmlForm = 'cases/cases_ViewAnyInputDocument3'; + break; + default: + $sXmlForm = 'cases/cases_ViewAnyInputDocument'; + break; + } + //$oAppDocument->Fields['VIEW'] = G::LoadTranslation('ID_OPEN'); + $oAppDocument->Fields['FILE'] = 'cases_ShowDocument?a=' . $_POST['APP_DOC_UID'] . '&r=' . rand(); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', $sXmlForm, '', G::array_merges( $Fields, $oAppDocument->Fields ), '' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showGeneratedDocuments': + global $G_PUBLISH; + $oCase = new Cases(); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_AllOutputdocsList', $oCase->getAllGeneratedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ) ); + + G::RenderPage( 'publish', 'raw' ); + break; + case 'uploadDocumentGrid_Ajax': + G::LoadClass( 'case' ); + G::LoadClass( "BasePeer" ); + global $G_PUBLISH; + + $arrayToTranslation = array( + "INPUT" => G::LoadTranslation("ID_INPUT_DB"), + "OUTPUT" => G::LoadTranslation("ID_OUTPUT_DB"), + "ATTACHED" => G::LoadTranslation("ID_ATTACHED_DB") + ); + + $oCase = new Cases(); + $aProcesses = Array (); + $G_PUBLISH = new Publisher(); + $c = $oCase->getAllUploadedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ); + + if ($c->getDbName() == 'dbarray') { + $rs = ArrayBasePeer::doSelectRs( $c ); + } else { + $rs = GulliverBasePeer::doSelectRs( $c ); + } + + $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $rs->next(); + + $totalCount = 0; + + for ($j = 0; $j < $rs->getRecordCount(); $j ++) { + $result = $rs->getRow(); + $result["TYPE"] = (array_key_exists($result["TYPE"], $arrayToTranslation))? $arrayToTranslation[$result["TYPE"]] : $result["TYPE"]; + $aProcesses[] = $result; + $rs->next(); + $totalCount ++; + } + + $r = new stdclass(); + $r->data = $aProcesses; + $r->totalCount = $totalCount; + + echo Bootstrap::json_encode( $r ); + break; + case 'generateDocumentGrid_Ajax': + + G::LoadClass( 'case' ); + G::LoadClass( "BasePeer" ); + G::LoadClass( 'configuration' ); + global $G_PUBLISH; + + $oCase = new Cases(); + $aProcesses = Array (); + $G_PUBLISH = new Publisher(); + $c = $oCase->getAllGeneratedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ); + + if ($c->getDbName() == 'dbarray') { + $rs = ArrayBasePeer::doSelectRs( $c ); + } else { + $rs = GulliverBasePeer::doSelectRs( $c ); + } + + $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $rs->next(); + + $totalCount = 0; + + for ($j = 0; $j < $rs->getRecordCount(); $j ++) { + $result = $rs->getRow(); + $result["FILEDOCEXIST"] = ($result["FILEDOC"]); + $result["FILEPDFEXIST"] = ($result["FILEPDF"]); + $result["DELETE_FILE"] = (isset( $result['ID_DELETE'] ) && $result['ID_DELETE'] == 'Delete') ? true : false; + + $aProcesses[] = $result; + + $rs->next(); + $totalCount ++; + } + + //!dateFormat + $conf = new Configurations(); + + try { + $globaleneralConfCasesList = $conf->getConfiguration( 'ENVIRONMENT_SETTINGS', '' ); + } catch (Exception $e) { + $generalConfCasesList = array (); + } + + $dateFormat = ""; + $varFlag = isset( $generalConfCasesList['casesListDateFormat'] ); + if ($varFlag && ! empty( $generalConfCasesList['casesListDateFormat'] )) { + $dateFormat = $generalConfCasesList['casesListDateFormat']; + } + + $r = new stdclass(); + $r->data = $aProcesses; + $r->totalCount = $totalCount; + $r->dataFormat = $dateFormat; + + echo Bootstrap::json_encode( $r ); + break; + case 'showGeneratedDocument': + //require_once 'classes/model/AppDocument.php'; + //require_once 'classes/model/AppDelegation.php'; + $oAppDocument = new AppDocument(); + $aFields = $oAppDocument->load( $_POST['APP_DOC_UID'] ); + require_once 'classes/model/OutputDocument.php'; + $oOutputDocument = new OutputDocument(); + $aOD = $oOutputDocument->load( $aFields['DOC_UID'] ); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->add( AppDelegationPeer::APP_UID, $aFields['APP_UID'] ); + $oCriteria->add( AppDelegationPeer::DEL_INDEX, $aFields['DEL_INDEX'] ); + $oDataset = AppDelegationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aRow = $oDataset->getRow(); + $oTask = new Task(); + $aTask = $oTask->load( $aRow['TAS_UID'] ); + $aFields['ORIGIN'] = $aTask['TAS_TITLE']; + require_once 'classes/model/Users.php'; + $oUser = new Users(); + $aUser = $oUser->load( $aFields['USR_UID'] ); + $aFields['CREATOR'] = $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME']; + $aFields['VIEW'] = G::LoadTranslation( 'ID_OPEN' ); + $aFields['FILE1'] = 'cases_ShowOutputDocument?a=' . $aFields['APP_DOC_UID'] . '&ext=doc&random=' . rand(); + $aFields['FILE2'] = 'cases_ShowOutputDocument?a=' . $aFields['APP_DOC_UID'] . '&ext=pdf&random=' . rand(); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_ViewAnyOutputDocument', '', G::array_merges( $aOD, $aFields ), '' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showDynaformList': + $oCase = new Cases(); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_AllDynaformsList', $oCase->getallDynaformsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ) ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showDynaform': + $G_PUBLISH = new Publisher(); + $oCase = new Cases(); + $Fields = $oCase->loadCase( $_SESSION['APPLICATION'] ); + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['PREVIOUS_STEP_LABEL'] = ''; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_STEP_LABEL'] = ''; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_STEP'] = '#'; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_ACTION'] = 'return false;'; + if (isset( $_POST['DYN_UID'] )) { + $_SESSION['DYN_UID_PRINT'] = $_POST['DYN_UID']; + } else { + $_SESSION['DYN_UID_PRINT'] = $_REQUEST['DYN_UID']; + } + if (! isset( $_SESSION['CURRENT_DYN_UID'] )) { + $_SESSION['CURRENT_DYN_UID'] = $_POST['DYN_UID'] ? $_POST['DYN_UID'] : $_REQUEST['DYN_UID']; + } + $G_PUBLISH->AddContent( 'dynaform', 'xmlform', $_SESSION['PROCESS'] . '/' . $_REQUEST['DYN_UID'], '', $Fields['APP_DATA'], '', '', 'view' ); + G::RenderPage( 'publish', 'blank' ); + break; + case 'showDynaformHistory': + $G_PUBLISH = new Publisher(); + $FieldsHistory = $_SESSION['HISTORY_DATA']; + $Fields['APP_DATA'] = $FieldsHistory[$_POST['HISTORY_ID']]; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['PREVIOUS_STEP_LABEL'] = ''; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_STEP_LABEL'] = ''; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_STEP'] = '#'; + $Fields['APP_DATA']['__DYNAFORM_OPTIONS']['NEXT_ACTION'] = 'return false;'; + $G_PUBLISH->AddContent( 'dynaform', 'xmlform', $_SESSION['PROCESS'] . '/' . $_POST['DYN_UID'], '', $Fields['APP_DATA'], '', '', 'view' ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'adhocAssignmentUsers': + G::LoadClass( 'groups' ); + G::LoadClass( 'tasks' ); + $oTasks = new Tasks(); + $aAux = $oTasks->getGroupsOfTask( $_SESSION['TASK'], 2 ); + $aAdhocUsers = array (); + $oGroups = new Groups(); + foreach ($aAux as $aGroup) { + $aUsers = $oGroups->getUsersOfGroup( $aGroup['GRP_UID'] ); + foreach ($aUsers as $aUser) { + if ($aUser['USR_UID'] != $_SESSION['USER_LOGGED']) { + $aAdhocUsers[] = $aUser['USR_UID']; + } + } + } + $aAux = $oTasks->getUsersOfTask( $_SESSION['TASK'], 2 ); + foreach ($aAux as $aUser) { + if ($aUser['USR_UID'] != $_SESSION['USER_LOGGED']) { + $aAdhocUsers[] = $aUser['USR_UID']; + } + } + //require_once 'classes/model/Users.php'; + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( UsersPeer::USR_UID ); + $oCriteria->addSelectColumn( UsersPeer::USR_FIRSTNAME ); + $oCriteria->addSelectColumn( UsersPeer::USR_LASTNAME ); + $oCriteria->add( UsersPeer::USR_UID, $aAdhocUsers, Criteria::IN ); + + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'processes/processes_viewreassignCase', $oCriteria, array ('THETYPE' => 'ADHOC' + ) ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showHistoryMessages': + $oCase = new Cases(); + global $G_PUBLISH; + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_Messages', $oCase->getHistoryMessagesTracker( $_SESSION['APPLICATION'] ) ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'showHistoryMessage': + $G_PUBLISH = new Publisher(); + $oCase = new Cases(); + + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_MessagesView', '', $oCase->getHistoryMessagesTrackerView( $_POST['APP_UID'], $_POST['APP_MSG_UID'] ) ); + G::RenderPage( 'publish', 'raw' ); + break; + case 'deleteUploadedDocument': + //require_once 'classes/model/AppDocument.php'; + $oAppDocument = new AppDocument(); + $oAppDocument->remove( $_POST['DOC'] ); + $oCase = new Cases(); + $oCase->getAllUploadedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ); + break; + case 'deleteGeneratedDocument': + //require_once 'classes/model/AppDocument.php'; + $oAppDocument = new AppDocument(); + $oAppDocument->remove( $_POST['DOC'] ); + $oCase = new Cases(); + $oCase->getAllGeneratedDocumentsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ); + break; + /* @Author Erik Amaru Ortiz */ + case 'resendMessage': + //require_once 'classes/model/Configuration.php'; + G::LoadClass( 'spool' ); + + $oCase = new Cases(); + $data = $oCase->getHistoryMessagesTrackerView( $_POST['APP_UID'], $_POST['APP_MSG_UID'] ); + //print_r($data); + + + G::LoadClass("system"); + + $aSetup = System::getEmailConfiguration(); + + $passwd = $aSetup['MESS_PASSWORD']; + $passwdDec = G::decrypt( $passwd, 'EMAILENCRYPT' ); + $auxPass = explode( 'hash:', $passwdDec ); + if (count( $auxPass ) > 1) { + if (count( $auxPass ) == 2) { + $passwd = $auxPass[1]; + } else { + array_shift( $auxPass ); + $passwd = implode( '', $auxPass ); + } + } + $aSetup['MESS_PASSWORD'] = $passwd; + if ($aSetup['MESS_RAUTH'] == false || (is_string($aSetup['MESS_RAUTH']) && $aSetup['MESS_RAUTH'] == 'false')) { + $aSetup['MESS_RAUTH'] = 0; + } else { + $aSetup['MESS_RAUTH'] = 1; + } + + $oSpool = new spoolRun(); + $oSpool->setConfig( + array ( + 'MESS_ENGINE' => $aSetup['MESS_ENGINE'], + 'MESS_SERVER' => $aSetup['MESS_SERVER'], + 'MESS_PORT' => $aSetup['MESS_PORT'], + 'MESS_ACCOUNT' => $aSetup['MESS_ACCOUNT'], + 'MESS_PASSWORD' => $aSetup['MESS_PASSWORD'], + 'SMTPSecure' => $aSetup['SMTPSecure'], + 'SMTPAuth' => $aSetup['MESS_RAUTH'] + ) + ); + $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' + ) ); + $oSpool->sendMail(); + break; + /* @Author Erik Amaru Ortiz */ + case 'showdebug': + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'view', 'cases/showDebugFrame' ); + G::RenderPage( 'publish', 'raw' ); + break; + /* @Author Erik Amaru Ortiz */ + case 'reassignByUserList': + $APP_UIDS = explode( ',', $_POST['APP_UIDS'] ); + $sReassignFromUser = $_POST['FROM_USR_ID']; + + G::LoadClass( 'tasks' ); + G::LoadClass( 'groups' ); + G::LoadClass( 'case' ); + + $oTasks = new Tasks(); + $oGroups = new Groups(); + $oUser = new Users(); + $oCases = new Cases(); + + $aCasesList = Array (); + + foreach ($APP_UIDS as $APP_UID) { + $aCase = $oCases->loadCaseInCurrentDelegation( $APP_UID, true ); + + $aUsersInvolved = Array (); + $aCaseGroups = $oTasks->getGroupsOfTask( $aCase['TAS_UID'], 1 ); + + foreach ($aCaseGroups as $aCaseGroup) { + $aCaseUsers = $oGroups->getUsersOfGroup( $aCaseGroup['GRP_UID'] ); + foreach ($aCaseUsers as $aCaseUser) { + if ($aCaseUser['USR_UID'] != $sReassignFromUser) { + $aCaseUserRecord = $oUser->load( $aCaseUser['USR_UID'] ); + $aUsersInvolved[$aCaseUser['USR_UID']] = $aCaseUserRecord['USR_FIRSTNAME'] . ' ' . $aCaseUserRecord['USR_LASTNAME']; + // . ' (' . $aCaseUserRecord['USR_USERNAME'] . ')'; + } + } + } + + $aCaseUsers = $oTasks->getUsersOfTask( $aCase['TAS_UID'], 1 ); + foreach ($aCaseUsers as $aCaseUser) { + if ($aCaseUser['USR_UID'] != $sReassignFromUser) { + $aCaseUserRecord = $oUser->load( $aCaseUser['USR_UID'] ); + $aUsersInvolved[$aCaseUser['USR_UID']] = $aCaseUserRecord['USR_FIRSTNAME'] . ' ' . $aCaseUserRecord['USR_LASTNAME']; + // . ' (' . $aCaseUserRecord['USR_USERNAME'] . ')'; + } + } + $oTmp = new stdClass(); + $oTmp->items = $aUsersInvolved; + $oTmp->id = $aCase['APP_UID']; + $aCase['USERS'] = $oTmp; + array_push( $aCasesList, $aCase ); + } + + $filedNames = Array ("APP_UID","APP_NUMBER","APP_UPDATE_DATE","DEL_PRIORITY","DEL_INDEX","TAS_UID","DEL_INIT_DATE","DEL_FINISH_DATE","USR_UID","APP_STATUS","DEL_TASK_DUE_DATE","APP_CURRENT_USER","APP_TITLE","APP_PRO_TITLE","APP_TAS_TITLE","APP_DEL_PREVIOUS_USER","USERS" + ); + + $aCasesList = array_merge( Array ($filedNames + ), $aCasesList ); + + global $_DBArray; + $_DBArray['reassign_byuser'] = $aCasesList; + G::LoadClass( 'ArrayPeer' ); + $oCriteria = new Criteria( 'dbarray' ); + $oCriteria->setDBArrayTable( 'reassign_byuser' ); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'propeltable', 'cases/paged-table-reassigByUser2', 'cases/cases_ToReassignByUserList2', $oCriteria ); + G::RenderPage( 'publish', 'raw' ); + break; + /* @Author Erik Amaru Ortiz */ + case 'reassignByUser': + G::LoadClass( 'case' ); + + $oCases = new Cases(); + $aCases = Array (); + + if (isset( $_POST['items'] ) && trim( $_POST['items'] ) != '') { + $sItems = $_POST['items']; + $aItems = explode( ',', $sItems ); + $FROM_USR_UID = $_POST['USR_UID']; + + foreach ($aItems as $item) { + list ($APP_UID, $USR_UID) = explode( '|', $item ); + $aCase = $oCases->loadCaseInCurrentDelegation( $APP_UID, true ); + $oCase->reassignCase( $aCase['APP_UID'], $aCase['DEL_INDEX'], $FROM_USR_UID, $USR_UID ); + array_push( $aCases, $aCase ); + } + //G::pr($aCases); + + + //require_once 'classes/model/Users.php'; + $oUser = new Users(); + $sText = ''; + foreach ($aCases as $aCase) { + $aCaseUpdated = $oCases->loadCaseInCurrentDelegation( $aCase['APP_UID'], true ); + $aUser = $oUser->load( $aCaseUpdated['USR_UID'] ); + $sText .= $aCaseUpdated['APP_PRO_TITLE'] . ' - ' . ' Case: ' . $aCaseUpdated['APP_NUMBER'] . '# (' . $aCaseUpdated['APP_TAS_TITLE'] . ') => Reassigned to => ' . $aUser['USR_FIRSTNAME'] . ' ' . $aUser['USR_LASTNAME'] . ' [' . $aUser['USR_USERNAME'] . ']' . '
'; + } + + $G_PUBLISH = new Publisher(); + $aMessage['MESSAGE'] = $sText; + $aMessage['URL'] = 'cases_ReassignByUser?REASSIGN_USER=' . $_POST['USR_UID']; + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_ReassignShowInfo', '', $aMessage ); + G::RenderPage( 'publish', 'raw' ); + } + break; + case "uploadInputDocument": + //krumo($_POST); + $G_PUBLISH = new Publisher(); + $Fields['DOC_UID'] = $_POST['docID']; + $Fields['APP_DOC_UID'] = $_POST['appDocId']; + $Fields['actionType'] = $_POST['actionType']; + $Fields['docVersion'] = $_POST['docVersion']; + $oInputDocument = new InputDocument(); + $InpDocData = $oInputDocument->load( $Fields['DOC_UID'] ); + + $inpDocMaxFilesize = $InpDocData["INP_DOC_MAX_FILESIZE"]; + $inpDocMaxFilesizeUnit = $InpDocData["INP_DOC_MAX_FILESIZE_UNIT"]; + $inpDocMaxFilesize = $inpDocMaxFilesize * (($inpDocMaxFilesizeUnit == "MB")? 1024 *1024 : 1024); //Bytes + + $Fields["INP_DOC_SUPPORTED_EXTENSIONS_FILENAME_LABEL"] = "[" . $InpDocData["INP_DOC_TYPE_FILE"]. "]"; + $Fields["INP_DOC_MAX_FILESIZE"] = $inpDocMaxFilesize; + $Fields["INP_DOC_MAX_FILESIZE_LABEL"] = ($inpDocMaxFilesize > 0)? "[" . $InpDocData["INP_DOC_MAX_FILESIZE"] . " " . $InpDocData["INP_DOC_MAX_FILESIZE_UNIT"] . "]" : ""; + $Fields['fileTypes'] = $InpDocData['INP_DOC_TYPE_FILE']; + + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_AttachInputDocumentGeneral', '', $Fields, 'cases_SaveDocument?UID=' . $_POST['docID'] ); + G::RenderPage( 'publish', 'raw' ); + break; + case "uploadToReviseInputDocument": + //krumo($_POST); + $G_PUBLISH = new Publisher(); + $Fields['DOC_UID'] = $_POST['docID']; + $Fields['APP_DOC_UID'] = $_POST['appDocId']; + $Fields['actionType'] = $_POST['actionType']; + $Fields["docVersion"] = (int)($_POST["docVersion"]); + + $appDocument = new AppDocument(); + $arrayAppDocumentData = $appDocument->load($_POST["appDocId"]); + + $oInputDocument = new InputDocument(); + $InpDocData = $oInputDocument->load( $Fields['DOC_UID'] ); + + $inpDocMaxFilesize = $InpDocData["INP_DOC_MAX_FILESIZE"]; + $inpDocMaxFilesizeUnit = $InpDocData["INP_DOC_MAX_FILESIZE_UNIT"]; + $inpDocMaxFilesize = $inpDocMaxFilesize * (($inpDocMaxFilesizeUnit == "MB")? 1024 *1024 : 1024); //Bytes + + $Fields["INP_DOC_SUPPORTED_EXTENSIONS_FILENAME_LABEL"] = "[" . $InpDocData["INP_DOC_TYPE_FILE"]. "]"; + $Fields["INP_DOC_MAX_FILESIZE"] = $inpDocMaxFilesize; + $Fields["INP_DOC_MAX_FILESIZE_LABEL"] = ($inpDocMaxFilesize > 0)? "[" . $InpDocData["INP_DOC_MAX_FILESIZE"] . " " . $InpDocData["INP_DOC_MAX_FILESIZE_UNIT"] . "]" : ""; + $Fields['fileTypes'] = $InpDocData['INP_DOC_TYPE_FILE']; + + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_AttachInputDocumentGeneral', '', $Fields, 'cases_SupervisorSaveDocument?APP_DOC_UID=' . $_POST['appDocId'] . "&DOC_VERSION=" . ($Fields['docVersion'] + 1) . '&APP_UID=' . $arrayAppDocumentData["APP_UID"] . '&UID=' . $_POST['docID']); + G::RenderPage( 'publish', 'raw' ); + break; + case "inputDocumentVersionHistory": + //krumo($_POST); + $G_PUBLISH = new Publisher(); + $Fields['DOC_UID'] = $_POST['docID']; + $Fields['APP_DOC_UID'] = $_POST['appDocId']; + $G_PUBLISH->AddContent( 'propeltable', 'paged-table', 'cases/cases_InputdocsListHistory', $oCase->getInputDocumentsCriteria( $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_POST['docID'], $_POST['appDocId'] ), array () ); //$aFields + //$G_PUBLISH->AddContent('xmlform', 'xmlform', 'cases/cases_AttachInputDocumentGeneral', + // '', $Fields, 'cases_SaveDocument?UID=' . $_POST['docID']); + G::RenderPage( 'publish', 'raw' ); + break; + case "getCountCasesFolder": + //$json = new Services_JSON(); + $aTypes = Array ('to_do','draft','cancelled','sent','paused','completed','selfservice','to_revise','to_reassign'); + $aTypesID = Array ('to_do' => 'CASES_INBOX','draft' => 'CASES_DRAFT','cancelled' => 'CASES_CANCELLED','sent' => 'CASES_SENT','paused' => 'CASES_PAUSED','completed' => 'CASES_COMPLETED','selfservice' => 'CASES_SELFSERVICE','to_revise' => 'CASES_TO_REVISE','to_reassign' => 'CASES_TO_REASSIGN'); + + if (! isset( $_POST['A'] )) { + $oCases = new Cases(); + $aCount = $oCases->getAllConditionCasesCount( $aTypes, true ); + echo Bootstrap::json_encode( $aCount ); + } else { + echo Bootstrap::json_encode( $aTypesID ); + } + break; + case "previusJump": + //require_once 'classes/model/Application.php'; + + $oCriteria = new Criteria( 'workflow' ); + $response = array ("success" => true ); + + $oCriteria->add( ApplicationPeer::APP_NUMBER, $_POST['appNumber'] ); + $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset->next(); + $aApplication = $oDataset->getRow(); + + if (is_array( $aApplication )) { + $response['exists'] = true; + } else { + $response['exists'] = false; + } + + echo Bootstrap::json_encode( $response ); + break; + default: + echo 'default'; +} + +function getCasesTypeIds () +{ + $aTypes = Array ('to_do','draft','cancelled','sent','paused','completed','selfservice','to_revise','to_reassign'); + return $aTypesID; +} +