// modificato il 2023-04-27 h 12.44
define("DIRECTCAR_ENVIRONMENT", "PROD");
$gaSites = Array
(
"directcar.motori.it"=>"ITA",
"es.direct.car"=>"ESP",
"uk.direct.car"=>"GBR",
);
$gsDomain = "";
if(is_array($_SERVER)&& array_key_exists("HTTP_HOST",$_SERVER)) {
$gsDomain = $_SERVER["HTTP_HOST"];
} else if(is_array($argv)) {
foreach($argv as $v) {
if(strpos($v,"domain=")===0) {
$gsDomain = substr($v,7);
}
}
}
// Default su versione ITA
if(!array_key_exists($gsDomain,$gaSites)) {
reset($gaSites);
$gsDomain = key($gaSites);
}
$gsSite = $gaSites[$gsDomain];
define('DIRECTCAR_URL', 'http://' . $gsDomain . '/');
if($gsSite=="ITA")
{
$gaEnvConfig = Array(
"modules" => Array(
"dbDefault" => Array
(
"connection" => Array
(
"type" => "MYSQLI",
//"host" => "127.0.0.1",
"host" => "landing.mysql.aws.trd.local",
"user" => "triboodirect_motori_it",
"passw" => "nA&CvRkqo#3r43#f",//"jakKv42BkdrGZg4c",//"aC2HCbutFGa6E28N",
"db" => "directcar_motori_it",
"charset" => "utf8",
),
"logSql" => Array
(
"enable" => true,
"soloErrate" => true,
"tempoMinimo" => 0,
"pathFile" => "var/log/",
),
),
"vehicles" => Array (
"url_cap_validator" =>"https://magellano.triboo.direct/index.php?module=site&method=ajaxExternalCapValid&name=postcode",
"404_alert_emails" => [ // Se vuoto o non presente non vengono inviate le email
'direct@triboo.it',
//'log.gabriele.brosulo@foreach.it',
],
"intengo_source" => 161
),
"utility" => Array(
"magellano" => Array( // produzione
"enabled" => true,
"client" => "/work/www/libraries/magellano/MagellanoClientAPI.php",
"url" => "https://magellano.triboo.direct/api/index.php",
"id_installation" => 1,
"id_site" => 5,
"id_landing" => 5,
"id_campaign" => 5,
"id_partner" => 1,
"password" => "xTrb#6Test",
"organic_source" => 3
),
),
"kernel"=>Array
(
"defaultVars"=>array
(
"language"=>"ITA",
),
),
"api"=>Array(
"ipWhiteList" => ["213.144.69.113", "213.144.69.115", "213.144.69.116", "34.241.211.37", "91.193.5.135", "35.152.100.62"]
),
"import"=>Array(
"notifications" => [
"provider" => "local", // local=smtp locale
"mail" => [
"smtp" => "127.0.0.1",
"from" => "directcar@triboo.direct",
"fromName" => "DirectCar",
"newJatoId" => [
"to" => ["christian.motan@triboo.it", "andrea.demarni@triboo.it", "antonio.lamberti@triboo.it", "direct@triboo.it"],
"cc" => [],
"bcc" => ["cristian.allesiardi@foreach.it"],
"reply_to" => "direct@triboo.it",
"body" => '
DirectCar
Nuovi Jato Id creati
{jatoids as k=>j}
Jato Id: {j.JatoId}
Marca: {j.Make}
Modello: {j.Model}
{END}
'
],
"endImport" => [
"to" => ["christian.motan@triboo.it", "andrea.demarni@triboo.it","antonio.lamberti@triboo.it", "direct@triboo.it"],
"cc" => [],
"bcc" => ["cristian.allesiardi@foreach.it"],
"reply_to" => "direct@triboo.it",
"body" => '
DirectCar
Importazione terminata correttamente
In allegato eventuali errori
'
]
],
]
),
"cronjob"=>Array(
"notifications" => [
"provider" => "local", // local=smtp locale
"mail" => [
"smtp" => "127.0.0.1",
"from" => "directcarmotori.it",
"fromName" => "DirectCar",
"logModelsErrors" => [
"to" => ["christian.motan@triboo.it", "andrea.demarni@triboo.it", "direct@triboo.it"],
"cc" => [],
"bcc" => [],
"reply_to" => "direct@triboo.it",
"body" => "
Attenzione, questi modelli pubblicati presentano degli errori.
| Marca |
Modello |
Cod. Carrozzeria |
Carrozzeria |
Errore |
{errors AS k=>e}
| {e.makeKey} |
{e.modelKey} |
{e.bodyCode} |
{e.bodyCodeDecode} |
{e.error} |
{END}
",
],
],
]
)
),
);
}
else if($gsSite=="ESP")
{
$gaEnvConfig = Array(
"modules" => Array(
"dbDefault" => Array
(
"connection" => Array
(
"type" => "MYSQLI",
//"host" => "127.0.0.1",
"host" => "landing.mysql.aws.trd.local",
"user" => "triboodirect_motori_it",
"passw" => "nA&CvRkqo#3r43#f",//"jakKv42BkdrGZg4c",//"aC2HCbutFGa6E28N",
"db" => "es_direct_car",
"charset" => "utf8",
),
"logSql" => Array
(
"enable" => true,
"soloErrate" => true,
"tempoMinimo" => 0,
"pathFile" => "var/log/",
),
),
"vehicles" => Array (
"url_cap_validator" =>"https://magellano.triboo.direct/index.php?module=site&method=ajaxExternalCapValid&name=postcode",
"intengo_source" => 161
),
"utility" => Array(
"magellano" => Array( // produzione
"enabled" => true,
"client" => "/work/www/libraries/magellano/esp/MagellanoClientAPI.php",
"url" => "https://magellano.triboo.direct/api/index.php",
"id_installation" => 2,
"id_site" => 31,
"id_landing" => 31,
"id_campaign" => 31,
"id_partner" => 2,
"password" => "138ce19cce",
"organic_source" => 19
),
),
"kernel"=>Array
(
"defaultVars"=>array
(
"language"=>"ESP",
),
),
"site"=>Array
(
"fuelType" => array(
"U" => array(
"descr"=>"Gasolina",
"image"=>"ico-alimentazione-benzina.png",
),
"D" => array(
"descr"=>"Diesel",
"image"=>"ico-alimentazione-diesel.png"
),
"G" => array(
"descr"=>"GLP",
"image"=>"ico-alimentazione-gpl.png"
),
"N" => array(
"descr"=>"Metano",
"image"=>"ico-alimentazione-metano.png"
),
"I" => array(
"descr"=>"Hibrido",
"image"=>"ico-alimentazione-ibrido.png"
),
"E" => array(
"descr"=>"Eléctrico",
"image"=>"ico-alimentazione-elettrico.png"
),
),
"bodyCode"=>Array
(
"MC" => array(
"descr"=>"Citycar",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-citycar.png",
"priorita"=>3
),
"HA" => array(
"descr"=>"Berlina 2 volúmenes",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-berlina-2.png",
"priorita"=>1
),
"SA" => array(
"descr"=>"Berlina 3 volúmenes",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-berlina-3.png",
"priorita"=>2
),
"ES" => array(
"descr"=>"Wagon",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-wagon.png",
"priorita"=>5
),
"OD" => array(
"descr"=>"Suv",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-suv.png",
"priorita"=>4
),
"FW" => array(
"descr"=>"Monovolumen",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-monovolume.png",
"priorita"=>6
),
"CO" => array(
"descr"=>"Coupé",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-coupe.png",
"priorita"=>7
),
"CA" => array(
"descr"=>"Descapotable",
"descr-agg"=>"Ver todo el",
"image"=>"icon-car-cabriolet.png",
"priorita"=>8
)
),
)
)
);
}
else if($gsSite=="GBR")
{
$gaEnvConfig = Array(
"modules" => Array(
"dbDefault" => Array
(
"connection" => Array
(
"type" => "MYSQLI",
//"host" => "127.0.0.1",
"host" => "landing.mysql.aws.trd.local",
"user" => "triboodirect_motori_it",
"passw" => "nA&CvRkqo#3r43#f",//"jakKv42BkdrGZg4c",//"aC2HCbutFGa6E28N",
"db" => "uk_direct_car",
"charset" => "utf8",
),
"logSql" => Array
(
"enable" => true,
"soloErrate" => true,
"tempoMinimo" => 0,
"pathFile" => "var/log/",
),
),
"vehicles" => Array (
"url_cap_validator" =>"https://magellano.triboo.direct/index.php?module=site&method=ajaxExternalCapValid&name=postcode",
"intengo_source" => 161
),
"utility" => Array(
"magellano" => Array( // produzione
"enabled" => true,
"client" => "/work/www/libraries/magellano/uk/MagellanoClientAPI.php",
"url" => "https://magellano.triboo.direct/api/index.php",
"id_installation" => 3,
"id_site" => 32,
"id_landing" => 32,
"id_campaign" => 32,
"id_partner" => 3,
"password" => "fe82dc9c18",
"organic_source" => 20
),
),
"kernel"=>Array
(
"defaultVars"=>array
(
"language"=>"GBR",
),
),
"site"=>Array
(
"fuelType" => array(
"U" => array(
"descr"=>"Petrol",
"image"=>"ico-alimentazione-benzina.png",
),
"D" => array(
"descr"=>"Diesel",
"image"=>"ico-alimentazione-diesel.png"
),
"G" => array(
"descr"=>"GLP",
"image"=>"ico-alimentazione-gpl.png"
),
"N" => array(
"descr"=>"Methane",
"image"=>"ico-alimentazione-metano.png"
),
"I" => array(
"descr"=>"Hybrid",
"image"=>"ico-alimentazione-ibrido.png"
),
"E" => array(
"descr"=>"Electric",
"image"=>"ico-alimentazione-elettrico.png"
),
),
"bodyCode"=>Array
(
"MC" => array(
"descr"=>"Citycar",
"descr-agg"=>"See all the",
"image"=>"icon-car-citycar.png",
"priorita"=>3
),
"HA" => array(
"descr"=>"Fastback",
"descr-agg"=>"See all the",
"image"=>"icon-car-berlina-2.png",
"priorita"=>1
),
"SA" => array(
"descr"=>"Sedan",
"descr-agg"=>"See all the",
"image"=>"icon-car-berlina-3.png",
"priorita"=>2
),
"ES" => array(
"descr"=>"Wagon",
"descr-agg"=>"See all the",
"image"=>"icon-car-wagon.png",
"priorita"=>5
),
"OD" => array(
"descr"=>"Suv",
"descr-agg"=>"See all the",
"image"=>"icon-car-suv.png",
"priorita"=>4
),
"FW" => array(
"descr"=>"MPV",
"descr-agg"=>"See all the",
"image"=>"icon-car-monovolume.png",
"priorita"=>6
),
"CO" => array(
"descr"=>"Coupé",
"descr-agg"=>"See all the",
"image"=>"icon-car-coupe.png",
"priorita"=>7
),
"CA" => array(
"descr"=>"Cabriolet",
"descr-agg"=>"See all the",
"image"=>"icon-car-cabriolet.png",
"priorita"=>8
),
"SC" => array
(
"descr"=>"Sportscar",
"descr-agg"=>"See all the",
"image"=>"icon-car-sports-car.png",
"priorita"=>9
)
),
)
)
);
}
?>
// ver 0104ml loadXml diventa pubblica per permettere il parsing da nodi xml oltre che da stringhe
class XMLParser
{
/**
* Trasforma un file xml nell'equivalente array multilivello.
*
* @param string $psXml stringa contenente xml
* @param bool $pbExcludeNS se false (Default) no toglie i NameSpace
* @param bool $pbIndexDuplicate se false (Default) modalità Standard di indicizzazione.
* *
* @return array Array dell'xml.
* @return false in caso di problemi.
*/
function loadFromFile($psFile,$pbExcludeNS=false,$pbIndexDuplicate=false)
{
$vsXml = file_get_contents($psFile);
return XMLParser::loadFromString($vsXml,$pbExcludeNS,$pbIndexDuplicate);
}
/**
* Trasforma un testo xml nell'equivalente array multilivello.
*
* @param string $psXml stringa contenente xml
* @param bool $pbExcludeNS se false (Default) no toglie i NameSpace
* @param bool $pbIndexDuplicate se false (Default) modalità Standard di indicizzazione.
* *
* @return array Array dell'xml.
* @return false in caso di problemi.
*/
function loadFromString($psXml,$pbExcludeNS=false,$pbIndexDuplicate=false)
{
$voXml = new DOMDocument();
$voXml->loadXML($psXml);
//$vsName=$voXml->doctype->name;
//echo "Name:".$vsName;
$vaRes=XMLParser::loadXml($voXml,$pbExcludeNS,$pbIndexDuplicate);
//print_r($vaRes);
if(is_object($voXml->doctype))
$vaRes["__dtd"]=$voXml->doctype->systemId;
if(defined("B_VERBOSE") && B_VERBOSE)
echo TreeArray($vaRes);
return $vaRes;
}
/**
* Trasforma un testo xml nell'equivalente array multilivello
* in questa versione vengono eliminati i #text e definiti
* gli attributi.
* Ogni nodo dell'XML è un elemento dell'array risultate che può
* avere i seguenti valori:
* [__attr] -> Attributi (che è un array chiave=valore)
* [__value]-> valore dell'elemento se presente
* [__name] -> nome originale del nodo
* [(x)] -> Nome del nodo se presente.
*NOTA IMPORTANTE:
* A PARTIRE DALLA VERSIONE 0101ga sono presenti due possibili indicizzazioni:
* Quella Standard:
* i nomi dei nodi sono nel formato [(x)]
* dove (x) è un numero messo dopo il primo elemento a pari nome
* per rendere univoci i nomi degli elementi dell'array.
* Quella Nuova:
* i nome dei nodi sono nel formato []
* in caso di elementi doppi, in automatico l'indiccazione
* passa in [][x] dove x è progressivo da zero se non
* ci sono attributi "name", altrimenti prende l'attributo name
*
* Esempio:
*
*
*
*
*
*
*
* Standard: ["Prova"], ["Prova(1)"], ["Prova(2)"]
* Nuova: ["Prova"][0], ["Prova"]["guido"], ["Prova"][1].
*
* @param object $poNode Oggetto DOMDocument (vedere manuale php)
* @param bool $pbExcludeNS se false (Default) no toglie i NameSpace
* @param bool $pbIndexDuplicate se false (Default) modalità Standard di indicizzazione.
*
* @return array Array dell'xml.
* @return false in caso di problemi.
*/
public function loadXml(&$poNode,$pbExcludeNS=false,$pbIndexDuplicate=false)
{
$paReturn = Array();
$vsName=$poNode->nodeName;
if($pbExcludeNS)
$vsName = XMLParser::stripNS($vsName);
$paReturn["__name"]=$vsName;
if($poNode->hasAttributes())
{
$voAtt=$poNode->attributes;
foreach( $voAtt as $i=>$voAttribute)
{
$vsName = $voAttribute->name;
if($pbExcludeNS)
$vsName = XMLParser::stripNS($vsName);
$paReturn["__attr"] [$vsName]= $voAttribute->value;
}
}
if($poNode->hasChildNodes())
{
$voChilds =$poNode->childNodes;
$vaDuplicate=array();
for($i=0; $i<$voChilds->length;$i++)
{
$voChild = $voChilds->item($i);
$y=0;
$vsNameOri=$voChild->nodeName;
if($pbExcludeNS)
$vsNameOri = XMLParser::stripNS($vsNameOri);
$vsName = $vsNameOri;
if($pbIndexDuplicate)
{
// E' stato richiesta la nuova modalità di indicizzazione
// in caso di nomi di elementi uguali a pari livello.
// esendo nel ciclo in cui abbiamo scoperto il SECONDO caso,
// trasformo il primo caso (qualora sia stato innescato dal caso C..dell'
// if che trovate più in basso) in un elemento [0] in preparazione
// dell'indicizzazione di questo secondo caso.
// potrebbe essere che già il primo caso sia stato indicizzato
// qualora "name" era settato (caso A dell'if che trovate più in basso),
// in questo caso $vaDuplicate[$vsName] e' settato e l'if non ha luogo.
// dal terzo caso in poi $vaDuplicate[$vsName] terrà conto
// dell'indice corrente di $vsName...
if(isset($paReturn[$vsName]) and !isset($vaDuplicate[$vsName]))
{
if(isset($paReturn[$vsName]["__attr"]["name"]))
{
$vsNameElement=$paReturn[$vsName]["__attr"]["name"];
$vaTmp=$paReturn[$vsName];
unset($paReturn[$vsName]);
$paReturn[$vsName][$vsNameElement]=$vaTmp;
$vaDuplicate[$vsName]=0;
}
else
{
$vaTmp=$paReturn[$vsName];
unset($paReturn[$vsName]);
$paReturn[$vsName][0]=$vaTmp;
$vaDuplicate[$vsName]=1;
}
}
}
else
{
// Siamo nel caso vecchio di indicizzazione
// in caso di nomi di elementi uguali a pari livello.
// qui semplicemente il secondo elemento $vsName si chiamerà
// ["$vsName(1)"], il terzo ["$vsName(2)"] ecc...
while(isset($paReturn[$vsName]))
{
$y++;
$vsName=$vsNameOri."(".$y.")";
}
}
if($voChild->nodeType==XML_TEXT_NODE)
{
$paReturn["__value"]=trim($voChild->nodeValue);
if(trim($paReturn["__value"])=="") unset($paReturn["__value"]);
}
else
{
$vaTmp=XMLParser::loadXml($voChild,$pbExcludeNS,$pbIndexDuplicate);
if($pbIndexDuplicate)
{
// E' stato richiesta la nuova modalità di indicizzazione
// metto i risultati nell'indice corrente di $vaDuplicate[$vsName]
if(isset($vaTmp["__attr"]["name"]))
{
// CASO A: indipendentemente se è il primo elemento indicizzo perchè
// c'è un name
$paReturn[$vsName][$vaTmp["__attr"]["name"]]=$vaTmp;
if(!isset($vaDuplicate[$vsName])) $vaDuplicate[$vsName]=0;
}
elseif(isset($vaDuplicate[$vsName]))
{
// CASO B: indicizzo perchè non è il primo elemento, altriment
// $vaDuplicate[$vsName] non sarebbe settato
$paReturn[$vsName][$vaDuplicate[$vsName]]=$vaTmp;
$vaDuplicate[$vsName]++;
}
else
{
// CASO C: non indicizzo e creo il primo elemento nella modalità
// standard. Volutamente non setto $vaDuplicate[$vsName]
// per innescare meglio if(isset($paReturn[$vsName]) and !isset($vaDuplicate[$vsName]))
// qui sopra.
$paReturn[$vsName]=$vaTmp;
}
}
else
{
// Siamo nel caso vecchio di indicizzazione
// qui non ci sono indicizzazioni tranne il solito trucco ["$vsName(x)"].
$paReturn[$vsName]= $vaTmp;
}
}
}
}
return $paReturn;
}
private function stripNS($psName)
{
$vaParts = explode(":",$psName);
return $vaParts[count($vaParts)-1];
}
/**
* Dato un array completo dell'XML e dato un percorso
* ritorna un valore o parte dell'array dato.
* Notare che $psLevel può contenere anche il valore "/.."
* che lo fa tornare indietro di un passo.
* Ad esempio:
* A/B/C/../../E coincide con A/E
* Utile per recuperare velocemente valori dell'array
* dell'xml in modo assoluto o dalla posizione in cui
* ci si trova.
*NOTA:
* Questo metodo può essere utilizzato in modo statico
* dall'esterno.
*
* @param array $paXml Array xml
* @param string $psLevel Percorso xml da trovare
* @return mixed elemento trovato
* @return false se non trova niente
*/
function getXMLValue($paXml,$psLevel)
{
$vaPath=explode("/",$psLevel);
if(!is_array($vaPath))
return isset($paXml[$psLevel]) ? $paXml[$psLevel] : false;
$vaPath[]="__END__";
while(($vsElem=array_shift($vaPath))<>"__END__")
{
if($vsElem=="..")
{
$vsPop=array_pop($vaPath);
if($vsPop=="__END__") array_push($vaPath,$vsPop);
}
else
array_push($vaPath,$vsElem);
}
foreach($vaPath as $vnKey => $vsElem)
{
if(isset($paXml[$vsElem]))
$paXml=$paXml[$vsElem];
else
return false;
}
return $paXml;
}
/**
* Questa funzione prende come parametro un array appena creato
* da un xml e converte i casi semplici di solo __name + __value
* in un singolo elemento.
* Esempio:
* ["prova"] = array("__name" => "prova", "__value" => "valore")
* diventa
* ["prova"] = "valore".
*
* Questo rende compatibile l'xml, ad esempio, per l'uso con WebLib5
*
* @param array $paXml Array nato da xml da Elaborare
* @return array Array elaborato.
*
*/
function getNoValueArray($paXml)
{
$vaRis=array();
if(!is_array($paXml))
return $vaRis;
foreach($paXml as $vsLabel => $vxInfo)
{
if(is_array($vxInfo))
$vaRis[$vsLabel]=self::getNoValueArray($vxInfo);
else
$vaRis[$vsLabel]=$vxInfo;
}
// aggiunto versione 1.03ml
if(count($vaRis)==2 and isset($vaRis["__name"]) and isset($vaRis["__attr"]) and isset($vaRis["__attr"]["name"]) and !isset($vaRis["__value"]))
return "";
elseif(count($vaRis)==2 and isset($vaRis["__name"]) and isset($vaRis["__value"]) and !is_array($vaRis["__value"]))
return $vaRis["__value"];
elseif(count($vaRis)==3 and isset($vaRis["__name"]) and isset($vaRis["__value"]) and isset($vaRis["__attr"]["name"]) and !is_array($vaRis["__value"]))
return $vaRis["__value"];
elseif(count($vaRis)==2 and isset($vaRis["__name"]) and isset($vaRis["__attr"]["value"]) and !is_array($vaRis["__attr"]["value"]))
return $vaRis["__attr"]["value"];
if(count($vaRis)==1 and isset($vaRis["__name"]) )
return "";
else
return $vaRis;
}
}
?>
/**
* v.0108 - SE - 10/04/2014 - modifica dateConvert che se il dato mi arriva "" imposto null
* v.0109 - ED - 09/07/2014 - aggiunta funzione textToUrl()
* v.0110 - ED - 31/08/2016 - aggiunta funzioni getLock() e releaseLock()
* v.0111 - ED - 10/07/2017 - aggiunta funzione getUserIp()
* v.0112 - ED - 25/09/2017 - aggiunta funzione arrayTreeToFlat()
*/
class Util
{
/**
* Trasforma un array multi-livello in uno su un livello singolo, concatenando le chiavi.
* Es: $arr[a][b][c]="val" diventa $arr['a.b.c']="val"
* @param $paSource l'array multi-livello da processare
* @param $psKeySeparator il carattere che fa da separatore nelle chivi concatenate
* @return l'array equivalente su un singolo livello
*/
public static function arrayTreeToFlat($paSource, $psKeySeparator=".")
{
$vaRet = Array();
self::arrayTreeToFlatRecursive($paSource, $vaRet, $psKeySeparator, "");
return $vaRet;
}
/**
* Funzione ricorsiva ad uso di arrayTreeToFlat()
* @param $paSource l'array multi-livello da processare
* @param $paDestination l'array ad un singolo livello da popolare
* @param $psKeySeparator il carattere che fa da separatore nelle chivi concatenate
* @param $psKeyPrefix il path di chiavi creato fin'ora, a cui aggiungere quella del livello in corso
*/
private static function arrayTreeToFlatRecursive($paSource, &$paDestination, $psKeySeparator, $psKeyPrefix)
{
foreach($paSource as $vsK=>$vxV)
{
$vsNewKey = $psKeyPrefix=="" ? $vsK : $psKeyPrefix.$psKeySeparator.$vsK;
if(is_array($vxV))
self::arrayTreeToFlatRecursive($vxV, $paDestination, $psKeySeparator, $vsNewKey);
else
$paDestination[$vsNewKey] = $vxV;
}
}
/**
* Restituisce l'indirizzo ip dell'utente che sta navigando il sito, null se non lo trova.
* @param $pbAllowPrivateIps true per ritornare anche ip di reti private (es: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, ...)
* @return l'ip dell'utente o null
*/
public static function getUserIp($pbAllowPrivateIps=false)
{
$vaKeys = Array("HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "REMOTE_ADDR");
foreach($vaKeys as $vskey)
{
if(array_key_exists($vskey, $_SERVER))
{
$vaPossibleIps = explode(",", $_SERVER[$vskey]);
foreach($vaPossibleIps as $vsIp)
{
$vsIp = trim($vsIp);
if($pbAllowPrivateIps && (filter_var($vsIp, FILTER_VALIDATE_IP)!==false))
return $vsIp;
if(filter_var($vsIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)!==false)
return $vsIp;
}
}
}
return null;
}
/**
* Richiede un lock esclusivo per evitare la sovrapposizione di processi. Il lock � basato su file.
* @param $psLockName nome del lock
* @param $pnTimeout tempo di attesa per ottenere il lock, in secondi
* @param $psLockPath eventuale path personalizzato in cui salvare il file su cui si basa il lock
* @return una risorsa PHP di tipo file se il lock viene ottenuto, false altrimenti
* @example
* $vxLock = Util::getLock("myLock", 30);
* if($vxLock!==false) {
* ...
* Util::releaseLock($vxLock);
* }
*/
public static function getLock($psLockName, $pnTimeout=5, $psLockPath=null)
{
if(is_null($psLockPath))
$psLockPath = FS_VAR."tmp/";
$vsLockFullName = $psLockPath."lock_".$psLockName.".txt";
// creazione file con permessi 660 per permettere accesso al file di lock da processi apache e crontab
if(!file_exists($vsLockFullName))
{
touch($vsLockFullName);
chmod($vsLockFullName, 0660);
}
$vrFile = fopen($vsLockFullName, "r+");
$vnTimeStart = microtime(true);
$vnWouldBlock = null;
$vbLock = true;
//echo "getLock(".$psLockName.") - pid:".getmypid()."\n";
while(($vbLock=flock($vrFile, LOCK_EX|LOCK_NB, $vnWouldBlock))===false) // LOCK_NB evita che si blocchi lo script se non ottiene il lock
{
$vnWaiting = microtime(true)-$vnTimeStart;
if($vnWouldBlock===1 && $vnWaiting<$pnTimeout) // attesa per nuovo tentativo di lock
{
$vnRand = rand(10000, 50000);
//echo "getLock(".$psLockName.") - pid:".getmypid()." - sleep:".$vnRand." - total-wait:".$vnWaiting."\n";
usleep($vnRand); //usleep(10000); // 0.01 secondi
}
else // timeout scaduto
return false;
}
//echo "getLock(".$psLockName.") - pid:".getmypid()." - success\n";
// lock ottenuto
return $vrFile;
}
/**
* Rilascia il lock ottenuto in precedenza.
* @param $prLock la risorsa ottenuta con getLock()
*/
public static function releaseLock($prLock)
{
//echo "releaseLock() - pid:".getmypid()."\n";
flock($prLock, LOCK_UN);
fclose($prLock);
}
/**
* Data una stringa, ne restituisce una il pi� simile possibile da usare in un url.
* NB: attenzione al charset della stringa!!!
* @param $psTxt la stringa da convertire, in UTF-8
*/
public static function textToUrl($psTxt)
{
$psTxt = strtolower($psTxt);
$psTxt = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $psTxt); // trasforma le vocali accentate nelle corrispondenti ASCII
$psTxt = preg_replace("/[^a-z0-9]+/m", "-", $psTxt);
$psTxt = trim($psTxt, "-");
return urlencode($psTxt);
}
static function trunc($psString,$pnNumChars,$psSuffix="...")
{
if (strlen($psString)>$pnNumChars)
$psString = substr($psString,0,$pnNumChars)."...";
return $psString;
}
static function loadFromDir($psDir,$psClass)
{
//echo "opening ".$psDir."
";
global $gaForceVersion;
$vsVersion = "[0-9]{4}[a-zA-Z]{2}";
if(isset($gaForceVersion) && isset($gaForceVersion[$psClass]))
$vsVersion = $gaForceVersion[$psClass];
$vsMatch = "/^".$psClass.".(".$vsVersion.").class.php\$/";
$vrDir = openDir($psDir);
if(!$vrDir)
die("Impossibile aprire ".$psDir." per caricare la classe ".$psCalss);
$vaFound = Array();
while (($vsFile = readdir($vrDir)) !== false)
{
if( ($vsFile!=".")&&($vsFile!="..") )
{
$vsFilePath = $psDir.$vsFile;
if(is_dir($vsFilePath))
{
if($vaRes = loadFromDir($vsFilePath."/",$psClass))
$vaFound[] = $vaRes;
}
else
{
if(preg_match($vsMatch,$vsFile,$vaMatch))
{
$vaTemp = Array
(
"class"=> $psClass,
"version" => $vaMatch[1],
"path"=> $vsFilePath
);
$vaFound[] = $vaTemp;
//echo "including: $vsFilePath
";
}
}
}
}
//print_r($vaFound);
closedir($vrDir);
if(count($vaFound)==0)
return false;
//echo "
not returned false
";
$vsMax = "";
//$i=0;
foreach($vaFound as $vaFile)
{
//echo "
".$i++."
";
if(strcmp($vaFile["version"],$vsMax)>0)
{
//echo "maggiore
";
$vsMax = $vaFile["version"];
$vaRes = $vaFile;
}
//echo "minore
";
}
//print_r($vaRes);
return $vaRes;
}
static function _null($s)
{
return ((string)$s==S_NULL);
}
//*************************************************
//DESCRIZIONE:
// Sostituisce print_r visualizzando un array nella
// modalit� ad albero.
//RITORNA:
// Una stringa corsiva "No Array" se il parametro non � una stringa
// Una Stringa HTML (albero array) da visualizzare.
//*************************************************
static function TreeArray($paArray)
{
if(!is_array($paArray)) return "No Array";
$HTMLCODE="\n";
reset($paArray);
while(list($vxKey,$vxValue)=each($paArray))
{
if(is_array($vxValue))
$HTMLCODE .="- ".$vxKey." (array)\n".TreeArray($vxValue);
else
$HTMLCODE .="
- ".$vxKey."= ".$vxValue."\n";
}
$HTMLCODE .="
\n";
return $HTMLCODE;
}
static function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2))
{
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2)
{
// originale
//$paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
// modificato
if(array_key_exists($sKey2,$paArray1))
$paArray1[$sKey2] = Util::array_merge_recursive2($paArray1[$sKey2], $sValue2);
else
$paArray1[$sKey2] = $paArray2[$sKey2];
}
return $paArray1;
}
function completeArrayDefault($paArray,$paDefault)
{
while(is_array($paArray) && array_key_exists("default",$paArray))
{
if(!array_key_exists($paArray["default"],$paDefault))
throw new WebPRGException("il default '".
$paArray["default"]."' non esiste");
$vsDefault = $paArray["default"];
unset($paArray["default"]);
$paArray = array_merge($paDefault[$vsDefault],$paArray);
}
if(is_array($paArray))
foreach($paArray as $k=>$v)
$paArray[$k]= completeArrayDefault($v,$paDefault);
return $paArray;
}
//alanic 29/03/2006
//Da un array, crea la query string da aggiungere ad un url
//se $pbAdd=true considera $paDati come parametri da aggiungere ad una
//url con altri parametri
//$paEscludi array di chiavi da escludere dalla ris finale
//marcob 13/02/07 resa la funzione ricorsiva per trasformare array di
//tutti i livelli con il formato padre:figlio
//aggiunto parametro psPrefix
function arrayToQs($paDati,$paEscludi=array("S"),$pbAdd=true, $psPrefix="")
{
$vsRis="";
if(!$paDati)
return $vsRis;
if($pbAdd)
$vsSep="&";
else
$vsSep="?";
if ($psPrefix!="")
$psPrefix.=":";
$vnCnt=0;
foreach($paDati as $k => $v)
{
//if (is_array($v))
if($vnCnt!=0)
$vsSep="&";
if (is_array($v))
{
$vsRis.=arrayToQs($v,$paEscludi,true, $psPrefix.$k);
}
else
{
if(!in_array($k,$paEscludi))
{
$vsRis.=$vsSep.$psPrefix.$k."=".urlencode($v);
}
}
$vnCnt++;
}
return $vsRis;
}
/**
* Author: Marco Begliardo
* Trasforma un array in una stringa del tipo Chiave: Valore,...
* Ricorsiva
*
* @param array $paArray Array
* @return string
*/
function arrayToSimpleString($paArray)
{
$vsOut="";
foreach($paArray as $k=>$v)
{
if ($vsOut!="")
$vsOut.=",";
if (is_array($v))
$vsOut.="$k: ".arrayToSimpleString($v);
else
$vsOut.="$k: $v";
}
return $vsOut;
}
static function arrayFilter($paSource,$psPrefix=null,$pbStripPrefix=false,$paAltri=null)
{
if (!is_array($paSource))
return $paSource;
reset($paSource);
$vaRes = Array();
while(list($vxKey,$vxValue)=each($paSource))
{
if(is_null($psPrefix)||(substr($vxKey,0,strlen($psPrefix))==$psPrefix))
{
if($pbStripPrefix)
$vaRes[substr($vxKey,strlen($psPrefix))]=$vxValue;
else
$vaRes[$vxKey]=$vxValue;
}
}
if(is_array($paAltri))
foreach($paAltri as $vxKey)
if(array_key_exists($vxKey,$paSource))
$vaRes[$vxKey] = $paSource[$vxKey];
return $vaRes;
}
static function arrayFilterNull($paSource)
{
foreach($paSource as $k=>$v)
if(is_null($v))
unset($paSource[$k]);
return $paSource;
}
static function strptimeTS($psData,$psFormat)
{
$ftime = Util::strptime($psData,$psFormat);
return mktime
(
$ftime['tm_hour'],
$ftime['tm_min'],
$ftime['tm_sec'],
1 ,
$ftime['tm_yday'] + 1,
$ftime['tm_year'] + 1900
);
}
static function urlStripParam($psUrl,$paParam)
{
$paPezzi=parse_url($psUrl);
$psQuery="";
//print_r($paPezzi);
if (isset($paPezzi["query"]))
{
$paQuery=explode("&",$paPezzi["query"]);
foreach($paQuery as $psSingParam)
{
//echo $psSingParam;
$paVar=explode("=",$psSingParam);
if ($psQuery!="")
$psQuery.="&";
if (!in_array($paVar[0],$paParam))
$psQuery.=$paVar[0]."=".$paVar[1];
}
}
if($psQuery!="")
$psQuery="?".$psQuery."&";
else
$psQuery="?";
//echo $paPezzi["path"].$psQuery;
return $paPezzi["path"].$psQuery;
}
static function getUniqueToken($pnLen)
{
if(!defined("S_UNIQUE_TOKEN_PASSWORD"))
define("S_UNIQUE_TOKEN_PASSWORD","lvuebckcidel�sdfk");
if(!defined("S_UNIQUE_TOKEN_MASK"))
define("S_UNIQUE_TOKEN_MASK","100110111010101011100010101010111001010100011110111");
if(($pnLen<11) || ($pnLen>35))
return false;
$vsMicroTime = microtime();
$vaMicroTime = explode(" ",$vsMicroTime);
$vnSeconds = $vaMicroTime[1];
$vaTemp = explode(".",$vaMicroTime[0]);
$vsMicroSeconds = substr($vaTemp[1],0,6);
$vnMicroSeconds =ltrim($vsMicroSeconds,"0");
// ottengo la stringa di 51 bit 31 dei secondi e 20 dei microsecondi
$vs51Bit = str_pad(base_convert($vnSeconds,10,2),31,"0",STR_PAD_LEFT).
str_pad(base_convert($vnMicroSeconds,10,2),20,"0",STR_PAD_LEFT);
$vs51BitC = $vs51Bit;
// metto un bit dall'inizio e 1 dalla fine per mischiare
$vs51Bit = strrev($vs51Bit);
$vs51Bit = substr($vs51Bit,4).substr($vs51Bit,0,4);
/*
$vsTemp = $vs51Bit;
$vs51Bit="";
while(strlen($vsTemp>0))
{
if( (strlen($vs51Bit)%2)==1 )
{
$vs51Bit.= substr($vsTemp,-1,1);
$vsTemp = substr($vsTemp,0,-1);
}
else
{
$vs51Bit.= substr($vsTemp,0,1);
$vsTemp = substr($vsTemp,1);
}
}
*/
$vs31Bit = substr($vs51Bit,0,31);
$vs20Bit =strrev(substr($vs51Bit,31));
$vn31Bit = (int)base_convert($vs31Bit,2,10);
$vn20Bit = (int)base_convert($vs20Bit,2,10);
$vs31BitM = substr(S_UNIQUE_TOKEN_MASK,0,31);
$vs20BitM = substr(S_UNIQUE_TOKEN_MASK,31);
$vn31BitM = (int)base_convert($vs31BitM,2,10);
$vn20BitM = (int)base_convert($vs20BitM,2,10);
$vn31Bit = $vn31Bit ^ $vn31BitM;
$vn20Bit = $vn20Bit ^ $vn20BitM;
$vsMicroTime36 = str_pad(base_convert($vn31Bit, 10, 36),6,"0",STR_PAD_LEFT).
str_pad(base_convert($vn20Bit, 10, 36),4,"0",STR_PAD_LEFT);
// md5 base36
$vsMd536 = str_pad(base_convert(md5($vsMicroTime36.S_UNIQUE_TOKEN_PASSWORD),16,36),25,"0",STR_PAD_RIGHT);
$vsMd536c = $vsMd536;
$vsMicroTime36c = $vsMicroTime36;
// compongo il codice finale alternando la stringa del tempo con l'md5
/*
$vsRes = "";
while(($pnLen-strlen($vsRes))>strlen($vsMicroTime36) )
{
if( ((strlen($vsRes)%2)==1)&&(strlen($vsMicroTime36)>0) )
{
$vsRes.= substr($vsMicroTime36,0,1);
$vsMicroTime36 = substr($vsMicroTime36,1);
}
else
{
$vsRes.= substr($vsMd536,0,1);
$vsMd536 = substr($vsMd536,1);
}
}
$vsRes.=$vsMicroTime36;
*/
// ora metto so lo il time seguito da md5 troncato per la lunghezza
$vsRes = substr($vsMicroTime36.$vsMd536,0,$pnLen);
$vsFirst = substr($vsRes,0,-1);
$vsLast = substr($vsRes,-1);
$vnSwap = ord($vsLast)%strlen($vsFirst);
$vsRes = substr($vsFirst,-$vnSwap).substr($vsFirst,0,-$vnSwap).$vsLast;
/*
echo $vsRes."|".
$vsMicroTime36c."|".
$vsMd536c."|".
$vsMicroTime."|".
$vs51BitC."|".
$vs51Bit."|".
"\r\n";
*/
return strtoupper($vsRes);
}
static function array_path_exists($psPath,&$paArray,$psSeparator=".")
{
$vaPath = explode($psSeparator,$psPath);
$vxTemp = &$paArray;
while(count($vaPath)>0)
{
$vsKey = array_shift($vaPath);
if(!is_array($vxTemp) || !array_key_exists($vsKey,$vxTemp))
return false;
$vxTemp =& $vxTemp[$vsKey];
}
return true;
}
static function array_ref($psPath,&$paArray,$psSeparator=".")
{
$vaPath = explode($psSeparator,$psPath);
$vxTemp = &$paArray;
while(count($vaPath)>0)
{
$vsKey = array_shift($vaPath);
if(!is_array($vxTemp) || !array_key_exists($vsKey,$vxTemp))
throw new WebPRGException($psPath." percorso non trovato");
$vxTemp =& $vxTemp[$vsKey];
}
return $vxTemp;
}
static function array_strip_tags(&$paData)
{
array_walk_recursive($paData, 'array_single_st');
}
static function array_single_st(& $item, $key)
{
if (is_string($item))
$item = strip_tags($item);
}
/**
* Crea un codice alfanumerico della lunghezza richiesta
*
* @param unknown_type $length
* @return unknown
*/
static function randomKeys($length)
{
$pattern = "123456789ABCDEFGHJKLMNPQRSTUVZ";
$key="";
for($i=0;$i<$length;$i++)
{
$key .= $pattern[rand(0,strlen($pattern)-1)];
}
return $key;
}
/**
* Crea un'immagine per i captcha
* $rand e' il codice da creare (vedi qui sopra randomKeys() )
* $vsFontPath e' il percorso dove trovare il file del font usato
*
* @param unknown_type $rand
* @param unknown_type $width
* @param unknown_type $height
* @param unknown_type $vsFontPath
* @return unknown
*/
static function imgCode($rand,$width,$height,$vsFontPath)
{
$image = imagecreate($width, $height);
$bgColor = imagecolorallocate ($image, 255, 255, 255);
$textColor = imagecolorallocate ($image, 0, 0, 0);
// Add Random noise
for ($i = 0; $i < 250; $i++)
{
$rx1 = rand(0,$width);
$rx2 = rand(0,$width);
$ry1 = rand(0,$height);
$ry2 = rand(0,$height);
$rcVal = rand(0,255);
$rc1 = imagecolorallocate($image,
rand(100,255),
rand(100,255),
rand(100,255));
imageline ($image, $rx1, $ry1, $rx2, $ry2, $rc1);
}
// write the random number
$font = imageloadfont($vsFontPath."caveman.gdf");
imagestring($image, $font, 10, 10, $rand, $textColor);
$voImg = imagejpeg($image);
imagedestroy($image);
return $voImg;
}
static function dateConvert($psValue,$psFrom,$psTo)
{
//print_r($psValue);die();
if(is_null($psValue)||(trim($psValue)==""))
$vsRes = null;
else
{
if($psFrom=="ANY-IT-DATE")
{
$vaTime = false;
$vsTemp = "";
for($i=0;$i'9')
$vsChar = "-";
$vsTemp.=$vsChar;
}
$vaTemp = explode("-",$vsTemp);
if(count($vaTemp)==3)
{
if(strlen($vaTemp[2])==2)
{
$vaTemp[2] = substr(date("Y"),0,2).$vaTemp[2];
}
$vaTime=Array();
$vaTime["tm_hour"]=0;
$vaTime["tm_min"]=0;
$vaTime["tm_sec"]=0;
$vaTime["tm_mday"]=ltrim($vaTemp[0],"0");
$vaTime["tm_mon"]=ltrim($vaTemp[1],"0")-1;
$vaTime["tm_year"]=$vaTemp[2]-1900;
}
}
else
$vaTime = Util::strptime($psValue,$psFrom);
//echo $psValue."|".$paPar[0];
//print_r($vaTime);echo "
";
if($vaTime)
{
//echo "2";
if(($vaTime["tm_hour"]<0)||($vaTime["tm_hour"]>23))
$vaTime["tm_hour"] = 0;
if(($vaTime["tm_min"]<0)||($vaTime["tm_min"]>59))
$vaTime["tm_min"] = 0;
if(($vaTime["tm_sec"]<0)||($vaTime["tm_sec"]>59))
$vaTime["tm_sec"] = 0;
$vnTime = mktime($vaTime["tm_hour"],$vaTime["tm_min"],$vaTime["tm_sec"],
$vaTime["tm_mon"]+1,$vaTime["tm_mday"],1900+$vaTime["tm_year"]);
$vsRes = strftime($psTo,$vnTime);
//echo "|".$vnTime."|
";
//echo $paPar[1].",".$vnTime.",".$vsRes;
}
else
$vsRes = null;
}
//die($vsRes);
//echo "!".$vsRes."!";
return $vsRes;
}
static function ifNull($pxValue,$pxSost = S_NULL)
{
if(is_null($pxValue))
return $pxSost;
return $pxValue;
}
/**
* Emula (parte) dell'strptime per Windows
* Accetta i seguenti formati:
* %Y-%m-%d [%H o %h]:[%i]:[%s]
* %y-%m-%d [%H o %h]:[%i]:[%s]
* %d-%m-%y [%H o %h]:[%i]:[%s]
* %d-%m-%Y [%H o %h]:[%i]:[%s]
* [%H o %h]:[%i]:[%s]
* %Y%m%d (per as/400)
* %H%i%s (per as/400)
*
* NOTE:
* oltre al "-" come divisore sono accettati "/" e "\" e lo spazio " "
* per le ore � obbligatorio il ":"
* in pratica accetta formati con data/ora o solo ora (inteso h:m:s o h:m o h)
*
* @param unknown_type $psDate
* @param unknown_type $psFormat
* @return unknown
*/
static function strptime($psDate,$psFormat="")
{
if ((!defined('B_USE_STRPTIME')) || B_USE_STRPTIME)
{
return(strptime($psDate,$psFormat));
}
$psDate=trim($psDate);
$vbErr=false;
if($psFormat=="")
{
$vsAnno="";
if($vsAnno=="")
{
$vsT=substr($psDate,0,4);
$vnT=(int)$vsT;
if($vnT>=1900)
$vsAnno="sx4";
}
if($vsAnno=="")
{
$vsT=substr($psDate,-4);
$vnT=(int)$vsT;
if($vnT>=1900)
$vsAnno="dx4";
}
$vsTime="";
$vsTime2="";
if(strpos($psDate,":")!==false)
{
if($vsAnno=="dx4")
$vbErr=true;
if(strlen($psDate)<=8 and $vsAnno=="")
$vsTime="onlyTime";
else
$vsTime="Time";
// se il primo : � nella stessa pos dell'ultimo :
// allora c'� n'� solo 1 e non si sono i secondi ma solo ore e minuti
if(strpos($psDate,":")==strrpos($psDate,":"))
$vsTime2="%H:%i";
else
$vsTime2="%H:%i:%s";
}
if(!$vbErr)
{
if($vsAnno=="sx4")
$psFormat="%Y-%m-%d";
elseif($vsAnno=="dx4")
$psFormat="%d-%m-%Y";
elseif($vsTime<>"onlyTime")
$psFormat="%d-%m-%y";
$psFormat .=$vsTime2;
}
}
/**
* Guido Allione. Adattamento per l'AS/400. Modifica molto brutta... ma questa funzione
* andr� riscritta prima o poi.
*/
if($psFormat=="%Y%m%d")
{
$psDate=substr($psDate,0,4)."-".substr($psDate,4,2)."-".substr($psDate,6,2);
$psFormat="%Y-%m-%d";
}
if($psFormat=="%H%i%s")
{
$psDate=substr($psDate,0,2).":".substr($psDate,2,2).":".substr($psDate,4,2);
$psFormat="%H:%i:%s";
}
//***********************************************************
// INIZIA PARTE DI CONVERSIONE
//***********************************************************
$vaRis=array("tm_mday"=>0,"tm_mon"=>0,"tm_year"=>0,"tm_hour"=>0,"tm_min"=>0,"tm_sec"=>0,"tm_wday"=>0,
"tm_yday"=>0,"unparsed"=>$psDate);
/**
tm_sec Seconds after the minute (0-61)
tm_min Minutes after the hour (0-59)
tm_hour Hour since midnight (0-23)
tm_mday Day of the month (1-31)
tm_mon Months since January (0-11)
tm_year Years since 1900
tm_wday Days since Sunday (0-6)
tm_yday Days since January 1 (0-365)
unparsed the date part which was not recognized using the specified format
*/
$vsDiv="";
if(strpos($psDate,"-")!==false)
$vsDiv="-";
elseif(strpos($psDate,"/")!==false)
$vsDiv="/";
elseif(strpos($psDate,"\\")!==false)
$vsDiv="\\";
$vbOnlyTime=false;
if($vsDiv=="")
{
if(strpos($psDate,":")!==false)
{
$vbOnlyTime=true;
$vsDiv=":";
}
else
return $vaRis;
}
$vsDate=$psDate;
if($vsDiv<>":") $vsDate=str_replace($vsDiv,":",$vsDate);
$vsDate=str_replace(" ",":",$vsDate);
$vaTmp=explode(":",$vsDate);
$vaPart=array();
foreach($vaTmp as $vsTmp)
{
$vsTmp=trim($vsTmp);
if($vsTmp<>"")
$vaPart[]=(int)$vsTmp;
}
if(count($vaPart)<3 and !$vbOnlyTime)
return $vaRis;
if(!$vbOnlyTime)
{
if(strtolower(substr($psFormat,0,2))=="%y")
{
if($vaPart[0]>1000)
$vaRis["tm_year"]=$vaPart[0];
elseif($vaPart[0]>50)
$vaRis["tm_year"]=1900+$vaPart[0];
else
$vaRis["tm_year"]=2000+$vaPart[0];
$vaRis["tm_mon"]=$vaPart[1];
$vaRis["tm_mday"]=$vaPart[2];
}
elseif(strtolower(substr($psFormat,0,2))=="%d")
{
$vaRis["tm_mday"]=$vaPart[0];
$vaRis["tm_mon"]=$vaPart[1];
if($vaPart[2]>1000)
$vaRis["tm_year"]=$vaPart[2];
elseif($vaPart[2]>50)
$vaRis["tm_year"]=1900+$vaPart[2];
else
$vaRis["tm_year"]=2000+$vaPart[2];
}
else
return $vaRis;
}
if($vbOnlyTime)
$vnX=0;
else
$vnX=3;
if(isset($vaPart[$vnX]))
$vaRis["tm_hour"]=$vaPart[$vnX];
$vnX++;
if(isset($vaPart[$vnX]))
$vaRis["tm_min"]=$vaPart[$vnX];
$vnX++;
if(isset($vaPart[$vnX]))
$vaRis["tm_sec"]=$vaPart[$vnX];
if($vaRis["tm_year"]<1000 or $vaRis["tm_year"]>2900)
$vaRis["tm_year"]=0;
else
$vaRis["tm_year"] = $vaRis["tm_year"] - 1900;
if($vaRis["tm_mon"]<1 or $vaRis["tm_mon"]>12)
$vaRis["tm_mon"]=0;
else
$vaRis["tm_mon"] = $vaRis["tm_mon"] - 1;
if($vaRis["tm_mday"]<1 or $vaRis["tm_mday"]>31) $vaRis["tm_mday"]=0;
if($vaRis["tm_hour"]<0 or $vaRis["tm_hour"]>23) $vaRis["tm_hour"]=0;
if($vaRis["tm_min"]<0 or $vaRis["tm_min"]>59) $vaRis["tm_min"]=0;
if($vaRis["tm_sec"]<0 or $vaRis["tm_sec"]>59) $vaRis["tm_sec"]=0;
if($vaRis["tm_year"]>0)
{
$vnTime=mktime($vaRis["tm_hour"],$vaRis["tm_min"],$vaRis["tm_sec"],$vaRis["tm_mon"],$vaRis["tm_mday"],$vaRis["tm_year"]);
$vaRis["tm_wday"]=date("w",$vnTime);
$vaRis["tm_yday"]=date("z",$vnTime);
}
$vaRis["unparsed"]="";
return $vaRis;
}
function array2String($paKey)
{
$vsRes = "";
foreach($paKey as $k => $v)
{
$vsRes .= $k."=".urlencode($v)."&";
}
return substr($vsRes,0,-1);
}
static function string2Array($pxKey)
{
if(is_array($pxKey))
{
$vaRes = $pxKey;
}
else
{
$pxKey = trim($pxKey,"&");
$vaChiavi = explode("&",$pxKey);
$vaRes = Array();
//echo "chiavi\r\n";
//print_r($vaChiavi);
foreach($vaChiavi as $vsChiave)
{
list($k,$v) = explode("=",$vsChiave);
$vaRes[$k] = urldecode($v);
}
}
return $vaRes;
}
public static function prettyVarDump($paInput, $poMore = null, $pbPrintStack = true, $pbDie = true, $pbUseRapidTree = true) {
echo 'Variabile monitorata
';
if (!empty($paInput) && is_array($paInput) && $pbUseRapidTree)
self::prettyArrayDump($paInput,false, array('title' => 'Input', 'id' => 'Input'), false);
else
echo '' . var_export($paInput, true) . '
';
if ($poMore != null) {
echo 'Ulteriori informazioni
';
if (!empty($poMore) && is_array($poMore) && $pbUseRapidTree)
self::prettyArrayDump($poMore,false, array('title' => 'More', 'id' => 'more'), false);
else
echo '' . var_export($poMore, true) .'
';
}
if ($pbPrintStack) {
echo 'Stack Trace
';
if ($pbUseRapidTree)
self::prettyArrayDump(debug_backtrace(),false, array('title' => 'Stack trace', 'id' => 'StackTrace'), false);
else
echo '' . var_export(debug_backtrace(), true) . '
';
}
if ($pbDie) die();
}
public static function addToElenco($psInput, $psNewString, $psSeparator = ' ') {
if (strlen($psInput) == 0) {
return $psNewString;
} else {
return $psInput . $psSeparator . $psNewString;
}
}
public static function prettyArrayDump($paInput, $pbTree=false,$paParam=array(), $pbDie = true) {
if ($pbDie) die(rapidTree::viewArray($paInput,$pbTree,$paParam));
echo rapidTree::viewArray($paInput,$pbTree,$paParam);
}
}
?>
/**
* Questa Classe si occupa di effettuare ricerche per le Classi (__autoload) o per template , configurazioni e
* quant'ambito si WebLib5
*
* @author Guido Allione 18/07/06 0100ga
* @author Guido Allione 23/08/06 0101ga Aggiunta la gestione delle configurazioni + xml.
* @author Guido Allione 29/01/07 0105ga Aggiunto CheckConfigAndSecurity + costante CONFIG_XML_EXT
* @author Marco Begliardo 09/02/07 0106mb Patch per gestione configurazione applicazione
* @author Marco Lerda 11/08/08 0108ml gestione di n path di ricerca
* @author Marco Lerda 16/09/08 0109ml aggiunto il chmod 777 del file cache
* @author Marco Lerda 22/09/08 0110ml se definito S_CHECK_CONFIG_AND_SECURITY_HOST la funzione checkConfigAndSecurity user� quall'host anzich� $_SERVER["HTTP_HOST"]
* @author Marco Lerda 27/01/10 0111ml gestione della configurazione dell'ambiente $gaEnvConfig
* @author Marco Lerda 17/08/10 0112ml abolite le configurazioni XML e modificato checkConfigAndSecurity per non verificare pi� la leggibilit� dei file xml da web
* @see Istruzione Operativa IS/WBL/005
* @author Erik Durbano 27/12/16 0114ed ottimizzazioni lettura/scrittura cache per autoload classi, rimozione vecchie funzioni dismesse/commentate
*/
define("AUTOLOAD_CACHE_SEP", "||"); //separatore nel file di cache
class AutoLoad
{
private $maCache; // Contiene la cache dei file ricercati. Il nome dell'elemento � il serialize dei parametri di GetRecentFile.
private $msFsApp; // Percorso Applicazione
private $msFsSys; // Percorso Sistema WebLib
private $msFsPathCache; // Percorso File di Cache per applicazione
private $mbCache; // se true, viene usata e scritta la cache.
private $maAppConfig; //configurazione applicazione
/**
* @param string $psFsApp Percorso file system applicazione (default FS_ROOT)
* @param string $psFsSys Percorso file system libreria sistema (Default FS_SYS)
* @param bool $pbCache Se true (default) � attivata la cache, false altrimenti
* se definita la costante B_CACHE_ENABLE, ha priorit� su $pbCache
* @param string $psFsCache Percorso file system cache (default FS_CACHE)
*/
public function __construct($pbCache=true,$psFsCache="")
{
global $gaSearchPaths;
$vsPath_file_cnf = $gaSearchPaths[0]["fs"]."config.cnf.php";
$vaConfig_array = array();
if(file_exists(($vsPath_file_cnf)))
{
include($vsPath_file_cnf);
$vaConfig_array = $gaConfig;
unset($gaConfig);
}
if(isset($vaConfig_array["app-constants"]))
$this->ArrayToConst($vaConfig_array["app-constants"]);
//salvo la configurazione dell'applicazione
$this->maAppConfig = $vaConfig_array;
$this->msFsPathCache = ($psFsCache=="" ? (defined("FS_CACHE") ? FS_CACHE : false) : $psFsCache)."path.cache.txt";
$this->mbCache = defined("B_CACHE_ENABLE") ? B_CACHE_ENABLE : $pbCache;
if($this->mbCache)
$this->maCache = $this->ReadCache($this->msFsPathCache);
}
/**
* Dato un array, lo legge e trasforma in costanti define() il contenuto
* Il nome della costante � la chiave dell'elemento dell'array
* il valore � il prefix + valore dell'elemento (se non � un array), altrimenti �, se presente
* il contenuto dell'elemento["__attr"]["value"] (per compatibilit� con gli output XML della classe
* XMLParser)
* @param array $paArray array di input
* @param string $psPrefix usato per i richiami ricorsivi, lasciare il default "".
* @return void
*/
private function ArrayToConst($paArray,$psPrefix="")
{
foreach($paArray as $vsKey=>$vxValue)
{
if(!is_array($vxValue) and !is_object($vxValue) and !defined($vsKey) and substr($vsKey,0,2)<>"__")
define($vsKey,$psPrefix.$vxValue);
elseif(is_array($vxValue))
{
if(isset($vxValue["__attr"]["value"]) and !defined($vsKey))
define($vsKey,$psPrefix.$vxValue["__attr"]["value"]);
if(substr($vsKey,0,2)<>"__")
{
$vaCons=get_defined_constants(true);
$vaCons=isset($vaCons["user"]) ? $vaCons["user"] : array();
$this->ArrayToConst($vxValue,$psPrefix.(isset($vaCons[$vsKey]) ? $vaCons[$vsKey] : ""));
}
}
}
}
/**
* Questa funzione legge il File di cache nella forma Nome;Tipo;FileConPercorso.
* Il nome del file di cache solitamente � in FS_APP/cache/path.cache.txt
* @return Array Vuoto se non esiste il file di cache, oppure Array[serialize(argomenti)] => FileConPercorso
*/
public function ReadCache()
{
$vaRis = array();
if(!file_exists($this->msFsPathCache))
return $vaRis;
$vrFile = @fopen($this->msFsPathCache, "r");
if($vrFile)
{
while(($vsLinea=fgets($vrFile, 4096))!==false)
{
$vsLinea = str_replace(array("\n","\r"), "", $vsLinea);
$vaTmp = explode(AUTOLOAD_CACHE_SEP, $vsLinea);
if(count($vaTmp)==3)
$vaRis[$vaTmp[1]] = $vaTmp[0];
}
fclose($vrFile);
}
return $vaRis;
}
/**
* Questo metodo scrive la cache (vedere ReadCache).
* La funzione chiamante deve ottenere prima un lock per evitare scritture contemporanee
* @param $psFile path del file
* @param $psArg serialize dei dati
* @return true se ha scritto la cache con successo. false altrimenti
*/
public function WriteCache($psFile, $psArg="nondef")
{
$vbRes = false;
$vbFE = file_exists($this->msFsPathCache);
$vbLineExists = false;
if($vbFE)
{
$vrFile = fopen($this->msFsPathCache, "r");
$vbLineExists = false;
while(!$vbLineExists && ($vsLineRead=fgets($vrFile, 4096))!==false)
$vbLineExists = strpos($vsLineRead, $psFile.AUTOLOAD_CACHE_SEP.$psArg.AUTOLOAD_CACHE_SEP)===0;
fclose($vrFile);
}
if(!$vbLineExists)
{
$vnRis = file_put_contents($this->msFsPathCache, $psFile.AUTOLOAD_CACHE_SEP.$psArg.AUTOLOAD_CACHE_SEP.time()."\n", FILE_APPEND);
if(!$vbFE)
chmod($this->msFsPathCache, 0777);
$vbRes = $vnRis>0;
}
return $vbRes;
}
/**
* Partendo da un path ritorna un array che descrive in quanti punti (Ed in che versioni) � stata trovata la libreria.
* La struttura del risultato � Array([livello] => array(lista path+file), [Livello] => ...)
* La lista � da ordinare con krsort()
* @param string $psNome Nome della classe da trovare
* @param string $pxPath (stringa) Percorso file system in cui fare la ricerca,
* @param array $pxPath (array) Lista di percorsi file system in cui fare la ricerca,
* @param string $psTipo (default="") si pu� specificare se solo "class", "func", "page", ...
* @param array $pxExt (default=array("php")) estensioni da considerare
* @param string $pxExt Singola estensione da considerare
* @param integer $pnMaxLevel (default=100) massimo livello di profondit� (per prevenire loop)
* @param integer $pnIndex variabile interna, non cambiare il default.
* @return Array Array([livello] => array(lista path+file), [Livello] => ...)
* @author Guido Allione 18/07/06 prima versione
* @author Guido Allione 18/07/06 seconda versione
*/
private function searchListFile($psNome,$pxPath,$psTipo="",$pxExt=array("php"),$pnMaxLevel=100,$pnIndex=1000)
{
$pnPath=0;
// se $pxExt non � un array, lo trasformo in un array.
if(!is_array($pxExt))
$pxExt=array($pxExt);
// se $psNome ha una estensione, gliela tolgo e aggiungo l'estensione nella ricerca.
$vaBase=pathinfo($psNome);
if(isset($vaBase["extension"]))
{
$psNome=basename($psNome,".".$vaBase["extension"]);
if(!in_array($vaBase["extension"],$pxExt))
$pxExt[]=$vaBase["extension"];
}
if(!is_array($pxPath))
{
$pxPath=array($pxPath);
$pnPath=$pnIndex;
}
else
$pnPath=count($pxPath);
$vaResult=Array();
foreach ($pxPath as $psPath)
{
if(!file_exists($psPath))
continue;
$voDir=dir($psPath);
while(($vsNome=$voDir->read())!==false)
{
if(is_dir($psPath."/".$vsNome) and $vsNome<>"." and $vsNome<>".." and $pnMaxLevel>0)
{
// e' una directory, percorro l'albero fino ad un livello max di $pnMaxLevel.
$vaResult_next=AutoLoad::searchListFile($psNome,$psPath."/".$vsNome,$psTipo,$pxExt,$pnMaxLevel-1,$pnPath);
foreach ($vaResult_next as $vsLivello => $vaPathFile)
foreach ($vaPathFile as $vsPathFile)
$vaResult[$vsLivello][]=$vsPathFile;
}
else
{
// e' un file, se mi interessa, lo elenco
$vaNome=explode(".",$vsNome);
$vaNome_info=pathinfo($vsNome);
if($vaNome[0]==$psNome and in_array($vaNome_info["extension"],$pxExt))
{
if(count($vaNome)==2)
{
// caso NomeFile.ext
if($psTipo=="")
$vaResult[str_pad($pnPath,5,"0",STR_PAD_LEFT)."-000000-".str_pad($pnMaxLevel,5,"0",STR_PAD_LEFT)][]=$psPath."/".$vsNome;
}
elseif(count($vaNome)==3)
{
// caso nomefile.tipo.ext
if($psTipo=="" or $psTipo==$vaNome[1])
$vaResult[str_pad($pnPath,5,"0",STR_PAD_LEFT)."-000000-".str_pad($pnMaxLevel,5,"0",STR_PAD_LEFT)][]=$psPath."/".$vsNome;
}
elseif(count($vaNome)==4)
{
// caso nomefile.livello.tipo.ext
if(($psTipo=="" or $psTipo==$vaNome[2]))
$vaResult[str_pad($pnPath,5,"0",STR_PAD_LEFT)."-".str_pad($vaNome[1],6,"0",STR_PAD_LEFT)."-".str_pad($pnMaxLevel,5,"0",STR_PAD_LEFT)][]=$psPath."/".$vsNome;
}
else
{
// gli altri casi gli ignoro.
}
}
}
}
$voDir->Close();
$pnPath--;
}
return $vaResult;
}
/**
* Questa funzione ritorna il file pi� recente (in termini di versione) tra i percorsi ricercati.
* Usabile in modalit� statica
* @param string $psNome Nome della classe da trovare
* @param variant $pxPath (stringa) Percorso file system in cui fare la ricerca,
* @param variant $pxPath (array) Lista di percorsi file system in cui fare la ricerca,
* @param string $psTipo (default="") si pu� specificare se solo "class", "func", "page", ...
* @param string $pxExt Singola Estensione da considerare
* @param array $pxExt (default array("php"), lista estensioni da considerare.
* @return string Percorso+Nome File pi� recente trovato.
* @return false Non trovato
*/
public function GetRecentFile($psNome,$pxPath,$psTipo="",$pxExt=array("php"))
{
$vaResult = AutoLoad::searchListFile($psNome,$pxPath,$psTipo,$pxExt);
if(count($vaResult)>0)
{
krsort($vaResult);
reset($vaResult);
$vaRis = current($vaResult);
$vxRis = $vaRis[0];
$vxRis = str_replace("//", "/", $vxRis);
}
else
$vxRis = false;
return $vxRis;
}
/**
* Questa funzione ritorna il file pi� recente (in termini di versione) tra i percorsi ricercati.
* Notare che, a parit� di parametri, la ricerca viene fatta una sola volta e poi messa in cache.
* Per resettare la cache, agire su $pbResetCache.
* NON usabile in modalit� statica.
* @param string $psNome Nome della classe da trovare
* @param variant $pxPath (stringa) Percorso file system in cui fare la ricerca,
* @param variant $pxPath (array) Lista di percorsi file system in cui fare la ricerca,
* @param string $psTipo (default="") si pu� specificare se solo "class", "func", "page", ...
* @param string $pxExt Singola Estensione da considerare
* @param array $pxExt (default array("php")), lista estensioni da considerare.
* @return string Percorso+Nome File pi� recente trovato.
* @return false Non trovato
*/
public function GetRecentFileCache($psNome,$pxPath,$psTipo="",$pxExt=array("php"))
{
$vaArg = func_get_args();
$vsArg = str_replace("\"","",serialize($vaArg));
if(isset($this->maCache[$vsArg]))
return $this->maCache[$vsArg];
// il path non � in sessione -> aggiornamento sessione in base al file di cache, se non basta ricerca su file-system
$vxRis = false;
$vxLock = Util::getLock("cache-weblib", 30);
if($vxLock!==false)
{
// aggiornamento cache in sessione
if($this->mbCache)
{
$this->maCache = $this->ReadCache($this->msFsPathCache);
if(isset($this->maCache[$vsArg]))
return $this->maCache[$vsArg];
}
// rierca su file-system
$vxRis = $this->GetRecentFile($psNome, $pxPath, $psTipo, $pxExt);
// aggiornamento cache su file e quindi in sessione
if($vxRis!==false and $this->mbCache)
{
$this->WriteCache($vxRis, $vsArg);
$this->maCache = $this->ReadCache($this->msFsPathCache);
}
Util::releaseLock($vxLock);
}
return $vxRis;
}
/**
* Funzione richiamata in sysx.x.x/lib/weblib5/framework.NNNNxx.page.php dalla funzione di autoload.
* Ritorna percorso e nome file pi� recente per la classe richiesta.
* La ricerca avviene secondo il seguente criterio di ricerca:
* App/modules App/managers, App/lib, Sys/modules, Sys/managers, Sys/Lib, Sys/WebLib5
* @param string $psNome nome della classe
* @return string percorso + nome file classe.
*/
public function GetRecentClass($psNome)
{
global $gaSearchPaths;
$vaPaths = Array();
foreach($gaSearchPaths as $vaPath)
{
$vaPaths[] = $vaPath["fs"]."modules/";
$vaPaths[] = $vaPath["fs"]."managers/";
$vaPaths[] = $vaPath["fs"]."lib/";
}
return $this->GetRecentFileCache($psNome, $vaPaths, "class", "php");
}
/**
* Ritorna percorso e nome file pi� recente per il template richiesto.
* La ricerca avviene secondo il seguente criterio di ricerca:
* App/module-xx/html/ App/manager-xx/html/, App/html/,
* sys/module-xx/html/ sys/manager-xx/html/, sys/html/,
* (solo App/html/ e sys/html/ se $psModule non viene specificato)
*
* @param string $psNome nome del template
* @param string $psModule Modulo che ha effettuato la richiesta
* @return string percorso + nome file template.
*/
public function GetRecentTemplate($psNome,$psModule="")
{
global $gaSearchPaths;
if(!isset($GLOBALS["goSystem"]) and $psModule<>"")
die("AutoLoad Class: non � possibile usare GetRecentTemplate senza avere l'ambiente WebLib5 caricato.");
if($psModule<>"")
{
global $goSystem;
// qui carico la cfg tenendo conto dell'istanza
$vaModConfig=$goSystem->getModuleConfig($psModule);
// qui tolgo l'istanza per cercare nella cartella giusta
list($psModule,$vsInstance) = $this->explodeModuleName($psModule);
}
$vaPaths = Array();
foreach($gaSearchPaths as $vaPath)
{
if($psModule<>"")
{
$vaPaths[]=$vaPath["fs"]."modules/".$psModule."/html/";
$vaPaths[]=$vaPath["fs"]."managers/".$vaModConfig["manager"]."/html/";
}
$vaPaths[]=$vaPath["fs"]."html/";
}
return $this->GetRecentFileCache($psNome,$vaPaths,"",array("html","htm","shtml","shtm","php"));
}
/**
* Prende un array e lo ritorna a pari struttura eseguendo alcuni comandi:
* in particolare:
* #EVAL: effettua un eval() di quello che segue, il risultato finisce nell'elemento dell'array corrente
* #TRUE: trasforma in true, il risultato finisce nell'elemento dell'array corrente
* #FALSE: trasforma in false, il risultato finisce nell'elemento dell'array corrente
*
* @param array $paArray array di input
* @return array array di output
*
* @author Guido Allione 0102ga 30/08/2006
*/
function EvalArray($paArray)
{
$vaRis=array();
if(is_array($paArray))
{
foreach ($paArray as $vsKey => $vxValue)
{
if(is_array($vxValue))
$vaRis[$vsKey]=$this->EvalArray($vxValue);
elseif(substr($vxValue,0,6)=="#EVAL:")
{
$vsTmp="\$vaRis[\"$vsKey\"]=".substr($vxValue,6);
@eval($vsTmp);
}
elseif($vxValue=="#FALSE")
$vaRis[$vsKey]=false;
elseif($vxValue=="#TRUE")
$vaRis[$vsKey]=true;
else
$vaRis[$vsKey]=str_replace(array("\\n","\\r","\\t","\\0","\\x0B"),array("\n","\r","\t","\0","\x0B"),$vxValue);
}
}
return $vaRis;
}
/**
* Questo Metodo ritorna la configurazione di un Modulo.
* La configurazione del modulo � composta dei seguenti file (in ordine
* di priorit�, dal pi� importante):
*
* eventuale configurazione $paConfig_init.
*
* app/modules/$psModule/$psModule.cnf.php
* app/modules/$psModule/$psModule.xml
* (se non trovati in)
* app/modules/$psModule.cnf.php
* app/modules/$psModule.xml
*
* MERGE CON.....
*
* (se trovata la configurazione del modulo e pertanto il relativo manager).
* app/manager/manager_del_modulo/manager_del_modulo.cnf.php
* app/modules/manager_del_modulo/manager_del_modulo.xml
* (se non trovati in)
* app/manager/manager_del_modulo.cnf.php
* app/modules/manager_del_modulo.xml
*
* MERGE CON.....
*
* (se trovata la configurazione del modulo e pertanto il relativo manager).
* app/config.cnf.php
* app/config.xml
*
* MERGE CON.....
*
* IDEM COME SOPRA ANCHE PER SYS/...
*
* NOTA DI NON RETROCOMPATIBILITA CON WEBLIB 5.0
* A) Non � previsto il caricamento di configurazioni di manager a pi� di un livello di extends
* B) Essendo gestiti gli XML, le configurazioni avranno degli elementi __attr, __name, __value, __dtd
* ecc... non previste nelle configurazioni standard.
*
* @param string $psModule Nome del modulo
* @param array $pxConfig_init Configurazione dinamica come array o stringa XML
* @return array Configurazione Finale.
*/
public function GetModuleConfig($psModule="",$pxConfig_init=array())
{
global $gaSearchPaths;
// Se sono in un modulo con multi istanza fingo di essere nel modulo puro e setto una variabile con il nome dell'istanza da utilizzare per caricare la configurazione aggiuntiva
list($psModule,$vsInstance) = $this->explodeModuleName($psModule);
if(is_array($pxConfig_init))
$vaConfig_array[]=$pxConfig_init;
elseif(is_string($paxConfig_init) and $pxConfig_init<>"")
$vaConfig_array[]=$this->GetArrayXml($pxConfig_init,"S");
$vsManager="";
/**
* Ricerca 0: In caso di modulo con istanza cerco la configurazione istanza se c'�
* File di configurazione del app/modules/nome_modulo/ versione cnf o xml
* e se non lo trova, in app/modules direttametne cnf o xml.
*/
/* per ogni path configurato eseguo le solite ricerche
rispetto alla precedente versione facci il marge anche all'intero della stessa casistica.
Ad esempio mergio modules/aaa/aaa.cnf.php modules/aaa.cnf.php
*/
$vaPaths = array
(
Array
(
"file"=>"modules/".$psModule."/".$psModule."_".$vsInstance.".cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>"modules/".$psModule."/".$psModule."_".$vsInstance.".".CONFIG_XML_EXT,
"xml"=>true,
),
*/
Array
(
"file"=>"modules/".$psModule."_".$vsInstance.".cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>"modules/".$psModule."_".$vsInstance.".".CONFIG_XML_EXT,
"xml"=>true,
),
*/
Array
(
"file"=>"modules/".$psModule."/".$psModule.".cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>"modules/".$psModule."/".$psModule.".".CONFIG_XML_EXT,
"xml"=>true,
),
*/
Array
(
"file"=>"modules/".$psModule.".cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>"modules/".$psModule.".".CONFIG_XML_EXT,
"xml"=>true,
),
*/
Array
(
"file"=>"managers/{manager}/{manager}.cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>true,
"xml"=>"managers/{manager}/{manager}.".CONFIG_XML_EXT,
),
*/
Array
(
"file"=>"managers/{manager}.cnf.php",
"xml"=>false,
),
/*
Array
(
"file"=>"managers/{manager}".CONFIG_XML_EXT,
"xml"=>true,
),
*/
/* questo lo tolgo per� contenendo costanti crea problemi
Array
(
"file"=>"config.cnf.php",
"xml"=>false,
),
*/
/*
Array
(
"file"=>"config.".CONFIG_XML_EXT,
"xml"=>true,
),
*/
);
$vaRes = array();
foreach($gaSearchPaths as $vaPath)
{
foreach($vaPaths as $vaSubPath)
{
$vsPath = $vaPath["fs"].$vaSubPath["file"];
$vbManager=false;
if(strpos($vaSubPath["file"],"managers/")===0) // se inizia per managers/
{
$vbManager=true;
if(array_key_exists("manager",$vaRes))
$vsPath = str_replace("{manager}",$vaRes["manager"],$vsPath);
}
$vbGlobal=false;
if(strpos($vaSubPath["file"],"config.")===0) // se inizia per config.
{
$vbGlobal=true;
}
// Sse sono in un path senza manager oppure conosco il nome del manager procedo
if(!$vbManager || array_key_exists("manager",$vaRes))
if(is_readable($vsPath))
{
if($vaSubPath["xml"]) // file xml
{
$vaRes=array_merge($vaRes,$this->GetArrayXml($vsPath,"F"));
}
else // file php
{
include($vsPath);
if($vbGlobal)
$vsVar = "gaConfig";
else if ($vbManager)
$vsVar = "gaManagerConfig";
else
$vsVar = "gaModuleConfig";
if(!isset($$vsVar))
trigger_error("Il File $vsPath deve contenere la definizione dell'array \$$vsVar.", E_USER_ERROR);
$vaRes=array_merge($vaRes,$$vsVar);
unset($gaModuleConfig);
}
}
}
}
global $gaEnvConfig;
if(is_array($gaEnvConfig)&&array_key_exists("modules",$gaEnvConfig)&&array_key_exists($psModule,$gaEnvConfig["modules"]))
$vaRes = $this->array_merge_recursive2($vaRes,$gaEnvConfig["modules"][$psModule]);
return $vaRes;
}
/**
* Questa funzione fonde insieme due array dando priorit� a $paArray2.
* A parit� di elemento (a qualsiasi livello) viene preso $paArray2 in caso
* di conflitto, altrimenti avviene la fusione.
*
* NOTA: identica a quella presente nelle librerie di funzioni, riportata
* unicamente per dare autonomia alla classe AutoLoad.
*
* @param array $paArray1 Array secondario
* @param array $paArray2 Array Principale
* @return array Fusione dei due array passati come parametro.
*/
public function array_merge_recursive2($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2))
{
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2)
{
// originale
//$paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
// modificato
if(array_key_exists($sKey2,$paArray1))
$paArray1[$sKey2] = $this->array_merge_recursive2($paArray1[$sKey2], $sValue2);
else
$paArray1[$sKey2] = $paArray2[$sKey2];
}
return $paArray1;
}
/**
* A fronte della nuova implementazione di sottomoduli,
* ModuloNome:instanza , questo metodo si occupa di
* ritornare la l'array con due elementi numerici: Modulo ed Istanza.
*
* @param string $psModule Modulo o Modulo:Istanza
* @return array
*/
static function explodeModuleName($psModule)
{
$vsInstance = null;
if(strpos($psModule,":")!==false)
{
$vaTemp = explode(":",$psModule);
$psModule = $vaTemp[0];
$vsInstance = $vaTemp[1];
}
return array($psModule,$vsInstance);
}
/**
* Questo metodo si occupa di fare alcuni controlli sulla configurazione
* o sulla sicurezza all'inizio della sessione di WebLib.
* Per questo motivo questo metodo va richimato nel framework
* all'interno dell'if che istanzia per la prima volta $goSystem.
*
*/
function checkConfigAndSecurity()
{
//
}
/**
* Restituisce la configurazione dell'applicazione
*
* @return array
*/
function getAppConfig()
{
return $this->maAppConfig;
}
}
?>