php socket server closing port after 24h - php

i have a php socket server but i'm facing problems.
I have a tracker socket system, where the tracker connects to my server and send data. The server get this data and store into a database.
I'm using xampp for windows and the server is using port 8080.
My problem is that after 24h of job the port 8080 just block all connections, even the connections that are already connected to server.
I have tried all but nothing is helping me, because after 24 hours server stops port 8080.
It's important to say that xampp didn't show any error when port stops and the php page still running.
Please, can someone help me fix this problem?
My code:
$servername = "xxx.xxx.xxx.xxx";
$username = "username";
$password = "pass";
$dbname = "dbname";
$ip_address = "my_machine_ip";
$port = "8080";
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors',1);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// open a server on port 8080
$server = stream_socket_server("tcp://$ip_address:$port", $errno, $errorMessage);
if ($server === false) {
die("stream_socket_server error: $errorMessage");
}
$client_sockets = array();
$ativos = array();
while (true) {
// prepare readable sockets
$read_sockets = $client_sockets;
$read_sockets[] = $server;
// start reading and use a large timeout
if(!stream_select($read_sockets, $write, $except, 30000)) {
die('stream_select error.');
}
// new client
if(in_array($server, $read_sockets)) {
$new_client = stream_socket_accept($server);
if($new_client != ""){
array_push($ativos, $new_client);
}
echo count($ativos);
if ($new_client) {
//print remote client information, ip and port number
echo 'new connection: ' . stream_socket_get_name($new_client, true) . "<br>";
$client_sockets[] = $new_client;
echo "total clients: ". count($client_sockets) . "<br>";
// $output = "hello new client.\n";
// fwrite($new_client, $output);
}
//delete the server socket from the read sockets
unset($read_sockets[ array_search($server, $read_sockets) ]);
}
// message from existing client
foreach ($read_sockets as $socket) {
$data = fread($socket, 1024); //original is $data = fread($socket, 128); but is freezing port after 30 connections in the same time.
echo "data: " . $data . "<br>";
$tk103_data = explode( ',', $data);
$response = "";
switch (count($tk103_data)) {
case 1: // 359710049095095 -> heartbeat requires "ON" response
$response = "ON";
echo "Enviado ON para o Client $tk103_data[0]!<br>";
break;
case 3: // ##,imei:359710049095095,A -> this requires a "LOAD" response
if ($tk103_data[0] == "##") {
$response = "LOAD";
echo "Enviado LOAD para o Client $tk103_data[1]!<br>";
}
break;
case 7: //868683028738833,O,latitude1,longitude1,latitude2,longitude2;
if($tk103_data[0] == "**"){
$imeiCerca = $tk103_data[1];
$lat1 = $tk103_data[3];
$lng1 = $tk103_data[4];
$lat2 = $tk103_data[5];
$lng2 = $tk103_data[6];
$response2 = "**,imei:$imeiCerca,O,$lat1,$lng1,$lat2,$lng2";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
}
break;
case 13: //imei:868683028738833,tracker,170627204932,,F,124929.000,A,0925.3265,S,04029.8821,W,0.00,0;
$new_imei = str_replace("imei:", "", "$tk103_data[0]");
$new_imei = substr($new_imei, 0, 15);
if ($tk103_data[1] != "" && $tk103_data[4] != "L" && $tk103_data[5] != "" && $tk103_data[6] !="" && $tk103_data[8] != "" && $tk103_data[10] != "") {
$str = $tk103_data[2];
$arr2 = str_split($str, 2);
$dia = $arr2[2];
$mes = $arr2[1];
$ano = $arr2[0];
$hora = $arr2[3];
$minuto = $arr2[4];
$sqlChecker = "SELECT id, comando, latitude, longitude, status FROM gps_data_single WHERE imei='$new_imei' ORDER BY id DESC LIMIT 1";
$resultChecker = $conn->query($sqlChecker);
if ($resultChecker->num_rows > 0) {
while($rowChecker = $resultChecker->fetch_assoc()) {
$id = $rowChecker["id"];
$comando = $rowChecker["comando"];
$lat = $rowChecker["latitude"];
$long = $rowChecker["longitude"];
$st = $rowChecker["status"];
$estatus = explode(";", $st);
if($comando==$tk103_data[1] && $lat==$tk103_data[7] && $long==$tk103_data[9] && $st==$tk103_data[12]){
echo "Continua o mesmo Comando e Posição! Dados não salvos!<br>";
}else{
$sqla = "INSERT INTO gps_data_single (imei, comando, datetime, numerotel, gps_sinal, full_hour, sinal_gps, latitude, lat_orientacao, longitude, long_orientacao, speed, status, dia, mes, ano, hora, minuto) VALUES ('$new_imei', '$tk103_data[1]', '$str', '$tk103_data[3]', '$tk103_data[4]', '$tk103_data[5]', '$tk103_data[6]', '$tk103_data[7]', '$tk103_data[8]', '$tk103_data[9]', '$tk103_data[10]', '$tk103_data[11]', '$estatus[0];', '$dia', '$mes', '$ano', '$hora', '$minuto')";
if ($conn->query($sqla) === TRUE) {
echo "Inserido na Base!<br>";
} else {
echo "Error: " . $sqla . "<br>" . $conn->error;
}
}
}
}
}
if ($tk103_data[1] == "tracker"){
//Bloquear pela Chave
$sqlHp = "SELECT id, minuto FROM gps_data_single WHERE imei='$new_imei' AND comando='help me' ORDER BY id DESC LIMIT 1";
$resultHp = $conn->query($sqlHp);
if ($resultHp->num_rows > 0) {
// output data of each row
while($rowHp = $resultHp->fetch_assoc()) {
$id = $rowHp["id"];
$time = $rowHp["minuto"];
$mnow = date("i");
$time2 = $time + 5;
if($mnow >= $time2){
$response = "**,imei:$new_imei,J";
echo "Enviado o código $response para o cliente!<br>";
$sqlUHp = "UPDATE gps_data_single SET comando='help' WHERE id='$id'";
if ($conn->query($sqlUHp) === TRUE) {
echo "Trocado o help me pelo helpme! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
}
//Armar pelo Browser
if ($tk103_data[1] == "armcar"){
$response2 = "**,imei:$new_imei,L";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlArm = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='armcar' ORDER BY id DESC LIMIT 1";
$resultArm = $conn->query($sqlArm);
if ($resultArm->num_rows > 0) {
// output data of each row
while($rowArm = $resultArm->fetch_assoc()) {
$idArm = $rowArm["id"];
$sqlUArm = "DELETE FROM gps_data_single WHERE id='$idArm'";
if ($conn->query($sqlUArm) === TRUE) {
echo "Apagado o pedido de armar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Desarmar pelo Browser
if ($tk103_data[1] == "disarmcar"){
$response2 = "**,imei:$new_imei,M";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlDArm = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='disarmcar' ORDER BY id DESC LIMIT 1";
$resultDArm = $conn->query($sqlDArm);
if ($resultDArm->num_rows > 0) {
// output data of each row
while($rowDArm = $resultDArm->fetch_assoc()) {
$idDArm = $rowDArm["id"];
$sqlUDArm = "DELETE FROM gps_data_single WHERE id='$idDArm'";
if ($conn->query($sqlUDArm) === TRUE) {
echo "Apagado o pedido de armar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Bloquear pelo Browser
if ($tk103_data[1] == "cut"){
$response2 = "**,imei:$new_imei,J";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlCut = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='cut' ORDER BY id DESC LIMIT 1";
$resultCut = $conn->query($sqlCut);
if ($resultCut->num_rows > 0) {
// output data of each row
while($rowCut = $resultCut->fetch_assoc()) {
$idCut = $rowCut["id"];
$sqlUCut = "UPDATE gps_data_single SET comando='help' WHERE id='$idCut'";
if ($conn->query($sqlUCut) === TRUE) {
echo "Atualizado o pedido de bloqeuar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Retornar pelo Browser
if ($tk103_data[1] == "resume"){
$response2 = "**,imei:$new_imei,K";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlResume = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='resume' ORDER BY id DESC LIMIT 1";
$resultResume = $conn->query($sqlResume);
if ($resultResume->num_rows > 0) {
// output data of each row
while($rowResume = $resultResume->fetch_assoc()) {
$idResume = $rowResume["id"];
$sqlUResume = "DELETE FROM gps_data_single WHERE id='$idResume'";
if ($conn->query($sqlUResume) === TRUE) {
echo "Apagado o pedido de religar pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Velocidade pelo Browser
if ($tk103_data[1] == "myspeed"){
$sqlVel = "SELECT id, speed FROM gps_data_single WHERE imei='$new_imei' AND comando='myspeed' ORDER BY id DESC LIMIT 1";
$resultVel = $conn->query($sqlVel);
if ($resultVel->num_rows > 0) {
// output data of each row
while($rowVel = $resultVel->fetch_assoc()) {
$idVel = $rowVel["id"];
$maxVel = $rowVel["speed"];
if($maxVel<100){
$maxVel = "0$maxVel";
}
$response2 = "**,imei:$new_imei,H,$maxVel";
echo "Enviado o código $response2 para o cliente!<br>";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlUVel = "DELETE FROM gps_data_single WHERE id='$idVel'";
if ($conn->query($sqlUVel) === TRUE) {
echo "Atualizado velocidade pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
}
//Remover Cerca
if ($tk103_data[1] == "removefence"){
$sqlRemFen = "SELECT id FROM gps_data_single WHERE imei='$new_imei' AND comando='removefence' ORDER BY id DESC LIMIT 1";
$resultRemFen = $conn->query($sqlRemFen);
if ($resultRemFen->num_rows > 0) {
// output data of each row
while($rowRemFen = $resultRemFen->fetch_assoc()) {
$idRemFen = $rowRemFen["id"];
}
$response2 = "**,imei:$new_imei,P";
$limit = count($ativos);
$i = $limit - 100;
while ($i < $limit){
fwrite($ativos[$i], $response2);
echo "Enviado o código $response2 para o cliente $ativos[$i]<br>";
$i++;
}
$sqlURemFen = "DELETE FROM gps_data_single WHERE id='$idRemFen'";
if ($conn->query($sqlURemFen) === TRUE) {
echo "Removido a cerca pelo browser! <br>";
}else{
echo "Não funcionou!<br>";
}
}
}
//Alarme de Porta
if ($tk103_data[1] == "door alarm"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlPush = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush = $conn->query($sqlPush);
if ($resultPush->num_rows > 0) {
// output data of each row
while($rowPush = $resultPush->fetch_assoc()) {
$push1 = $rowPush["usr"];
$placa1 = $rowPush["placa_veiculo"];
// Push The notification with parameters
if($push1!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push1);
// Notification Settings
$pb->Alert("Porta do veículo $placa1 aberta sem autorização!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Porta do veículo $placa1 aberta sem autorização em $dia/$mes/$ano às $hora:$minuto!', '$push1', '3')";
if ($conn->query($sqlNot) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alarme Veículo Ligado
if ($tk103_data[1] == "acc alarm" || $tk103_data[1] == "ac alarm" && $tk103_data[4] != "L"){
$sqlPush1 = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush1 = $conn->query($sqlPush1);
if ($resultPush1->num_rows > 0) {
// output data of each row
while($rowPush1 = $resultPush1->fetch_assoc()) {
$push2 = $rowPush1["usr"];
$placa2 = $rowPush1["placa_veiculo"];
// Push The notification with parameters
if($push2!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push2);
// Notification Settings
$pb->Alert("Veículo $placa2 ligado sem autorização!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot2 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa2 ligado sem autorização em $dia/$mes/$ano às $hora:$minuto!', '$push2', '3')";
if ($conn->query($sqlNot2) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alerta Velocidade
if ($tk103_data[1] == "speed"){
$sqlPush5 = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush5 = $conn->query($sqlPush5);
if ($resultPush5->num_rows > 0) {
// output data of each row
while($rowPush5 = $resultPush5->fetch_assoc()) {
$push5 = $rowPush5["usr"];
$placa5 = $rowPush5["placa_veiculo"];
// Push The notification with parameters
if($push5!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push5);
// Notification Settings
$pb->Alert("Veículo $placa5 atingiu a velocidade máxima!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNot5 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa5 atingiu a velocidade máxima em $dia/$mes/$ano às $hora:$minuto!', '$push5', '3')";
if ($conn->query($sqlNot5) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alerta Fora da Cerca
if ($tk103_data[1] == "stockade"){
$sqlPushSt = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPushSt = $conn->query($sqlPushSt);
if ($resultPushSt->num_rows > 0) {
// output data of each row
while($rowPushSt = $resultPushSt->fetch_assoc()) {
$pushSt = $rowPushSt["usr"];
$placaSt = $rowPushSt["placa_veiculo"];
// Push The notification with parameters
if($pushSt!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($pushSt);
// Notification Settings
$pb->Alert("Veículo $placaSt saiu da cerca definida!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNotSt = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placaSt saiu da cerca definida no $dia/$mes/$ano às $hora:$minuto!', '$pushSt', '3')";
if ($conn->query($sqlNotSt) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
//Alarme de Vibração
if ($tk103_data[1] == "sensor alarm"){
$sqlPushSen = "SELECT usr, placa_veiculo FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPushSen = $conn->query($sqlPushSen);
if ($resultPushSen->num_rows > 0) {
// output data of each row
while($rowPushSen = $resultPushSen->fetch_assoc()) {
$push1Sen = $rowPushSen["usr"];
$placa1Sen = $rowPushSen["placa_veiculo"];
// Push The notification with parameters
if($push1Sen!=""){
require_once('PushBots.class.php');
$pb = new PushBots();
// Application ID
$appID = 'myappid';
// Application Secret
$appSecret = 'myappsecret';
$pb->App($appID, $appSecret);
$pb->Alias($push1Sen);
// Notification Settings
$pb->Alert("Veículo $placa1Sen detectou uma forte vibração!");
$pb->Platform(array("0","1"));
$pb->Badge("+1");
$pb->Push();
}
$sqlNotPush = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Veículo $placa1Sen detectou uma forte vibração em $dia/$mes/$ano às $hora:$minuto!', '$push1Sen', '3')";
if ($conn->query($sqlNotPush) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
if ($tk103_data[1] == "acc on"){
$response = "**,imei:$new_imei,C,03m";
echo "Enviado o código $response para o cliente!<br>";
}
if ($tk103_data[1] == "acc off"){
$response = "**,imei:$new_imei,C,60m";
echo "Enviado o código $response para o cliente!<br>";
}
if($tk103_data[1] == "help me"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlPush3 = "SELECT usr FROM login WHERE imei='$new_imei' ORDER BY id ASC LIMIT 1";
$resultPush3 = $conn->query($sqlPush3);
if ($resultPush3->num_rows > 0) {
// output data of each row
while($rowPush3 = $resultPush3->fetch_assoc()) {
$push3 = $rowPush3["usr"];
$sqlNot3 = "INSERT INTO notificacao (notif, para, msgtipo)
VALUES ('Pedido de Bloqueio registrado no $dia/$mes/$ano às $hora:$minuto!', '$push3', '3')";
if ($conn->query($sqlNot3) === TRUE) {
echo "Notificação encaminhada com sucesso!<br>";
}
}
}
}
if ($tk103_data[1] == "jt"){
$response = "**,imei:$new_imei,E";
echo "Enviado o código $response para o cliente!<br>";
$sqlD = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='jt'";
if ($conn->query($sqlD) === TRUE) {
echo "Deletado com sucesso o JT<br>";
}
}
if ($tk103_data[1] == "et"){
$sqlDe = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='et'";
if ($conn->query($sqlDe) === TRUE) {
echo "Deletado com sucesso o ET<br>";
}
}
if ($tk103_data[1] == "kt"){
$sqlDel = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='kt'";
if ($conn->query($sqlDel) === TRUE) {
echo "Deletado com sucesso o KT<br>";
}
}
if ($tk103_data[1] == "lt"){
$sqlDele = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='lt'";
if ($conn->query($sqlDele) === TRUE) {
echo "Deletado com sucesso o LT<br>";
}
}
if ($tk103_data[1] == "mt"){
$sqlDelet = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='mt'";
if ($conn->query($sqlDelet) === TRUE) {
echo "Deletado com sucesso o MT<br>";
}
}
if ($tk103_data[1] == "ht"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='ht'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o HT<br>";
}
}
if ($tk103_data[1] == "ot"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='ot'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o OT<br>";
}
}
if ($tk103_data[1] == "pt"){
$sql = "DELETE FROM gps_data_single WHERE imei='$new_imei' AND comando='pt'";
if ($conn->query($sql) === TRUE) {
echo "Deletado com sucesso o PT<br>";
}
}
break;
}
if (!$data) {
unset($client_sockets[ array_search($socket, $client_sockets) ]);
#fclose($socket);
echo "client $socket disconnected. total clients: ". count($client_sockets) . "\n";
continue;
}
//send the message back to client
if (sizeof($response) > 0) {
fwrite($socket, $response);
}
}
} // end while loop
$conn->close();
?>`

Related

Put Mysql query result in array inside a class

Hello everybody again I'm tryin to resolve my issue poste in this topic -> Fetch data from Prestashop custom field
I've have made a MySql query outside my class and now it works but i need to put the result in an array inside the class. I paste my code below:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT codice_target FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id_customer"]. " - Codice target: " . $row["codice_target"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
Then there is the class and the function i need to put the result from the query
class AdvancedExport extends Module
{
//other methods here...
public function fputToFile($file, $allexportfields, $object, $ae)
{
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
// need to put mysql query result here inside $readyForExport['codice_target'];
$this->counter[$readyForExport['id_order']] = (!empty($this->counter[$readyForExport['id_order']])) ? ++$this->counter[$readyForExport['id_order']] : 1; // try here
$readyForExport['orderLine'] = $this->counter[$readyForExport['id_order']]; // and try here
//print_r('The id_order is added: ' . $readyForExport['orderLine']); // see if it is added
//echo '<pre>' . var_dump($readyForExport) . '</pre>';
// modifiche === Dario === prezzo
$newPrice = substr($readyForExport['product_price'], 0, strpos($readyForExport['product_price'], "."));
$readyForExport['product_price'] = $newPrice;
// === data
$newDateAdd = new DateTime($readyForExport['date_add']);
$readyForExport['date_add'] = $newDateAdd->format('d/m/Y');
// aggiungo 21 giorni - 3 settimane - alla data di acquisto
$date_mod = clone $newDateAdd;
$date_mod->add(new DateInterval('P21D'));
$readyForExport['delivery_date'] = $date_mod->format('d/m/Y');
// === data invoice
$newDateInvoice = clone $newDateAdd;
$readyForExport['invoice_date'] = $newDateAdd->format('d/m/Y');
//scambio l'id customer con il codice_target
//$readyForExport['codice_target'] = 8989;
$textTarget = (string)$readyForExport['codice_target'];
$readyForExport['id_customer'] = $textTarget;
// aggiungo gli zeri davanti al customer id
$id_count = strlen($readyForExport['id_customer']);
if ($id_count == 1) {
$newCustomer = "0000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 2) {
$newCustomer = "000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 3) {
$newCustomer = "00000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 4) {
$newCustomer = "0000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 5) {
$newCustomer = "000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 6) {
$newCustomer = "00".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}
// elaboro lo SKU
$textSku = (string)$readyForExport['product_name'];
$newSku_1 = $readyForExport['product_name'];
$newSku_1 = substr($newSku_1,0,4);
$newSku_2 = "/".substr($textSku,-4,4);
$newSku_tot = $newSku_1.$newSku_2;
$newSku_tot = str_replace(' ', '', $newSku_tot);
$newSku_tot = str_replace('-', '', $newSku_tot);
$newSku_tot = str_replace('co', '', $newSku_tot);
$newSku_tot = str_replace('e', '', $newSku_tot);
$newSku_tot = str_replace('r', '', $newSku_tot);
$readyForExport['product_name'] = $newSku_tot;
// aggiungo un campo fisso
$readyForExport['causale'] = "NR";
// aggiungo un campo fisso
$readyForExport['ORCL'] = "ORCL";
//$readyForExport['G'] = "";
$readyForExport['J'] = "";
$readyForExport['K'] = "";
$readyForExport['L'] = "";
$readyForExport['M'] = "";
$readyForExport['N'] = "";
$readyForExport['P'] = "";
$readyForExport['Q'] = "";
$readyForExport['R'] = "30";
$index_arr=array("id_customer","date_add","ORCL","product_name","causale","product_quantity","product_price","delivery_date","id_order","J","K","L","M","N","orderLine","P","Q","R");
//riordino i campi in base a come li dispongo nella variabile $index_arr
$arr_t=array();
foreach($index_arr as $i=>$v) {
foreach($readyForExport as $k=>$b) {
if ($k==$v) $arr_t[$k]=$b;
}
}
$readyForExport=$arr_t;
//write into csv line by line
fputcsv($file, $readyForExport, $ae->delimiter, $ae->separator);
}
}
Thanks far all done until now, Im really close to the goal.
Array values initialized to $rtoclass variable outside the class, then passed to an AdvancedExport object through its method - $obj->set_arr_needed( $rtoclass );
On $obj->fputToFile() call, the needed array will automatically be available for use inside it via the variable $arr_needed_in.
Try:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT codice_target FROM customer";
$result = $conn->query($sql);
$rtoclass = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id_customer"]. " - Codice target: " . $row["codice_target"]."<br>";
$rtoclass[] = $row;
}
} else {
echo "0 results";
}
$obj = new AdvancedExport();
$obj->set_arr_needed( $rtoclass );
$conn->close();
For the class:
class AdvancedExport extends Module
{
//other methods here...
private $arr_needed = array();
public function set_arr_needed( $arr ) {
$this->arr_needed = $arr;
}
public function get_arr_needed() {
return $this->arr_needed;
}
public function fputToFile($file, $allexportfields, $object, $ae)
{
$arr_needed_in = $this->get_arr_needed(); // array needed already inside..
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
// need to put mysql query result here inside $readyForExport['codice_target'];
$this->counter[$readyForExport['id_order']] = (!empty($this->counter[$readyForExport['id_order']])) ? ++$this->counter[$readyForExport['id_order']] : 1; // try here
$readyForExport['orderLine'] = $this->counter[$readyForExport['id_order']]; // and try here
//print_r('The id_order is added: ' . $readyForExport['orderLine']); // see if it is added
//echo '<pre>' . var_dump($readyForExport) . '</pre>';
// modifiche === Dario === prezzo
$newPrice = substr($readyForExport['product_price'], 0, strpos($readyForExport['product_price'], "."));
$readyForExport['product_price'] = $newPrice;
// === data
$newDateAdd = new DateTime($readyForExport['date_add']);
$readyForExport['date_add'] = $newDateAdd->format('d/m/Y');
// aggiungo 21 giorni - 3 settimane - alla data di acquisto
$date_mod = clone $newDateAdd;
$date_mod->add(new DateInterval('P21D'));
$readyForExport['delivery_date'] = $date_mod->format('d/m/Y');
// === data invoice
$newDateInvoice = clone $newDateAdd;
$readyForExport['invoice_date'] = $newDateAdd->format('d/m/Y');
//scambio l'id customer con il codice_target
//$readyForExport['codice_target'] = 8989;
$textTarget = (string)$readyForExport['codice_target'];
$readyForExport['id_customer'] = $textTarget;
// aggiungo gli zeri davanti al customer id
$id_count = strlen($readyForExport['id_customer']);
if ($id_count == 1) {
$newCustomer = "0000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 2) {
$newCustomer = "000000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 3) {
$newCustomer = "00000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 4) {
$newCustomer = "0000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 5) {
$newCustomer = "000".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}elseif ($id_count == 6) {
$newCustomer = "00".$readyForExport['id_customer'];
$readyForExport['id_customer'] = $newCustomer;
}
// elaboro lo SKU
$textSku = (string)$readyForExport['product_name'];
$newSku_1 = $readyForExport['product_name'];
$newSku_1 = substr($newSku_1,0,4);
$newSku_2 = "/".substr($textSku,-4,4);
$newSku_tot = $newSku_1.$newSku_2;
$newSku_tot = str_replace(' ', '', $newSku_tot);
$newSku_tot = str_replace('-', '', $newSku_tot);
$newSku_tot = str_replace('co', '', $newSku_tot);
$newSku_tot = str_replace('e', '', $newSku_tot);
$newSku_tot = str_replace('r', '', $newSku_tot);
$readyForExport['product_name'] = $newSku_tot;
// aggiungo un campo fisso
$readyForExport['causale'] = "NR";
// aggiungo un campo fisso
$readyForExport['ORCL'] = "ORCL";
//$readyForExport['G'] = "";
$readyForExport['J'] = "";
$readyForExport['K'] = "";
$readyForExport['L'] = "";
$readyForExport['M'] = "";
$readyForExport['N'] = "";
$readyForExport['P'] = "";
$readyForExport['Q'] = "";
$readyForExport['R'] = "30";
$index_arr=array("id_customer","date_add","ORCL","product_name","causale","product_quantity","product_price","delivery_date","id_order","J","K","L","M","N","orderLine","P","Q","R");
//riordino i campi in base a come li dispongo nella variabile $index_arr
$arr_t=array();
foreach($index_arr as $i=>$v) {
foreach($readyForExport as $k=>$b) {
if ($k==$v) $arr_t[$k]=$b;
}
}
$readyForExport=$arr_t;
//write into csv line by line
fputcsv($file, $readyForExport, $ae->delimiter, $ae->separator);
}
}
}

Can't record script time correctly

I have an script that sometimes takes more than 40 seconds to run. But the microtime thing returns less thatn 1 second.
First issue is WHY IS THIS TAKING SO LONG???? and second issue is why microtime don't return time correctly?
<?
$inicio = microtime(true);
session_start();
header('Content-Type: text/html; charset=utf-8');
include 'coneccion-base-mails.php';
include 'coneccion.php';
include 'funciones.php';
$id = $_POST["id"];
//recuperamos los datos del envio
$R = $mysqli->query("SELECT * FROM envios WHERE id=".$id."")->fetch_array();
$remitente = $R["remitente"];
$lista = $R["lista"];
$asunto = $R["asunto"];
$cuerpo = $R["cuerpo"];
$sustituto = $R["sustituto"];
$contactos = array();
//ahora creamos cargamos la lista
if($lista=="Todos"){
$result = $mysqli->query("SELECT * FROM listas WHERE usuario='".$_SESSION["usuario"]."'");
while($R = $result->fetch_array()){
$dato = array($R["nombre"],$R["apellido"],$R["mail"]);
array_push($contactos,$dato);
}
}
else{
$result = $mysqli->query("SELECT * FROM segmentos WHERE titulo='".$lista."' and usuario='".$_SESSION["usuario"]."'");
$R = $result->fetch_array();
$idsegmento = $R["id"];
$result = $mysqli->query("SELECT * FROM listasegmentos WHERE idsegmento=".$idsegmento."");
while($R = $result->fetch_array()){
$dato = array(nombreContacto($R["idcontacto"]),apellidoContacto($R["idcontacto"]),mailContacto($R["idcontacto"]));
array_push($contactos,$dato);
}
}
//ya tenemos los contactos,
//ahora los recorremos uno a uno, fijandonos si ya fue enviado ese mail, si fue enviado vamos al siguiente, sino lo mandamos y cortamos.
$total = count($contactos);
$mm = 0;
if( mailsEnviadosEstaHora() < $limiteMailsPorHora){
foreach($contactos as $contacto){
$nombre = $contacto[0];
$apellido = $contacto[1];
$mail = $contacto[2];
if(mailEnviado($mail)=="no"){
if(strpos($mail,";")===false){
enviarMail($nombre." ".$apellido." <".$mail.">",$mail,$nombre);
}
else{
$mails = explode(";",$mail);
$comp = "";
foreach($mails as $mailss){
if($comp == ""){
$comp = $nombre." ".$apellido." <".$mailss.">";
}
else{
$comp .= ",".$nombre." ".$apellido." <".$mailss.">";
}
}
enviarMail($comp,$mail,$nombre);
}
break;
}
else{
$mm++;
}
}
if($mm == $total){
$mysqli->query("UPDATE envios SET estado='enviada' WHERE id=".$id."");
echo "actualizar";
}
}
else{
//se llego al limite de mails por hora
echo "limite";
}
function marcarEnviado($mail){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $mm;
global $total;
global $inicio;
$fecha = date("Y")."-".date("m")."-".date("d");
$mysqli->query("INSERT INTO procesoenvio (idenvio,destinatario,estado,fecha,hora,solohora) VALUES (".$id.",'".$mail."','enviado','".$fecha."','".date('H:i:s')."','".date('H')."')");
$caca = $mm+1;
echo $caca." / ".$total;
$actual = microtime(true);
$totalsss= $actual- $inicio;
echo 'Tiempo : '.$totalsss.' segundos<br>';
}
function enviarMail($para,$mail,$nombre){
global $mysqli;
global $id;
global $remitente;
global $lista;
global $asunto;
global $cuerpo;
global $sustituto;
if($nombre==''){
$nombre = $sustituto;
}
//from
$from = array();
$_datos = explode("<",$remitente);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$from[$_mail] = $_nombre;
$cuentas = explode("---",$_SESSION['correo']);
foreach($cuentas as $cuenta){
$correo = explode("|||",$cuenta);
$username = $correo[0];
$password = $correo[1];
if($username == $_mail){
break;
}
}
//
require_once 'swiftmailer-master/lib/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SmtpTransport::newInstance("mail.dxxxxxxxxxxx.com",25);
$transport->setUsername($username);
$transport->setPassword($password);
// Create the message
$message = Swift_Message::newInstance();
$destinatarios = explode(",",$para);
$destin = array();
foreach($destinatarios as $destinatario){
$s = strpos($destinatario,"<");
if($s===false){
array_push($destin,$destinatario);
}
else{
$_datos = explode("<",$destinatario);
$_nombre = trim($_datos[0]);
$_mail = $_datos[1];
$_mail = trim(str_replace(">","",$_mail));
$destin[$_mail] = $_nombre;
}
}
$message->setTo($destin);
$message->setSubject($asunto);
$message->setFrom($from);
// adjuntos!!!
$ruta = '../../panel/envios/adjuntos/' . $id . '/'; // Relative to the root
if(file_exists($ruta)){ // Abrir archivos
$n = 0;
$archivos = array();
foreach (new DirectoryIterator($ruta) as $file) {
if($file->isDot()) continue;
array_push($archivos,$file->getFilename());
}
sort($archivos);
foreach($archivos as $archivo){
$message->attach(Swift_Attachment::fromPath('http://xxxxxxxxxxxxxxxxxxxx.com'.str_replace('../../','/',$ruta).str_replace(' ','-',$archivo)));
$n+=1;
//break;
}
if($n==0){
//no hay fotos en la carpeta
}
}
$cuerpoPersonalizado = str_replace('[[[Nombre]]]',$nombre,$cuerpo);
$message->setBody($cuerpoPersonalizado,'text/html');
$msg = $message->toString();
$msg = str_replace('http://xxxxxxxxxxxx.com/img.php?i','#',$msg);
$verificacion = base64_encode($id.'|||'.$mail);
$cuerpoPersonalizado = str_replace('numeroidentificacion',$verificacion,$cuerpoPersonalizado);
$message->setBody($cuerpoPersonalizado,'text/html');
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
//$mailer->send($message) or die($msg);
$mailer->send($message);
marcarEnviado($mail);
$hostname = '{localhost:143}Sent Items';
$conn = imap_open($hostname,$username,$password) or die('No se pudo conectar con: usuario: '.$username.' y clave: '.$password.' ' . imap_last_error());
imap_append($conn, '{localhost:143}Sent Items', $msg, "\\Seen") or die("error");
}
?>
As an important tangent to your question, please ensure you cleanse your data - those $_POSTs are wide open for SQL injection:
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Think about using PDO prepared statements. It's more secure (helps prepare statements against SQL injection) and makes transactions easy (for several repeated queries).
As for your answer, I think you are misunderstanding what microtime() returns. I've included a link to format the number of microseconds in the way you may expect.
php microtime() format value

Return true or false from if statements in model to use afterwards in view

Im using a MVC and I have the following function in my model:
public function subscribirUser(){
$item_id = JRequest::getCmd('id');
$user_id = JFactory::getUser()->id;
//Coger todos los campos del cupon
$db = $this->getDbo();
$query = 'SELECT * FROM #__k2_items where id='.$item_id;
$db->setQuery($query);
$resultado = $db->loadObject();
//Insertar el cupon como suscrito
$query = 'INSERT INTO #__cuphoneo_subscripcion (user_id, item_id, fecha, estado) VALUES ('.$user_id.', '.$item_id.', now(), 1)';
$result = $db->setQuery($query);
$db->query();
//Sacamos los valores de los campos extra
$campos_extra = json_decode($resultado->extra_fields);
foreach($campos_extra as $value){
if($value->id == 4){
$num_max_cup_descargar = $value->value;
$num_max_cup_descargar = $num_max_cup_descargar - 1;
$value->value = $num_max_cup_descargar;
$campos_extra_updated = json_encode($campos_extra);
$query = 'UPDATE #__k2_items SET extra_fields=\''.mysql_real_escape_string($campos_extra_updated).'\' WHERE id='.$item_id;
$db->setQuery($query);
$db->query();
}
if($value->id == 8){
$num_max_cup_desc_user = $value->value;
$query = 'SELECT count(item_id) as contador FROM #__cuphoneo_subscripcion WHERE item_id='.$item_id.' AND estado=1';
$db->setQuery($query);
$resultado = $db->loadResult();
if($resultado == $num_max_cup_desc_user){
}
}
$fechaHoy = date("Y-m-d");
//Comprobamos si la fecha de validez es igual a la fecha de hoy
if($value->id == 12){
if($value->value == $fechaHoy){
$query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
$db->setQuery($query);
$db->query();
}
}
//Comprobamos si la fecha de validez es igual a la fecha de hoy
if($value->id == 23){
if($value->value == $fechaHoy){
$query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
$db->setQuery($query);
$db->query();
}
}
}
}
I want to return true or false within each if so I can later use these to validate a button in my view. How can I do this?
You can probably store them in multi dimentional array like:
$a = array();
foreach($campos_extra as $k=>$value){
if($value->id == 4){
$num_max_cup_descargar = $value->value;
$num_max_cup_descargar = $num_max_cup_descargar - 1;
$value->value = $num_max_cup_descargar;
$campos_extra_updated = json_encode($campos_extra);
$query = 'UPDATE #__k2_items SET extra_fields=\''.mysql_real_escape_string($campos_extra_updated).'\' WHERE id='.$item_id;
$db->setQuery($query);
$a[$k] = $db->query();
}
if($value->id == 8){
$num_max_cup_desc_user = $value->value;
$query = 'SELECT count(item_id) as contador FROM #__cuphoneo_subscripcion WHERE item_id='.$item_id.' AND estado=1';
$db->setQuery($query);
$resultado = $db->loadResult();
if($resultado == $num_max_cup_desc_user){
}
}
$fechaHoy = date("Y-m-d");
//Comprobamos si la fecha de validez es igual a la fecha de hoy
if($value->id == 12){
if($value->value == $fechaHoy){
$query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
$db->setQuery($query);
$a[$k] = $db->query();
}
}
//Comprobamos si la fecha de validez es igual a la fecha de hoy
if($value->id == 23){
if($value->value == $fechaHoy){
$query = 'UPDATE #__k2_items SET publish_down=DATE_ADD("'.$fecha.'", INTERVAL 2 DAY) WHERE id='.$item_id;
$db->setQuery($query);
$a[$k] = $db->query();
}
}
}
here are stored in array $a

Entering data twice

I made a php code for insert data on mysql.
if(isset($_POST['submitted'])){
$img = NULL;
if(isset($_FILES['upload'])){
include('classes/imagens.class.php');
$imagem = new imagem($_FILES['upload']['name'],$_FILES['upload']['tmp_name'],$_FILES['upload']['size'],$_FILES['upload']['error']);
if($imagem->verifica_extensao($_FILES['upload']['type']) && $imagem->verifica_tamanho()){
$erro = $imagem->upload();
$img = $imagem->getNome();
}
}
$trimmed = array_map('trim', $_POST); // usa a função trim() em todas as variáveis POST
$tit = $cat = $dat = $end = $des = $pr = $dono = $hor = FALSE; // atribui falso para as variaveis que poderão receber as variaveis POST
$mysql = new mysql('eventos');
if(!empty($trimmed['nome'])){
$tit = $mysql->escape_string($trimmed['nome']);
}
if(!empty($trimmed['categoria'])){
$cat = $mysql->escape_string($trimmed['categoria']);
}
if(!empty($trimmed['data'])){
$dat = $mysql->escape_string($trimmed['data']);
}
if($trimmed['hora'] != '--' && $trimmed['minuto'] != '--'){
$hor = $trimmed['hora'].":".$trimmed['minuto'];
$hor = $mysql->escape_string($hor);
}
if(!empty($trimmed['endereco'])){
$end = $mysql->escape_string($trimmed['endereco']);
}
if(!empty($trimmed['descricao'])){
$des = $mysql->escape_string($trimmed['descricao']);
}
if(!empty($trimmed['preco'])){
$pr = $mysql->escape_string($trimmed['preco']);
}
$dono = $_SESSION['user_id'];
if($tit && $cat && $dat && $end && $des && $pr && $dono && $hor){
$evento = new evento($tit, $cat, $end, $dat, $hor, $des, $pr, NULL, NULL, $img,$dono, NULL, NULL);
$evento->cadastrar();
echo '<h3>Evento cadastrado com sucesso!</h3>';
echo "<h1>Clique aqui para voltar para a página inicial</h1>";
exit();
}
}
and my function cadastrar()
function cadastrar(){
$this->mysql->sql("INSERT INTO eventos (nome, categoria, data, endereco, descricao,ref_imagem,preco,user_id, hora, data_registro) VALUES ('$this->Titulo','$this->Categoria','$this->Data','$this->Endereco','$this->Descricao','$this->RefImagem','$this->Preco','$this->Dono','$this->Horario',NOW())");
}
and my function sql()
function sql($query){
$this->connect();
$this->query = $query;
if(mysqli_query($this->dbc,$this->query)){
$linhas_afetadas = mysqli_affected_rows($this->dbc);
echo $query;
$this->result=mysqli_query($this->dbc,$this->query);
$this->disconnect();
$retorno = array($this->result,$linhas_afetadas);
return $retorno;
} else {
die("Ocorreu um erro ao executar a Query SQL abaixo:<br>$query");
$this->disconnect();
}
}
and... the result is 2 same columns on the table.
Every time you call mysqli_query, a query is launched to the database. You are doing that twice:
if (mysqli_query(...))
{
....
$this->result = mysqli_query(...);
}
So that's why you end with duplicated data.

Alfresco "admin" password keeps getting deleted when i call the same webscript multiple times

I've got a weird problem. I've created a procedure in PHP that does these things:
Read data (9.000 rows) from a MySQL table
Writes a row to another table
Create a folder in Alfresco based on a field in the row
I've got this strange problem (only on one Alfresco installation, on others I don't have the problem), after the first 2-3 rows the password for the admin user gets deleted from Alfresco (if you look in the db, you can't find it) and so the procedure stops. I'm using Alfresco Community 3.2.
Here is the PHP code of the procedure:
require_once("../components/com_astra/libs/AlfrescoConnect.php");
require_once("../components/com_astra/libs/FirePHPCore/fb.php");
$username = "***";
$password = "****;";
$hostname = "localhost";
ob_start();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("lbs_8",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT count(*) as quanti FROM ast_tabellaTemporaneaNdg");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
$totaleTabella = mysql_result($result, 0);
echo("La tabella ast_tabellaTemporaneaNdg contiene [$totaleTabella] records<br>");
echo("Conto il numero di record della vista di transcodifica<br>");
$result = mysql_query("SELECT count(*) as quanti FROM vista_ndg_normalizzati");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
$totaleVista = mysql_result($result, 0);
echo("La vista vista_ndg_normalizzati contiene [$totaleVista] records<br>");
if ($totaleTabella == $totaleVista){
echo("Tutte le righe della tabella ast_tabellaTemporaneaNdg sono transcodificate correttamente<br>");
echo("Saranno quindi importati [$totaleTabella] records<br>");
}else{
echo("Non tutte le righe della tabella ast_tabellaTemporaneaNdg sono transcodificate correttamente<br>");
echo("nella tabella ast_tabellaTemporaneaNdg sono presenti [$totaleTabella] records, di questi solo [$totaleVista] transcodificano correttamente<br>");
$handle = fopen("ndgNonImportabili.txt", "w");
$result = mysql_query("SELECT ndg FROM ast_tabellaTemporaneaNdg WHERE ndg NOT IN (SELECT ndg from vista_ndg_normalizzati)");
if (!$result) {
die('ERRORE: ' . mysql_error());
}
while ($row = mysql_fetch_assoc($result)){
$ndg = "NDG: ".$row["ndg"]."\n";
fwrite ($handle, $ndg);
}
fclose($handle);
echo("Gli NDG non importabili sono stati loggati nel file ndgNonImportabili.txt<br>");
//die("L'importazione avra' inizio solo quando tutti gli NDG saranno importabili. I motivi per cui un ndg non è importabile possono essere: incorenza fra Natura Giuridica 1 e natura giuridica 2, Incoerenza fra comune, Provincia e Regione<br>");
}
$result = mysql_query("SELECT * FROM vista_ndg_normalizzati");
//fb($result, 'risultati');
$handle = fopen("logImportazione.txt", "w");
while ($row = mysql_fetch_assoc($result)) {
$user = "admin";
$ndg = $row['ndg'];
$response = AlfrescoConnect::createNDG($ndg, $user);
$status = $response['esito'];
if($status == "OK"){
$ragioneSociale = mysql_real_escape_string($row['ragioneSociale']);
$query = "SET FOREIGN_KEY_CHECKS=0";
$resultSetKeys = mysql_query($query);
$query = "INSERT INTO ast_Cliente (idUtente, idNaturaGiuridica, idTipoSegmento, idRegione, idProvincia, idComune, ragioneSociale, ndg, idNaturaGiuridica2) VALUES ";
$query .= " (1, ".$row['idNaturaGiuridica'].", 2 , ".$row['idRegione'].", ".$row['idProvincia'].", ".$row['idComune'].", '".$ragioneSociale."', '".$ndg."', ".$row['idNaturaGiuridica2'].")";
//fb($query);
$resultInsert = mysql_query($query);
if (!$resultInsert) {
$messaggio = "Si è verificato un errore nell'importazione dell'ndg [$ndg]: [".mysql_error()."]\n";
}else{
$messaggio = "[$ndg] importato con successo\n";
}
fwrite ($handle, $messaggio);
}else{
$messaggio = "Si è verificato un errore nella creazione della cartella per l'ndg [$ndg] su alfresco. ERRORE: [".$response['motivazione']."]\n";
fwrite ($handle, $messaggio);
}
}
fclose($handle);
echo("importazione completata: i risultati dell'importazione sono stati salvati nel file logImportazione.txt");
?>
The folder is created by calling $response = AlfrescoConnect::createNDG($ndg, $user); where $ndg is the name of the folder and $user is the user who created it
Here is the code of AlfrescoConnect.php:
class AlfrescoConnect
{
static public $webscriptURL = "http://localhost:8080/alfresco/service";
static public $login = "/api/login";
static public $login_ticket = "/api/login/ticket";
static public $alfrescoPath = "http://localhost:8080";
static public $alfrescoContext = "/alfresco";
static public $upload_file_script = "/astra/upload";
static public $uploadFile = "/astra/uploaddoc";
static public $search_document = "/astra/cercadocumenti";
static public $createNDG = "/astra/creandg";
static public $createPEFPerNDG = "/astra/creapef";
static public $searchDocumentPerConfirm = "/astra/cercadocumentoperconferma";
static public $confirmDocument = "/astra/confermadocumenti";
static public $getPEF = "/astra/estraidatipef";
static public $updatePEF = "/astra/aggiornapef";
static public $documentCounter = "/astra/contadocumenti";
static public $userLogin = "/astra/creautente";
static public $cancella = "/astra/managedocumentversions";
static public $alfUsername = "admin";
static public $alfPassword = "admin";
static public $ticket = "";
static public $userTicket = "";
static public function Authenticate($username='') {
//fb($username);
if(strcmp($username,'')==0){
if (AlfrescoConnect::isAuthenticated()) return true;
$link = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$login."?u=".AlfrescoConnect::$alfUsername."&pw=".AlfrescoConnect::$alfPassword . "&noCache=" .time();
fb($link, "LINK");
}else{
AlfrescoConnect::$userTicket = AlfrescoConnect::CustomAuthentication($username);
return true;
}
try {
//perform a http/get request to get tiket
// Try to create a ticket
// If the ticket fails, it means that the username and/or password are wrong
$r= new HttpRequest($link, HttpRequest::METH_GET);
$r->send() ;
$http_response = $r->getResponseBody();fb($http_response, "RISPOSTA");
$pos1 = stripos($http_response, "<ticket>");
$pos2 = stripos($http_response, "</ticket>");
//ceck if token is returned
if ($pos1<0 | !is_int($pos1) || $pos2<0 | !is_int($pos2)) {
AlfrescoConnect::$ticket = "";
$returnValue = false;
} else {
$pos1 += 8;
$pos2 -= $pos1;
// clean the xml info
AlfrescoConnect::$ticket = substr($http_response, $pos1, $pos2);
$returnValue = true;
}
//fb(AlfrescoConnect::$ticket);
$_SESSION["ticket"] = AlfrescoConnect::$ticket;
return true;
}
catch (Exception $e) {
fb($e, "Eccezione");
AlfrescoConnect::$ticket = "";
$_SESSION["ticket"] = AlfrescoConnect::$ticket;
return $returnValue;
}
}
static public function isAuthenticated() {
if (!isset($_SESSION["ticket"])) return false;
$link = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$login_ticket."/".$_SESSION["ticket"]."?alf_ticket=".$_SESSION["ticket"]."&noCache=" .time();
fb($link, 'link in isauth');
try {
//perform a http/get request to get tiket
// Try to create a ticket
// If the ticket fails, it means that the username and/or password are wrong
$r= new HttpRequest($link, HttpRequest::METH_GET);
$r->send() ;
$http_response = $r->getResponseBody();
$pos1 = stripos($http_response, "<ticket>");
$pos2 = stripos($http_response, "</ticket>");
//ceck if token is returned
if ($pos1<0 | !is_int($pos1) || $pos2<0 | !is_int($pos2)) {
return false;
} else {
$pos1 += 8;
$pos2 -= $pos1;
// clean the xml info
if ($_SESSION["ticket"] == substr($http_response, $pos1, $pos2)) {
AlfrescoConnect::$ticket = $_SESSION["ticket"];
return true;
}
}
}
catch (Exception $e) {
return false;
}
}
static public function CustomAuthentication($username=''){
$url = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$userLogin;
if ($auth) {
if (!AlfrescoConnect::Authenticate()) return -1;
$url .= "?alf_ticket=".AlfrescoConnect::$ticket;
}
$parameter = array('username' => $username);
//
$response = AlfrescoConnect::Query($url, $parameter,HttpRequest::METH_POST,1,0);fb($url);fb($parameter);
fb($response,'custom authentication result');
return $response;
}
* perform query on alfresco webscripts
*
* #param string $url alfresco webscript url
* #param string $params parameter for the query
* #param string $meth metohod for http request HTTP_METH_POST/HTTP_METH_GET default HTTP_METH_POST
* #param boolean $auth set whether or not to need authentication
* #return mixed -1 for authentication faliure, -2 for query faliure
*/
static public function Query($url, $params, $meth = HTTP_METH_POST, $auth = 1, $decode = 1, $ticketUser='') {
//Aggiunto per evitare il caching
//fb($url, "Query url");
//fb($params, "Query params");
//print_r(debug_backtrace());
$nocache=time();
$params['nocache']=$nocache;
if ($auth) {
if(strcmp($ticketUser,'')==0){
if (!AlfrescoConnect::Authenticate()) return -1;
$params['alf_ticket'] = AlfrescoConnect::$ticket;
}
else{
$params['alf_ticket'] = $ticketUser;
}
}
fb($params,'param');
try {
//fb("invio della richiesta");
$url=$url."?nocache=$nocache";
$r= new HttpRequest($url, $meth);
$r->addQueryData($params);
$r->send() ;
fb($r);
$http_response = $r->getResponseBody();
fb($http_response);
if (!$decode) return $http_response;
$json = new Services_JSON();
return object2array($json->decode($http_response));
//return json_decode($http_response, true);
}
catch (Exception $e) {
return -2;
}
}
/**
* Azioni su Alfresco
*
*/
static public function createNDG($ndg, $user){
$url = AlfrescoConnect::$webscriptURL.AlfrescoConnect::$createNDG;
fb("Crea l'ndg,$url");
if (strcmp($user,'')!=0) {
$ticket = AlfrescoConnect::Authenticate($user);
if (!$ticket) return -1;
}
$parameter = array(ModelParameter::$ndg => $ndg);
$response = AlfrescoConnect::Query($url, $parameter,HTTP_METH_POST,1,1,AlfrescoConnect::$userTicket);
return $response;
}
}
It was a memory problem. Never ever try to run Alfresco on a machine with only 1GB of memory!

Categories