".PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION.""); } define("INDI_CORE", dirname(dirname(__FILE__)).'/'); define('INDI_DIR', @$_GET['useIndi'] ? $_GET['useIndi'] : 'INDI_ver1.1'); define("INDI_PATH", INDI_CORE.INDI_DIR.'/'); define("INDI_LIB_PATH", INDI_CORE.'lib/'); 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; } 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 isPhpNew(){ mail("c@localhost", "Questa funzione non dovrebbe essere usata", __FILE__.":".__LINE__."\n".print_r(array($_REQUEST, $_SERVER), true)); return !isPhp5_2(); } function isPhp5_2(){ if (substr(phpversion(), 0, 3) == "5.2") return true; return false; } define("TNX_SECURE_CURL", PHP_MAJOR_VERSION >= 7);//per ora manca il certificato // define(TNX_SECURE_CURL, false); if(!TNX_SECURE_CURL && function_exists("stream_context_set_default")/*su php5.2 non c'è*/){ stream_context_set_default(array( 'ssl'=>array( "verify_peer"=>TNX_SECURE_CURL, ), )); } 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 = 30;//limiti di google: 60 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 = 2; //numero max errori dello stesso tipo nella stesso sito //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
"; $esisteSize = @shmop_size($shres);//se non esiste ancora il segmento, open ha comunque tornato un id e qui può dare errore $erroriCounterArray = $esisteSize ? unserialize(shmop_read($shres, 0, $esisteSize)) : array(); $erroriIntervallo = $erroriCounterArray[$intervalloTempoKey];//prendo i valori dell'intervallo corretto, così eventualmente si resetta } $oggetto = ""; $testo = ""; //$cacheStat = indiCacheStat(); $erroriStats = "
".
		"intervallo ".$intervalloTempoKey."
". "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". "
" ; 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.$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]++; } if($erroriIntervallo['globale'] == $max_errori_globale){ //raggiunto limite errori globali $oggetto = "Raggiunto limite $max_errori_globale segnalazioni globali in $intervallo_tempo\" (intervallo $intervalloTempoKey)"; $testo = $erroriStats; } else if($erroriIntervallo['errori'][$err_key] == $max_errori_identici){ //raggiunto limite errori dello stesso tipo $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 = "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]; return ['=?UTF-8?B?'.base64_encode($oggetto).'?=', $testo];//fix temporaneo } } //PHP > 5.6 if(!isPhp5_2()){ //funzione da richiamare negli script che danno per scontato che che le magic_quotes siano on, ovvero non chiamano mai get_magic_quotes_gpc() //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); } 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 '

'.$apcu_cache_info['num_entries']." variabili, ".apcuFormatSize($apcu_sma_info['avail_mem']).' su '.apcuFormatSize($apcu_sma_info['seg_size']*$apcu_sma_info['num_seg']).' disponibili dal '.strftime("%d/%m/%Y %H:%M:%S", apcuTimeFix($apcu_cache_info['start_time'])).'

'; echo '

per cancellare in blocco: &delLike={parteDiId} oppure &delAll=1

'; foreach($apcu_cache_info['cache_list'] as $k=>$c){ if(!$k){ echo ""; foreach($c as $title=>$value){ if($title == 'mem_size') $title = 'mem_size (kb)'; echo ""; } echo ""; } echo ""; foreach($c as $title=>$value){ if($title == 'info') $value = ' '.$value; else if($title == 'mem_size') $value = ceil($value/1024);//se metto suffisso vengono sortate come stringhe else if(substr($title, -4) == 'time') $value = strftime("%Y-%m-%d %H:%M:%S", apcuTimeFix($value)); echo ""; } echo ""; } echo '
$title
$value
'; die; // 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 set_magic_quotes_runtime($bool) { 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())", __FILE__.":".__LINE__."\n".print_r(array($_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(); die("Aggiornare a mysqli (chiamata a ".$debugBacktrace[1]['function']."() in ".$debugBacktrace[1]['file'].":".$debugBacktrace[1]['line'].")"); } function mysql_query($a, $b = null){ if(!function_exists("mysql_tnx_query")) mysql_tnx_debug_backtrace(); return mysql_tnx_query($a, $b); } function mysql_fetch_assoc($a){ if(!function_exists("mysql_tnx_fetch_assoc")) mysql_tnx_debug_backtrace(); return mysql_tnx_fetch_assoc($a); } function mysql_fetch_array($a){ if(!function_exists("mysql_tnx_fetch_array")) mysql_tnx_debug_backtrace(); return mysql_tnx_fetch_array($a); } function mysql_fetch_row($a){ if(!function_exists("mysql_tnx_fetch_row")) mysql_tnx_debug_backtrace(); return mysql_tnx_fetch_row($a); } function mysql_connect($a, $b, $c){ if(!function_exists("mysql_tnx_connect")) mysql_tnx_debug_backtrace(); return mysql_tnx_connect($a, $b, $c); } function mysql_close($a = null){ if(!function_exists("mysql_tnx_close")) mysql_tnx_debug_backtrace(); return mysql_tnx_close($a = null); } function mysql_select_db($a, $b = null){ if(!function_exists("mysql_tnx_select_db")) mysql_tnx_debug_backtrace(); return mysql_tnx_select_db($a, $b = null); } function mysql_free_result($a){ if(!function_exists("mysql_tnx_free_result")) mysql_tnx_debug_backtrace(); return mysql_tnx_free_result($a); } function mysql_num_fields($a){ if(!function_exists("mysql_tnx_num_fields")) mysql_tnx_debug_backtrace(); return mysql_tnx_num_fields($a); } function mysql_num_rows($a) { if(!function_exists("mysql_tnx_num_rows")) mysql_tnx_debug_backtrace(); return mysql_tnx_num_rows($a) ; } function mysql_field_name($a, $i){ if(!function_exists("mysql_tnx_field_name")) mysql_tnx_debug_backtrace(); return mysql_tnx_field_name($a, $i); } function mysql_errno($a = null){ if(!function_exists("mysql_tnx_errno")) mysql_tnx_debug_backtrace(); return mysql_tnx_errno($a = null); } function mysql_error($a = null){ if(!function_exists("mysql_tnx_error")) mysql_tnx_debug_backtrace(); return mysql_tnx_error($a = null); } function mysql_insert_id($a = null) { if(!function_exists("mysql_tnx_insert_id")) mysql_tnx_debug_backtrace(); return mysql_tnx_insert_id($a = null) ; } function mysql_affected_rows($a = null) { if(!function_exists("mysql_tnx_affected_rows")) mysql_tnx_debug_backtrace(); return mysql_tnx_affected_rows($a = null) ; } function mysql_escape_string($a){ if(!function_exists("mysql_tnx_escape_string")) mysql_tnx_debug_backtrace(); return mysql_tnx_escape_string($a); } function mysql_real_escape_string($a){ if(!function_exists("mysql_tnx_real_escape_string")) mysql_tnx_debug_backtrace(); return mysql_tnx_real_escape_string($a); } function mssql_connect($servername, $username = null, $password = null, $new_link = FALSE) { $connectionInfo = array("UID"=> $username, "PWD"=> $password); $conn = sqlsrv_connect($servername, $connectionInfo); if(!$conn) { echo "Connection could not be established.
"; die( print_r( sqlsrv_errors(), true)); } return $conn; } function mssql_query($query, $conn){ return sqlsrv_query($conn, $query); } function mssql_fetch_assoc($result){ return sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC); } function mssql_select_db($database, $conn){ return sqlsrv_query($conn, "USE $database"); } } ?>