<?
class DataBase {

    function DataBase($parameters) {
        $this->char_conversion = array(
            chr(146) => '\'',
            chr(147) => '"',
            chr(148) => '"',
            chr(128) => 'EUR',
            chr(164) => 'EUR',
            '<'  => '&lt;',
            '>'  => '&gt;',
        );

        foreach ($parameters AS $nomecampo => $valorecampo) {
            $this->$nomecampo = $valorecampo;
        }

        $stringaconnect = 'dbname='.$this->dbname;
        if ($this->dbhost) $stringaconnect .= ' host='.$this->dbhost;
        if ($this->dbport) $stringaconnect .= ' port='.$this->dbport;
        if ($this->dbuser) $stringaconnect .= ' user='.$this->dbuser;
        if ($this->dbpassword) $stringaconnect .= ' password='.$this->dbpassword;
        $this->dblink = pg_connect($stringaconnect);

    }

    function close() {
        pg_close($this->dblink);
    }

    function select($ricerca, $tabella, $condizioni="", $ordina="", $offset="", $righe="", $outer="", $group="") {
        $query = "SELECT $ricerca FROM $tabella ";
        if (!empty($outer)) $query .= $outer.' ';
        if (!empty($condizioni)) $query .= "WHERE $condizioni ";
        if (!empty($group)) $query .= "GROUP BY $group ";
        if (!empty($ordina)) $query .= "ORDER BY $ordina ";
        if (!empty($offset)) $query .= "OFFSET $offset ";
        if (!empty($righe)) $query .= "LIMIT $righe ";
        $this->lastquery = $query;
        if ($this->debug) {
            echo $this->lastquery;
        }
        $result = pg_query($this->dblink, $query);
        if (!($result)) $this->errore = '<PRE>'.pg_last_error()."\nQuery executed: $query\n</PRE>";
        if ($this->debug and $this->errore) {
            echo $this->errore;
        }
        for($i=0; $i <pg_numrows($result); $i++) {
            $risultato[] = pg_fetch_array($result, $i, PGSQL_ASSOC);
        }
        return $risultato;
    }

    function insert($tabella, $dati) {
        if ($this->debug) {
            echo "<PRE>";print_r($dati); echo "</PRE>";return;
        }
        $nomicampo = '(';
        $valoricampo = '(';
        foreach ($dati AS $nomecampo => $valorecampo) {
            $nomicampo .= '"'.$nomecampo.'", ';
            $valoricampo .= "'".$this->myaddslashes($valorecampo)."', ";
        }
        $nomicampo = preg_replace('/, $/', ')', $nomicampo);
        $valoricampo = preg_replace('/, $/', ')', $valoricampo);
        $query = "INSERT INTO $tabella $nomicampo VALUES $valoricampo";
        $this->lastquery = $query;
        $result = pg_query($this->dblink, $query);
        if (!($result)) $this->errore = '<PRE>'.pg_last_error()."\nQuery executed: $query\n</PRE>";
    }

    function update($tabella, $where, $dati) {
        if (empty($where)) return;
        foreach ($dati AS $nomecampo => $valorecampo) {
            $update .= "$nomecampo = '".$this->myaddslashes($valorecampo)."', ";
        }
        $update = preg_replace('/, $/', '', $update);
        $query = "UPDATE $tabella SET $update WHERE $where";
        if ($this->debug) {
            echo $query;
        }
        $this->lastquery = $query;
        $result = pg_query($this->dblink, $query);
        if (!($result)) $this->errore = '<PRE>'.pg_last_error()."\nQuery executed: $query\n</PRE>";
    }

    function delete($tabella, $condizione) {
        $query = "DELETE FROM $tabella WHERE $condizione";
        if ($this->debug) {
            echo "<PRE>";print_r($query); echo "</PRE>";return;
        }
        $this->lastquery = $query;
        $result = pg_query($this->dblink, $query);
    }

    function exec($query) {
        $result = pg_query($this->dblink, $query);
        if (!($result)) $this->errore = '<PRE>'.pg_last_error()."\nQuery executed: $query\n</PRE>";
    }


    function select_province() {
        $risultato = $this->select('codice, provincia', 'province', '', 'provincia ASC');
        foreach ($risultato AS $riga) {
            $province[$riga['codice']] = array(codice => $riga['codice'], provincia => $riga['provincia']);
        }
        return $province;
    }

    function select_provincia($codice) {
        $risultato = $this->select('provincia', 'province', "codice = '$codice'");
        return $risultato[0]['provincia'];
    }

    function select_nazioni() {
        $risultato = $this->select('codice, nazione', 'nazioni', '', 'nazione ASC');
        foreach ($risultato AS $riga) {
            $nazioni[$riga['codice']] = array(codice => $riga['codice'], nazione => $riga['nazione']);
        }
        return $nazioni;
    }

    function select_nazione($codice) {
        $risultato = $this->select('nazione', 'nazioni', "codice = '$codice'");
        return $risultato[0]['nazione'];
    }

    function select_modipagamento($lingua) {
        $risultato = $this->select('codice, modopagamento', 'modipagamento', "lingua = '$lingua'", 'modopagamento ASC');
        foreach ($risultato AS $riga) {
            $modipagamento[$riga['codice']] = array(codice => $riga['codice'], modopagamento => $riga['modopagamento']);
        }
        return $modipagamento;
    }

    function select_modiarrivo($lingua) {
        $risultato = $this->select('codice, modoarrivo', 'modiarrivo', "lingua = '$lingua'", 'modoarrivo ASC');
        foreach ($risultato AS $riga) {
            $modiarrivo[$riga['codice']] = array(codice => $riga['codice'], modoarrivo => $riga['modoarrivo']);
        }
        return $modiarrivo;
    }

    function select_modopagamento($codice) {
        $risultato = $this->select('modopagamento', 'modipagamento', "codice = '$codice'");
        return $risultato[0]['modopagamento'];
    }

    function select_modoarrivo($codice) {
        $risultato = $this->select('modoarrivo', 'modiarrivo', "codice = '$codice'");
        return $risultato[0]['modoarrivo'];
    }

    function select_domande($lingua) {
        $risultato = $this->select('codice, domanda', 'domande', "lingua = '$lingua'", 'domanda ASC');
        foreach ($risultato AS $riga) {
            $domande[$riga['codice']] = array(codice => $riga['codice'], domanda => $riga['domanda']);
        }
        return $domande;
    }

    function select_sezioni($codice='', $padre='') {
        if (!empty($codice)) {
            $risultato = $this->select('*', 'sezioni', "codice = '$codice'", 'ordine asc');
        } elseif (!empty($padre)) {
            $risultato = $this->select('*', 'sezioni', "padre = '$padre'", 'ordine asc');
        } else {
            $risultato = $this->select('*', 'sezioni', "padre is null or padre = '0'", 'ordine asc');
        }
        return $risultato;
    }

    function select_sezioni_tree($padre='') {
        $risultato = $this->select_sezioni('', $padre);
        while (count($risultato) > 0) {
            $riga = array_shift($risultato);
            if ($riga[padre] > 0) {
                $array[$riga[codice]] = $array[$riga[padre]] . ' - ';
            }
            $array[$riga[codice]] .= $riga[sezione];
            if ($riga[figli] == 't') {
                $temp = $this->select_sezioni('', $riga[codice]);
                if (is_array($temp)) {
                    $temp = array_reverse($temp, TRUE);
                    foreach ($temp AS $temp2) {
                        array_unshift($risultato, $temp2);
                    }
                }
            }
        }
        return $array;
    }

    function select_sezioni_array() {
        $risultato = $this->select('codice,sezione,padre,ordine',
                        'sezioni', '', 'padre desc, ordine asc, sezione asc');
        foreach ($risultato AS $riga) {
            $stack[$riga[padre]][$riga[codice]] =
                array(
                    codice => $riga[codice],
                    sezione => $riga[sezione],
                    padre => $riga[padre],
                    ordine => $riga[ordine]
                );
            if (isset($stack[$riga[codice]])) {
                $stack[$riga[padre]][$riga[codice]][figli] = $stack[$riga[codice]];
                unset($stack[$riga[codice]]);
            }
        }
        return $stack[0];
    }


    function select_categorie($codice='', $padre='') {
        if (!empty($codice)) {
            $risultato = $this->select('*', 'categorie', "codice = '$codice'");
        } elseif (!empty($padre)) {
            $risultato = $this->select('*', 'categorie', "padre = '$padre'", 'categoria ASC');
        } else {
            $risultato = $this->select('*', 'categorie', "padre is null or padre = '0'", 'categoria ASC');
        }
        return $risultato;
    }

    function select_categorie_tree($padre='', $e='') {
        $risultato = $this->select_categorie('', $padre);
        while (count($risultato) > 0) {
            $riga = array_shift($risultato);
            if ($riga[padre] > 0) {
                $array[$riga[codice]] = $e;
            }
            $array[$riga[codice]] .= $riga[categoria];
            $temp = $this->select_categorie('', $riga[codice]);
            if (count($temp) > 0) {
                $temp = array_reverse($temp, TRUE);
                foreach ($temp AS $temp2) {
                    array_unshift($risultato, $temp2);
                }
            }
        }
        return $array;
    }

    function select_categorie_array() {
        $risultato = $this->select('codice,categoria,padre', 'categorie', '', 'padre desc, categoria asc');
        foreach ($risultato AS $riga) {
            $stack[$riga[padre]][$riga[codice]] =
                array(
                    codice => $riga[codice],
                    categoria => $riga[categoria],
                    padre => $riga[padre],
                );
            if (isset($stack[$riga[codice]])) {
                $stack[$riga[padre]][$riga[codice]][figli] = $stack[$riga[codice]];
                unset($stack[$riga[codice]]);
            }
        }
        return $stack[0];
#       return $this->add_categorie_etichette($stack[0], '', '::');
    }

    function add_categorie_etichette($categorie, $e1='', $e2='') {
        $temparray = array();
        foreach ($categorie AS $codice => $riga) {
            if (count($riga[figli]) > 0) $riga['figli'] = $this->add_categorie_etichette($riga[figli], $e2, $e2.$e2);
            $riga['etichetta'] = $e1;
            $temparray[$codice] = $riga;
        }
        return $temparray;
    }

    function select_sezione($codice) {
        $risultato = $this->select_sezioni($codice);
        return $risultato[0];
    }

    function elimina_sezione($codice) {
        /* La funzione di cancellazione sezioni è complessa, perché
           è necessario estrarre tutti i figli, cancellare tutti i
           prodotti in essi contenuti, poi cancellare i prodotti
           della sezione stessa e infine la sezione.
           Nel caso in cui la sezione cancellata sia l'unico figlio
           di un'altra sezione, è necessario anche impostare il campo
           figli a FALSE.

           Poiché non possiamo sapere dove sono le immagini del programma
           che sta chiamando questa classe, ritorneremo un array
           contenente i nomi di tutte le immagini delle sezioni
           cancellate, così che il programma possa eliminarle. */


        /* Popoliamo gli array $immagini e $sezionidacancellare.
           $listasezioni è un array di appoggio per il ciclo while. */

        $immagini = array();
        $sezionidacancellare = array();
        $listasezioni = array();

        /* Inseriamo prima di tutto i dati della sezione padre. */

        array_push($sezionidacancellare, $codice);
        array_push($listasezioni, $codice);
        $riga = $this->select_sezione($codice);
        array_push($immagini, $riga[immagine], $riga[immagine2], $riga[immagine_titolo]);

        /* In $padre inseriamo il codice della sezione padre. */

        $padre = $riga[padre];

        /* E ora cerchiamo ricorsivamente i figli */

        while (count($listasezioni) > 0) {
            $corrente = array_pop($listasezioni);
            $risultato = $this->select('codice, figli, immagine, immagine2, immagine_titolo', 'sezioni', "padre = '$corrente'");
            if ($risultato) {
                foreach ($risultato AS $riga) {
                    array_push($immagini, $riga[immagine], $riga[immagine2], $riga[immagine_titolo]);
                    array_push($sezionidacancellare, $riga[codice]);
                    if ($riga[figli] == 't') {
                        array_push($listasezioni, $riga[codice]);
                    }
                }
            }
        }

        /* A questo punto abbiamo la lista di tutte le sezioni. Dobbiamo
           fare una select per ottenere la lista dei prodotti contenuti in
           esse. */

        foreach ($sezionidacancellare AS $codicesezione) {
            $where .= "sezione = '$codicesezione' OR ";
            $wheresezioni .= "codice = '$codicesezione' OR ";
        }

        $where = ereg_replace(' OR $', '', $where);
        $wheresezioni = ereg_replace(' OR $', '', $wheresezioni);
        $risultato = $this->select('codice, immagine, immagine2', 'prodotti', $where);

        /* Inseriamo questi prodotti nell'array $prodottidacancellare e le
           relative immagini nell'array $immagini */

        $prodottidacancellare = array();

        if ($risultato) {
            foreach ($risultato AS $riga) {
                array_push($immagini, $riga[immagine], $riga[immagine2]);
                $this->elimina_prodotto($codice);
            }
        }

        /* Possiamo eseguire la cancellazione di sezioni e prodotti*/
        $this->delete('sezioni', $wheresezioni);


        /* Ora controlliamo se questa sezione era l'unico figlio
           di un'altra sezione */

        $risultato = $this->select_sezioni('', $padre);
        if (count($risultato) < 1) $this->update('sezioni', "codice = '$padre'", array(figli => 'f'));

        /* Eliminiamo le righe vuote e duplicate dall'array immagini e lo
           ritorniamo al programma che ha eseguito la cancellazione. */

        $immagini = $this->vuoti_e_duplicati($immagini);

#       echo "<PRE>Ultima query\n";print_r($risultato);echo"--Immagini:\n";print_r($immagini);echo"--sezioni da cancellare\n";print_r($sezionidacancellare);echo"--prodotti da cancellare\n";print_r($prodottidacancellare);echo "</PRE>";

        return $immagini;
    }

    function insert_foto($utente, $dati) {
        if (!isset($dati['cartella'])) {
            $risultato = $this->select('*', 'cartelle', "utente = '$utente' and cartella = 'Nuova cartella'");

            if (count($risultato) == 0) {
                $dati['cartella'] = $this->insert_cartella($utente, 'Nuova cartella');
            } else {
                $dati['cartella'] = $risultato[0]['codice'];
            }
        }

        $this->insert('foto', $dati);
        $risultato = $this->select('codice', 'foto', "cartella = '$dati[cartella]' AND img2 = '$dati[img2]'");
        return $risultato[0][codice];
    }

    function delete_foto($codice, $commenti=0) {
        $this->delete('foto', "codice = '$codice'");
        if ($commenti == 1) {
            $this->delete('commenti', "foto = '$codice'");
        }
    }

    function update_foto($foto, $dati) {
        $this->update('foto', "codice = '$foto'", $dati);
    }

    function sposta_foto($foto, $cartella) {
        $this->update_foto($foto, array(cartella => $cartella));
    }

    function select_foto_copertina() {
        $risultato = $this->select('codice', 'foto', 'copertina is true');
        if (count($risultato) > 0) {
            $foto = mt_rand(0, count($risultato)-1);
            $foto = $this->select_foto($risultato[$foto]['codice'], '', '', 4, '', 1);
            return $foto[0];
        } else {
            $risultato = $this->select('codice', 'foto');
            $foto = mt_rand(0, count($risultato)-1);
            $foto = $this->select_foto($risultato[$foto]['codice'], '', '', 4, '', 1);
            return $foto[0];
        }
    }

    function vota_foto($foto, $utente) {
        $risultato = $this->select('codice, utente, voto', 'foto', "codice = '$foto'");
        if (count($risultato) == 0) return false;

        $questafoto = $risultato[0];

        if ($questafoto['utente'] == $utente) return 1;

        $risultato = $this->select('*', 'voti', "utente = '$utente' AND foto = '$foto'");
        if (count($risultato) > 0) return 2;

        $this->insert('voti', array(utente => $utente, foto => $foto));
        $questafoto['voto']++;
        $this->update('foto', "codice = '$foto'", array(voto => $questafoto['voto']));
        return 0;
    }

    function commenta_foto($foto, $utente, $commento) {
        $risultato = $this->select('codice, utente, voto', 'foto', "codice = '$foto'");
        if (count($risultato) == 0) return false;

        $questafoto = $risultato[0];

        if ($questafoto['utente'] == $utente) return 1;

        $this->insert('commenti', array(utente => $utente, foto => $foto, commento => $commento));
        return 0;
    }

    function select_foto($codice='', $categoria='', $utente='', $a='', $cartella='', $approved=1, $limit='', $search='', $order='') {
        $where = '';
        if ($a) {
            $what = 'a.data, a.approved, a.descrizione, a.copertina, a.codice, a.titolo, a.utente, d.cartella, a.voto, a.categoria, b.categoria AS catname, c.nome, c.cognome, c.nickname, ';
            $what .= 'img'.$a.'w, ';
            $what .= 'img'.$a.'h, ';
            $what .= 'img1w, ';
            $what .= 'img1h ';
        } else {
            $what = 'a.*, b.categoria AS catname, c.nome, c.cognome, c.nickname';
        }

        if (!empty($cartella)) {
            $where = " AND a.cartella = '$cartella'";
        }

        if ($approved == 1) {
            $where .= " AND a.approved IS TRUE";
        } elseif ($approved == 2) {
            $where .= " AND a.approved IS FALSE";
        }

        if (!empty($search)) {
            $where .= ' AND (';
            $tempsearch = split(' ', $search);
            foreach ($tempsearch AS $unariga) {
                $where .= "(a.titolo ~* '$unariga' OR a.descrizione ~* '$unariga') AND ";
            }
            $where = preg_replace("/ AND $/", ')', $where);
        }

        if ($order == 'data') {
            $order = 'a.data DESC, a.voto DESC, a.titolo ASC';
        } else {
            $order = 'a.voto DESC, a.titolo ASC';
        }

        if (!empty($codice)) {
            $risultato = $this->select($what, 'foto a, categorie b, utenti c, cartelle d', "a.codice = '$codice' AND a.utente = c.codice AND a.categoria = b.codice AND a.cartella = d.codice $where");
        } elseif (!empty($categoria)) {
            $cats = $this->select_categorie('', $categoria);
            $where .= ' AND (';
            $where .= "a.categoria = '$categoria' OR ";
            if (is_array($cats)) {
                foreach ($cats AS $riga) {
                    $where .= "a.categoria = '$riga[codice]' OR ";
                }
            }
            $where = preg_replace('/ OR $/', ')', $where);
            $risultato = $this->select($what, 'foto a, categorie b, utenti c, cartelle d', "a.utente = c.codice AND a.categoria = b.codice AND a.cartella = d.codice $where", $order, '', $limit);
        } elseif (!empty($utente)) {
            $risultato = $this->select($what, 'foto a, categorie b, utenti c, cartelle d', "a.utente = c.codice AND a.categoria = b.codice AND a.utente = '$utente' AND a.cartella = d.codice $where", $order, '', $limit);
        } else {
            $risultato = $this->select($what, 'foto a, categorie b, utenti c, cartelle d', "a.utente = c.codice AND a.categoria = b.codice AND a.cartella = d.codice $where", $order, '', $limit);
        }
        return $risultato;
    }

    function select_foto_commenti($foto) {
        $risultato = $this->select('a.utente, a.commento, b.nome, b.cognome, b.nickname', 'commenti a, utenti b', "a.foto = '$foto' AND a.utente = b.codice");
        return $risultato;
    }

    function select_foto_cartelle($utente, $nuova=1, $conta=0) {
        if ($conta == 0) {
            $risultato = $this->select('*', 'cartelle', "utente = '$utente'", 'cartella ASC');
        } else {
            $risultato = $this->select('a.codice, a.cartella, count(b.codice) AS foto', 'cartelle a', "a.utente = '$utente'", 'a.cartella ASC', '', '', 'LEFT OUTER JOIN foto b ON (b.cartella = a.codice)', 'a.codice, a.cartella');
        }
        if (count($risultato) > 0) {
            $ce = 0;
            foreach ($risultato AS $riga) {
                if ($riga['cartella'] == 'Nuova cartella') $ce = 1;
            }
        }
        if ($ce != 1 and $nuova == 1) {
            $codice = $this->insert_cartella($utente, 'Nuova cartella');
            $risultato[] = array(codice => $codice, utente => $utente, cartella => 'Nuova cartella', foto => '0');
        }
        return $risultato;
    }

    function insert_cartella($utente, $cartella) {
        $this->insert('cartelle', array(utente => $utente, cartella => $cartella));
        $risultato = $this->select('codice', 'cartelle', "utente = '$utente' AND cartella = '$cartella'");
        return $risultato[0]['codice'];
    }

    function insert_sezione($sezione) {
        $this->insert('sezioni', $sezione);
        if ($sezione[padre]) {
            $this->update('sezioni', "codice = '$sezione[padre]'", array(figli => 't'));
        }
    }

    function delete_cartella($utente, $cartella) {
        $risultato = $this->select('*', 'cartelle', "utente = '$utente' and cartella = 'Nuova cartella'");
        if (count($risultato) == 0) {
            $codice = $this->insert_cartella($utente, 'Nuova cartella');
        } else {
            $codice = $risultato[0]['codice'];
        }
        $this->update('foto', "cartella = '$cartella'", array(cartella => $codice));
        $this->delete('cartelle', "codice = '$cartella'");
    }

    function update_cartella($cartella, $dati) {
        $this->update('cartelle', "codice = '$cartella'", $dati);
    }

    function select_prodotti($codice='', $sezione='', $padre='', $offertespeciali=0, $ordine='ordine ASC', $search='', $all=0, $nozero=0) {
        if ($nozero == 1) {
            $wnozero = " AND prezzo > '0'";
        } else {
            $wnozero = '';
        }

        if ($this->approvazione_prodotti == 1) {
            $wapproved = " AND approved IS TRUE AND deleted IS FALSE";
        } else {
            $wapproved = '';
        }

        if (!empty($codice)) {
            $risultato = $this->select('*', 'prodotti', "codice = '$codice' $wnozero $wapproved", $ordine);
        } elseif (!empty($sezione)) {
            $risultato = $this->select('*', 'prodotti', "sezione = '$sezione' AND (padre is null OR padre = '0') $wnozero $wapproved", $ordine);
        } elseif (!empty($padre)) {
            $risultato = $this->select('*', 'prodotti', "padre = '$padre' $wnozero $wapproved", $ordine);
        } elseif ($offertespeciali == 1) {
            $risultato = $this->select('*', 'prodotti', "offertaspeciale IS TRUE $wnozero $wapproved", $ordine);
        } elseif ($all == 1) {
            $risultato = $this->select('*', 'prodotti', '1=1'.$wnozero.$wapproved, $ordine);
        } elseif (!empty($search)) {
            $where = '';
            $tempsearch = split(' ', $search);
            foreach ($tempsearch AS $unariga) {
                $where .= "(nome ~* '$unariga' OR descrizione ~* '$unariga' OR mtcode ~* '$unariga') AND ";
            }
            $where = preg_replace("/ AND $/", '', $where);
            $where .= ' '.$wnozero.$wapproved;

            $risultato = $this->select('*', 'prodotti', $where, $ordine);
        }
        for ($i=0; $i < count($risultato); $i++) {
            if ($risultato[$i][figli] == 't') {
                $figli = $this->select('*', 'prodotti', "padre = '".$risultato[$i][codice]."' $wnozero $wapproved", 'nome asc, prezzo asc');
                $risultato[$i][dati_figli] = $figli;
            }
        }
        return $risultato;
    }

    function select_search($value, $nome=1, $descrizione=1, $and=0, $clcodice=0) {


        $valori = preg_split("/\s/", $value);

        $where = ' AND (';

        foreach ($valori AS $value) {
            $where .= '(';

            if ($nome == 1) {
                $where .= "nome ~* '$value' OR ";
            }

            if ($descrizione == 1) {
                $where .= "descrizione ~* '$value' OR ";
            }

            if ($clcodice == 1) {
                $where .= "clcodice = '$value' OR ";
            }

            $where = preg_replace('/ OR $/', '', $where);

            if ($and == 1) {
                $where .= ') AND ';
            } else {
                $where .= ') OR ';
            }
        }

        $where = preg_replace('/ OR $/', ')', $where);
        $where = preg_replace('/ AND $/', ')', $where);

        $risultato = $this->select('*', 'prodotti', "(padre is null OR padre = '0')".$where, 'ordine asc');

        for ($i=0; $i < count($risultato); $i++) {
            if ($risultato[$i][figli] == 't') {
                $figli = $this->select('*', 'prodotti', "padre = '".$risultato[$i][codice]."'", 'nome asc, prezzo asc');
                $risultato[$i][dati_figli] = $figli;
            }
        }

        return $risultato;
    }

    function select_prodotto($codice) {
        $risultato = $this->select_prodotti($codice);
        return $risultato[0];
    }

    function update_prodotto($codice, $dati) {
    $risultato = $this->update('prodotti', "codice = '$codice'", $dati);
    $risultato = $this->select('*', 'prodotti', "codice = '$codice'");
    return $risultato[0];
    }

    function select_offertespeciali() {
        $risultato = $this->select_prodotti('', '', '', 1);
        return $risultato;
    }

    function elimina_prodotto($codice) {
        $riga = $this->select_prodotto($codice);
        $immagini = array();
        array_push($immagini, $riga[immagine], $riga[immagine2]);
        $this->delete('prodotti', "codice = '$codice' OR padre = '$codice'");

        /* Ora controlliamo se questo prodotto era l'unico figlio
           di un altro prodotto */

        $risultato = $this->select_prodotti('', '', $riga[padre]);
        if (count($risultato) < 1) $this->update('prodotti', "codice = '$riga[padre]'", array(figli => 'f'));

        return $immagini;
    }

    function select_offerte() {
        $risultato = $this->select('*', 'offerte', '', 'data desc, codice desc');
        return $risultato;
    }

    function select_offerta($codice) {
        $risultato = $this->select('*', 'offerte', "codice = '$codice'");
        return $risultato[0];
    }

    function insert_offerta($dati) {
        $this->insert('offerte', $dati);
    }

    function update_offerta($codice, $dati) {
        $this->update('offerte', "codice = '$codice'", $dati);
    }

    function delete_offerta($codice) {
        $this->delete('offerte', "codice = '$codice'");
    }

    function insert_prodotto($prodotto) {
        $this->insert('prodotti', $prodotto);
        if ($prodotto[padre]) {
            $this->update('prodotti', "codice = '$prodotto[padre]'", array(figli => 't'));
        }
    }

    function listino_completo($codice='') {
        /* La funzione listino_completo parte da una sezione e ne
           ricava una lista di tutti le sottosezioni/prodotti in
           essa contenuti. Se la sezione non è indicata, estrae
           l'intero database prodotti.                  */

        /* Mettiamo in $sezioni[] il codice di questa sezione */

        $temp[] = $codice;

#       echo "<PRE>";


        /* E ora facciamo un walking ricorsivo per ottenere la lista
           di tutte le sottosezioni. */

        while (count($temp) > 0) {
            $codice = array_shift($temp);
#           echo "Lavoro sulla sezione $codice...";
#           print_r($temp);
            $risultato = $this->select_sezione($codice);

            $output[] = array(tipo => 's', nome => $risultato[sezione]);

            $prodotti = $this->select_prodotti('', $codice);

#           print_r($prodotti);

            if ($GLOBALS[attiva_codice_prodotto] == '1') {
                $mtcode = 'mtcode';
            } else {
                $mtcode = 'codice';
            }

            if ($prodotti) {
                foreach ($prodotti AS $prodotto) {
                    $output[] = array(tipo => 'p', nome => $prodotto[nome], prezzo => $prodotto[prezzo], codice => $prodotto[$mtcode], sconto => $prodotto[sconto]);
                    if ($prodotto[figli] == 't') {
                        foreach ($prodotto[dati_figli] AS $figlio) {
                            $output[] = array(tipo => 'sp', nome => $figlio[nome], prezzo => $figlio[prezzo], codice => $figlio[$mtcode], sconto => $figlio[sconto]);
                        }
                    }
                }
            }

            if ($risultato[figli] == 't') {
#               echo "ha figli.\n";
                $risultato = $this->select_sezioni('', $codice);
                foreach ($risultato AS $figlio) {
                    array_push($temp, $figlio[codice]);
                }
            } else {
#               echo "non ha figli\n";
            }
        }
#       print_r($output);
#       echo "</PRE>";

        return $output;

    }

/*  function login($username, $password) {
        $risultato = $this->select('*', 'utenti', "username = '$username' AND password = '$password' AND attivo IS TRUE");
        if ((count($risultato) > 1) or (count($risultato) < 1)) {
            $this->errore = '<PRE>Too many or too few results.</PRE>';
            return;
        } else {
            $risultato[0][securelevel] = $this->autorizza($risultato[0][securelevel]);
            return $risultato[0];
        }
    }

    function autorizza($level=1) {
            $binary = strrev(decbin($level));
            preg_match_all("/(\d)/", $binary, $bit);
            $i = 0;
            foreach ($bit[1] as $temp) {
                    if ($temp == '1') {
                            $securelevel[$this->livelli[$i]] = $this->nomilivelli[$i];
                    }
                    $i++;
        }
            return $securelevel;
    }
*/

    function vuoti_e_duplicati($array) {
        foreach ($array AS $riga) {
            if (empty($riga)) continue;
            if (isset($newarray[$riga])) continue;
            $newarray[$riga] = 1;
        }
        if ($newarray) {
            $newarray = array_keys($newarray);
            sort($newarray);
            return($newarray);
        } else {
            return null;
        }
    }

    function gestisci_immagine($immagine, $prefisso, $path, $mime=0) {
        $immaginename = $immagine."_name";
        $immaginename = $GLOBALS[$immaginename];
                $info = GetImageSize($GLOBALS[$immagine]);
        $immaginew = $info[0];
                $immagineh = $info[1];
        $immaginemime = $info['mime'];
        $nomedefinitivo = $prefisso.'-'.$immaginename;
                `mv "$GLOBALS[$immagine]" "$path/$nomedefinitivo"`;
        if ($mime) {
            return array($nomedefinitivo, $immaginew, $immagineh, $immaginemime);
        } else {
            return array($nomedefinitivo, $immaginew, $immagineh);
        }
    }

    function gestisci_allegato($allegato, $prefisso, $path, $mime=0) {
        $allegatoname = $allegato."_name";
        $allegatoname = $GLOBALS[$allegatoname];
        $nomedefinitivo = $prefisso.'-'.$allegatoname;
                `mv "$GLOBALS[$allegato]" "$path/$nomedefinitivo"`;
        if ($mime) {
            return array($nomedefinitivo, $allegatomime);
        } else {
            return array($nomedefinitivo);
        }
    }

    function gestisci_immagine_new($immagine, $prefisso, $path) {
        if ($immagine[name]) {
            $immaginename = $immagine[name];
                    $info = GetImageSize($immagine[tmp_name]);
                    $immaginew = $info[0];
                    $immagineh = $info[1];
            $nomedefinitivo = $prefisso.'-'.$immaginename;
                    `mv "$immagine[tmp_name]" "$path/$nomedefinitivo"; chmod a+r "$path/$nomedefinitivo"`;
            return array($nomedefinitivo, $immaginew, $immagineh);
        } else {
            return array(0,0,0);
        }
    }

    function elimina_file($path, $file) {
        if (is_array($file)) {
            foreach ($file AS $riga) {
                unlink($path.'/'.$riga);
            }
        } else {
            unlink($path.'/'.$file);
        }
    }

    function myaddslashes($stringa) {
        $stringa = str_replace("\'", "'", $stringa);
        $stringa = str_replace("'", "\'", $stringa);
        return $stringa;
    }

    function form_search($class="search") {
?>
<FORM METHOD="POST">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="search">
<TABLE ALIGN="CENTER" BORDER=0>
  <TR>
    <TD>
    <input type="text" class="<?=$class?>" NAME="value" size="20" VALUE="<?=$GLOBALS[value]?>">
    <input type="submit" class="<?=$class?>" VALUE="Cerca!">
    </TD>
  </TR>
</TABLE>
<?
    }

    function form_sezione($action) {
?>
<FORM METHOD="POST" ENCTYPE="multipart/form-data">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="<?=$action?>">
<?
        if ($GLOBALS[value] != 0 and $GLOBALS[enablemover] != 1) {
?>
<input type="hidden" name="padre" value="<?=$GLOBALS[value]?>">
<?
        }

        if ($GLOBALS[enablemover] == 1 and isset($GLOBALS[padre])) {
            $questa = $GLOBALS[value];
            $GLOBALS[value] = $GLOBALS[padre];
        }

        if ($GLOBALS[codice]) {
?>
<input type="hidden" name="codice" value="<?=$GLOBALS[codice]?>">
<?
        }
?>
<table align="center" cellpadding="5" cellspacing="5" width="75%" border=1>
  <tr>
    <td>
    Nome della sezione / sottosezione
    </td>
    <td>
    <input type="text" class="administration" NAME="sezione" size="40" VALUE="<?=$GLOBALS[sezione]?>">
    </td>
  </tr>
<?
    if ($GLOBALS[enablemover] == 1) {
?>
  <tr>
    <td>
    Sezione di appartenenza
    </td>
    <td>
    <SELECT NAME="padre" class="administration">
      <OPTION VALUE="">Nessuna sezione superiore
<?
    $risultato = $this->select_sezioni_tree();
    foreach ($risultato AS $codicepadre => $nomepadre) {
        if ($codicepadre == $questa) { next; }
?>
      <OPTION VALUE="<?=$codicepadre?>" <? if ($codicepadre == $GLOBALS[value]) { echo "SELECTED"; }?>><?=$nomepadre?>
<?
    }
?>
    </td>
  </tr>
<?
    }
?>
  <tr>
    <td>
    Ordine di visualizzazione
    </td>
    <td>
    <input type="text" class="administration" NAME="ordine" size="40" VALUE="<?=$GLOBALS[ordine]?>">
    </td>
  </tr>
  <tr>
    <td>
    Descrizione
    </td>
    <td>
    <textarea class="administration" NAME="descrizione" cols="40" rows="8"><?=$GLOBALS[descrizione]?></textarea>
    </td>
  </tr>
  <tr>
    <td>
    Immagine (facoltativa)
    </td>
    <td>
    <input type="file" class="administration" NAME="immagine" size="40">
    </td>
  </tr>
  <tr>
    <td>
    Seconda immagine (facoltativa, per fare il flip con la prima)
    </td>
    <td>
    <input type="file" class="administration" NAME="immagine2" size="40">
    </td>
  </tr>
  <tr>
    <td>
    Immagine titolo (facoltativa, da visualizzare come titolo)
    </td>
    <td>
    <input type="file" class="administration" NAME="immagine_titolo" size="40">
    </td>
  </tr>
  <tr>
    <TD colspan=2 align="center">
    <input type="submit" class="administration" VALUE="Inserisci/Modifica sezione/sottosezione">
    </td>
  </tr>
</TABLE>
<?
    }

    function form_prodotto($action) {
        global $helper_prog, $help;
?>
<FORM METHOD="POST" NAME="form_prodotto" ENCTYPE="multipart/form-data" ACTION="<?=$GLOBALS[modifier_prog]?>">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="<?=$action?>">
<?
        if ($GLOBALS[enablemover] != 1) {
            if ($GLOBALS[sezione]) {
?>
<INPUT TYPE="HIDDEN" NAME="sezione" VALUE="<?=$GLOBALS[sezione]?>">
<?
            } elseif ($GLOBALS[value]) {
?>
<INPUT TYPE="HIDDEN" NAME="sezione" VALUE="<?=$GLOBALS[value]?>">
<?
            }
        }

        if ($GLOBALS[sezione]) {
            $sezione = $GLOBALS[sezione];
        } elseif ($GLOBALS[value]) {
            $sezione = $GLOBALS[value];
        }
        if ($GLOBALS[codice]) {
?>
<INPUT TYPE="HIDDEN" NAME="codice" VALUE="<?=$GLOBALS[codice]?>">
<?
        }
?>
<table align="center" cellpadding="5" cellspacing="5" width="75%" border=1>
<?
        if ($GLOBALS[attiva_codice_prodotto]) {
?>
  <tr>
    <td>
    Codice prodotto
    </td>
    <td>
    <input type="text" class="administration" NAME="mtcode" size="40" VALUE="<?=$GLOBALS[mtcode]?>">
    </td>
    <td>
    <?$help->ShowImg('mtcode');?>
    </td>
  </tr>
<?
        }
?>
  <tr>
    <td>
    Nome del prodotto
    </td>
    <td>
    <input type="text" class="administration" NAME="nome" size="40" VALUE="<?=$GLOBALS[nome]?>">
    </td>
    <td>
    <?$help->ShowImg('nomeprodotto');?>
    </td>
  </tr>
<?
    if ($GLOBALS[enablemover] == 1) {
?>
  <tr>
    <td>
    Sezione di appartenenza
    </td>
    <td>
    <SELECT NAME="sezione" class="administration">
<?
    $risultato = $this->select_sezioni_tree();
#   print_r($risultato);
    foreach ($risultato AS $codicepadre => $nomepadre) {
?>
      <OPTION VALUE="<?=$codicepadre?>" <? if ($codicepadre == $sezione) { echo "SELECTED"; }?>><?=$nomepadre?>
<?
    }
?>
    </td>
  </tr>
<?
    }
?>
  <tr>
    <td>
    Ordine di visualizzazione
    </td>
    <td>
    <input type="text" class="administration" NAME="ordine" size="40" VALUE="<?=$GLOBALS[ordine]?>">
    </td>
    <td>
    <?$help->ShowImg('ordinedivisualizzazione');?>
    </td>
  </tr>
  <tr>
    <td>
    Descrizione
    </td>
    <td>
    <textarea class="administration" NAME="descrizione" cols="40" rows="8"><?=$GLOBALS[descrizione]?></textarea>
    </td>
    <td>
    <?$help->ShowImg('descrizione');?>
    </td>
  </tr>
  <tr>
    <td>
    Variazioni (facoltative, una per riga)<br><br>
    </td>
    <td>
    <textarea class="administration" NAME="variazioni" cols="40" rows="8"><?=$GLOBALS[variazioni]?></textarea>
    <br>
    Selezionare questa casella se <br>le variazioni hanno prezzi diversi
    <input type="checkbox" onClick="hide('prezzo', 'form_prodotto');" <? if (isset($GLOBALS[prezzo]) and $GLOBALS[prezzo] == 0) echo 'checked';?>>
    </td>
    <td>
    <?$help->ShowImg('variazioni');?>
    </td>
  </tr>
  <tr>
    <td>
    Peso del prodotto (in grammi)
    </td>
    <td>
    <input type="text" class="administration" NAME="peso" size="40" VALUE="<?=$GLOBALS[peso]?>">
    </td>
    <td>
    <?$help->ShowImg('peso');?>
    </td>
  </tr>
  <tr>
    <td>
    Prodotto in offerta?
    </td>
    <td>
    <input class="administration" type="radio" name="offertaspeciale" VALUE="t" <? if ($GLOBALS[offertaspeciale] == 't') echo 'checked';?>> Si
    <input class="administration" type="radio" name="offertaspeciale" VALUE="f" <? if ($GLOBALS[offertaspeciale] != 't') echo 'checked';?>> No
    </td>
    <td>
    <?$help->ShowImg('offertaspeciale');?>
    </td>
  </tr>
</table>
<br>
<div ID="prezzodiv">
<table align="center" cellpadding="5" cellspacing="5" width="75%" border=1>
  <tr>
    <td>
    Prezzo
    </td>
    <td>
    <input type="text" class="administration" NAME="prezzo" size="40" VALUE="<?=$GLOBALS[prezzo]?>">
    <input type="hidden" class="administration" NAME="prezzosave" size="40" VALUE="">
    <center><input type="button" class="administration" VALUE="Calcolatore di sconto" onClick="window.open('<?=$GLOBALS[sconto_prog]?>?form=form_prodotto&prezzo=prezzo&sconto=sconto','scontoWindow','width=200,height=200,left=200,top=200');"></center>
    </td>
    <td>
    <?$help->ShowImg('prezzoadmin');?>
    </td>
  </tr>
  <tr>
    <td>
    Sconto<br>(facoltativo, in percentuale, senza segno %)<br><br>
    </td>
    <td>
    <input type="text" class="administration" NAME="sconto" size="40" VALUE="<?=$GLOBALS[sconto]?>"><br>
    </td>
    <td>
    <?$help->ShowImg('scontoadmin');?>
    </td>
  </tr>
</table>
</div>
<br>
<table align="center" cellpadding="5" cellspacing="5" width="75%" border=1>
  <tr>
    <td>
    Immagine del prodotto
    </td>
    <td>
    <input type="file" class="administration" NAME="immagine" size="30">
<?
        if ($action == 'modifica_prodotto_ok') {
?>
    <br><B>Attenzione:</b> Inserire solo se si desidera modificare l'immagine già esistente.
<?
        }
?>
    </td>
    <td>
    <?$help->ShowImg('immagineprodotto');?>
    </td>
  </tr>
  <tr>
    <td>
    Immagine <b>zoom</b> del prodotto (facoltativa)
    </td>
    <td>
    <input type="file" class="administration" NAME="immagine2" size="30">
<?
        if ($action == 'modifica_prodotto_ok') {
?>
    <br><B>Attenzione:</b> Inserire solo se si desidera modificare l'immagine già esistente.
<?
        }
?>
    </td>
    <td>
    <?$help->ShowImg('immagine2prodotto');?>
    </td>
  </tr>
  <tr>
    <TD colspan=3 align="center">
    <input type="submit" class="administration" VALUE="Inserisci/Modifica prodotto">
    </td>
  </tr>
</TABLE>
<?
    if (isset($GLOBALS[prezzo]) and $GLOBALS[prezzo] == 0) {
?>
<SCRIPT LANGUAGE="JavaScript">
hide('prezzo', 'form_prodotto');
</SCRIPT>
<?
    }
?>
<?
    }

    function form_variazioni($action, $codice, $variazioni) {
        global $helper_prog, $help;
        $i = 0;
?>
<FORM METHOD="POST" NAME="form_variazioni">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="<?=$action?>">
<INPUT TYPE="HIDDEN" NAME="codice" VALUE="<?=$codice?>">
<INPUT TYPE="HIDDEN" NAME="quantevariazioni" VALUE="<?=count($variazioni)?>">
<table align="center" cellpadding="5" cellspacing="5" width="75%" border=1>
  <tr>
    <td ALIGN="CENTER">
    <b>Variazione</b>
    </td>
    <td ALIGN="CENTER">
    <b>Prezzo</b>
    </td>
    <td ALIGN="CENTER">
    <b>Sconto</b>
    </td>
    <td ALIGN="CENTER">
    <b>Help</b>
    </td>
  </tr>
<?
        foreach ($variazioni AS $variazione) {
            $i++;
?>
  <tr>
    <td ALIGN="CENTER">
    <input type="hidden" NAME="codice<?=$i?>" VALUE="<?=$variazione[codice]?>">
    <textarea class="administration" NAME="variazioni<?=$i?>" rows="3" cols="30"><?=$variazione[nome]?></textarea>
    </td>
    <td ALIGN="CENTER">
    <input type="text" class="administration" NAME="prezzi<?=$i?>" VALUE="<?=$variazione[prezzo]?>" SIZE="10"><br>
    <input type="button" class="administration" VALUE="C/S" onClick="window.open('<?=$GLOBALS[sconto_prog]?>?form=form_variazioni&prezzo=prezzi<?=$i?>&sconto=sconti<?=$i?>','scontoWindow','width=200,height=200,left=200,top=200');">
    </td>
    <td ALIGN="CENTER" VALIGN="TOP">
    <input type="text" class="administration" NAME="sconti<?=$i?>" VALUE="<?=$variazione[sconto]?>" SIZE="10">
    </td>
    <td ALIGN="CENTER" VALIGN="MIDDLE">
    <?$help->ShowImg('formvariazioni');?>
    </td>
  </tr>
<?
        }
?>
  <tr>
    <TD COLSPAN="6" ALIGN="CENTER">
    <input type="submit" VALUE="Inserisci/Modifica variazioni" class="administration">
    </TD>
  </tr>
</table>
<script language="JavaScript">
document.form_variazioni.prezzi1.focus();
</script>
<?
    }

    function form_conferma($action, $value) {
?>
<TABLE ALIGN="CENTER" WIDTH="100%">
  <tr>
    <td ALIGN="CENTER">
        <FORM METHOD="POST">
        <INPUT TYPE="SUBMIT" VALUE="SI" CLASS="administration">
        <input type="hidden" name="value" value="<?=$value?>">
        <input type="hidden" name="action" value="<?=$action?>">
        </FORM>
    </td>
    <td ALIGN="CENTER">
        <form>
        <input type="button" class="administration" value="NO" onClick="javascript:history.back();">
        </form>
    </td>
  </tr>
</TABLE>

<?

    }

    function alterna_colori($lock=0) {
        if ($lock == 0) {
            $this->colori['temp'] = $this->colori['a'];
            $this->colori['c'] = $this->colori['a'];
            $this->colori['a'] = $this->colori['b'];
            $this->colori['b'] = $this->colori['c'];
        }
        return $this->colori['temp'];
    }

    function set_alterni($array=array()) {
        $this->valorialternati = $array;
    }

    function alterna($lock=0) {
        if ($lock == 0) {
        $valore = array_shift($this->valorialternati);
        $this->valorialternati[] = $valore;
        }
        return $this->valorialternati[0];
    }

    function despam($a) {
        return str_replace('@', '[at]', $a);
    }

    function add_temp_file($dati, $mime, $w='0', $h='0', $nomefile='') {
        $ora = time();
        if ($this->salva_nomefile == 1) {
            $risultato = $this->insert('temp_files', array(data => $ora, file => $dati, mime => $mime, w => $w, h => $h, nomefile => $nomefile));
        } else {
            $risultato = $this->insert('temp_files', array(data => $ora, file => $dati, mime => $mime, w => $w, h => $h));
        }
        $risultato = $this->select('codice', 'temp_files', "data = '$ora' AND file = '$dati'");
        return $risultato[0]['codice'];
    }

    function get_temp_file($file) {
        $risultato = $this->select('*', 'temp_files', "codice = '$file'");
        if (count($risultato) > 0) {
            if ($this->salva_nomefile == 1) {
                return array($risultato[0]['file'], $risultato[0]['mime'], $risultato[0]['w'], $risultato[0]['h'], $risultato[0]['nomefile']);
            } else {
                return array($risultato[0]['file'], $risultato[0]['mime'], $risultato[0]['w'], $risultato[0]['h']);
            }
        } else {
            return false;
        }
    }

    function clean_temp_files() {
        $timetodelete = time() - 60*60; // cancella i tempfile più vecchi di un'ora
        $this->delete('temp_files', "data < '$timetodelete'");
    }

    function resize_foto($foto, $mime, $w=0, $h=0) {
        $temppath = $GLOBALS['temppath'];
        $filename = $temppath.'/'.time().getmypid();
        $newfile = $temppath.'/new-'.time().getmypid();

        $fh = fopen($filename, 'w');
        fwrite($fh, base64_decode($foto));
        fclose($fh);

        $tempdata = getimagesize($filename);
        if ($tempdata[0] <= $w) {
            return array(
                file => $this->add_temp_file($foto, $mime, $w, $h),
                data => $foto,
                mime => $mime,
                w => $tempdata[0],
                h => $tempdata[1],
            );
        }


        `/usr/bin/convert -scale $w $filename $newfile`;

        $tempdata = getimagesize($newfile);
        $array['w'] = $tempdata[0];
        $array['h'] = $tempdata[1];
        $array['mime'] = mime_content_type($newfile);
        $array['data'] = base64_encode(file_get_contents($newfile));
        $array['file'] = $this->add_temp_file($array['data'], $array['mime'], $array['w'], $array['h']);

        unlink($filename);
        unlink($newfile);

        return $array;
    }

    function resize_foto_gd($foto, $mime, $w=0) {
        $src = imageCreateFromString(base64_decode($foto));

        $srcw = imagesx($src);
        $srch = imagesy($src);

        if ($srcw <= $w) {
            return array(
                file => $this->add_temp_file($foto, $mime, $srcw, $srch),
                data => $foto,
                mime => $mime,
                w => $srcw,
                h => $srch,
            );
        }

        $h = floor($w*$srch/$srcw);

        $im = imageCreateTrueColor($w, $h);
        imageCopyResampled ($im, $src, 0, 0, 0, 0, $w, $h, $srcw, $srch);
        imagedestroy($src);

        ob_start();
        imagepng($im);
        $data = base64_encode(ob_get_contents());
        ob_end_clean();

        imagedestroy($im);

        $array['w'] = $w;
        $array['h'] = $h;
        $array['mime'] = 'image/png';
        $array['data'] = $data;
        $array['file'] = $this->add_temp_file($array['data'], $array['mime'], $array['w'], $array['h']);

        return $array;
    }

    function resample_foto_gd($foto, $mime, $w=0, $h=0) {
        if ($w==0 and $h==0) return false;

        $src = imageCreateFromString(base64_decode($foto));

        $srcw = imagesx($src);
        $srch = imagesy($src);

        if ($srcw <= $w and $srch <= $h) {
            return array(
                file => $this->add_temp_file($foto, $mime, $srcw, $srch),
                data => $foto,
                mime => $mime,
                w => $srcw,
                h => $srch,
            );
        }

        if ($srcw > $srch) {
            // foto larga e bassa
            $h = floor($w*$srch/$srcw);
        } else {
            $w = floor($h*$srcw/$srch);
        }

        $im = imageCreateTrueColor($w, $h);
        imageCopyResampled ($im, $src, 0, 0, 0, 0, $w, $h, $srcw, $srch);
        imagedestroy($src);

        ob_start();
        imagepng($im);
        $data = base64_encode(ob_get_contents());
        ob_end_clean();

        imagedestroy($im);

        $array['w'] = $w;
        $array['h'] = $h;
        $array['mime'] = 'image/png';
        $array['data'] = $data;
        $array['file'] = $this->add_temp_file($array['data'], $array['mime'], $array['w'], $array['h']);

        return $array;
    }

    function foto2temp($foto, $name, &$array) {
        $risultato = $this->select('*', 'foto', "codice = '$foto'");
        $risultato = $risultato[0];
        $array[$name] = 't-'.$this->add_temp_file($risultato['img1'], $risultato['img1mime'], $risultato['img1w'], $risultato['img1h']);
        $array[$name.'w'] = $risultato['img1w'];
        $array[$name.'h'] = $risultato['img1h'];

        for ($i=2;$i<5;$i++) {
            $array[$name.$i] = 't-'.$this->add_temp_file($risultato['img'.$i], $risultato['img'.$i.'mime'], $risultato['img'.$i.'w'], $risultato['img'.$i.'h']);
            $array[$name.$i.'w'] = $risultato['img'.$i.'w'];
            $array[$name.$i.'h'] = $risultato['img'.$i.'h'];
        }
    }

    function temp2foto($campo, $name, &$array, &$tounset) {
        $i=1;
        list($null, $file) = explode('-', $tounset[$campo]);
        list ($array[$name.$i], $array[$name.$i.'mime'], $array[$name.$i.'w'], $array[$name.$i.'h']) = $this->get_temp_file($file);

        unset($tounset[$campo]);
        unset($tounset[$campo.'w']);
        unset($tounset[$campo.'h']);
        unset($tounset[$campo.'mime']);
        unset($tounset[$campo.'data']);

        for ($i=2;$i<5;$i++) {
            list($null, $file) = explode('-', $tounset[$campo.$i]);
            list ($array[$name.$i], $array[$name.$i.'mime'], $array[$name.$i.'w'], $array[$name.$i.'h']) = $this->get_temp_file($file);

            unset($tounset[$campo.$i]);
            unset($tounset[$campo.$i.'w']);
            unset($tounset[$campo.$i.'h']);
            unset($tounset[$campo.$i.'mime']);
            unset($tounset[$campo.$i.'data']);
        }
    }


    function verifica_dati(&$dati, $controllo) {

        $temppath = $GLOBALS['temppath'];
        $stringhe = $GLOBALS['localization'][$GLOBALS['activelocale']];

        foreach ($controllo AS $campo => $daticampo) {

            if ($daticampo['tipo'] == 'file') {
                if ($dati[$campo.'del'] != 't') {
                    if ($daticampo['obbligatorio'] == 't' and
                        (($_FILES[$campo]['name'] == '' or
                          $_FILES[$campo]['name'] == 'none' or
                          $_FILES[$campo]['tmp_name'] == ''
                         ) and
                         !isset($dati[$campo.'old']) and
                         !isset($dati[$campo.'temp'])
                        )
                       ) {
                        $array = array(
                            0 => 'nak',
                            1 => $stringhe['campomancante'].$stringhe[$campo],
                            2 => $campo,
                        );
                        return $array;
                    }

                    if ($_FILES[$campo]['name'] and file_exists($_FILES[$campo]['tmp_name'])) {
                        if ($daticampo['immagine'] == 't') {
                            $tempdata = getimagesize($_FILES[$campo]['tmp_name']);
                            if ($tempdata) {
                                $dati[$campo.'w'] = $tempdata[0];
                                $dati[$campo.'h'] = $tempdata[1];
                                $array[$campo.'w'] = $tempdata[0];
                                $array[$campo.'h'] = $tempdata[1];
                                if ($tempdata[2] == 2) {
                                    $im = @imagecreatefromjpeg($_FILES[$campo]['tmp_name']);
                                    if ($im) {
                                        ob_start();
                                        imagepng($im);
                                        $dati[$campo.'data'] = base64_encode(ob_get_contents());
                                        ob_end_clean();
                                        $dati[$campo.'mime'] = 'image/png';
                                    } else {
                                        $array = array(
                                            0 => 'nak',
                                            1 => $stringhe['imgpngjpg'].$stringhe[$campo],
                                            2 => $campo,
                                        );
                                        return $array;
                                    }
                                } elseif ($tempdata[2] == 3) {
                                    $im = @imagecreatefrompng($_FILES[$campo]['tmp_name']);
                                    if ($im) {
                                        ob_start();
                                        imagepng($im);
                                        $dati[$campo.'data'] = base64_encode(ob_get_contents());
                                        ob_end_clean();
                                        $dati[$campo.'mime'] = 'image/png';
                                    } else {
                                        $array = array(
                                            0 => 'nak',
                                            1 => $stringhe['imgpngjpg'].$stringhe[$campo],
                                            2 => $campo,
                                        );
                                        return $array;
                                    }
                                } else {
                                    $array = array(
                                        0 => 'nak',
                                        1 => $stringhe['imgpngjpg'].$stringhe[$campo],
                                        2 => $campo,
                                    );
                                    return $array;
                                }
                            } else {
                                $array = array(
                                    0 => 'nak',
                                    1 => $stringhe['imgpngjpg'].$stringhe[$campo],
                                    2 => $campo,
                                );
                                return $array;
                            }
                        } else {
                            $dati[$campo.'data'] = base64_encode(file_get_contents($_FILES[$campo]['tmp_name']));
                            $finfo_res = finfo_open(FILEINFO_MIME);
                            $dati[$campo.'mime'] = finfo_file($finfo_res, $_FILES[$campo]['tmp_name']);
                            finfo_close($finfo_res);
                        }
                        $array[$campo.'mime'] = $dati[$campo.'mime'];
                        $array[$campo.'data'] = $dati[$campo.'data'];
                        if ($this->salva_nomefile == 1) {
                            $array[$campo.'nomefile'] = $_FILES[$campo]['name'];
                            $dati[$campo.'nomefile'] = $_FILES[$campo]['name'];
                            $dati[$campo] = $this->add_temp_file($array[$campo.'data'], $dati[$campo.'mime'], $dati[$campo.'w'], $dati[$campo.'h'], $dati[$campo.'nomefile']);
                        } else {
                            $dati[$campo] = $this->add_temp_file($array[$campo.'data'], $dati[$campo.'mime'], $dati[$campo.'w'], $dati[$campo.'h']);
                        }
                        $dati[$campo] = 't-'.$dati[$campo];
                        $array[$campo] = $dati[$campo];
                    } elseif ($dati[$campo.'old']) {
                        list($null, $dati[$campo]) = explode('-', $dati[$campo.'old']);
                        if ($this->salva_nomefile == 1) {
                            list($dati[$campo.'data'], $dati[$campo.'mime'], $dati[$campo.'w'], $dati[$campo.'h'], $dati[$campo.'nomefile']) = $this->get_temp_file($dati[$campo]);
                        } else {
                            list($dati[$campo.'data'], $dati[$campo.'mime'], $dati[$campo.'w'], $dati[$campo.'h']) = $this->get_temp_file($dati[$campo]);
                        }
                        $dati[$campo] = 't-'.$dati[$campo];
                        $array[$campo] = $dati[$campo];
                        $array[$campo.'data'] = $dati[$campo.'data'];
                        $array[$campo.'mime'] = $dati[$campo.'mime'];
                        if ($this->salva_nomefile == 1) {
                            $array[$campo.'nomefile'] = $dati[$campo.'nomefile'];
                        }
                        $array[$campo.'w'] = $dati[$campo.'w'];
                        $array[$campo.'h'] = $dati[$campo.'h'];
                    }

                    continue;

                }
            }


            $mancante = 0;
            if ($daticampo['obbligatorio'] == 't') {
                if ($daticampo['tipo'] == 'multi') {
                    if  (!is_array($dati[$campo]) or count($dati[$campo] == '') < 1) $mancante = 1;

                } else {
                    if  (!isset($dati[$campo]) or $dati[$campo] == '' or empty($dati[$campo])) $mancante = 1;
                }

                if ($mancante == 1) {
                    $array = array(
                        0 => 'nak',
                        1 => $stringhe['campomancante'].$stringhe[$campo],
                        2 => $campo,
                    );
                    return $array;
                }
            }

            if ($daticampo['tipo'] == 'date' and (!isset($dati[$campo]) or $dati[$campo] == '' or empty($dati[$campo]))) {
                continue;
            }

            if (isset($dati[$campo]) and $dati[$campo] != '' and !empty($dati[$campo])) {

                if ($daticampo['checkvalore'] == 't') {
                    if (
                        ($dati[$campo] < $daticampo['valoremin'])
                        or
                        ($dati[$campo] > $daticampo['valoremax'])
                       ) {
                        $array = array(
                            0 => 'nak',
                            1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['valoretra'].$daticampo['valoremin'].' '.$stringhe['e'].$daticampo['valoremax'].'.',
                            2 => $campo,
                        );

                        return $array;
                    }
                }

                if ($daticampo['checklunghezza'] == 't') {
                    if (
                        (strlen($dati[$campo]) < $daticampo['lunghezzamin'])
                        or
                        (strlen($dati[$campo]) > $daticampo['lunghezzamax'])
                       ) {
                        $array = array(
                            0 => 'nak',
                            1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['deveavereda'].$daticampo['lunghezzamin'].' '.$stringhe['a'].$daticampo['lunghezzamax'].' '.$stringhe['caratteri'].'.',
                            2 => $campo,
                        );

                        return $array;
                    }
                }

                if (isset($daticampo['tipo'])) {
                    if ($daticampo['tipo'] == 'alnum' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:alnum:]\.,\s]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['erralnum'],
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'date' and (isset($dati[$campo]) and $dati[$campo] != '' and !empty($dati[$campo]))) {
                        $tempresult = preg_match('/^([[:digit:]]{1,2})\/([[:digit:]]{1,2})\/([[:digit:]]{4})$/', $dati[$campo], $tempdate);
                        if ($tempresult == 0 or !checkdate($tempdate[2], $tempdate[1], $tempdate[3])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errdate'],
                                2 => $campo,
                            );
                            return $array;
                        }
                        $array[$campo] = $tempdate[3].'-'.$tempdate[2].'-'.$tempdate[1];
                        continue;
                    } elseif ($daticampo['tipo'] == 'text' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        $dati[$campo] = strtr($dati[$campo], $this->char_conversion);
                        if (!preg_match('/^[[:print:]àèìòùé\n\s\t]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errtext'],
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'prezzo' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:digit:]\.,]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errprezz'],
                                2 => $campo,
                            );
                            return $array;
                        }
                        $dati[$campo] = preg_replace('/,/', '.', $dati[$campo]);
                    } elseif ($daticampo['tipo'] == 'prezzoreal' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:digit:]\.,+-]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errprezz'],
                                2 => $campo,
                            );
                            return $array;
                        }
                        $dati[$campo] = preg_replace('/,/', '.', $dati[$campo]);
                    } elseif ($daticampo['tipo'] == 'digit' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:digit:]]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errdigit'].'.',
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'telefono' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:digit:]\.\+\-\s]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errphone'].'.',
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'telefonostrict' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:digit:]\+]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errphonestrict'].'.',
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'email' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[A-Z0-9\._%-]+@[A-Z0-9\._%-]{2,}\.[A-Z]{2,4}$/', strtoupper($dati[$campo]))) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['nonvalido'].'.',
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'list' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        $valorivari = explode(';', $daticampo['valori']);
                        if (!in_array($dati[$campo], $valorivari)) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['valnonprop'].'.',
                                2 => $campo,
                            );
                            return $array;
                        }
                    } elseif ($daticampo['tipo'] == 'multitext' and (isset($dati[$campo]) and $dati[$campo] != '')) {
                        if (!preg_match('/^[[:print:]àèìòùé\n\s\t]+$/', $dati[$campo])) {
                            $array = array(
                                0 => 'nak',
                                1 => $stringhe['campoerrato'].$stringhe[$campo].' '.$stringhe['errtext'],
                                2 => $campo,
                            );
                            return $array;
                        }
                        $array[$campo] = preg_replace("/\r/", '', $dati[$campo]);
                        $temparray = explode("\n", $array[$campo]);
                        foreach ($temparray AS $unariga) {
                            if (empty($unariga)) continue;
                            $outarray[] = $unariga;
                        }
                        $array[$campo] = implode(';', $outarray);
                        continue;
                    } elseif ($daticampo['tipo'] == 'multi' and (is_array($dati[$campo]) and count($dati[$campo]) > 0)) {
                        $array[$campo] = implode(';', $dati[$campo]);
                        continue;
                    }
                }

            }

            $array[$campo] = $dati[$campo];

        }

        $array[0] = 'ok';
        return $array;

    }

    function menu_javascript($start,$text,$dim,$url,$valore='codice',$testo='sezione',$array) {
        foreach ($array AS $riga) {
?>
    <?=$text?>_<?=$start?>=new Array("<?=$this->myaddslashes($riga[$testo])?>","<?=$url.$riga[$valore]?>","", <?=count($riga['figli'])?><? if($start == 1) echo ",$dim";?>);
<?
            if (isset($riga[figli])) {
                $this->menu_javascript(1,$text.'_'.$start,$dim,$url,$valore,$testo,$riga[figli]);
            }
            $start++;
        }
        }

    function time_elapsed($startstop=0, $print=0) {
        $mtime = microtime();
        $mtime = explode(" ",$mtime);
        $mtime = $mtime[1] + $mtime[0];

        if ($startstop == 0) {
            $this->elapsed_start = $mtime;
        } else {
            $this->elapsed_end = $mtime;
            $this->elapsed_totaltime = ($this->elapsed_end - $this->elapsed_start);
        }

        if ($print == 1) {
            printf ("Pagina generata in in %f secondi.", $this->elapsed_totaltime);
        }
    }
}
?>
