Can't record script time correctly - php

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

Related

PHP Array POST UPDATE only affects the last row

I'm trying to UPDATE multiple rows of my DB, but it UPDATE only the last row.
I got all DATA from database and fill the SELECT OPTION MULTIPLE:
<select name="numerosdasorte[]" class="form-control" multiple="">
<?php
$consulta = $PDO->query("SELECT * FROM cota1 WHERE status = '0' ORDER BY cota ASC");
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
?>
<option value="<?php echo $linha['cota']; ?>"><?php echo $linha['cota']; ?></option>
<?php } ?>
</select>
I got these numbers and I put ',' before save data:
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
I INSERT the data on DATABASE. It works like I want:
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
Now, I got the problem: I need to get the number that was picked in the form to change this status. All the numbers picked, I need to change to '1'. All the numbers picked needs to be unavailable:
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
The problem is, the only row affected is the last. If I choice 5 numbers, for example (001, 002, 003, 004 and 005), only the last number (005) will be affected and changed to '1'.
COMPLETE CODE:
<?php
require '../config.a/conexao.php';
$name = $_POST['name'];
$email = $_POST['email'];
$password = md5(uniqid(""));
$endereco = $_POST['endereco'];
$numero = $_POST['numero'];
$bairro = $_POST['bairro'];
$cep = $_POST['cep'];
$cidade = $_POST['cidade'];
$estado = $_POST['estado'];
$telefonefixo = $_POST['telefonefixo'];
$telefonecelular = $_POST['telefonecelular'];
$datadenascimento = $_POST['datadenascimento'];
$cpfcnpj = $_POST['cpfcnpj'];
$rg = $_POST['rg'];
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':endereco', $endereco);
$stmt->bindParam(':numero', $numero);
$stmt->bindParam(':bairro', $bairro);
$stmt->bindParam(':cep', $cep);
$stmt->bindParam(':cidade', $cidade);
$stmt->bindParam(':estado', $estado);
$stmt->bindParam(':telefonefixo', $telefonefixo);
$stmt->bindParam(':telefonecelular', $telefonecelular);
$stmt->bindParam(':datadenascimento', $datadenascimento);
$stmt->bindParam(':cpfcnpj', $cpfcnpj);
$stmt->bindParam(':rg', $rg);
$stmt->bindParam(':numerosdasorte', $numerosdasorte);
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
$result = $stmt->execute();
if (!$result) {
var_dump($stmt->errorInfo());
} else {
$subjectPrefix = '[Você foi cadastrado na TOP BRASIL]';
$assunto = 'Você foi cadastrado na TOP BRASIL';
$mensagemHTML = '<h3>Parabéns por fazer parte do nosso GRUPO COOPERATIVO!</h3>
<p>Olá <b>' . $name . '</b>, você fez uma ótima escolha! Acompanhe os sorteios e boa sorte! <br> Agora você está habilitado a acompanhar todo o processo por seu PAINEL de cliente. Para acessar, é muito simples: <br> Acesse nosso site (https://topbrasilbr.com.br/painel), digite seu usuário e senha, e pronto! Fique por dentro das novidades! <br><br> Segue seus dados de cadastro:
<p><b>E-mail:</b> ' . $email . ' <br> <b>Senha:</b> ' . $password . '
<p>Para dúvidas, entre em contato conosco, pelo telefone (24) 2252-3196, ou pelo e-mail: contato#topbrasilbr.com.br.
<p>Um grande abraço!
<p><b>Equipe TOP BRASIL</b>
<hr>';
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: TOP BRASIL\r\n";
$headers .= 'Cc: contato#topbrasilbr.com.br' . "\r\n";
$headers .= "Return-Path: $email \r\n";
$envio = mail($email, $assunto, $mensagemHTML, $headers);
if ($envio)
echo "<script>alert('Cadastro realizado com sucesso!'); window.top.location.href = 'index.php';</script>";
}
exit;
?>
For your first insert query, you never execute it. No records are being created. For the second, you're preparing a statement over and over again with different values, but you only execute once at the end of it all. One of the primary reasons for using a prepared statement is so that you DO NOT put the user data directly into the SQL, as you are doing.
In addition to all that, your whole script can be shortened considerably.
<?php
require '../config.a/conexao.php';
// I don't know what you're doing here, but it's not good
$_POST["password"] = md5(uniqid(""));
// here just turn post into your parameters by prefixing key with :
foreach ($_POST as $k=>$v) {
$params[":$k"] = $v;
}
// this is a special case, but the fact that it's here means
// your database structure is no good and needs normalizing
$params[":numerosdasorte"] = implode($_POST["numerosdasorte"], ',');
// prepare the statement
$stmt = $PDO->prepare(
"INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte"
);
// no need to bind parameters, just include them as an array in the execution
$result = $stmt->execute($params);
// again, prepare a statement
$stmt = $PDO->prepare("UPDATE cota1 SET status = 1 WHERE cota = ?");
foreach($_POST["numerosdasorte"] as $value ) {
// execute it repeatedly
$stmt->execute([$value]);
}
if (!$result) {
// don't show users this stuff
var_dump($stmt->errorInfo());
} else {
// send your email
}
Try where ... in query for the update. I am assuming that $exploded has an array of numbers like [121, 122, 123];
$exploded = explode(",", $numerosdasorte); // holds only numbers in the array
Then you can do something like this:
$query = "UPDATE cota1 SET status = '1' WHERE cota in ($exploded)"; // it is similar to fire query like "UPDATE cota1 SET status = '1' WHERE cota in (121, 122, 123)"
$stmt = $PDO->prepare($query);
In that case, you don't need the foreach loop as you are passing an array directly for update.
Just a quick reference to help you https://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php

PHP - Error to push Resources from PHP to JSON nested for different resource/dayofweek

I've this resultset from SQL:
My PHP code:
function getMasterBookRoomsaAvailability(){
$DisponibilitaRoom = [
'Resource' => null,
'IntervalTime' => [],
];
$conn = new mysqli($this->servername, $this->username, $this->password,$this->MySQLDB);
$sql = "SELECT IDRoom,Nomeroom,Dayofweek,Nome,Aperto,OrarioApertura,OrarioChiusura,Durataminuti FROM room
INNER JOIN giorni ON room.IDRoom = giorni.FKRoom
INNER JOIN durategame ON room.IDRoom = durategame.FKRoom
WHERE room.Statobloccato <> 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row/*
while($row = $result->fetch_assoc()) {
$IDRoom = $row['IDRoom'];
$Nomeroom = $row['Nomeroom'];
$Dayofweek = $row['Dayofweek'];
$Nome = $row['Nome'];
$Aperto = $row['Aperto'];
$OrarioApertura = $row['OrarioApertura'];
$OrarioChiusura = $row['OrarioChiusura'];
$Durataminuti = $row['Durataminuti'];
$DisponibilitaRoom['Resource'] = $Nomeroom;
$DisponibilitaRoom['IntervalTime'][$Nome] = $this->selectTimesOfDay($OrarioApertura,$OrarioChiusura,$Durataminuti);
}
}
return $DisponibilitaRoom;
}
// Funzione: prende tutti gli orari di intervallo tra due date splittate dalla durata.
// Params: Array contenente Orario Apertura della room, Orario di chiusura della room, durata prenotabile
// Resultset: restituisce un Array contenente gli orari disponibili
function selectTimesOfDay($startTime,$endTime,$duratagame) {
$hours = null;
//var_dump($DisponibilitaRoom);
$open_time = strtotime($startTime);
$close_time = strtotime($endTime);
$duratagame = $duratagame * 60;
$output = "";
for( $i=$open_time; $i<$close_time; $i+=$duratagame) {
//if( $i < $now) continue;
$output = date("H:i",$i);
$hours[] = date('H:i', $i);
}
return $hours;
}
echo json_encode($RB->getMasterBookRoomsaAvailability());
My result is this: {"Resource":"Padel 1","IntervalTime":{"Lun":["11:00"],"Mar":["11:00"],"Mer":["11:00"],"Gio":["11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00"],"Ven":["11:00"],"Sab":["11:00"],"Sun":["09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00"]}}
but there are missing the "Tennis 1" resource and all it availability hours.
I dont know the semanthic right way, do you have any idea?
I'm expecting something like:
Resources
- Padel 1
-- LUN ['09:00','10:00','11:00']
-- MAR ['09:00','10:00']
...
- Tennis 1
-- LUN ['09:00','10:00','11:00']
-- MAR ['09:00','10:00']
I would try changing this:
$DisponibilitaRoom['Resource'] = $Nomeroom;
$DisponibilitaRoom['IntervalTime'][$Nome] = $this->selectTimesOfDay($OrarioApertura,$OrarioChiusura,$Durataminuti);
to this, to append the rooms rather than replace:
$DisponibilitaRoom[$Nomeroom]['IntervalTime'][$Nome] = $this->selectTimesOfDay($OrarioApertura,$OrarioChiusura,$Durataminuti);
The answer below was just an illustration geared towards resolving your issue.
In normal php queries you can do something like this below to get all json data returned by php
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT IDRoom,Nomeroom,Dayofweek,Nome,Aperto,OrarioApertura,OrarioChiusura,Durataminuti FROM room
INNER JOIN giorni ON room.IDRoom = giorni.FKRoom
INNER JOIN durategame ON room.IDRoom = durategame.FKRoom
WHERE room.Statobloccato <> 1";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$IDRoom = $row['IDRoom'];
$Nomeroom = $row['Nomeroom'];
$Dayofweek = $row['Dayofweek'];
$Nome = $row['Nome'];
$Aperto = $row['Aperto'];
$OrarioApertura = $row['OrarioApertura'];
$OrarioChiusura = $row['OrarioChiusura'];
$Durataminuti = $row['Durataminuti'];
$return_arr[] = array("IDRoom" => $IDRoom,
"Nomeroom" => $Nomeroom,
"Dayofweek" => $Dayofweek,
"Dayofweek" => $Dayofweek,
"Nome" => $Nome,
"Aperto" => $Aperto,
"OrarioChiusura" => $OrarioChiusura,
"OrarioChiusura" => $OrarioChiusura,
"Durataminuti" => $Durataminuti,
);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
To help answer your question, you can emulated the code above hence the emulated answer below. Try and see if it helps
//function getMasterBookRoomsaAvailability(){
$DisponibilitaRoom = [
'Resource' => null,
'IntervalTime' => [],
];
$return_arr = array();
$conn = new mysqli($this->servername, $this->username, $this->password,$this->MySQLDB);
$sql = "SELECT IDRoom,Nomeroom,Dayofweek,Nome,Aperto,OrarioApertura,OrarioChiusura,Durataminuti FROM room
INNER JOIN giorni ON room.IDRoom = giorni.FKRoom
INNER JOIN durategame ON room.IDRoom = durategame.FKRoom
WHERE room.Statobloccato <> 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row/*
while($row = $result->fetch_assoc()) {
$IDRoom = $row['IDRoom'];
$Nomeroom = $row['Nomeroom'];
$Dayofweek = $row['Dayofweek'];
$Nome = $row['Nome'];
$Aperto = $row['Aperto'];
$OrarioApertura = $row['OrarioApertura'];
$OrarioChiusura = $row['OrarioChiusura'];
$Durataminuti = $row['Durataminuti'];
$DisponibilitaRoom['Resource'] = $Nomeroom;
$DisponibilitaRoom['IntervalTime'][$Nome] = $this->selectTimesOfDay($OrarioApertura,$OrarioChiusura,$Durataminuti);
$return_arr[] = array("IDRoom" => $IDRoom,
"Nomeroom" => $Nomeroom,
"Dayofweek" => $Dayofweek,
"Dayofweek" => $Dayofweek,
"Nome" => $Nome,
"Aperto" => $Aperto,
"OrarioChiusura" => $OrarioChiusura,
"OrarioChiusura" => $OrarioChiusura,
"DisponibilitaRoom" => $Nomeroom,
"DisponibilitaRoom1" => $this->selectTimesOfDay($OrarioApertura,$OrarioChiusura,$Durataminuti)
);
}
}
return $DisponibilitaRoom;
}
// Funzione: prende tutti gli orari di intervallo tra due date splittate dalla durata.
// Params: Array contenente Orario Apertura della room, Orario di chiusura della room, durata prenotabile
// Resultset: restituisce un Array contenente gli orari disponibili
function selectTimesOfDay($startTime,$endTime,$duratagame) {
$hours = null;
//var_dump($DisponibilitaRoom);
$open_time = strtotime($startTime);
$close_time = strtotime($endTime);
$duratagame = $duratagame * 60;
$output = "";
for( $i=$open_time; $i<$close_time; $i+=$duratagame) {
//if( $i < $now) continue;
$output = date("H:i",$i);
$hours[] = date('H:i', $i);
}
return $hours;
//}
echo json_encode($return_arr);

php socket server closing port after 24h

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();
?>`

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