setQuery("SHOW COLUMNS FROM `jos_vxc_order` LIKE 'uuid';"); if ($db->loadResult()) return TRUE; else return FALSE; } static function getFilesRDir() { return '/vxfiles/'.LegacyHelper::getFranchiseStoragePrefix(); } static function translate($id) { $dict =& LegacyHelper::getCurrentDictionary(); if ($dict && $dict[$id]) return $dict[$id]; else return $id; } static function getResourceDir() { $dir = LegacyHelper::getFilesDir(). '/resources'; if (@is_dir($dir)===FALSE) @mkdir($dir,0777,true); return $dir; } static function getResourceRDir() { return LegacyHelper::getFilesRDir().'/resources'; } static function getAttributesDir() { $dir = LegacyHelper::getFilesDir(). '/attributes'; if (@is_dir($dir)===FALSE) @mkdir($dir,0777,true); return $dir; } static function getAttributesRDir() { return LegacyHelper::getFilesRDir().'/attributes'; } static function getCurrentDictionary() { if (LegacyHelper::$_dictionary===null) { $curLanguage = LegacyHelper::getMVCLanguage(); $dictionary =& LegacyHelper::getDictionary(); if ($dictionary && $dictionary[$curLanguage] && $dictionary[$curLanguage]["texts"]) { LegacyHelper::$_dictionary = $dictionary[$curLanguage]["texts"]; } } return LegacyHelper::$_dictionary; } static function getDefaultDictionary() { if (LegacyHelper::$_defaultDictionary===null) { $curLanguage = LegacyHelper::getMVCDefaultLanguage(); $dictionary =& LegacyHelper::getDictionary(); if ($dictionary && $dictionary[$curLanguage] && $dictionary[$curLanguage]["texts"]) LegacyHelper::$_defaultDictionary = $dictionary[$curLanguage]["texts"]; } return LegacyHelper::$_defaultDictionary; } static function getMVCDefaultLanguage() { $mvcParams = unserialize($_SESSION["mvcParams"]); if ($mvcParams && $mvcParams->defaultLanguage) return $mvcParams->defaultLanguage; else { $lang =& JFactory::getLanguage(); return LegacyHelper::getNewLanguageCode($lang->_default); } } static function getMVCLanguage() { $mvcParams = unserialize($_SESSION["mvcParams"]); if ($mvcParams && $mvcParams->lang) return $mvcParams->lang; else { $lang =& JFactory::getLanguage(); return LegacyHelper::getNewLanguageCode($lang->_lang); } } static function getMVCAuthToken() { $mvcParams = unserialize($_SESSION["mvcParams"]); if ($mvcParams && $mvcParams->authToken) return $mvcParams->authToken; else return ''; } // Obtiene el persistentName de un elemento del persistentSchema a partir del fullkey static function getDBNameFromFullkey($fullkey) { // Obtenemos el persistentSchema (cacheado) $schema = LegacyHelper::getPersistentSchema(); // Obtenemos los atributos del fullkey $ats = LegacyHelper::getSchemaNodeAttributes($schema,$fullkey); // Si tenemos persistentName para ese atributo lo devolvemos if ($ats && isset($ats["persistentName"])) return $ats["persistentName"]; // Sino tendremos que quitar el prefijo "attributes." o dejarlo tal cual $dbname = $fullkey; if (strpos($dbname,"attributes.")===0) $dbname = substr($dbname,11); return $dbname; } static function _getElementsByAttribute(&$schema, $atName,$atValue,$partialName,&$ats) { if (is_object($schema) || is_array($schema)) { foreach($schema as $key => $value) { if ($key == "_attributes") { $atStruct =& $schema[$key]; if (isset($atStruct[$atName]) && $atStruct[$atName]===$atValue) $ats[$partialName] = $schema; } else { if ($partialName) $newName = $partialName.'.'.$key; else $newName = $key; LegacyHelper::_getElementsByAttribute($schema[$key],$atName,$atValue,$newName,$ats); } } } } static function _getSchemaNodeAttributes(&$schema, $fullkey, $partialName,&$ats) { if ((is_object($schema) || is_array($schema)) && $fullkey) { $pointPos = strpos ($fullkey ,'.' ); if ($pointPos === FALSE) { if ($schema[$fullkey] && $schema[$fullkey]["_attributes"]) $ats = $schema[$fullkey]["_attributes"]; } else { $key = substr($fullkey,0,$pointPos); $reducedFullkey = substr($fullkey,$pointPos+1); $newPartialName = $partialName ? $partialName.".".$key : $key; LegacyHelper::_getSchemaNodeAttributes($schema[$key],$reducedFullkey,$newPartialName,$ats); } } } // Obtiene los atributos asociados a un nodo del schema static function getSchemaNodeAttributes(&$schema, $fullkey) { $ats = array(); LegacyHelper::_getSchemaNodeAttributes($schema, $fullkey, '',$ats); return $ats; } // Devuelve todos los atributos de los nodos con un atributo igual a un valor en concreto static function getElementsByAttribute(&$schema, $atName,$atValue) { $ats = array(); LegacyHelper::_getElementsByAttribute($schema,$atName,$atValue,'',$ats); return $ats; } // Devuelve la URL completa del servicio MVC del middleware static function getMiddlewareServiceURL() { $middlewareInfo = LegacyHelper::getPHPGlobalVar('mvcMiddleware'); if (!$middlewareInfo || !is_array($middlewareInfo)) return null; $url = LegacyHelper::getMiddlewareURL(); $service = $middlewareInfo['service']; return $url . '/'. $service; } static function getStorageService() { return LegacyHelper::getPHPGlobalVar('storageService'); } // Devuelve la URL complete del middleware static function getMiddlewareURL() { $middlewareInfo = LegacyHelper::getPHPGlobalVar('mvcMiddleware'); if (!$middlewareInfo || !is_array($middlewareInfo)) return null; $server = $middlewareInfo['server']; $port = $middlewareInfo['port']; $protocol = $middlewareInfo['protocol']; if (!$port) $port = 80; if (!$protocol) $protocol = "http"; return $protocol.'://'.$server . ':' . $port; } static function get_headers_from_curl_response($headerContent) { $headers = array(); // Split the string on every "double" new line. $arrRequests = explode("\r\n\r\n", $headerContent); // Loop of response headers. The "count() -1" is to //avoid an empty row for the extra line break before the body of the response. for ($index = 0; $index < count($arrRequests) -1; $index++) { foreach (explode("\r\n", $arrRequests[$index]) as $i => $line) { if ($i === 0) $headers[$index]['http_code'] = $line; else { list ($key, $value) = explode(': ', $line); $headers[$index][$key] = $value; } } } return $headers; } static function httpRequest($method='GET', $url, $data=null, $requestHeaders=null, &$statusCode,&$headers) { $curl = curl_init(); $opt = array( CURLOPT_HEADER => true, // we want headers CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_CONNECTTIMEOUT => 300, CURLOPT_TIMEOUT => 300, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_USERAGENT => 'Codular Sample cURL Request' ); if ($requestHeaders && is_array($requestHeaders)) { $reqHeaders = array(); foreach($requestHeaders as $key=> $value) $reqHeaders[] = "$key:$value"; $opt[CURLOPT_HTTPHEADER] = $reqHeaders; } curl_setopt_array($curl, $opt); switch($method) { case "POST": if (is_array($data)) { $params=""; foreach ($data as $key => $value) { if ($params!="") $params.="&"; $params.=urlencode($key)."=".urlencode($value); } $data = $params; } curl_setopt ($curl, CURLOPT_POST, 1); // set POST method if ($data!==null) curl_setopt ($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": $fh = tmpfile(); if ($data!==null) fwrite($fh,$data); $input_stat = fstat($fh); $input_size = $input_stat['size']; fseek($fh, 0); curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); curl_setopt($curl, CURLOPT_INFILE, $fh); curl_setopt($curl, CURLOPT_INFILESIZE, $input_size); break; } // Send the request & save response to $resp $resp = curl_exec($curl); $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $header = substr($resp, 0, $header_size); $body = substr( $resp, $header_size ); $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $headers = LegacyHelper::get_headers_from_curl_response($header); // Close request to clear up some resources curl_close($curl); return $body; } static function getCurrentTransaction() { if (session_id()) return $_SESSION['transaction']; else return NULL; } static function getCacheDir() { $prefix = LegacyHelper::getFranchisePrefix(); if (!$prefix) $prefix = 'PROBLEM'; return $_SERVER['DOCUMENT_ROOT'].'/../cache/'.$prefix; } static function getDictionary() { // Obtenemos la transaccion $transaction = LegacyHelper::getCurrentTransaction(); $cacheDir = LegacyHelper::getCacheDir(); @mkdir($cacheDir,0777,true); // Contruimos los path de la cache del persistentSchema y la url del middleware $cachePath = $cacheDir.'/dictionaryCache'; if ($transaction) $cachePath .="_$transaction"; $cacheEtagPath = $cachePath.".etag"; $cachePath .= ".php"; $requestHeaders = array(); // Cabeceras de la peticion $statusCode = 0; // Codigo de respuesta $responseHeaders = array(); // Cabeceras de la respuesta $mvcServiceURL = LegacyHelper::getMiddlewareServiceURL(); $url = $mvcServiceURL . '/getPersistentDictionary'; // AƱadimos la transaccion si procede if ($transaction) $url .= '?transaction='. $transaction; // Comprobamos si tenemos un etag guardado para enviarlo por si el server tuviera la misma version del archivo if (file_exists($cacheEtagPath)) { $etag = file_get_contents($cacheEtagPath); if ($etag!==FALSE) $requestHeaders["if-none-match"] = $etag; } // Realizamos la peticion al middleware $contents = LegacyHelper::httpRequest('GET', $url, '',$requestHeaders, $statusCode,$responseHeaders); // Analizamos la respuesta switch((int)$statusCode) { case 200: // Si nos ha devuelvo 200 quiere decir que el contenido era distinto y tenemos que actualizar // el fichero de cache y el etag file_put_contents($cachePath, $contents); if (count($responseHeaders)>0) { $header = $responseHeaders[0]; if ($header && $header['etag']) file_put_contents($cacheEtagPath,$header['etag']); } break; case 304: // Si nos devuelve 304 quiere decir que podemos usar la version del archivo cacheada break; default: // Si nos devuelve otra cosa, es un error return array(); } // Si tenemos el archivo de cache lo incluimos if (file_exists($cachePath)) include($cachePath); else return array(); //@(include $_SERVER['DOCUMENT_ROOT'].'/php/persistentTranslations.php'); // Cojemos la informacion de conexion de if (is_array($SPersistentTranslations)) return $SPersistentTranslations; else return array(); } // Obtiene el persistenSchema (conteniendo unicamente los atributos persistentes) static function getPersistentSchema() { // Si no lo tenemos cacheado lo pedimos if (!LegacyHelper::$_persistentSchema) { // Obtenemos la transaccion $userId = LegacyHelper::getUserId(); $transaction = LegacyHelper::getCurrentTransaction(); $cacheDir = LegacyHelper::getCacheDir(); $modelSchemaName = LegacyHelper::getPHPGlobalVar('modelSchemaName'); $franchisePrefix = LegacyHelper::getFranchisePrefix(); @mkdir($cacheDir,0777,true); // Contruimos los path de la cache del persistentSchema y la url del middleware $cachePath = $cacheDir.'/schemaCache'; if ($modelSchemaName) $cachePath .= "_$modelSchemaName"; if ($userId) $cachePath .= "_$userId"; if ($transaction) $cachePath .="_$transaction"; $cacheEtagPath = $cachePath.".etag"; $cachePath .= ".php"; $requestHeaders = array(); // Cabeceras de la peticion $statusCode = 0; // Codigo de respuesta $responseHeaders = array(); // Cabeceras de la respuesta $mvcServiceURL = LegacyHelper::getMiddlewareServiceURL(); $url = $mvcServiceURL . '/getSchema?forPHP=true'; if ($modelSchemaName) $url .= "&name=".$modelSchemaName; else if ($franchisePrefix) $url .= "&prefix=".$franchisePrefix; // Pasamos el usuario actual if ($userId) $url .= '&userId='.$userId; // AƱadimos la transaccion si procede if ($transaction) $url .= '&transaction='. $transaction; // Comprobamos si tenemos un etag guardado para enviarlo por si el server tuviera la misma version del archivo if (file_exists($cacheEtagPath)) { $etag = file_get_contents($cacheEtagPath); if ($etag!==FALSE) $requestHeaders["if-none-match"] = $etag; } // Realizamos la peticion al middleware $contents = LegacyHelper::httpRequest('GET', $url, '',$requestHeaders, $statusCode,$responseHeaders); // Analizamos la respuesta switch((int)$statusCode) { case 200: // Si nos ha devuelvo 200 quiere decir que el contenido era distinto y tenemos que actualizar // el fichero de cache y el etag file_put_contents($cachePath, $contents); if (count($responseHeaders)>0) { $header = $responseHeaders[0]; if ($header && $header['etag']) file_put_contents($cacheEtagPath,$header['etag']); } break; case 304: // Si nos devuelve 304 quiere decir que podemos usar la version del archivo cacheada break; default: // Si nos devuelve otra cosa, es un error return null; } // Si tenemos el archivo de cache lo incluimos if (file_exists($cachePath)) include($cachePath); else return null; // Devolvemos la variable if (isset($SPersistentSchema)) LegacyHelper::$_persistentSchema = $SPersistentSchema; else LegacyHelper::$_persistentSchema = null; } return LegacyHelper::$_persistentSchema; } static function getPHPGlobalVar($varName) { @(include $_SERVER['DOCUMENT_ROOT'].'/php/globals.php'); /* if ($varName == "useCommonInS3") { return TRUE; }*/ // Cojemos la informacion de conexion de if (is_array($SGLOBAL) && isset($SGLOBAL[$varName])) return $SGLOBAL[$varName]; else return null; } static function getFranchiseStoragePrefix() { @(include $_SERVER['DOCUMENT_ROOT'].'/php/globals.php'); // Cojemos la informacion de conexion de if (is_array($SGLOBAL) && is_array($SGLOBAL['franchise']) && $SGLOBAL['franchise']['storagePrefix'] ) return $SGLOBAL['franchise']['storagePrefix']; else return LegacyHelper::getFranchisePrefix(); } static function getFranchisePrefix() { @(include $_SERVER['DOCUMENT_ROOT'].'/php/globals.php'); // Cojemos la informacion de conexion de if (is_array($SGLOBAL) && is_array($SGLOBAL['franchise']) && $SGLOBAL['franchise']['prefix'] ) { return $SGLOBAL['franchise']['prefix']; } switch($_SERVER['SERVER_NAME']) { case 'local.voxelcare.com': case 'voxelcare': case 'www.voxelcare.com': case 'newvoxelcare': return 'VX'; break; case 'backup.voxelcare.com': return 'OVX'; case 'newppr': case 'ppr': case 'legacy.orthocad.de': case 'www.orthocad.de': case 'neworthocad': case 'devorthocad': return 'PPR'; case 'rotterdam': case 'cor.voxelcare.com': return 'ROT'; case 'jjcorne': case 'production.voxelcare.com': return 'JJC'; case 'india': case 'india.voxelcare.com': return 'IND'; case 'newlafoot': case 'lafoot': case 'www.lafoottechnics.com': return 'LFT'; case 'tecnoinsole': case 'newtecnoinsole': case 'devtecnoinsole': case 'localtecnoinsole': case 'local.tecnoinsole.com': case 'new.tecnoinsole.com': case 'www.tecnoinsole.com': case 'app.tecnoinsole.com': case 'elche.voxelcare.com': return 'TI'; case 'jjpodo': case 'podo.voxelcare.com': return 'JJP'; case 'velasco': case 'velasco.voxelcare.com': return 'VEL'; default: return ''; } } static function getNewMode() { return (str_replace("\\",'/',JPATH_BASE) != $_SERVER['DOCUMENT_ROOT']); } static function getNewUserId() { $db =& VoxelCareDB::getDatabase(); $sql = "SELECT MAX(id) FROM #__vxc_user "; $db->setQuery($sql); $maxid = $db->loadResult(); return (($maxid)?($maxid+1):1); } static function getUserId() { if (self::$_customUserId) return self::$_customUserId; else { if ($_GET['newWebsiteUserId']) { self::$NewMode = true; $_SESSION['userId'] = $_GET['newWebsiteUserId']; return $_GET['newWebsiteUserId']; } else { $userId = $_SESSION['userId']; if ($userId) { self::$NewMode = true; return $userId; } else { self::$NewMode = false; $user =& JFactory::getUser(); if ($user->id) return $user->id; else return 0; } } } } static function generateUUID() { return substr(md5(rand()),0,9).'.'.substr(md5(rand()),0,9); } /** * Funcion que devuelve el codigo de lenguaje de Joomla asociado a un codigo de lenguaje de la web MVC * @param $lang Codigo de lenguaje de la web MVC * @return string Codigo de lenguaje de Joomla! */ static function getOldLanguageCode($lang) { switch($lang) { case "EN": return "en-GB"; break; case "ES": return "es-ES"; break; case "NL": return "nl-NL"; break; case "IT": return "it-IT"; break; case "DE": return "de-DE"; break; case "DK": return "da-DK"; break; case "FR": return "fr-FR"; break; default: return "en-GB"; } } static function getNewLanguageCode($lang) { switch($lang) { case "en-GB": return "EN"; break; case "es-ES": return "ES"; break; case "nl-NL": return "NL"; break; case "it-IT": return "IT"; break; case "de-DE": return "DE"; break; case "da-DK": return "DK"; break; case "fr-FR": return "FR"; break; default: return "EN"; } } /** * Obtiene la carpeta en el disco local que referencia al directorio anterior a vxcommon */ static function getCommonParentFolder() { if (LegacyHelper::getNewMode()) { include(JPATH_BASE.'/components/com_vxc/helpers/commonpath.php'); return $commonPath .'/../'; } else { return JPATH_BASE.'/../'; } } static public function VLog($error) { $filename=$_SERVER['DOCUMENT_ROOT']."/voxelservice.log"; // $filename="voxelservice.log"; $fic=@fopen($filename,"at"); if ($fic) { @chmod($filename,0666); $date=date("Y-m-d H:i:s"); @fputs($fic,"(".$date.") ".$error."\n"); @fclose($fic); } } static function isAdminUser($userId) { $managers = array('admin'); $db =& VoxelCareDB::getDatabase(); $sql = "SELECT username FROM #__vxc_user WHERE id = ". $userId; $db->setQuery($sql); $username = $db->loadResult(); if ($username && in_array($username,$managers)) return true; else return false; } static function getOpenOrderFolder($orderId, $currentStep, $orderUUID) { if (LegacyHelper::getNewMode() && $orderUUID) { $openOrderURL = '#'; $openOrderEvent = "onclick=\"window.parent.RequestOrder('{$orderUUID}')\""; } else { $openOrderURL = JRoute::_("index.php?option=com_vxc&orderId={$orderId}&controller=routingorder&task=gotoStep&noSave=1&step={$currentStep}"); $openOrderEvent =''; } return ""; } static function getDownloadPackageLink($orderUUID) { if (!LegacyHelper::getNewMode() || !$orderUUID) return ''; return " "; } static function getNotLoggedURL() { if (self::getNewMode()==true) return JRoute::_('index.php?option=com_vxc&view=maloginerror&controller=myaccount'); else return JRoute::_('index.php?option=com_comprofiler&task=login'); } } ?>