// die('REMOTE_ADDR'.$_SERVER['REMOTE_ADDR']); // if($_SERVER['REMOTE_ADDR'] == '192.168.0.177') // mailtnx('c@localhost', "Debug 177 ".microtime(true), __FILE__.":".__LINE__."\n".print_r(array($_REQUEST, $_SERVER), true)); // if($_SERVER['REMOTE_ADDR'] == '192.168.0.37'){ // mailtnx('c@localhost', "Debug ".microtime(true), __FILE__.":".__LINE__."\n".print_r(array($_REQUEST, $_SERVER), true)); // $_SERVER['REMOTE_ADDR'] = '192.168.0.177'; // } // if($_POST) // print_r_tnx($_POST, $_SERVER['REMOTE_ADDR'] == '192.168.0.177') || die; if((!true //true mette tutto offline // || strpos($_SERVER['REMOTE_ADDR'], "20.171.207.") === 0 // || strpos($_SERVER['REMOTE_ADDR'], "87.20.55.") === 0 )){ header("HTTP/1.1 503 Service Temporarily Unavailable"); header("Status: 503 Service Temporarily Unavailable"); header("Retry-After: 60"); ?>
';
$debugBacktrace = debug_backtrace();
// array_unshift($debugBacktrace, array('file'=>__FILE__, 'line'=>__LINE__, 'function'=>'debugTnx'));
foreach($debugBacktrace as $debugLine) echo "".str_replace( "/tnx/www/html/www/", "", $debugLine['file']).""." ".$debugLine['function']."()
";
ob_start();
if(is_object($printMe)||is_array($printMe)) print_r($printMe);
else var_dump($printMe);
echo htmlentities(ob_get_clean(), ENT_COMPAT|ENT_HTML401|ENT_SUBSTITUTE, 'UTF-8');
echo '';
}
function aSMQ($var){//addslashes solo con Magic Quote (ricorsiva)
if(get_magic_quotes_gpc()) return $var;
else return aS_ricorsivo($var);
}
function aS_ricorsivo($var){
if(is_array($var)){
$return = array();//la chiave potrebbe cambiare
foreach($var as $k=>$v) $return[addslashes($k)] = aS_ricorsivo($v);
return $return;
}
else if(is_string($var)) return addslashes($var);
else return $var;
}
//SMTPUTF8
//partono sempre ma va encodato l'oggetto per i server mail di ricezione che non supportano SMTPUTF8
function mailtnx(){
$args = func_get_args();
if (mb_detect_encoding($args[1], 'UTF-8, ISO-8859-1') === 'UTF-8'){
$args[1] = '=?UTF-8?B?' . base64_encode($args[1]) . '?=';
}
return call_user_func_array('mail', $args);
}
function sSMQ($var){//stripslashes solo con Magic Quote (ricorsiva)
if(!get_magic_quotes_gpc()) return $var;
else return sS_ricorsivo($var);
}
function sS_ricorsivo($var){
if(is_array($var)){
$return = array();//la chiave potrebbe cambiare
foreach($var as $k=>$v) $return[stripslashes($k)] = sS_ricorsivo($v);
return $return;
}
else if(is_string($var)) return stripslashes($var);
else return $var;
}
function is_tnx_raw() {
//carlo: nelle chiamate server-to-server REMOTE_ADDR è l'ip del server, quindi risulta "SIAMO NOI", cercare di passare fromIp
$ip = @$_GET['fromIp'] ? @$_GET['fromIp'] : $_SERVER["REMOTE_ADDR"];
return
($_SERVER['TNX_SERVER_ID'] == "demo" && stristr($ip, "192.168."))
||
$ip == "95.241.81.138"//fibra telecom, precedenti: 79.8.244.233, 79.57.78.232, 79.1.102.214, 87.25.151.61 (adsl)
||
$ip == "93.71.228.131"//fibra vodafone, precedenti: 2.39.174.156, 37.116.130.160
||
$ip == "178.32.137.20"//web.tnx.it, precedenti: 66.71.191.146
||
$ip == "148.251.64.174"//web3.tnx.it
||
$ip == "65.21.70.35"//voip.tnx.it - centralino per avatable/ordinalo
// ||
// $ip == "213.243.232.46"//adsl terrecablate
// ||
// $ip == gethostbyname("tnx3.no-ip.org")//chiavetta 3 aggiornata da draytek
;
}
define("TNX_SECURE_CURL", PHP_MAJOR_VERSION >= 7);//openssl non aggiornata su server php 5.6
function limitatoreMailTnx($msg, $body, $sito_key) {
if($GLOBALS['CONF']['disattivaSegnalazioniEmailTnx'] || SEGNALAZIONE_ERRORI_TNX === false) return;
//cecca - tux
//if($GLOBALS['CONF']['sito'] == "toysforyou2013") return;
$file = "/tmp/mysqlkill/".$GLOBALS['DB']['database'];
if(is_file($file)){
$time = 30;
if(time() - filemtime($file) < 60){
return;
}
}
//se supero i limiti il log è su disco
$intervallo_tempo = $GLOBALS['CONF']['dove_sono'] == 'loc' ? 300 : 30;//limiti di google: 60 email ogni minuto - https://support.google.com/a/answer/1366776
//il numero massimo di email comprende anche quelle di segnalazione limite raggiunto
$max_errori_globale = 15; //numero max di errori su tutti i siti
$max_errori_sito = 5; //numero max di errori per sito
$max_errori_identici = 5; //numero max errori dello stesso tipo
//gestione 1: xcache array unica => 18/4/2018 accertato che non è atomica => 31/1/2019 dopo ristrutturazione funzione e nuovi test, sembrava essere atomica in locale, ma online no
//gestione 2: xcache con inc / dec => 3/7/2018 accertato che non è atomica => 31/1/2019 dopo ristrutturazione funzione e nuovi test, sembra essere atomica online / locale => 5/3/2019 sovraccarico sul server ha dimostrato non essere atomica
//gestione 3: shared memory read/write (su php 5.3 ci sono shm_get_var / shm_put_var su cui non va gestito l'id di memoria) => 31/1/2019 accertato che non è atomica (vedi anche "atomic" su http://php.net/manual/en/ref.shmop.php)
//gestione 4: file_get_contents + flock => creata il 31/1/2019 insieme a ristrutturazione funzione e nuovi test, testata ok locale/online, non la uso per ora riprovo metodo 2
//gestione 5?: su php 5.3 ci sono shm_get_var / shm_put_var su cui non va gestito l'id di memoria da testare (simile gestione 3)
//test con:
//for i in {1..30};do wget "http://demo.tnx.it/base/?testErrori=1" & wget "http://demo.tnx.it/enoicawinetrail/admin_tnx/users/login?testErrori=1" & wget "https://demo.tnx.it/vesuviotour/?testErrori=1" & done;
//for i in {1..30};do wget "http://www.tpnebulizer.it/?testErrori=1" & wget "http://www.enoicawinetrail.it/admin_tnx/users/login?testErrori=1" & wget "https://www.vesuviotour.nl/?testErrori=1" & done;
$gestioneAttiva = 4;
if(!is_array($msg)) $msg = array('errore' => $msg);
$err_key = md5(serialize($msg['errore']));//potrebbe essere un array
if(!$err_key) $err_key = "err_unknow";
$err_key = $sito_key.$err_key;//voglio ricevere lo stesso errore se proviene da siti diversi
// if(in_array($GLOBALS['CONF']['sito'], array("premioceleste"/*, "toysforyou2013"*/))){
// $GLOBALS['_dev_email'] = "a.toce@tnx.it,sysadmin@tnx.it";
// }
// else if($_GET['testErrori']){
// $GLOBALS['_dev_email'] = "c@localhost";
// }
// else if(in_array($GLOBALS['CONF']['sito'], array("elletipi"))){
// $GLOBALS['_dev_email'] = "carlo@tnx.it";
// }
//in questa maniera intervalloTempoKey varia da 0 a 9 e non spreco caratteri per la chiave di cache
$resto = time() % ($intervallo_tempo * 9);
$intervalloTempoKey = round($resto / $intervallo_tempo);
if($gestioneAttiva == 4){
// $file = $GLOBALS['CONF']['logPath']."errorCounter.txt";
$file = "/tmp/errorCounter.txt";//indipendente da variabili indi, perchè chiamato anche da admin_tnx
// if(!is_file($file)){
//SIAMO NEL GESTORE ERRORI NON TRIGGERARE ERRORI!
// trigger_error($GLOBALS['indiRoot']);
// trigger_error("controllare come mai non trovo il file ".$file);
// return;
// }
$lastErrorInterval = time()-filemtime($file);
$pointer = fopen($file, "c+");
if(!$pointer || !flock($pointer, LOCK_EX | LOCK_NB)){//con LOCK_NB non aspetto che il file si liberi, quindi se c'è un altra segnalazione in corso abbandono
// mail("c@localhost", "Can't lock", __FILE__.":".__LINE__."\n".print_r(array($_REQUEST, $_SERVER), true));
fclose($pointer);
return;
}
else{
clearstatcache();//il risultato di filesize è cachato
if($lastErrorInterval < $intervallo_tempo * 2) $esite = filesize($file);
if(!$esite) $erroriCounterArray = array();
else{
$read = fread($pointer, $esite);
$erroriCounterArray = unserialize($read);
}
$erroriIntervallo = $erroriCounterArray[$intervalloTempoKey];//prendo i valori dell'intervallo corretto, così eventualmente si resetta
}
}
else if($gestioneAttiva == 1){
$xCacheKey = "indi_error_handler_apc";
$erroriCounterArray = indiCacheGet($xCacheKey);
$erroriIntervallo = $erroriCounterArray[$intervalloTempoKey];//prendo i valori dell'intervallo corretto, così eventualmente si resetta
}
else if($gestioneAttiva == 2){
$erroriIntervallo = array();
$erroriIntervallo['globale'] = xcache_get("errG_globale".$intervalloTempoKey);
$erroriIntervallo['errori'][$err_key] = xcache_get("errE".$intervalloTempoKey."_".$err_key);
$erroriIntervallo['siti'][$sito_key] = xcache_get("errS".$intervalloTempoKey."_".$sito_key);
}
else if($gestioneAttiva == 3){
$shmid = ftok(__FILE__, 'i');
//in creazione serve la dimensione, lo apro solo in lettura
//chiocciola perchè da errore se cnon esiste ancora
//RITORNA SEMPRE E COMUNQUE UN ID!
$shres = @shmop_open($shmid, "a", 0, 0);
// if($_GET['testErrori']) echo "shres $shmid - $shres". "intervallo ".$intervalloTempoKey."" ; if($erroriIntervallo['globale'] <= $max_errori_globale && $erroriIntervallo['errori'][$err_key] <= $max_errori_identici && $erroriIntervallo['siti'][$sito_key] <= $max_errori_sito){ $oggetto = ""; if($msg['gruppo']) $oggetto .= $msg['gruppo']." "; if($msg['nome']) $oggetto .= $msg['nome']." "; if($GLOBALS['DATI']['utente']) $oggetto .= $GLOBALS['DATI']['utente']." "; if($oggetto) $oggetto .= " - "; $oggetto .= $msg['errore']; $testo = $body; // $testo .= $erroriStats; if($gestioneAttiva == 2){ $erroriIntervallo['globale'] = xcache_inc("errG_globale".$intervalloTempoKey, 1, $intervallo_tempo); $erroriIntervallo['errori'][$err_key] = xcache_inc("errE".$intervalloTempoKey."_".$err_key, 1, $intervallo_tempo); $erroriIntervallo['siti'][$sito_key] = xcache_inc("errS".$intervalloTempoKey."_".$sito_key, 1, $intervallo_tempo); } else{ $erroriIntervallo['globale']++; $erroriIntervallo['errori'][$err_key]++; $erroriIntervallo['siti'][$sito_key]++; } $urgente = $_SERVER['TNX_SERVER_ID'] != 'demo' ? ' urgente' : ''; if($erroriIntervallo['globale'] == $max_errori_globale){ //raggiunto limite errori globali $oggetto = "[LIMITE GLOBALE] ".$oggetto.$urgente; // $oggetto = " Raggiunto limite $max_errori_globale segnalazioni globali in $intervallo_tempo\", urgente (intervallo $intervalloTempoKey)"; // $testo = $erroriStats; } else if($erroriIntervallo['errori'][$err_key] == $max_errori_identici){ //raggiunto limite errori dello stesso tipo $oggetto = "[LIMITE ERRORE] ".$oggetto.$urgente; // $oggetto = " Raggiunto limite $max_errori_identici segnalazioni \"$msg[errore]\" in \"$sito_key\" in $intervallo_tempo\" (intervallo $intervalloTempoKey)"; // $testo = $erroriStats; } else if($erroriIntervallo['siti'][$sito_key] == $max_errori_sito){ //raggiunto limite errori dallo stesso sito $oggetto = "[LIMITE SITO] ".$oggetto; // $oggetto = " Raggiunto limite $max_errori_sito segnalazioni per sito \"$sito_key\" in $intervallo_tempo\" (intervallo $intervalloTempoKey)"; // $testo = $erroriStats; } } if($gestioneAttiva == 4){ $serialized = serialize(array($intervalloTempoKey => $erroriIntervallo));//ripulisco da vecchi intervalli ftruncate($pointer, 0 /*mb_strlen($serialized)*/); rewind($pointer); fwrite($pointer, $serialized); fflush($pointer); flock($pointer, LOCK_UN); fclose($pointer); } else if($gestioneAttiva == 1){ indiCacheSet($xCacheKey, array($intervalloTempoKey => $erroriIntervallo), $intervallo_tempo); //ripulisco da vecchi intervalli } // else if($gestioneAttiva == 2){ //non c'è da fare niente // } else if($gestioneAttiva == 3){ if($esisteSize){ shmop_delete($shres);//la cancello per ricrearla della dimensione esatta shmop_close($shres); } //salvo gestione 3 $serialized = serialize(array($intervalloTempoKey => $erroriIntervallo));//ripulisco da vecchi intervalli $shres = shmop_open($shmid, "c", 0644, strlen($serialized)); if($shres){ shmop_write($shres, $serialized, 0); shmop_close($shres); } else{ //successo durante un carico alto di mysql //shmop_open triggera comunque un warning che va su error.log //faccio return, perchè sicuramente è un momento di sovraccarico che invierebbe parecchie mail (verificato 19/9/2018 dopo aver aggiunto shmop_close()) return; } } if($oggetto){ if($_GET['testErrori']){ // $GLOBALS['_dev_email'] = "c@localhost"; // $GLOBALS['_dev_email'] = "test@tnx.it"; $oggetto = "[".$intervalloTempoKey."] ".$oggetto; } return [$oggetto, $testo]; } } if(PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION === 2){//5.2 define("ERROR_LEVEL_HANDLER_TNX", E_ALL &~ E_NOTICE &~ E_STRICT); } if(PHP_MAJOR_VERSION > 5 || (PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION >= 6)){//>5.6 //funzione da richiamare negli script che danno per scontato che che le magic_quotes siano on, ovvero non chiamano mai get_magic_quotes_gpc() //in indi viene usata automaticamente se esiste ($CONF['simulaMagicQuotesPhp5.2'] = function_exists("simulaMagicQuotesTnx")) //per compatibilita php 5.2 / 5.6 usare con: //if(function_exists("simulaMagicQuotesTnx")) simulaMagicQuotesTnx(); function simulaMagicQuotesTnx(){ if($GLOBALS['simulaMagicQuotesTnxEseguito']) return; $GLOBALS['simulaMagicQuotesTnxEseguito'] = 1; $_POST = aSMQ($_POST); $_GET = aSMQ($_GET); $_COOKIE = aSMQ($_COOKIE); $_REQUEST = aSMQ($_REQUEST); } //importante non far passare tutti gli errori dal gestore perchè anche un operazione semplice tipo is_array($CONF) prima di controllare e ignorare alcuni tipi di errore consuma oltre 1 secondo per via dei molti notice //E_ALL da php 5.4 comprende anche E_STRICT //E_DEPRECATED esiste da 5.3 //non posso usare lo stesso valore sul php 5.2, succede che ignora gli warning define("ERROR_LEVEL_HANDLER_TNX", E_ALL &~ E_NOTICE &~ E_STRICT &~ E_DEPRECATED);//22519 if(!TNX_SECURE_CURL){ stream_context_set_default(array( 'ssl'=>array( "verify_peer"=>TNX_SECURE_CURL, ), )); } } if(PHP_MAJOR_VERSION >= 8){ function get_magic_quotes_gpc() { return false; } } if(PHP_MAJOR_VERSION >= 7){ if(@$_GET['apcutnx']){ function apcuFormatSize($size,$unit="") { if( (!$unit && $size >= 1<<30) || $unit == "GB") return number_format($size/(1<<30),2)."GB"; if( (!$unit && $size >= 1<<20) || $unit == "MB") return number_format($size/(1<<20),2)."MB"; if( (!$unit && $size >= 1<<10) || $unit == "KB") return number_format($size/(1<<10),2)."KB"; return number_format($size)." bytes"; } function apcuTimeFix($time){ //apcu usa un conteggio dei secondi a partire dal boot della macchina (macchina contenitore in caso di virtualizzazione!) //attenzione: per quanto riguarda "start_time" all'avvio c'è un timestamp normale, al primo reset inizia a usare il suo formato if($time < 999999999){ if(!$GLOBALS['apcutimeServerBoot']) $GLOBALS['apcutimeServerBoot'] = exec('cat /proc/stat | grep btime | awk \'{ print $2 }\''); return $time + $GLOBALS['apcutimeServerBoot']; } else return $time; } if($_GET['del'] || $_GET['delLike'] || $_GET['delAll']){ if($_GET['del']) apcu_delete($_GET['del']); if($_GET['delLike'] || $_GET['delAll']){ $apcu_cache_info = apcu_cache_info(); foreach($apcu_cache_info['cache_list'] as $c) if($_GET['delAll'] || strpos($c['info'], $_GET['delLike']) !== false) apcu_delete($c['info']); } header("Location: ".$_SERVER['HTTP_REFERER']); } $apcu_sma_info = apcu_sma_info(); $apcu_cache_info = apcu_cache_info(); echo '
". "durata richiesta ".(time()-$_SERVER['REQUEST_TIME'])."
". // "cacheFree ".(round($cacheStat['avail'] / $cacheStat['size'] * 10000)/100)."%
". // "shmid:
".$shmid."\n\n". // "errori counter:
".(print_r($erroriCounterArray, true))."\n\n". "errori intervallo:
".(print_r($erroriIntervallo, true))."\n\n". "
| $title | "; } echo "
|---|
| $value | "; } echo "
';
// foreach($apcu_cache_info['cache_list'] as $c){
// echo $c['info']." hits:".$c['num_hits']." size:".str_repeat("|", round($c['mem_size']/1000))."\n";
// }
// echo '';
}
/* https://web.archive.org/web/20190204180013/http://xcache.lighttpd.net/wiki/XcacheApi */
function xcache_set($var, $value, $ttl = 0) {
return apcu_store($var, $value, $ttl);
}
function xcache_isset($var) {
return apcu_exists($var);
}
function xcache_unset($var) {
return apcu_delete($var);
}
function xcache_get($var) {
return apcu_fetch($var);
}
function xcache_list($type, $id) {
$ci = apcu_cache_info();
foreach($ci["cache_list"] as &$v) {
$v["name"] = $v["info"];
}
return $ci;
}
function xcache_clear_cache($type) {
apcu_clear_cache();
}
function set_magic_quotes_runtime($bool) {
if($_SERVER['REMOTE_ADDR'] == '192.168.0.177' || $_GET['debugtnx']){
echo '';
$debugBacktrace = debug_backtrace(); array_unshift($debugBacktrace, array('file'=>__FILE__, 'line'=>__LINE__, 'function'=>'debugTnx')); foreach($debugBacktrace as $debugLine) echo "".str_replace("/tnx/www/html/www/", "", $debugLine['file']).""." ".$debugLine['function']."()
";
$printMe = $_SERVER; ob_start(); if(is_object($printMe)||is_array($printMe)) print_r($printMe); else var_dump($printMe); echo htmlentities(ob_get_clean(), ENT_COMPAT|ENT_HTML401|ENT_SUBSTITUTE, 'UTF-8');
echo '';
die;
}
$plainText = ["http".(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : '')."://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']];
$debugBacktrace = debug_backtrace(); array_unshift($debugBacktrace, array('file'=>__FILE__, 'line'=>__LINE__, 'function'=>'debugTnx')); foreach($debugBacktrace as $debugLine) $plainText[] = $debugLine['file'].":".$debugLine['line']." ".$debugLine['function']."()";
mail(
"c@localhost",
"Uno script sta cercando di ".($bool?'attivare':'disattivare')." le magic_quotes (funzione rimossa in php 5.4, ma simulata nei nostri script con simulaMagicQuotesTnx())",
print_r(array($plainText, $_REQUEST, $_SERVER), true)
);
}
function mysql_ping($a = null){
if(!function_exists("mysql_tnx_ping")) mysql_tnx_debug_backtrace();
return mysql_tnx_ping($a);
}
function mysql_tnx_debug_backtrace(){
$debugBacktrace = debug_backtrace();
trigger_error("Aggiornare a mysqli (chiamata a ".$debugBacktrace[1]['function']."() in ".$debugBacktrace[1]['file'].":".$debugBacktrace[1]['line'].")");
if($_SERVER['REMOTE_ADDR'] == '192.168.0.177' || $_GET['debugtnx'])//serve per errori admin in locale
echo "Aggiornare a mysqli (chiamata a ".$debugBacktrace[1]['function']."() in ".$debugBacktrace[1]['file'].":".$debugBacktrace[1]['line'].")