Subversion Repositories eFlore/Applications.cel

Compare Revisions

No changes between revisions

Ignore whitespace Rev 1974 → Rev 1975

/tags/v1.8-debroussailleuse/jrest/tests/IO-fields-unittest.php
New file
0,0 → 1,160
<?php
 
$options = getopt("hu:d:e:p:P:D",array("help", "user:", "domain:", "email:", "pass:", "phpsessid", "debug"));
if(isset($options['h']) || isset($options['help'])) {
printf(<<<EOF
%s [fichiers de test]
--help|-h: cette aide
-debug|-D: informations sur les requêtes curl
[-u|--user = 22506]
[-d|--domain = "http://cel"]
--pass|-p: pour l'authentifiation
--email|-e: pour l'authentifiation
--phpsessid|-P: pour l'authentifiation, alternative à -e/-p
 
* --phpsessid permet de passer un identifiant de session PHP pour effectuer l'export.
Exemple:
$ sqlite3 ~/.mozilla/firefox/*.default/cookies.sqlite<<<"SELECT * FROM moz_cookies WHERE baseDomain = 'cel' AND name = 'PHPSESSID';"
 
* [fichiers de test]: un ou plusieurs fichier(s) de test valide(s), commençant par "phptests/" et finissant en ".test.php"
Exemple: phptests/a*.test.php ou bien phptests/latitude-virgule.test.php
 
Exemple:
$ php IO-fields-unittest.php -P s97knu4axzi6440n1ihja9ppk1
$ php IO-fields-unittest.php -e me@tela -p blah -u 23004 -d http://localhost phptests/determ-espece*
 
Attention: lancer un test supprime TOUTES les observations existantes de l'utilisateur !
 
EOF
, /* relax emacs*/
basename(__FILE__));
die;
}
 
// stocke les test
define('_TESTDIR', dirname(__FILE__) . '/' . 'phptests');
// stocke les CSV générés à partir des test (répertoire de cache)
define('_RUNDIR', dirname(__FILE__) . '/' . 'run');
 
define('DOMAIN', isset($options['d']) ? $options['d'] : (isset($options['domain']) ? $options['domain'] : 'http://cel'));
define('EMAIL', isset($options['e']) ? $options['e'] : (isset($options['email']) ? $options['email'] : NULL));
define('PASS', isset($options['p']) ? $options['p'] : (isset($options['pass']) ? $options['pass'] : NULL));
define('DEBUG', isset($options['D']) ? 1 : (isset($options['debug']) ? 1 : 0));
 
// could be defined by the API::auth()
if(isset($options['u']) || isset($options['user'])) {
define('USER', isset($options['u']) ? $options['u'] : $options['user']);
}
 
// could be defined by the API::auth()
if(isset($options['P']) || isset($options['phpsessid'])) {
define('COOKIE', isset($options['P']) ? $options['P'] : $options['phpsessid']);
}
 
require_once('api.php');
 
if(!auth()) {
die('auth problem');
}
 
function setupTestEnv() {
cel_delete_all_obs();
cel_delete_all_images();
cel_upload_image('image-test.jpg');
cel_upload_image('image-test2.jpg');
}
 
if(! is_dir(_TESTDIR)) die('no phptests/ directory inside ' . __DIR__);
if(! is_dir(_RUNDIR)) mkdir(_RUNDIR);
if(! is_dir(_RUNDIR)) die('no run/ directory inside ' . __DIR__);
 
$all_tests = array_map('basename', glob(_TESTDIR . '/*.test.php'));
$tests = array_intersect(array_map('basename', $argv), $all_tests);
if(!$tests) $tests = $all_tests;
 
//@array_walk(glob('run/*'), function(&$i) { unlink($i);});
 
foreach($tests as $test) {
setupTestEnv();
$testfile = _TESTDIR . '/' . $test;
 
// cache car l'upload de fichier PHP-curl ne peut être
// simulé avec le contenu d'une variable (cf CURLOPT_POSTFIELDS et @fichier)
$runfile = _RUNDIR . '/' . $test;
 
$test_array = require($testfile);
 
$cols = isset($test_array['dumpCols']) ? $test_array['dumpCols'] : 'standard';
 
if(!is_file($runfile) || filemtime($runfile) < filemtime($testfile)) {
$csv = genCSV($test_array['data']);
file_put_contents($runfile, $csv);
}
 
//echo "\tcurl -F \"upload=@$runfile\" -F utilisateur=" . USER . " \"" . DOMAIN . "/jrest/ImportXLS\"\n";
echo "$test: ";
$var_expected = include(_TESTDIR . '/' . str_replace('.test.', '.result.', $test));
 
$retour = import($runfile);
$count_warn = 0;
preg_match('/^ligne /', $retour, $count_warn);
$count_warn = count($count_warn);
 
$result = getCSV_line(export($cols), 1);
if(!$result) {
echo ("\n!!! export vide, problème probable d'authentification ?\n");
continue;
}
 
//var_dump(champsLongToShort2($test_array['data']));die;
if($var_expected) {
$result = __diff_fields($test_array, $result, $var_expected);
// unset($result['date_creation'], $result['date_modification'], $result['id_observation']);
 
$d1 = array_diff($var_expected, $result);
$d2 = array_diff($result, $var_expected);
if(!$d1 && !$d2) echo "OK\n";
else {
echo "FAIL\n";
if($d1) { echo "expect: "; print_r($d1); }
if($d2) { echo "result: "; print_r($d2); }
//var_dump($var_expected, $result);
}
if(DEBUG) echo $retour;
if($count_warn && (!isset($test_array['warn']) || $test_array['warn'] != $count_warn)) { echo "warnings: $count_warn\n"; }
}
// pas de résultat de test défini ?
else {
if(DEBUG) echo $retour;
if($count_warn && (!isset($test_array['warn']) || $test_array['warn'] != $count_warn)) { echo "warnings: $count_warn\n"; }
 
echo '<?php return ' . var_export($result, true) . ';';
}
}
 
 
 
 
 
function __diff_fields($test_array, $result, $var_expected) {
if(! isset($test_array['cmpCols'])) {
return array_intersect_key($result, $var_expected);
}
 
if($test_array['cmpCols'] == 'def') {
return array_intersect_key($result, champsLongToShort2($test_array['data']));
}
 
$e = array_flip(champsLongToShort2(array_flip(explode(',', ltrim($test_array['cmpCols'], '+-')))));
if($test_array['cmpCols'][0] == '-') {
return array_diff_key($result, array_flip(champsLongToShort2($e)));
}
else { //if($test_array['cmpCols'][0] == '+') {
return array_intersect_key($result, array_flip(champsLongToShort2($e)));
}
 
// pas de 'cmpCols' définie: comparaison de tous les champs par rapport au tableau de résultats attendus
}
 
// sed -i -e '1{/<?php return/!s:^:<?php return :}' -e '${/^)$/s:$:;:}' phptests/*.result.php
/tags/v1.8-debroussailleuse/jrest/tests/api.php
New file
0,0 → 1,350
<?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-test: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;
}
/tags/v1.8-debroussailleuse/jrest/tests/multi-tests.xls
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
/tags/v1.8-debroussailleuse/jrest/tests/multi-tests.xls
New file
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/XLS-IO-fields-unittest.php
New file
0,0 → 1,160
<?php
 
$options = getopt("hu:d:e:p:P:D",array("help", "user:", "domain:", "email:", "pass:", "phpsessid", "debug"));
if(isset($options['h']) || isset($options['help'])) {
printf(<<<EOF
%s [fichiers de test]
--help|-h: cette aide
-debug|-D: informations sur les requêtes curl
[-u|--user = 22506]
[-d|--domain = "http://cel"]
--pass|-p: pour l'authentifiation
--email|-e: pour l'authentifiation
--phpsessid|-P: pour l'authentifiation, alternative à -e/-p
 
* --phpsessid permet de passer un identifiant de session PHP pour effectuer l'export.
Exemple:
$ sqlite3 ~/.mozilla/firefox/*.default/cookies.sqlite<<<"SELECT * FROM moz_cookies WHERE baseDomain = 'cel' AND name = 'PHPSESSID';"
 
* [fichiers de test]: un ou plusieurs fichier(s) de test valide(s), commençant par "phptests/" et finissant en ".test.php"
Exemple: phptests/a*.test.php ou bien phptests/latitude-virgule.test.php
 
Exemple:
$ php IO-fields-unittest.php -P s97knu4axzi6440n1ihja9ppk1
$ php IO-fields-unittest.php -e me@tela -p blah -u 23004 -d http://localhost phptests/determ-espece*
 
Attention: lancer un test supprime TOUTES les observations existantes de l'utilisateur !
 
EOF
, /* relax emacs*/
basename(__FILE__));
die;
}
 
// stocke les test
define('_TESTDIR', dirname(__FILE__) . '/' . 'phptests');
// stocke les CSV générés à partir des test (répertoire de cache)
define('_RUNDIR', dirname(__FILE__) . '/' . 'run');
 
define('DOMAIN', isset($options['d']) ? $options['d'] : (isset($options['domain']) ? $options['domain'] : 'http://cel'));
define('EMAIL', isset($options['e']) ? $options['e'] : (isset($options['email']) ? $options['email'] : NULL));
define('PASS', isset($options['p']) ? $options['p'] : (isset($options['pass']) ? $options['pass'] : NULL));
define('DEBUG', isset($options['D']) ? 1 : (isset($options['debug']) ? 1 : 0));
 
// could be defined by the API::auth()
if(isset($options['u']) || isset($options['user'])) {
define('USER', isset($options['u']) ? $options['u'] : $options['user']);
}
 
// could be defined by the API::auth()
if(isset($options['P']) || isset($options['phpsessid'])) {
define('COOKIE', isset($options['P']) ? $options['P'] : $options['phpsessid']);
}
 
require_once('api.php');
 
if(!auth()) {
die('auth problem');
}
 
function setupTestEnv() {
cel_delete_all_obs();
cel_delete_all_images();
cel_upload_image('image-test.jpg');
cel_upload_image('image-test2.jpg');
}
 
if(! is_dir(_TESTDIR)) die('no phptests/ directory inside ' . __DIR__);
if(! is_dir(_RUNDIR)) mkdir(_RUNDIR);
if(! is_dir(_RUNDIR)) die('no run/ directory inside ' . __DIR__);
 
$all_tests = array_map('basename', glob(_TESTDIR . '/*.test.php'));
$tests = array_intersect(array_map('basename', $argv), $all_tests);
if(!$tests) $tests = $all_tests;
 
//@array_walk(glob('run/*'), function(&$i) { unlink($i);});
 
foreach($tests as $test) {
setupTestEnv();
$testfile = _TESTDIR . '/' . $test;
 
// cache car l'upload de fichier PHP-curl ne peut être
// simulé avec le contenu d'une variable (cf CURLOPT_POSTFIELDS et @fichier)
$runfile = _RUNDIR . '/' . $test;
 
$test_array = require($testfile);
 
$cols = isset($test_array['dumpCols']) ? $test_array['dumpCols'] : 'standard';
 
if(!is_file($runfile) || filemtime($runfile) < filemtime($testfile)) {
$csv = genCSV($test_array['data']);
file_put_contents($runfile, $csv);
}
 
//echo "\tcurl -F \"upload=@$runfile\" -F utilisateur=" . USER . " \"" . DOMAIN . "/jrest/ImportXLS\"\n";
echo "$test: ";
$var_expected = include(_TESTDIR . '/' . str_replace('.test.', '.result.', $test));
 
$retour = importXLS($runfile);
$count_warn = 0;
preg_match('/^ligne /', $retour, $count_warn);
$count_warn = count($count_warn);
 
$result = getCSV_line(exportXLS($cols), 1);
if(!$result) {
echo ("\n!!! export vide, problème probable d'authentification ?\n");
continue;
}
 
//var_dump(champsLongToShort2($test_array['data']));die;
if($var_expected) {
$result = __diff_fields($test_array, $result, $var_expected);
// unset($result['date_creation'], $result['date_modification'], $result['id_observation']);
 
$d1 = array_diff($var_expected, $result);
$d2 = array_diff($result, $var_expected);
if(!$d1 && !$d2) echo "OK\n";
else {
echo "FAIL\n";
if($d1) { echo "expect: "; print_r($d1); }
if($d2) { echo "result: "; print_r($d2); }
//var_dump($var_expected, $result);
}
if(DEBUG) echo $retour;
if($count_warn && (!isset($test_array['warn']) || $test_array['warn'] != $count_warn)) { echo "warnings: $count_warn\n"; }
}
// pas de résultat de test défini ?
else {
if(DEBUG) echo $retour;
if($count_warn && (!isset($test_array['warn']) || $test_array['warn'] != $count_warn)) { echo "warnings: $count_warn\n"; }
 
echo '<?php return ' . var_export($result, true) . ';';
}
}
 
 
 
 
 
function __diff_fields($test_array, $result, $var_expected) {
if(! isset($test_array['cmpCols'])) {
return array_intersect_key($result, $var_expected);
}
 
if($test_array['cmpCols'] == 'def') {
return array_intersect_key($result, champsLongToShort2($test_array['data']));
}
 
$e = array_flip(champsLongToShort2(array_flip(explode(',', ltrim($test_array['cmpCols'], '+-')))));
if($test_array['cmpCols'][0] == '-') {
return array_diff_key($result, array_flip(champsLongToShort2($e)));
}
else { //if($test_array['cmpCols'][0] == '+') {
return array_intersect_key($result, array_flip(champsLongToShort2($e)));
}
 
// pas de 'cmpCols' définie: comparaison de tous les champs par rapport au tableau de résultats attendus
}
 
// sed -i -e '1{/<?php return/!s:^:<?php return :}' -e '${/^)$/s:$:;:}' phptests/*.result.php
/tags/v1.8-debroussailleuse/jrest/tests/IO-file-diff.sh
New file
0,0 → 1,30
#!/bin/bash
 
orig=/tmp/orig.csv
ret=${1:-/tmp/result.csv}
 
# curl -sF "upload=@test.xls" -F utilisateur=22506 "http://cel/jrest/ImportXLS"
# $ sqlite3 .mozilla/firefox/*.default/cookies.sqlite<<<"SELECT * FROM moz_cookies WHERE baseDomain = 'cel' AND name = 'PHPSESSID';"
# GET -H "Cookie: PHPSESSID=ID" "http://cel/jrest/CelWidgetExport/export/?colonnes=standard,avance,etendu,baseflor&id_utilisateur=22506&format=csv > $ret
[[ ! -f $ret || ! -f test.xls ]] && echo "err" && exit 1
 
[[ ! -f $orig ]] && xls2csv -s cp1252 test.xls 2>/dev/null > $orig
[[ ! -f $orig ]] && echo "err" && exit 1
 
 
IFS=$'\n' cols=( $(csvtool head 1 $orig|tr , "\n") )
 
# test header
#diff <(csvtool head 1 $orig|tr , "\n") <(csvtool head 1 $ret |tr , "\n"); exit;
 
w=$(csvtool width $ret); w=32
 
# wdiff <(xls2csv -s cp1252 test.xls|csvtool readable -) <(csvtool readable $ret)
for i in ${cols[@]}; do
[[ $i =~ ^(Date Transmission|Date Création|Date Modification|Nom Commun|Identifiant|Ordre)$ ]] && continue;
echo "== $i";
wdiff -w "$(tput bold;tput setaf 1)" -x "$(tput sgr0)" -y "$(tput bold;tput setaf 2)" -z "$(tput sgr0)" <(csvtool namedcol "$i" $orig) <(csvtool namedcol "$i" $ret)
done
 
 
#ddiff <(csvtool namedcol Notes,Date /tmp/orig.csv ) <(csvtool namedcol Notes,Date /tmp/result.csv)
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/cmd-test.php
New file
0,0 → 1,80
#!/usr/bin/env php
<?php
 
define('DEFAULT_DOMAIN', 'http://cel');
define('DEFAULT_USER', 22506);
 
$options = getopt("hiou:d:e:p:FU:P:D",array("help", "images", "obs", "user:", "domain:", "email:", "pass:", "flush", "upload:", "phpsessid", "debug"));
if(isset($options['h']) || isset($options['help'])) die(__help());
 
 
if(isset($options['u'])) define('USER', $options['u']);
elseif(isset($options['user'])) define('USER', $options['user']);
 
define('DOMAIN', isset($options['d']) ? $options['d'] : (isset($options['domain']) ? $options['domain'] : DEFAULT_DOMAIN));
define('EMAIL', isset($options['e']) ? $options['e'] : (isset($options['email']) ? $options['email'] : NULL));
define('PASS', isset($options['p']) ? $options['p'] : (isset($options['pass']) ? $options['pass'] : NULL));
define('DEBUG', isset($options['D']) ? 1 : (isset($options['debug']) ? 1 : 0));
 
if (isset($options['P'])) define('COOKIE', $options['P']);
elseif (isset($options['phpsessid'])) define('COOKIE', $options['phpsessid']);
 
// API::auth() define()'s COOKIE
require_once('api.php');
 
if(!defined('USER')) auth();
if(!defined('USER')) define('USER', DEFAULT_USER);
 
 
if(isset($options['o']) || isset($options['obs']) || isset($options['F']) || isset($options['flush'])) {
cel_delete_all_obs();
}
 
if(isset($options['i']) || isset($options['images']) || isset($options['F']) || isset($options['flush'])) {
cel_delete_all_images();
}
 
$upload = isset($options['U']) ? $options['U'] : (isset($options['upload']) ? $options['upload'] : NULL);
if($upload) cel_upload_image($upload);
 
if(! defined('COOKIE')) { if(!auth()) die('no auth'); }
 
 
// $csv = genCSV(array('ordre' => 1, 'Date' => '23/06/1991', 'rien' => 'rien'));
var_dump(getCSV_line(export(), 1));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
function __help() {
$m = sprintf(
<<<EOF
%1\$s -i|--images -o|--obs -F|--flush
Supprime les images ou les observations, ou les deux, de l'utilisateur donné sur le CEL donné.
 
Options:
%1\$s [-u|--user = %3\$d] [-d|--domain = %2\$s] [-e|--email] [-p|--pass mot de passe] [-P|--phpsessid PHPSESSID]
La priorité est donnée à -P sur le couple (-e , -p) pour l'authentification, eg:
$ sqlite3 .mozilla/firefox/*.default/cookies.sqlite<<<"SELECT * FROM moz_cookies WHERE baseDomain = 'cel' AND name = 'PHPSESSID';"
 
%1\$s -U|--upload <file>
Upload le fichier "file".
 
EOF
, // */
basename(__FILE__),
DEFAULT_DOMAIN,
DEFAULT_USER);
die($m);
}
/tags/v1.8-debroussailleuse/jrest/tests/bin/csv2xls
New file
0,0 → 1,203
#!/usr/bin/env perl
 
# csv2xls: Convert csv to xls
# (m)'11 [06 Oct 2011] Copyright H.M.Brand 2007-2013
 
use strict;
use warnings;
 
our $VERSION = "1.71";
 
sub usage
{
my $err = shift and select STDERR;
print <<EOU;
usage: csv2xls [-s <sep>] [-q <quot>] [-w <width>] [-d <dtfmt>]
[-o <xls>] [file.csv]
-s <sep> use <sep> as seperator char. Auto-detect, default = ','
The string "tab" is allowed.
-e <esc> use <sep> as seperator char. Auto-detect, default = ','
The string "undef" is allowed.
-q <quot> use <quot> as quotation char. Default = '"'
The string "undef" will disable quotation.
-w <width> use <width> as default minimum column width (4)
-o <xls> write output to file named <xls>, defaults
to input file name with .csv replaced with .xls
if from standard input, defaults to csv2xls.xls
-F allow formula's. Otherwise fields starting with
an equal sign are forced to string
-f force usage of <xls> if already exists (unlink before use)
-d <dtfmt> use <dtfmt> as date formats. Default = 'dd-mm-yyyy'
-D cols only convert dates in columns <cols>. Default is everywhere.
-u CSV is UTF8
-v [<lvl>] verbosity (default = 1)
EOU
exit $err;
} # usage
 
use Getopt::Long qw(:config bundling nopermute passthrough);
my $sep; # Set after reading first line in a flurry attempt to auto-detect
my $quo = '"';
my $esc = '"';
my $wdt = 4; # Default minimal column width
my $xls; # Excel out file name
my $frc = 0; # Force use of file
my $utf = 0; # Data is encoded in Unicode
my $frm = 0; # Allow formula's
my $dtf = "dd-mm-yyyy"; # Date format
my $opt_v = 1;
my $dtc;
 
GetOptions (
"help|?" => sub { usage (0); },
 
"c|s=s" => \$sep,
"q=s" => \$quo,
"e=s" => \$esc,
"w=i" => \$wdt,
"o|x=s" => \$xls,
"d=s" => \$dtf,
"D=s" => \$dtc,
"f" => \$frc,
"F" => \$frm,
"u" => \$utf,
"v:1" => \$opt_v,
) or usage (1);
 
my $title = @ARGV && -f $ARGV[0] ? $ARGV[0] : "csv2xls";
($xls ||= $title) =~ s/(?:\.csv)?$/.xls/i;
 
-s $xls && $frc and unlink $xls;
if (-s $xls) {
print STDERR "File '$xls' already exists. Overwrite? [y/N] > N\b";
scalar <STDIN> =~ m/^[yj](es|a)?$/i or exit;
}
 
# Don't split ourselves when modules do it _much_ better, and follow the standards
use Text::CSV_XS;
use Date::Calc qw( Delta_Days Days_in_Month );
use Spreadsheet::WriteExcel;
use Encode qw( from_to );
 
my $csv;
 
my $wbk = Spreadsheet::WriteExcel->new ($xls);
my $wks = $wbk->add_worksheet ();
$dtf =~ s/j/y/g;
my %fmt = (
date => $wbk->add_format (
num_format => $dtf,
align => "center",
),
 
rest => $wbk->add_format (
align => "left",
),
);
 
my ($h, $w, @w) = (0, 1); # data height, -width, and default column widths
my $row;
my $firstline;
unless ($sep) { # No sep char passed, try to auto-detect;
while (<>) {
m/\S/ or next; # Skip empty leading blank lines
$sep = # start auto-detect with quoted strings
m/["\d];["\d;]/ ? ";" :
m/["\d],["\d,]/ ? "," :
m/["\d]\t["\d,]/ ? "\t" :
# If neither, then for unquoted strings
m/\w;[\w;]/ ? ";" :
m/\w,[\w,]/ ? "," :
m/\w\t[\w,]/ ? "\t" :
";" ;
# Yeah I know it should be a ',' (hence Csv), but the majority
# of the csv files to be shown comes from fucking Micky$hit,
# that uses semiColon ';' instead.
$firstline = $_;
last;
}
}
$csv = Text::CSV_XS-> new ({
sep_char => $sep eq "tab" ? "\t" : $sep,
quote_char => $quo eq "undef" ? undef : $quo,
escape_char => $esc eq "undef" ? undef : $esc,
binary => 1,
keep_meta_info => 1,
auto_diag => 1,
});
if ($firstline) {
$csv->parse ($firstline) or die $csv->error_diag ();
$row = [ $csv->fields ];
}
if ($opt_v > 3) {
foreach my $k (qw( sep_char quote_char escape_char )) {
my $c = $csv->$k () || "undef";
$c =~ s/\t/\\t/g;
$c =~ s/\r/\\r/g;
$c =~ s/\n/\\n/g;
$c =~ s/\0/\\0/g;
$c =~ s/([\x00-\x1f\x7f-\xff])/sprintf"\\x{%02x}",ord$1/ge;
printf STDERR "%-11s = %s\n", $k, $c;
}
}
 
if (my $rows = $dtc) {
$rows =~ s/-$/-999/; # 3,6-
$rows =~ s/-/../g;
eval "\$dtc = { map { \$_ => 1 } $rows }";
}
 
while ($row && @$row or $row = $csv->getline (*ARGV)) {
my @row = @$row;
@row > $w and push @w, ($wdt) x (($w = @row) - @w);
foreach my $c (0 .. $#row) {
my $val = $row[$c] || "";
my $l = length $val;
$l > $w[$c] and $w[$c] = $l;
 
if ($utf and $csv->is_binary ($c)) {
from_to ($val, "utf-8", "ucs2");
$wks->write_unicode ($h, $c, $val);
next;
}
 
if ($csv->is_quoted ($c)) {
if ($utf) {
from_to ($val, "utf-8", "ucs2");
$wks->write_unicode ($h, $c, $val);
}
else {
$wks->write_string ($h, $c, $val);
}
next;
}
 
if (!$dtc or $dtc->{$c + 1}) {
my @d = (0, 0, 0); # Y, M, D
$val =~ m/^(\d{4})(\d{2})(\d{2})$/ and @d = ($1, $2, $3);
$val =~ m/^(\d{2})-(\d{2})-(\d{4})$/ and @d = ($3, $2, $1);
if ( $d[2] >= 1 && $d[2] <= 31 &&
$d[1] >= 1 && $d[1] <= 12 &&
$d[0] >= 1900 && $d[0] <= 2199) {
my $dm = Days_in_Month (@d[0,1]);
$d[2] < 1 and $d[2] = 1;
$d[2] > $dm and $d[2] = $dm;
my $dt = 2 + Delta_Days (1900, 1, 1, @d);
$wks->write ($h, $c, $dt, $fmt{date});
next;
}
}
 
if (!$frm && $val =~ m/^=/) {
$wks->write_string ($h, $c, $val);
}
else {
$wks->write ($h, $c, $val);
}
}
++$h % 100 or $opt_v && printf STDERR "%6d x %6d\r", $w, $h;
} continue { $row = undef }
$opt_v && printf STDERR "%6d x %6d\n", $w, $h;
 
$wks->set_column ($_, $_, $w[$_]) for 0 .. $#w;
$wbk->close ();
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/bin/xls2csv-separate-sheets.pl
New file
0,0 → 1,159
#!/usr/bin/env perl
 
use strict;
use warnings;
use Modern::Perl;
 
use autodie qw{ :all };
use utf8;
use File::Spec;
 
use Smart::Comments '####';
use Getopt::Euclid;
 
use Text::CSV;
use File::Basename;
use Spreadsheet::ParseExcel;
use Text::Trim;
 
my $input_filename = $ARGV{'--infile'};
warn "Warning: The input file does not look like an Excel spreadsheet file."
unless looks_like_xls($input_filename);
my $workbook = Spreadsheet::ParseExcel::Workbook->Parse($input_filename);
 
my ($inbase,$inpath,$insuffix) = fileparse($input_filename, qr{\.[^.]*});
my $output_base = File::Spec->catfile($inpath, $inbase);
my $csv = Text::CSV->new();
 
for my $worksheet ( $workbook->worksheets() ) { #### Processing worksheets (% done)...
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
 
my @sheet_data;
 
for my $row ( $row_min .. $row_max ) {
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet->get_cell( $row, $col ) or undef;
next unless $cell;
$sheet_data[$row][$col] = trim($cell->value());
}
}
### @sheet_data;
 
my $ws_name = $worksheet->{Name};
$ws_name =~ s{\s}{_}xsmg; # no spaces
my $csvname = "${output_base}-${ws_name}.csv";
### $csvname
 
my $output = IO::File->new($csvname, '>') or die $!;
### $output
 
foreach my $line (@sheet_data) {
### $line
$csv->print($output, $line) or die $csv->error_diag();
print $output "\n";
}
 
close $output;
}
 
sub extract_sheet_contents {
my $sheet = $_[0];
my ($nrow, $ncol) = ($sheet->{maxrow}, $sheet->{maxcol});
return extract_rect_from_listref($sheet->{cell}, 1, $nrow, 1, $ncol);
}
 
sub extract_slice_of_listref {
my ($listref, @slice) = @_;
return [ map { $listref->[$_] } @slice ];
}
 
sub extract_rect_from_listref {
my ($listref, $row_start, $row_end, $col_start, $col_end) = @_;
return [ map {
extract_slice_of_listref($_, $col_start..$col_end)
} @{extract_slice_of_listref($listref, $row_start..$row_end)} ];
}
 
sub looks_like_xls {
state $xls_regex = qr{\.xls$};
return 1 if $_[0] =~ m{$xls_regex}i;
return;
}
 
 
__END__
 
=head1 NAME
 
spreadsheet2csv-separate-sheets.pl - Split a spreadsheet into one csv file for each worksheet
 
 
=head1 VERSION
 
Version 1.0
 
 
=head1 USAGE
 
progname [options]
 
 
=head1 REQUIRED ARGUMENTS
 
=over
 
=item --infile [=] <file> | -i <file>
 
The input spreadsheet file.
 
=for Euclid:
file.type: readable
file.default: '-'
 
=back
 
 
=head1 OPTIONS
 
=over
 
=item --version
 
=item --usage
 
=item --help
 
=item --man
 
Print the usual program information
 
=back
 
=head1 DESCRIPTION
 
This program will read a spreadsheet file and output one csv file for
each worksseht in the input file. The name of each output file will be
determined by the name of the input file and the name of the
worksheet. For example, a worksheet "Sheet1" in a file called
"reports.xls" will be output to "reports-Sheet1.csv".
 
=head1 NOTES
 
Empty rows and columns at the beginning of a worksheet will be
omitted. So if a worksheet has columns C through F filled, then the
output for that sheet will have exactly 4 columns, not 6.
 
=head1 AUTHOR
 
Ryan C. Thompson
 
=head1 BUGS
 
If you encounter a problem with this program, please email
rct+perlbug@thompsonclan.org. Bug reports and other feedback are
welcome.
 
=head1 COPYRIGHT
 
Copyright (c) 2010, Ryan C. Thompson
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/data/image-test.jpg
Cannot display: file marked as a binary type.
svn:mime-type = image/jpeg
/tags/v1.8-debroussailleuse/jrest/tests/data/image-test.jpg
New file
Property changes:
Added: svn:mime-type
+image/jpeg
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/data/images.sh
New file
0,0 → 1,8
# upload
curl -s -F file=@test/image-test.jpg -F ce_utilisateur=22506 http://cel/jrest/InventoryImage|grep OK
 
# list
http://cel/jrest/InventoryImageList/22506/?limite=50&numero_page=0|json_pp|egrep 'id_image|nom_original'|awk -F'"' '{print $4}'
 
# IO
POST http://cel/jrest/ExportXLS/22506<<<"format=csv&range=342212"|curl -F "upload=@-" -F utilisateur=22506 "http://cel/jrest/ImportXLS"
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/data/image-test2.jpg
Cannot display: file marked as a binary type.
svn:mime-type = image/jpeg
/tags/v1.8-debroussailleuse/jrest/tests/data/image-test2.jpg
New file
Property changes:
Added: svn:mime-type
+image/jpeg
\ No newline at end of property
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-format-invert.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '1991/01/23',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-format-revert.test.php
New file
0,0 → 1,3
<?php
// test date format inverse YYYY/MM/DD
return array('data' => array('Date' => '23/01/1991'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-ref-badbdnffnn.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec mauvais bdnffnn mais bon référentiel
return array('data' => array('Espèce' => 'bdtfx:nn:72475000', 'nom_referentiel' => 'bdtfx'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/accents.result.php
New file
0,0 → 1,5
<?php return array (
'lieudit' => 'œufs',
'station' => 'Ératostène',
'milieu' => 'Byørg',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-comm-PHPExcel-double.result.php
New file
0,0 → 1,3
<?php return array (
'zone_geo' => 'Villeneuve-Loubet',
'ce_zone_geo' => '06');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-detect.test.php
New file
0,0 → 1,3
<?php
// test localisation simple (commune seule)
return array('data' => array('Commune' => 'Marseille'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/transmission.result.php
New file
0,0 → 1,6
<?php
date_default_timezone_set("Europe/Paris");
return array (
'transmission' => 'oui',
'date_transmission' => date("Y-m-d H:i:s") // attention au décallage (1sec par exemple)
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nonom-num.result.php
New file
0,0 → 1,0
<?php return array ('nom_referentiel' => 'autre');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/colonne-abbrev.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec bdnffnn
return array('data' => array('espece' => 'blah'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-cp-PHPExcel-double.test.php
New file
0,0 → 1,4
<?php
// PHPExcel peut caster CE_ZONE_GEO en (double) et stripper le leading '0'
// d'où problème de détection du code commune
return array('data' => array('Identifiant Commune' => '06161'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nom-num.test.php
New file
0,0 → 1,9
<?php
/* test détermination setting du référentiel:
Théorie, valable pour insert et update:
- pas de nom_sel = pas de num_nom
MAIS:
- pas de nom_sel = pas de référentiel (NULL)
- nom_sel mais pas de num_nom = référentiel = "autre"
*/
return array('data' => array('nom_referentiel' => 'bdtfx', 'nom_sel' => 'blah', 'nom_sel_nn' => -42));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-bdnffnt.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec bdnffnt, minuscules
return array('data' => array('Espèce' => 'bdtfx:nt:5757'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-noref-bdnffnn.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec bdnffnn mais sans référentiel
return array('data' => array('Espèce' => 'bdtfx:nn:72475', 'nom_referentiel' => 'autre'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-format-revert.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '1991/01/23',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-ref-badbdnffnn.result.php
New file
0,0 → 1,4
<?php return array (
'nom_sel' => 'bdtfx:nn:72475000',
'nom_referentiel' => 'autre',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-insee.test.php
New file
0,0 → 1,3
<?php
// test localisation nom (cp sur deux chiffres)
return array('data' => array('ce_zone_geo' => 'INSEE-C:34172'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-cp-seul.result.php
New file
0,0 → 1,3
<?php return array (
'zone_geo' => 'Montpellier',
'ce_zone_geo' => '34');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-post-1900.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '1991/01/23',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/latitude-virgule.test.php
New file
0,0 → 1,3
<?php
// test latitude, séparateur décimales = virgule
return array('data' => array('latitude' => '3,3'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/transmission.test.php
New file
0,0 → 1,4
<?php
// test transmission
return array('dumpCols' => 'avance',
'data' => array('Transmis' => 'OuI'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-bdnffnn.result.php
New file
0,0 → 1,8
<?php return array (
'nom_sel' => 'Viola riviniana subsp. bavarica',
'nom_sel_nn' => '72475',
'nom_ret' => 'Viola x bavarica Schrank',
'nom_ret_nn' => '72090',
'nt' => '7705',
'famille' => 'Violaceae',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-nom-cp2.test.php
New file
0,0 → 1,3
<?php
// test localisation nom (cp sur deux chiffres)
return array('data' => array('Commune' => 'Villers-lès-Nancy (54)'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/colonne-abbrev.result.php
New file
0,0 → 1,3
<?php return array (
'nom_sel' => 'blah'
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nonom-num.test.php
New file
0,0 → 1,9
<?php
/* test détermination setting du référentiel:
Théorie, valable pour insert et update:
- pas de nom_sel = pas de num_nom
MAIS:
- pas de nom_sel = pas de référentiel (NULL)
- nom_sel mais pas de num_nom = référentiel = "autre"
*/
return array('data' => array('nom_referentiel' => 'bdtfx', 'nom_sel_nn' => 182));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/01-sample.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '1991/06/23',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nom-num.result.php
New file
0,0 → 1,0
<?php return array ('nom_sel' => 'blah','nom_referentiel' => 'autre');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-noref-bdnffnn.result.php
New file
0,0 → 1,3
<?php return array (
'nom_sel' => 'Viola riviniana subsp. bavarica',
'nom_referentiel' => 'bdtfx');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/latitude-point.test.php
New file
0,0 → 1,3
<?php
// test latitude, séparateur décimales = point
return array('data' => array('latitude' => '3.3'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/altitude.result.php
New file
0,0 → 1,3
<?php return array (
'altitude' => '800',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-badref-bdnffnn.test.php
New file
0,0 → 1,5
<?php
// test détermination espèce avec bdnffnn mais avec un référentiel erroné
// TODO: RechercheInfosTaxonBeta.php, ligne 186 devrait être modifié afin que la détermination
// prennent en priorité le préfixe "bdtfx" et ignore la colonne "nom_referentiel"
return array('data' => array('Espèce' => 'bdtfx:nn:72475', 'nom_referentiel' => 'bdtxa'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-insee.result.php
New file
0,0 → 1,3
<?php return array (
'zone_geo' => 'Montpellier',
'ce_zone_geo' => '34');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce, simple avec erreur, sans référentiel
return array('data' => array('Espèce' => 'heliotropium europaeum Xxumm'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-syno-bdnff.result.php
New file
0,0 → 1,9
<?php
return array (
'nom_sel' => 'Leuzea conifera',
'nom_sel_nn' => '38821',
'nom_ret' => 'Rhaponticum coniferum (L.) Greuter',
'nom_ret_nn' => '101838',
'nt' => '1050',
'famille' => 'Asteraceae');
?>
/tags/v1.8-debroussailleuse/jrest/tests/phptests/latitude-virgule.result.php
New file
0,0 → 1,3
<?php return array (
'latitude' => '3.3',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-post-1900.test.php
New file
0,0 → 1,3
<?php
// test date format texte, post 1900
return array('data' => array('Date' => '23/01/1991'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-cp-seul.test.php
New file
0,0 → 1,3
<?php
// test localisation sur code insee seul
return array('data' => array('Commune' => '34172'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-post-2900.test.php
New file
0,0 → 1,4
<?php
// test date format texte, futur
return array('warn' => 1,
'data' => array('Date' => '23/06/2900'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-pre-1900.test.php
New file
0,0 → 1,4
<?php
// test date format texte, pré 1900
// il est normal que ce test faillisse avec une arch 32bits (ou un xampp 32bits)
return array('data' => array('Date' => '23/06/1811'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-nom-cp2.result.php
New file
0,0 → 1,3
<?php return array (
'zone_geo' => 'Villers-lès-Nancy',
'ce_zone_geo' => '54');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nonom-nonum.test.php
New file
0,0 → 1,9
<?php
/* test détermination setting du référentiel:
Théorie, valable pour insert et update:
- pas de nom_sel = pas de num_nom
MAIS:
- pas de nom_sel = pas de référentiel (NULL)
- nom_sel mais pas de num_nom = référentiel = "autre"
*/
return array('data' => array('nom_referentiel' => 'bdtfx'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-bdnffnn.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec bdnffnn
return array('data' => array('Espèce' => 'bdtfx:nn:72475'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nom-nonum.result.php
New file
0,0 → 1,0
<?php return array ('nom_sel' => 'blah','nom_referentiel' => 'autre');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/milieu-255.result.php
New file
0,0 → 1,3
<?php return array (
'milieu' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur test long commentaire : adipisicing elit, sed do eiusmod tempor incididunt consectetur adi',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/commentaire-quote.test.php
New file
0,0 → 1,3
<?php
// test commentaire avec quotes et double-quotes
return array('data' => array('notes' => "test quote : a'’\"a"));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/01-sample.test.php
New file
0,0 → 1,14
<?php
/*
Clefs prises en compte:
 
* dumpCols = 'standard,...':
colonnes (standard, avancé, ...) : '
* cmpCols' = [+]date,transmis,.. |-date,id_observation,... |"def"
Champs à comparer, ou à exclure de la comparaison. Par défaut: "def" = les champs de "data".
* warn = \d
nombre de warnings attendus
*/
// sample test
return array('cmpCols' => 'Date', // colonne à comparer
'data' => array('ordre' => 1, 'Date' => '23/06/1991', 'rien' => 'rien'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/latitude-point.result.php
New file
0,0 → 1,3
<?php return array (
'latitude' => '3.3',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-from-nom-ret.test.php
New file
0,0 → 1,3
<?php
// test détermination espèce avec un nom retenu (contenant déjà le nom_sci concaténé)
return array('data' => array('Espèce' => 'Hieracium lysanum Arv.-Touv. & Gaut.', 'nom_referentiel' => 'bdtfx'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-format-invert.test.php
New file
0,0 → 1,3
<?php
// test date format inverse YYYY/MM/DD
return array('data' => array('Date' => '1991/01/23'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-badref-bdnffnn.result.php
New file
0,0 → 1,3
<?php return array (
'nom_sel' => 'Viola riviniana subsp. bavarica',
'nom_referentiel' => 'bdtfx');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/altitude.test.php
New file
0,0 → 1,3
<?php
// test altitude
return array('data' => array('altitude' => '800'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/accents.test.php
New file
0,0 → 1,3
<?php
// test date format texte, pré 1900
return array('data' => array('Lieu-dit' => 'œufs', 'Station' => 'Ératostène', 'Milieu' => 'Byørg'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece.result.php
New file
0,0 → 1,8
<?php return array (
'nom_sel' => 'heliotropium europaeum Xxumm',
'nom_sel_nn' => '31468',
'nom_ret' => 'Heliotropium europaeum L.',
'nom_ret_nn' => '31468',
'nt' => '1382',
'famille' => 'Boraginaceae',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-syno-bdnff.test.php
New file
0,0 → 1,11
<?php
// test détermination espèce sur synonyme:
/*
+---------+----------------+-----------------------+
| num_nom | num_nom_retenu | nom_sci |
+---------+----------------+-----------------------+
| 38821 | 101838 | Leuzea conifera |
| 101838 | 101838 | Rhaponticum coniferum |
+---------+----------------+-----------------------+
*/
return array('data' => array('Espèce' => 'bdtfx:nn:38821'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-detect.result.php
New file
0,0 → 1,4
<?php return array (
'zone_geo' => 'Marseille',
'ce_zone_geo' => '13',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-post-2900.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/date-pre-1900.result.php
New file
0,0 → 1,3
<?php return array (
'date_observation' => '1811/06/23',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-comm-PHPExcel-double.test.php
New file
0,0 → 1,4
<?php
// PHPExcel peut caster ZONE_GEO en (double) et stripper le leading '0'
// d'où problème de détection du code commune
return array('data' => array('Commune' => '06161'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nonom-nonum.result.php
New file
0,0 → 1,0
<?php return array ( 'nom_referentiel' => 'autre' );
/tags/v1.8-debroussailleuse/jrest/tests/phptests/ref-nom-nonum.test.php
New file
0,0 → 1,9
<?php
/* test détermination setting du référentiel:
Théorie, valable pour insert et update:
- pas de nom_sel = pas de num_nom
MAIS:
- pas de nom_sel = pas de référentiel (NULL)
- nom_sel mais pas de num_nom = référentiel = "autre"
*/
return array('data' => array('nom_referentiel' => 'bdtfx', 'nom_sel' => 'blah'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/milieu-255.test.php
New file
0,0 → 1,3
<?php
// test milieu, 255 caractères
return array('data' => array('milieu' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur test long commentaire : adipisicing elit, sed do eiusmod tempor incididunt consectetur adipisicing'));
/tags/v1.8-debroussailleuse/jrest/tests/phptests/commentaire-quote.result.php
New file
0,0 → 1,3
<?php return array (
'commentaire' => 'test quote : a\'’"a',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/localisation-cp-PHPExcel-double.result.php
New file
0,0 → 1,3
<?php return array (
'zone_geo' => 'Villeneuve-Loubet',
'ce_zone_geo' => '06');
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-bdnffnt.result.php
New file
0,0 → 1,8
<?php return array (
'nom_sel' => 'Viola riviniana f. riviniana',
'nom_sel_nn' => '72478',
'nom_ret' => 'Viola riviniana f. riviniana',
'nom_ret_nn' => '72478',
'nt' => '5757',
'famille' => 'Violaceae',
);
/tags/v1.8-debroussailleuse/jrest/tests/phptests/determ-espece-from-nom-ret.result.php
New file
0,0 → 1,9
<?php return array (
'nom_sel' => 'Hieracium lysanum Arv.-Touv. & Gaut.',
'nom_sel_nn' => '33392',
'nom_ret' => 'Hieracium lysanum Arv.-Touv. & Gaut.',
'nom_ret_nn' => '33392',
'nt' => '11235',
'famille' => 'Asteraceae',
'nom_referentiel' => 'bdtfx'
);
/tags/v1.8-debroussailleuse/jrest/tests/api-old.php
New file
0,0 → 1,272
<?php
 
global $champs;
$champs = Array(
'nom_sel' => 'Espece',
'nom_sel_nn' => 'Numero nomenclatural',
'nom_ret' => 'Nom retenu',
'nom_ret_nn' => 'Numero nomenclatural nom retenu',
'nt' => 'Numero 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' => 'Referentiel Geographique',
 
'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',
);
 
 
function cel_get_obs() {
$URL = DOMAIN . '/jrest/InventoryObservationList/' . USER;
return json_decode(file_get_contents($URL . '/?limite=100000&numero_page=0'));
}
 
function cel_get_images() {
$URL = DOMAIN . '/jrest/InventoryImageList/' . USER;
return json_decode(file_get_contents($URL . '/?limite=100000&numero_page=0'));
}
 
function cel_delete_obs($obs) {
$URL = DOMAIN . '/jrest/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);
//execute post
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
 
function cel_delete_image($img) {
$URL = DOMAIN . '/jrest/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() {
$obs = cel_get_obs();
$ordres = array_map(function($item) { return $item->ordre; }, $obs);
cel_delete_obs($ordres);
}
 
 
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 . '/jrest/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
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
 
function cel_link_images($user, $id_image, $id_obs) {
$URL = DOMAIN . '/jrest/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 . '/jrest/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 . '/jrest/InventoryImportExcel';
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");
//if(DEBUG) fwrite(STDERR, __DIR__ . "/bin/csv2xls -v 0 -f -o /tmp/a $d\n");
if(DEBUG) fwrite(STDERR, __DIR__ . "/bin/csv2xls -v 0 -f -o /tmp/a /tmp/a.csv\n");
$d = "/tmp/a.xls";
$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 export($cols = NULL) {
if(!defined('COOKIE')) return FALSE;
 
/*$URL = DOMAIN . '/jrest/CelWidgetExport/csv?format=csv&utilisateur=' . EMAIL;
$cookie = 'PHPSESSID=' . COOKIE . '; ' . 'utilisateur=' . EMAIL . '; ' . 'cel_id=' . USER;*/
$URL = DOMAIN . '/jrest/InventoryExport/' . USER . '/';
$cookie = 'PHPSESSID=' . COOKIE;
 
$ch = curl_init();
 
curl_setopt($ch,CURLOPT_URL, $URL);
curl_setopt($ch,CURLOPT_COOKIE, $cookie);
$fh = fopen('/tmp/b.xls', 'w');
curl_setopt($ch,CURLOPT_FILE, $fh);
 
if(DEBUG) fwrite(STDERR, "curl -b \"$cookie\" \"$URL\"\n");
 
//execute post
$result = curl_exec($ch);
fflush($fh);
fclose($fh);
curl_close($ch);
exec("xls2csv /tmp/b.xls", $result);
if(DEBUG) fwrite(STDERR, "xls2csv /tmp/b.xls\n");
$result = implode("\n", $result);
return $result;
}
 
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;
return array_combine($head, $l);
}
 
 
function champsLongToShort($a) {
$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;
}
/tags/v1.8-debroussailleuse/jrest/tests/.
New file
Property changes:
Added: svn:ignore
+run