Subversion Repositories eFlore/Applications.cel

Rev

Rev 1914 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php

global $champs;
$champs = Array(
        'nom_sel' => 'Espèce',
        'nom_sel_nn' => 'Numéro nomenclatural',
        'nom_ret' => 'Nom retenu',
        'nom_ret_nn' => 'Numéro nomenclatural nom retenu',
        'nt' => 'Numéro taxonomique',
        'famille' => 'Famille',
        'nom_referentiel' => 'Referentiel taxonomique',
        'zone_geo' => 'Commune',
        'ce_zone_geo' => 'Identifiant Commune',
        'date_observation' => 'Date',
        'lieudit' => 'Lieu-dit',
        'station' => 'Station',
        'milieu' => 'Milieu',
        'commentaire' => 'Notes',
        'latitude' => 'Latitude',
        'longitude' => 'Longitude',
        'altitude' => 'Altitude',
        'geodatum' => 'Référentiel Géographique',

        'ordre' => 'Ordre',
        'id_observation' => 'Identifiant',

        'mots_cles_texte' => 'Mots Clés',

        'date_creation' => 'Date Création',
        'date_modification' => 'Date Modification',

        'transmission' => 'Transmis',
        'date_transmission' => 'Date Transmission',
        'abondance' => 'Abondance',
        'certitude' => 'Certitude',
        'phenologie' => 'Phénologie',
        'images' => 'Image(s)',
        'nom_commun' => 'Nom Commun',

        'observateur' => 'Observateur',
);

define('URLPREFIX', 'service:cel:');

function cel_get_obs() {
        $URL = DOMAIN . '/' . URLPREFIX . 'InventoryObservationList/' . USER;
        // 5000 (memory_limit)
        return json_decode(file_get_contents($URL . '/?limite=5000&numero_page=0'));
}

function cel_get_images() {
        $URL = DOMAIN . '/' . URLPREFIX . 'InventoryImageList/' . USER;
        return json_decode(file_get_contents($URL . '/?limite=100000&numero_page=0'));
}

function cel_delete_obs($obs) {
        $URL = DOMAIN . '/' . URLPREFIX . 'InventoryObservationList/' . USER;
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $URL . '/' . implode(',', $obs));
        curl_setopt($ch,CURLOPT_POSTFIELDS, array('action' => 'DELETE'));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);

        if(DEBUG) @fwrite(STDERR, sprintf("curl -F action=DELETE '%s/%s'\n", $URL, implode(',', $obs)));
        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}

function cel_delete_image($img) {
        $URL = DOMAIN . '/' . URLPREFIX . 'InventoryImageList/' . USER;
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $URL . '/' . implode(',', $img));
        curl_setopt($ch,CURLOPT_POSTFIELDS, array('action' => 'DELETE'));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}


function cel_delete_all_obs() {
    while( ($obs = cel_get_obs()) ) {
        $ordres = array_map(function($item) { return $item->ordre; }, $obs);
        // les chunks permettent d'éviter des REQUEST-URI too long (500 id * 4 digits + 500 (virgules)) < 4k
        while( $ordres_chunk = array_splice($ordres, 0, 500)) {
            cel_delete_obs($ordres_chunk);
        }
    }
}


function cel_delete_all_images() {
        $img = cel_get_images();
        $ids = array_map(function($item) { return $item->id_image; }, $img);
        cel_delete_image($ids);
}

function cel_upload_image($file) {
        if(! file_exists($file)) return NULL;
        $URL = DOMAIN . '/' . URLPREFIX . 'InventoryImage';

        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_POSTFIELDS, array(
                'file' => '@' . $file,
                'ce_utilisateur' => USER
        ));

        //curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        //execute post
        if(DEBUG) @fwrite(STDERR, sprintf("curl -F file=@%s '%s'\n", $file, $URL));

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}

function cel_link_images($user, $id_image, $id_obs) {
        $URL = DOMAIN . '/' . URLPREFIX . 'inventoryImageLink/';
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_POSTFIELDS, array(
                'id_image' => $id_obs,
                'id_observation' => $id_obs,
                'ce_utilisateur' => $user
        ));

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}


function auth() {
        // TODO: CURLOPT_NETRC + Cel API support
        if(!defined('EMAIL') || !defined('PASS') || ! EMAIL || ! PASS) return FALSE;
        if(defined('COOKIE') && COOKIE) return TRUE;
        $URL = DOMAIN . '/' . URLPREFIX . 'User/' . EMAIL . '/' . PASS;

        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_HEADER, true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);

        $result = curl_exec($ch);
        curl_close($ch);
        $sess = $id = array();
        preg_match('/.*PHPSESSID=(\w+)/', $result, $sess);
        preg_match('/"id_utilisateur":"(\d+)"/', $result, $id);

        if(DEBUG) @fwrite(STDERR, "curl \"".$URL ."\" : {$sess[1]} / {$id[1]}\n");
        if(isset($sess[1])) {
                define('COOKIE', $sess[1]);
                if(!defined('USER')) {
                        if(!isset($id[1])) return FALSE;
                        define('USER', $id[1]);
                }
                return TRUE;
        }
        return FALSE;
}

function genCSV($d = Array()) {
        $out = fopen("php://temp", 'r+');
        // don't filter-out unknown field (for testing)
        // $d = array_intersect_key($d, $GLOBALS['champs']);
        $head = array();
        foreach($d as $k => $v) {
                if(isset($GLOBALS['champs'][$k])) $head[$GLOBALS['champs'][$k]] = $v;
                else $head[$k] = $v;
        }
        fputcsv($out, array_keys($head) , ',', '"');
        fputcsv($out, array_values($head) , ',', '"');
        rewind($out);
        $csv = stream_get_contents($out);
        fclose($out);
        return $csv;
}

function import($d) {
        $URL = DOMAIN . '/' . URLPREFIX . 'ImportXLS';
        if(!is_file($d)) return FALSE;
        $ch = curl_init();

        // curl does not support setting filename="X.csv";type=application/octet-stream'
        // with plain POST variables

        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_POSTFIELDS, array(
                'upload' => '@' . $d . ';filename=test.csv',
                'utilisateur' => USER
        ));

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);

        if(DEBUG) fwrite(STDERR, "curl -F \"upload=@$d;filename=test.csv\" -F utilisateur=" . USER . " \"$URL\"\n");

        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}

function importXLS($d) {
        $URL = DOMAIN . '/' . URLPREFIX . 'ImportXLS';
        if(!is_file($d)) return FALSE;
        exec("csvtool -o /tmp/a.csv col 1- $d");
        exec(__DIR__ . "/bin/csv2xls -v 0 -f -o /tmp/a /tmp/a.csv &>/dev/null");
        if(DEBUG) fwrite(STDERR,
                                         "csvtool -o /tmp/a.csv col 1- $d;\n" . 
                                         __DIR__ . "/bin/csv2xls -v 0 -f -o /tmp/a /tmp/a.csv\n");
        $d = "/tmp/a.xls";
        if(!is_file($d)) { die('error: ' . __FILE__ . ':' . __LINE__); }

        $ch = curl_init();

        // curl does not support setting filename="X.csv";type=application/octet-stream'
        // with plain POST variables

        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_POSTFIELDS, array(
                'upload' => '@' . $d . ';filename=test.xls',
                'utilisateur' => USER
        ));

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);

        if(DEBUG) fwrite(STDERR, "curl -F \"upload=@$d;filename=test.xls\" -F utilisateur=" . USER . " \"$URL\"\n");

        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}

function export($cols = "standard,avance") {
        if(!defined('COOKIE')) return FALSE;

        $URL = DOMAIN . '/' . URLPREFIX . 'CelWidgetExport/export?';
        $URL .= http_build_query(array('colonnes' => $cols,
                                                                   'id_utilisateur' => USER,
                                                                   'format' => 'csv'));
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_COOKIE, 'PHPSESSID=' . COOKIE);

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);

        if(DEBUG) fwrite(STDERR, "curl -b PHPSESSID=" . COOKIE . ' "' . $URL ."\"\n");
        //execute post
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
}

function exportXLS($cols = "standard,avance") {
        if(!defined('COOKIE')) return FALSE;

        $file = "/tmp/b.xls";

        $URL = DOMAIN . '/' . URLPREFIX . 'CelWidgetExport/export?';
        $URL .= http_build_query(array('colonnes' => $cols,
                                                                   'id_utilisateur' => USER,
                                                                   'format' => 'xls'));
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $URL);
        curl_setopt($ch,CURLOPT_COOKIE, 'PHPSESSID=' . COOKIE);

        $fh = fopen($file, 'w'); 
        curl_setopt($ch,CURLOPT_FILE, $fh);

        if(DEBUG) fwrite(STDERR, "curl -o $file -b PHPSESSID=" . COOKIE . ' "' . $URL ."\"\n");
        //execute post
        curl_exec($ch);

        fflush($fh); 
        fclose($fh);
        curl_close($ch);

        // if(DEBUG) fwrite(STDERR, "xls2csv $file\n");
        // exec("xls2csv $file", $result, $ret);
        // return implode("\n", $result);
        if(DEBUG) fwrite(STDERR, __DIR__ . "/bin/xls2csv-separate-sheets.pl -i $file\n");
        exec(__DIR__ . "/bin/xls2csv-separate-sheets.pl -i $file &>/dev/null", $result, $ret);
        $newfile = substr($file, 0, -4) . '-Liste' . '.csv';

        // because xls2csv-separate-sheets.pl does latin9
        if(DEBUG) fwrite(STDERR, "iconv -f latin9 -t utf8 $newfile >| /tmp/.x; mv -f /tmp/.x $newfile\n");
        exec("iconv -f latin9 -t utf8 -o /tmp/.x $newfile; mv -f /tmp/.x $newfile");
        if($ret) die('error: ' . __FILE__ . ':' . __LINE__);

        return file_get_contents($newfile);
}

function getCSV_line($csv, $line) {
        $line = max(0, intval($line - 1)); // -1 à cause du header

        $out = fopen("php://temp", 'rw');
        fwrite($out, $csv);
        rewind($out);

        $head = champsLongToShort(fgetcsv($out));
        while ($line--) fgetcsv($out);
        $l = fgetcsv($out);
        fclose($out);
        if(!$l) return FALSE;
        // xls2csv-separate-sheets.pl supprime les trailing champs vides
        if(count($l) != count($head)) {
                $l += array_fill(count($l), count($head) - count($l), "");
        }
        return array_combine($head, $l);
}


function champsLongToShort($a) {
    if(! $a) return array();
        $r = array();
        $x = array_flip($GLOBALS['champs']);
        foreach($a as $k => $v) {
                if(isset($x[$v])) $r[$k] = $x[$v];
                else $r[$k] = -1;
        }
        return $r;
}

function champsLongToShort2($a) {
        $r = array();
        $x = array_flip($GLOBALS['champs']);
        foreach($a as $k => $v) {
                if(isset($x[$k])) $r[$x[$k]] = $v;
                else $r[$k] = $v;
        }
        return $r;
}