Compare commits

...

No commits in common. "master" and "1.0" have entirely different histories.
master ... 1.0

446 changed files with 250253 additions and 66809 deletions

5
.gitignore vendored
View File

@ -1,5 +0,0 @@
/.settings/
/.buildpath
/.project
/vendor/
/composer-develop.lock

View File

@ -1,22 +0,0 @@
# WebService
## Installation du projet
1. Création de la configuration du VHOST apache
2. Référencer le domaine virtuel dans le fichier host de la machine
* ex : 192.168.33.10 webservice.sd.dev
3. Executer composer install pour charger les librairies externes dans vendor
4. Configurer l'application (application.ini)
* exemple fourni - `docs/config` ou projet `ansible`
Voir le fichier `docs/README` pour plus d'éléments
## Mode développement pour les librairies externes
Utiliser la branche `develop` de `scores/library`
`$ COMPOSER=composer-develop.json composer install`

View File

@ -1,218 +0,0 @@
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Processor\IntrospectionProcessor;
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
define('MYSQL_HOST', $config->profil->db->metier->params->host);
define('MYSQL_USER', $config->profil->db->metier->params->username);
define('MYSQL_PASS', $config->profil->db->metier->params->password);
define('LOG_PATH', $config->profil->path->shared.'/log');
// Entreprise
define('SPHINX_ENT_HOST', $config->profil->sphinx->ent->host);
define('SPHINX_ENT_PORT', intval($config->profil->sphinx->ent->port));
define('SPHINX_ENT_VERSION', $config->profil->sphinx->ent->version);
// Dirigeants
define('SPHINX_DIR_HOST', $config->profil->sphinx->dir->host);
define('SPHINX_DIR_PORT', intval($config->profil->sphinx->dir->port));
define('SPHINX_DIR_VERSION', $config->profil->sphinx->dir->version);
// Historique
define('SPHINX_HISTO_HOST', $config->profil->sphinx->histo->host);
define('SPHINX_HISTO_PORT', intval($config->profil->sphinx->histo->port));
define('SPHINX_HISTO_VERSION', $config->profil->sphinx->histo->version);
// Actionnaire
define('SPHINX_ACT_HOST', $config->profil->sphinx->act->host);
define('SPHINX_ACT_PORT', intval($config->profil->sphinx->act->port));
define('SPHINX_ACT_VERSION', $config->profil->sphinx->act->version);
//Old
define('SPHINX_HOST', $config->profil->sphinx->ent->host);
define('SPHINX_PORT', intval($config->profil->sphinx->ent->port));
return $config;
}
//Initialisation global des paramètres de vue
protected function _initViewSettings()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->setEncoding('UTF-8');
$view->doctype('HTML5');
$view->headMeta()
->appendName('viewport', 'width=device-width, initial-scale=1.0')
->appendHttpEquiv('X-UA-Compatible', 'IE=edge')
->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8')
->appendHttpEquiv('Content-Language', 'fr-FR');
//Favicon - Touch icon for iOS 2.0+ and Android 2.1+
$view->headLink()->headLink(array(
'rel' => 'apple-touch-icon-precomposed',
'href' => '/favicon-152.png'
));
//Favicon - targeted to any additional png size
$view->headLink()->headLink(array(
'rel' => 'icon',
'type' => 'image/png',
'href' => '/favicon-32.png'
));
$view->headLink()->headLink(array(
'rel' => 'shortcut icon',
'type' => 'image/x-icon',
'href' => '/favicon.ico')
);
$view->headLink()
->appendStylesheet('/assets/libs/bootstrap-3.3.7/css/bootstrap.min.css', 'all')
->appendStylesheet('/assets/themes/default/css/docs.css', 'all')
->appendStylesheet('/assets/themes/default/css/main.css', 'all');
$view->headScript()
->appendFile('/assets/libs/html5shiv.min.js', 'text/javascript', array('conditional' => 'lt IE 9'))
->appendFile('/assets/libs/respond.min.js', 'text/javascript', array('conditional' => 'lt IE 9'))
->appendFile('/assets/libs/jquery-1.12.4.min.js', 'text/javascript')
->appendFile('/assets/libs/bootstrap-3.3.7/js/bootstrap.min.js', 'text/javascript');
$view->headTitle()->setSeparator(' - ');
$view->headTitle('Web Service API - Scores & Decisions');
}
protected function _initRouter()
{
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$router = $front->getRouter();
// Lire les services disponibles et créer les routes
$services = require_once APPLICATION_PATH . '/../library/WsScore/ServicesConfig.php';
foreach ($services as $section => $params) {
if ($params['actif']) {
$route = new Zend_Controller_Router_Route($section.'/:version', array(
'controller' => 'service',
'action' => 'index',
'service' => $section,
'version' => '',
));
$router->addRoute($section, $route);
}
}
// Route pour WS Clients
$route = new Zend_Controller_Router_Route('clients/:client/:version', array(
'controller' => 'service',
'action' => 'index',
'service' => 'clients',
'client' => '',
'version' => ''
));
$router->addRoute('client', $route);
$fichierRoute = new Zend_Controller_Router_Route('fichier/:action/:fichier', array(
'controller' => 'fichier',
'fichier' => '',
));
$router->addRoute('fichier', $fichierRoute);
return $router;
}
protected function _initDb()
{
$c = new Zend_Config($this->getOptions());
try {
$db = Zend_Db::factory($c->profil->db->metier);
} catch (Exception $e) {
if (APPLICATION_ENV == 'development') {
echo '<pre>';
print_r($e);
echo '</pre>';
} else {
echo "Le service rencontre actuellement un problème technique.";
}
exit;
}
/**
* Set the default adapter to use with all model
*/
Zend_Db_Table::setDefaultAdapter($db);
}
protected function _initDoctrine()
{
$c = new Zend_Config($this->getOptions());
$config = new \Doctrine\DBAL\Configuration();
if (APPLICATION_ENV == 'development') {
$logger = new Scores_Logger_Sql();
$config->setSQLLogger($logger);
}
$connectionParams = array(
'dbname' => $c->profil->db->metier->params->dbname,
'user' => $c->profil->db->metier->params->username,
'password' => $c->profil->db->metier->params->password,
'host' => $c->profil->db->metier->params->host,
'charset' => 'utf8',
'driver' => 'pdo_mysql',
);
try {
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
} catch (\Doctrine\DBAL\DBALException $e) {
if (APPLICATION_ENV == 'development') {
echo '<pre>';
print_r($e);
echo '</pre>';
} else {
echo "Le service rencontre actuellement un problème technique.";
}
exit;
}
Zend_Registry::set('doctrine', $conn);
}
protected function _initCache()
{
if (APPLICATION_ENV!='development') {
//MetadataCache pour la base de données
$frontendOptions = array(
'lifetime' => 14400,
'automatic_serialization' => true
);
$backendOptions = array();
$cache = Zend_Cache::factory('Core', 'Apc', $frontendOptions, $backendOptions);
Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
}
}
protected function _initLogger()
{
$config = new Zend_Config($this->getOptions());
$logFile = $config->profil->path->shared.'/log/application.log';
$log = new Logger('APP');
if (APPLICATION_ENV == 'development') {
$level = Logger::DEBUG;
} else {
$level = Logger::NOTICE;
}
$log->pushHandler(new StreamHandler($logFile, $level));
$log->pushProcessor(new IntrospectionProcessor());
Zend_Registry::set('logger', $log);
}
}

View File

@ -1,40 +0,0 @@
<?php
// --- Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(__DIR__ . '/../application'));
// --- Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// --- Composer autoload
require_once realpath(__DIR__ . '/../vendor/autoload.php');
// --- Create application, bootstrap, and run
$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$c = new Zend_Config($application->getOptions());
Zend_Registry::set('config', $c);
// Database - Zend Style
$db = Zend_Db::factory($c->profil->db->metier);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
// Database - Doctrine Style
$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array(
'dbname' => $c->profil->db->metier->params->dbname,
'user' => $c->profil->db->metier->params->username,
'password' => $c->profil->db->metier->params->password,
'host' => $c->profil->db->metier->params->host,
'charset' => 'utf8',
'driver' => 'pdo_mysql',
);
try {
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
Zend_Registry::set('doctrine', $conn);
} catch (\Doctrine\DBAL\DBALException $e) {
echo "Connection Database impossible.\n";
exit;
}

View File

@ -1 +0,0 @@
/application.ini

View File

@ -1,55 +0,0 @@
<?php
return array(
array(
'label'=> "Accueil",
'controller' => 'index',
'action' => 'index',
'pages' => array(),
),
array(
'label'=> "Documentation",
'controller' => 'documentation',
'action' => 'index',
'pages' => array(
array(
'label'=> "Information générale",
'controller' => 'documentation',
'action' => 'index',
'pages' => array(),
),
array(
'uri' => '#',
),
array(
'label'=> "Liste des services",
'controller' => 'documentation',
'action' => 'services',
'pages' => array(),
),
),
),
array(
'label'=> "Démonstration",
'controller' => 'demo',
'action' => 'index',
'pages' => array(),
),
array(
'label'=> "Contact",
'controller' => 'index',
'action' => 'contact',
'pages' => array(),
),
array(
'label'=> "Paramètres",
'controller' => 'user',
'action' => 'params',
'pages' => array(),
),
array(
'label'=> "A propos",
'controller' => 'index',
'action' => 'about',
'pages' => array(),
),
);

View File

@ -1,20 +0,0 @@
[production]
webservice.scores.wsdl = ""
webservice.scores.options.location = "http://192.168.3.2/ws2/"
webservice.scores.options.uri = "http://192.168.3.2/"
webservice.scores.options.trace = 1
webservice.scores.options.soap_version = SOAP_1_1
[staging]
webservice.scores.wsdl = ""
webservice.scores.options.location = "http://78.31.45.206/ws2/"
webservice.scores.options.uri = "http://78.31.45.206/"
webservice.scores.options.trace = 1
webservice.scores.options.soap_version = SOAP_1_1
[development]
webservice.scores.wsdl = ""
webservice.scores.options.location = "http://78.31.45.206/ws2/"
webservice.scores.options.uri = "http://78.31.45.206/"
webservice.scores.options.trace = 1
webservice.scores.options.soap_version = SOAP_1_1

View File

@ -1,107 +0,0 @@
<?php
class DemoController extends Zend_Controller_Action
{
protected $_username;
protected $_hash;
protected $methods = array(
'getIdentite' => array(
'ws' => 'entreprise/v0.8?wsdl',
'form' => 'getIdentite',
),
);
public function init()
{
$auth = Zend_Auth::getInstance();
$this->_username = $auth->getIdentity()->username;
$this->_hash = $auth->getIdentity()->hash;
}
public function indexAction()
{
//Liste
$tabMethods = array();
foreach ($this->methods as $method => $element) {
$url = $this->view->url(array(
'controller' => 'demo',
'action' => 'method',
'name' => $method,
));
$tabMethods[] = array(
'nom' => $method,
'url' => $url,
);
}
$this->view->assign('methods', $tabMethods);
}
public function methodAction()
{
$method = $this->_getParam('name', '');
$this->view->assign('method', $method);
//Affichage du formulaire
if (array_key_exists($method, $this->methods)) {
$class = 'Scores_Ws_Form_'.ucfirst($method);
if (class_exists($class)) {
$form = new $class;
$form->addElement('hidden', 'method', array(
'value' => $method,
));
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
$form->populate($formData);
}
$this->view->assign('form', $form);
} else {
$this->view->assign('message', "Impossible d'afficher le formulaire !");
}
}
}
public function requeteAction()
{
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
$method = $formData['method'];
$class = 'Scores_Ws_Form_'.ucfirst($method);
if (class_exists($class)) {
$form = new $class;
if ($form->isValid($formData)) {
$method = $formData['method'];
$siret = $formData['siret'];
$accesWs = $this->methods[$method]['ws'];
$hostName = $this->getRequest()->getHttpHost();
$options = array(
'login' => $this->_username,
'password' => $this->_hash,
'features' => SOAP_USE_XSI_ARRAY_TYPE + SOAP_SINGLE_ELEMENT_ARRAYS
);
$client = new Zend_Soap_Client('http://'.$hostName.'/'.$accesWs, $options);
$params = new StdClass();
$params->siret = $siret;
try {
$reponse = $client->getIdentite($params);
} catch (Zend_Soap_Client_Exception $e) {
$reponse = $e->getMessage();
}
$soap = array(
'requete' => $params,
'reponse' => $reponse,
);
$this->view->assign('soap', $soap);
$xml = array(
'requete' => $client->getLastRequest(),
'reponse' => $client->getLastResponse()
);
$this->view->assign('xml', $xml);
} else {
$this->_forward('method', 'demo', null, array('name'=> 'getIdentite'));
}
}
}
}
}

View File

@ -1,223 +0,0 @@
<?php
class DocumentationController extends Zend_Controller_Action
{
/**
* Affichage de la documentation des webservices
*/
public function indexAction()
{
//Do nothing
}
/**
* Liste des services
*/
public function servicesAction()
{
}
/**
* Liste des version par service
*/
public function servicevAction()
{
$request = $this->getRequest();
$name = $request->getParam('name');
$this->view->key = $name;
}
public function serviceAction()
{
$request = $this->getRequest();
$type = $request->getParam('type', 'sd');
$ws = strtolower($request->getParam('name', 'entreprise'));
$myService = $this->view->WsServices[$ws];
// Gestion des versions
$serviceVersions = array();
$configServiceVersions = $myService['versions'];
foreach ($configServiceVersions as $section => $params) {
$serviceVersions[$section] = $params;
if ($params['defaut']) {
$defautVersion = $section;
}
}
$version = $request->getParam('version', $defautVersion);
$this->view->assign('serviceName', $myService['name']);
$this->view->assign('serviceVersion', $version);
$isDeprecated = false;
if ($myService['versions'][$version]['defaut'] == '') {
$isDeprecated = true;
}
$this->view->assign('isDeprecated', $isDeprecated);
if ($type == 'client') {
$client = $ws;
$ws = 'entreprise';
}
// Charger les classes et les types pour le service suivant la version
if ($type == 'client') {
$pathClassService = 'WsScore/Clients/'.ucfirst($client).'/v'.$version.'/';
} else {
$pathClassService = 'WsScore/'.ucfirst($ws).'/v'.$version.'/';
}
//Génération du tableau de mapping
$classmap = include $pathClassService.'Config.php';
//Définir l'url d'accès au WSDL
$wsdl_url = $this->view->baseUrl();
if ($type == 'client') {
$wsdl_url.= '/clients/'.$client.'/v'.$version;
} else {
$wsdl_url.= '/'.$ws.'/v'.$version;
}
if (APPLICATION_ENV == 'production') {
$wsdl_url.= '?wsdl';
} else {
$wsdl_url.= '?wsdl-auto';
}
// Affichage de la documentation
$doc = new Scores_Ws_Doc(ucfirst($ws), $classmap, $pathClassService);
$tabServiceMethods = $doc->getServiceMethods();
// Tri des méthodes par ordre alphabétique
$tabServiceMethodsK = array();
foreach ($tabServiceMethods as $method) {
$tabServiceMethodsK[$method['name']] = $method;
}
ksort($tabServiceMethodsK);
$tabServiceTypes = $doc->getServiceTypes();
$this->view->assign('wsdl', $wsdl_url);
$this->view->assign('serviceMethods', $tabServiceMethodsK);
$this->view->assign('serviceTypes', $tabServiceTypes);
}
/**
* Liste les exemples de code disponible pour chaque méthode
*/
public function exemplesAction()
{
$request = $this->getRequest();
$ws = strtolower($request->getParam('ws', 'Entreprise'));
$auth = Zend_Auth::getInstance();
//Si client possède un webservice particulier alors on redirige vers la doc clients
$clients = include APPLICATION_PATH . '/../library/WsScore/Clients/ClientsConfig.php';
foreach ($clients as $section => $params) {
if ($params['actif']) {
$wsClients[$params['idClient']] = $section;
}
}
if (array_key_exists($auth->getIdentity()->idClient, $wsClients)) {
$this->_forward('clients', 'documentation', null, array(
'nom' => $wsClients[$auth->getIdentity()->idClient]
));
} else {
// Liste des webservices
$services = include APPLICATION_PATH . '/../library/WsScore/ServicesConfig.php';
foreach ($services as $section => $params) {
if ($params['actif']) {
$wsServices[$section] = $params;
}
}
// On vérifie que l'utilisateur peut accèder à la documentation
$username = $auth->getIdentity()->username;
$idClient = $auth->getIdentity()->idClient;
if (array_key_exists($ws, $wsServices)) {
if (isset($wsServices['idClient']) && $idClient!=$wsServices['idClient']) {
$this->renderScript('documentation/nodoc.phtml');
exit;
}
if (isset($wsServices['user']) && !in_array($username, $wsServices['user'])) {
$this->renderScript('documentation/nodoc.phtml');
exit;
}
}
// Gestion des versions
$serviceVersions = array();
$configServiceVersions = $wsServices[$ws]['versions'];
foreach ($configServiceVersions as $section => $params) {
$serviceVersions[$section] = $params;
if ($params['defaut']) {
$defautVersion = $section;
}
}
$version = $request->getParam('version', $defautVersion);
// Charger les classes et les types pour le service suivant la version
$pathClassService = 'WsScore/'.ucfirst($ws).'/v'.$version.'/';
//Génération du tableau de mapping
$classmap = include $pathClassService.'Config.php';
//Définir l'url d'accès au WSDL
$wsdl_url = $this->view->baseUrl();
if (APPLICATION_ENV == 'production') {
$wsdl_url.= '/'.$ws.'/v'.$version.'?wsdl';
} else {
$wsdl_url.= '/'.$ws.'/v'.$version.'?wsdl-auto';
}
// Affichage de la documentation
$doc = new Scores_Ws_Doc(ucfirst($ws), $classmap, $pathClassService);
$tabServiceMethods = $doc->getServiceMethods();
// Tri des méthodes par ordre alphabétique
$tabServiceMethodsK = array();
foreach ($tabServiceMethods as $method) {
$tabServiceMethodsK[$method['name']] = $method;
}
ksort($tabServiceMethodsK);
$tabServiceTypes = $doc->getServiceTypes();
$this->view->assign('wsdl', $wsdl_url);
$this->view->assign('serviceMethods', $tabServiceMethodsK);
$this->view->assign('serviceTypes', $tabServiceTypes);
}
}
/**
* Affichage exemple de code avec coloration syntaxique
* Le code doit être placé dans public/code et doit être nommé
* [nom de la méthode]-langage.txt
*/
public function codeAction()
{
$langage = strtolower($this->_getParam('langage', ''));
$element = $this->_getParam('element', '');
$fichier = APPLICATION_PATH . '/../public/assets/code/' . $element . '-' . $langage . '.txt';
if (file_exists($fichier)) {
$sourceCode = file_get_contents($fichier);
$geshi = new GeSHi($sourceCode, $langage);
$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
$sourceHighlight = $geshi->parse_code();
$this->view->assign('langage', strtoupper($langage));
$this->view->assign('code', $sourceHighlight);
} else {
$this->view->assign('langage',
'Element non traités, Vous pouvez aussi nous fournir des exemples.');
}
}
/**
* Affichage de la liste des erreurs avec leur code
*/
public function erreurAction()
{
$ws = new Scores_Ws_Server();
$erreurs = $ws->listError;
$this->view->assign('erreurs', $erreurs);
}
}

View File

@ -1,46 +0,0 @@
<?php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$this->view->message = 'Application error';
break;
}
// Log exception, if logger available
if ($log = $this->getLog()) {
$log->crit($this->view->message, $errors->exception);
}
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
$this->view->exception = $errors->exception;
}
$this->view->request = $errors->request;
}
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasPluginResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
}
}

View File

@ -1,261 +0,0 @@
<?php
class FichierController extends Zend_Controller_Action
{
/**
* PDO Connection with Doctrine
* @var \Doctrine\DBAL\Connection
*/
protected $conn;
public function init()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$this->conn = Zend_Registry::get('doctrine');
}
public function bodaccAction()
{
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$c = Zend_Registry::get('config');
$directory = $c->profil->path->shared.'/datafile/bodacc/histo';
$q = $this->getRequest()->getParam('q');
$filename = base64_decode($q);
$file = $directory.'/'.$filename;
if (file_exists($file) && filesize($file) > 0) {
//Log de la requete
$data = array(
'login' => $auth->getIdentity()->username,
'idClient' => $auth->getIdentity()->idClient,
'page' => 'histobodacc',
'siren' => '',
'nic' => '',
'params' => $file,
'test' => 0,
'raisonSociale' => '',
'cp' => '',
'ville' => '',
'ipClient' => $_SERVER['REMOTE_ADDR'],
);
$this->conn->insert('sdv1.logs', $data);
$content_type = 'application/pdf';
// --- Envoi du fichier sur la sortie standard
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
echo "Erreur lors de l'affichage du fichier.";
}
} else {
echo "Authentification échoué.";
}
}
public function logsAction()
{
$content_type = 'application/csv-tab-delimited-table';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = $c->profil->path->shared . '/files/'.$filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
public function csvAction()
{
$content_type = 'application/csv-tab-delimited-table';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = $c->profil->path->shared . '/files/'. $filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
public function kbisAction()
{
$content_type = 'application/pdf';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = realpath($c->profil->path->shared).'/datafile/kbis/'.$filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
public function associationsAction()
{
$content_type = 'application/pdf';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = $c->profil->path->shared . '/files/' . $filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
public function greffesAction()
{
$content_type = 'application/pdf';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = $c->profil->path->shared . '/files/' .$filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
public function crmAction()
{
$content_type = 'application/x-bzip';
$filename = $this->getRequest()->getParam('fichier');
$c = Zend_Registry::get('config');
$file = $c->profil->path->shared . '/files/' .$filename;
// --- Envoi du fichier sur la sortie standard
if (file_exists($file)) {
$modules = array(); //apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
header('X-Sendfile: ' . $file);
header('Content-Type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $content_type . '"');
exit;
} else {
ini_set('zlib.output_compression', '0');
header('Content-Transfer-Encoding: none');
header('Content-Type: ' . $content_type.'');
header('Content-Length: ' . filesize($file));
header('Content-MD5: ' . base64_encode(md5_file($file)));
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
readfile($file);
exit;
}
} else {
$this->getResponse()->setHttpResponseCode(404);
}
}
}

View File

@ -1,15 +0,0 @@
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function contactAction()
{
}
public function aboutAction()
{
}
}

View File

@ -1,106 +0,0 @@
<?php
class JsonrpcController extends Zend_Controller_Action
{
public function indexAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$request = $this->getRequest();
//Nom du service
$serviceName = strtolower($request->getParam('service', 'Entreprise'));
//Service spécifique client
if ($serviceName == 'clients') {
$client = $request->getParam('client', '');
//Liste des clients
$clients = array();
$listeClients = include APPLICATION_PATH . '/../library/WsScore/Clients/ClientsConfig.php';
foreach ($listeClients as $section => $params) {
if ($params['actif']) {
$clients[] = $section;
}
}
if (!in_array($client, $clients)) {
echo 'Service clients introuvable !';
exit;
}
$configServiceVersions = $clients[$client]['versions'];
} else {
//Service versions
$services = include APPLICATION_PATH . '/../library/WsScore/ServicesConfig.php';
$configServiceVersions = $services[$serviceName]['versions'];
}
//Liste des versions
foreach ($configServiceVersions as $section => $params) {
$serviceVersions[$section] = $params;
if ($params['defaut']) {
$defautVersion = $section;
}
}
$version = $request->getParam('version', 'v'.$defautVersion);
$version = substr($version, 1);
// Version inexistante
if (!array_key_exists($version, $serviceVersions)) {
echo "Version inexistante.";
exit;
}
// Version désactivé
if (!$serviceVersions[$version]['actif']) {
echo "Version désactivée.";
exit;
}
// Charger les classes et les types pour le service suivant la version
if ($serviceName == 'clients') {
$pathServiceClassIni = 'WsScore/Clients/'.ucfirst($client).'/v'.$version.'/Entreprise.ini';
$pathServiceClassPhp = 'WsScore/Clients/'.ucfirst($client).'/v'.$version.'/Entreprise.php';
$pathServiceUrl = 'clients/'.$client.'/v'.$version.'?wsdl-auto';
//On redéfini le nom du service
$serviceName = 'Entreprise';
$fichierWsdl = ucfirst($client).'-'.$serviceName.'-'.$version.'.wsdl';
} else {
$pathServiceClassIni = 'WsScore/'.ucfirst($serviceName).'/v'.$version.'/'.ucfirst($serviceName).'.ini';
$pathServiceClassPhp = 'WsScore/'.ucfirst($serviceName).'/v'.$version.'/'.ucfirst($serviceName).'.php';
$pathServiceUrl = $serviceName.'/v'.$version.'?wsdl-auto';
$fichierWsdl = ucfirst($serviceName).'-'.$version.'.wsdl';
}
//Génération du tableau de mapping
$wsConfig = new Zend_Config_Ini($pathServiceClassIni);
foreach ($wsConfig->Type->toArray() as $Type) {
$classmap[$Type] = $Type;
}
//Inclusion des classes de données
require_once $pathServiceClassPhp;
// Instance du server
$server = new Zend_Json_Server();
// Define class name
$server->setClass(ucfirst($serviceName));
// Gestion du SMD
if ($this->getRequest()->isGet()) {
// Indiquer URL endpoint
//$this->getHelper('url')->url(array('controller'=>'', 'action'=>'' ));
$server->setTarget('/jsonrpc/'.$serviceName.'/'.$version.'/')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
//Return the SMD to the client
if (!headers_sent()) {
header('Content-Type: application/json');
}
echo $smd;
return;
} else {
$server->setAutoEmitResponse(true);
$server->handle();
}
}
}

View File

@ -1,128 +0,0 @@
<?php
use League\Csv\Writer;
class RefController extends Zend_Controller_Action
{
public function indexAction()
{
//Ne fait rien...
}
/**
* Donne accès au fichier
*/
public function fichierAction()
{
//Lecture du nom du fichier
$fichier = $this->_getParam('q', '');
$fichier = $fichier . '.csv';
if (!empty($fichier) && file_exists('fichiers/'.$fichier)) {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
list($nomFichier, $extFichier) = explode('.', $fichier);
//Distribution du fichier sur la sortie standard
switch ($extFichier) {
case 'png': $content_type = 'image/png'; break;
case 'gif': $content_type = 'image/gif'; break;
case 'jpeg':
case 'jpg': $content_type = 'image/jpeg'; break;
case 'pdf': $content_type = 'application/pdf'; break;
case 'csv': $content_type = 'application/csv-tab-delimited-table'; break;
}
$this->getResponse()->setHeader('Content-Type', $content_type);
$contentDisposition = 'attachment';
switch ($contentDisposition) {
case 'inline':
$this->getResponse()->setHeader('Content-Disposition', 'inline');
break;
case 'attachment':
$this->getResponse()->setHeader('Content-Disposition', "attachment; filename=\"$fichier\"");
break;
}
$data = file_get_contents('assets/fichiers/'.$fichier);
$this->getResponse()->setHeader('Content-Length', strlen($data))
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setBody($data);
} else {
$this->view->assign('message', 'Fichier introuvable !');
}
}
/**
* Donne accès aux données contenues dans une table de base de données
*/
public function tableAction()
{
$request = $this->getRequest();
$requetesql = $request->getParam('q', '');
$fichierCsv = $requetesql.'.csv';
$fichierSql = $requetesql.'.sql';
//Emplacement des fichiers générés - lien symbolique en PRODUCTION
$c = Zend_Registry::get('config');
$path = $c->profil->path->shared . '/files/fichiers/';
if (!is_dir($path)) {
mkdir($path);
}
if (!empty($requetesql)) {
if (!file_exists($path . $fichierCsv)) {
if (file_exists('assets/sql/'.$fichierSql)) {
/**
* @var \Doctrine\DBAL\Connection $conn
*/
$conn = Zend_Registry::get('doctrine');
$sql = file_get_contents('assets/sql/'.$fichierSql);
$stmt = $conn->prepare($sql);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$csv = Writer::createFromPath($path . $fichierCsv.'.tmp', 'w');
$csv->setNewline("\r\n");
$headers = array_keys($stmt->fetch());
$csv->insertOne($headers);
$csv->insertAll($stmt);
}
rename($path . $fichierCsv.'.tmp', $path . $fichierCsv);
}
}
if (file_exists($path . $fichierCsv)) {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
//Distribution du fichier sur la sortie standard
list($nomFichier, $extFichier) = explode('.', $fichierCsv);
switch ($extFichier) {
case 'png': $content_type = 'image/png'; break;
case 'gif': $content_type = 'image/gif'; break;
case 'jpeg':
case 'jpg': $content_type = 'image/jpeg'; break;
case 'pdf': $content_type = 'application/pdf'; break;
case 'csv': $content_type = 'application/csv-tab-delimited-table'; break;
}
$this->getResponse()->setHeader('Content-Type', $content_type);
$contentDisposition = 'attachment';
switch ($contentDisposition) {
case 'inline':
$this->getResponse()->setHeader('Content-Disposition', 'inline');
break;
case 'attachment':
$this->getResponse()->setHeader('Content-Disposition', "attachment; filename=\"$fichierCsv\"");
break;
}
$data = file_get_contents($path . $fichierCsv);
$this->getResponse()->setHeader('Content-Length', strlen($data))
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setBody($data);
}
} else {
$this->view->assign('message', 'Paramètres incorrects !');
}
}
}

View File

@ -1,202 +0,0 @@
<?php
/**
* Distribute all SOAP based Web Services
*
*/
class ServiceController extends Zend_Controller_Action
{
public function indexAction()
{
/**
* Be sure we don't make any render
*/
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$request = $this->getRequest();
// --- Get the service name, make sure the string is in lower case
$serviceName = strtolower($request->getParam('service', 'Entreprise'));
// --- ClassName and Directory with first letter capitalized
$serviceClassName = ucfirst($serviceName);
// --- Customize service for customers
if ('clients' == $serviceName) {
$client = strtolower($request->getParam('client', ''));
$clientClassName = ucfirst($client);
// --- Get list of customers
$clients = array();
$listeClients = include APPLICATION_PATH . '/../library/WsScore/Clients/ClientsConfig.php';
foreach ($listeClients as $section => $params) {
if ($params['actif']) {
$clients[$section] = $params;
}
}
if (!array_key_exists($client, $clients)) {
echo 'Service clients introuvable !';
exit;
}
$configServiceVersions = $clients[$client]['versions'];
}
// --- Service versions
else {
$services = include APPLICATION_PATH . '/../library/WsScore/ServicesConfig.php';
$configServiceVersions = $services[$serviceName]['versions'];
}
// --- Check versions
foreach ($configServiceVersions as $section => $params) {
$serviceVersions[$section] = $params;
if ($params['defaut']) {
$defautVersion = $section;
}
}
$version = $request->getParam('version', 'v'.$defautVersion);
$version = substr($version, 1);
// --- Version inexistante
if (!array_key_exists($version, $serviceVersions)) {
echo "Version inexistante.";
exit;
}
// --- Version désactivé
if (!$serviceVersions[$version]['actif']) {
echo "Version désactivée.";
exit;
}
// --- Charger les classes et les types pour le service suivant la version
if ('clients' == $serviceName) {
$pathServiceClassIni = 'WsScore/Clients/'.$clientClassName.'/v'.$version.'/Config.php';
$pathServiceClassPhp = 'WsScore/Clients/'.$clientClassName.'/v'.$version.'/Service.php';
// --- Gestion du mode de génération du wsdl
if (APPLICATION_ENV == 'development'
|| array_key_exists('mode', $serviceVersions[$version])
&& $serviceVersions[$version]['mode']=='auto') {
$pathServiceUrl = 'clients/'.$client.'/v'.$version.'?wsdl-auto';
} else {
$pathServiceUrl = 'clients/'.$client.'/v'.$version.'?wsdl';
}
$pathServiceUri = 'clients/'.$client.'/v'.$version;
// --- On redéfini le nom du service
$serviceClassName = 'Entreprise';
$fichierWsdl = $clientClassName.'-'.$serviceClassName.'-'.$version.'.wsdl';
} else {
$pathServiceClassIni = 'WsScore/'.$serviceClassName.'/v'.$version.'/Config.php';
$pathServiceClassPhp = 'WsScore/'.$serviceClassName.'/v'.$version.'/Service.php';
// --- Gestion du mode de génération du wsdl
if (APPLICATION_ENV == 'development'
|| array_key_exists('mode', $serviceVersions[$version])
&& $serviceVersions[$version]['mode']=='auto') {
$pathServiceUrl = $serviceName.'/v'.$version.'?wsdl-auto';
} else {
$pathServiceUrl = $serviceName.'/v'.$version.'?wsdl';
}
$pathServiceUri = $serviceName.'/v'.$version;
$fichierWsdl = $serviceClassName.'-'.$version.'.wsdl';
}
// --- Get map of WSDL type to PHP Classes
$classmap = include $pathServiceClassIni;
// --- Inclusion des classes de données
require_once $pathServiceClassPhp;
// --- Get hostname - add compatibility with Reverse Proxy
$hostName = $request->getHttpHost();
$hostScheme = $request->getScheme();
$http = new Zend_Controller_Request_Http();
$proxyScheme = $http->getHeader('X-Forwarded-Proto');
if ($proxyScheme == 'https') {
$hostScheme = 'https';
}
$fichierWsdl = $hostName . '-' . $hostScheme . '-' . $fichierWsdl;
$c = Zend_registry::get('config');
$wsdlPath = $c->profil->path->shared . '/wsdl';
// --- Fourniture du wsdl
if (isset($_GET['wsdl']) && file_exists($wsdlPath . '/' . $fichierWsdl)) {
if (!headers_sent()) {
header('Content-Type: text/xml');
}
readfile($wsdlPath . '/' . $fichierWsdl);
} elseif (isset($_GET['wsdl']) && !file_exists($wsdlPath . '/' . $fichierWsdl)
|| isset($_GET['wsdl-generate'])
|| isset($_GET['wsdl-auto'])) {
// --- Définition du webservice
$wsdl = new Zend_Soap_AutoDiscover();
$wsdl->setComplexTypeStrategy('Zend_Soap_Wsdl_Strategy_ArrayOfTypeSequence');
$wsdl->setOperationBodyStyle(array('use' => 'literal'));
$wsdl->setBindingStyle(array('style' => 'document'));
$wsdl->setClass($serviceClassName);
if ($hostScheme == 'https') {
$wsdl->setUri($hostScheme.'://'.$hostName.'/'.$pathServiceUri);
}
// --- Enregistrement du WSDL dans un fichier
if (isset($_GET['wsdl-generate'])) {
if (file_exists($wsdlPath . '/' . $fichierWsdl)) {
unlink($wsdlPath . '/' . $fichierWsdl);
}
$wsdl->dump($wsdlPath . '/' . $fichierWsdl);
echo "Le fichier $fichierWsdl a été généré";
// --- Génération/Fourniture du wsdl
} elseif (isset($_GET['wsdl']) && !file_exists($wsdlPath . '/' . $fichierWsdl)) {
$wsdl->dump($wsdlPath . '/' . $fichierWsdl);
if (!headers_sent()) {
header('Content-Type: text/xml');
}
readfile($wsdlPath . '/' . $fichierWsdl);
}
// --- Envoi sur la sortie standard le wsdl sans enregistrement dans un fichier
elseif (isset($_GET['wsdl-auto'])) {
$wsdl->handle();
}
}
// --- Fourniture du service
else {
// --- Traitement
if (in_array(APPLICATION_ENV, array('production', 'staging'))
&& file_exists($wsdlPath . '/' . $fichierWsdl)) {
$server = new Zend_Soap_Server($wsdlPath . '/' . $fichierWsdl);
} else {
$server = new Zend_Soap_Server($hostScheme.'://'.$hostName.'/'.$pathServiceUrl);
}
// --- Sonde paramètres server
$debug = false;
$debugUser = '';
if ($debug && $_SERVER['PHP_AUTH_USER'] == $debugUser) {
file_put_contents(APPLICATION_PATH . '/../debugserver.log',
"FichierWSDL : ".$fichierWsdl."\n".
"Hostname : ".$hostName."\n"
);
}
// --- Options et traitement de la requete
$server->setSoapFeatures(SOAP_USE_XSI_ARRAY_TYPE + SOAP_SINGLE_ELEMENT_ARRAYS);
$server->setClassmap($classmap);
$server->setEncoding('UTF-8');
$server->registerFaultException(array('Scores_Ws_Exception'));
$server->setWsiCompliant(true);
// --- Création du service
$server->setObject(new $serviceClassName());
$server->handle();
// --- Pour débuggage ultime
$debug = false;
$debugUser = '';
if ($debug && $_SERVER['PHP_AUTH_USER'] == $debugUser) {
file_put_contents(APPLICATION_PATH . '/../debugcall.log',
"FichierWSDL : ".$fichierWsdl."\n"."Hostname : ".$hostName."\n");
$request = $server->getLastRequest();
file_put_contents(APPLICATION_PATH . '/../debugcall.log', $request . "\n", FILE_APPEND);
$response = $server->getLastResponse();
file_put_contents(APPLICATION_PATH . '/../debugcall.log', $response. "\n", FILE_APPEND);
}
}
}
}

View File

@ -1,133 +0,0 @@
<?php
class UserController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function loginAction()
{
$this->_helper->layout()->disableLayout();
$this->view->headLink()->appendStylesheet('/assets/themes/default/css/signin.css', 'all');
$this->view->headTitle()->append('Connexion');
$form = new Application_Form_Login();
$this->view->form = $form;
$request = $this->getRequest();
if ($request->isPost()) {
$formData = $request->getPost();
if ($form->isValid($formData)) {
$login = $form->getValue('login');
$pass = $form->getValue('pass');
$auth = Zend_Auth::getInstance();
$authAdapter = new Scores_Auth_Adapter_Db($login, $pass, true);
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$timeout = $auth->getIdentity()->timeout;
//Ecrit un cookie persistant valide pendant le temps definit
Zend_Session::rememberMe($timeout);
$storage = new Zend_Auth_Storage_Session();
$sessionNamespace = new Zend_Session_Namespace($storage->getNamespace());
$sessionNamespace->setExpirationSeconds($timeout);
$auth->setStorage($storage);
$this->redirect('/');
} else {
$this->view->message = '';
foreach ($result->getMessages() as $message) {
$this->view->message.= $message."<br/>";
}
}
}
}
}
public function logoutAction()
{
$this->_helper->layout()->disableLayout();
Zend_Auth::getInstance()->clearIdentity();
}
public function paramsAction()
{
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
$login = $identity->username;
$pass = $identity->hash;
$this->view->login = $login;
$this->view->authorizationHeader = base64_encode($login.':'.$pass);
/**
* @var \Doctrine\DBAL\Connection $conn
*/
$conn = Zend_Registry::get('doctrine');
$userSql = "SELECT * FROM sdv1.utilisateurs WHERE id=:id";
$stmt = $conn->prepare($userSql);
$stmt->bindValue('id', $identity->id);
$stmt->execute();
$user = $stmt->fetch(\PDO::FETCH_OBJ);
$this->view->IdFullName = $user->civilite . ' ' . $user->nom . ' ' . $user->prenom;
$this->view->IdEmail = $user->email;
//Liste des droits
$listdroit = explode(' ', $user->droits);
//Association méthodes - droits
$assoc = array(
'getAnnoncesAsso' => array('ANNONCES'),
'getAnnoncesBalo' => array('ANNONCES'),
'getAnnoncesBoamp' => array('ANNONCES'),
'getAnnoncesLegales' => array('ANNONCES'),
'getAnnoncesNum' => array('ANNONCES'),
'getAvisRncs' => array('AVISRNCS'),
'getBanques' => array('BANQUES'),
'getBilan' => array('LIASSE'),
'getDirigeants' => array('DIRIGEANTS'),
'getIdentite' => array('IDENTITE'),
'getIdentiteProcol' => array('IDPROCOL'),
'getIndiScore' => array('INDISCORE1', 'INDISCORE2', 'INDISCORE3'),
'getInfosBourse' => array('BOURSE'),
'getInfosReg' => array('INFOSREG'),
'getLiasseInfos' => array(),
'getLienRef' => array('LIENS'),
'getLiens' => array('LIENS'),
'getLiensById' => array('LIENS'),
'getListeBilans' => array('LIASSE'),
'getListeCompetences' => array('COMPETENCES'),
'getListeEtablissements' => array('ETABLISSEMENTS'),
'getListeEvenements' => array('EVENINSEE'),
'getRapport' => array('INDISCORE3'),
'getRatios' => array('RATIOS'),
'getSubventionDetail' => array(''),
'getSubventionList' => array(''),
'getTVA' => array(''),
'getValo' => array('VALORISATION'),
'isSirenExistant' => array(''),
'searchAutreId' => array('SEARCHENT'),
'searchDir' => array('SEARCHDIR'),
'searchEntreprise' => array('SEARCHENT'),
'searchNomAdr' => array('SEARCHENT'),
'searchRefClient' => array(),
'searchSiren' => array('SEARCHENT'),
'searchTelFax' => array('SEARCHENT'),
);
$display = array();
foreach ($listdroit as $droit) {
foreach ($assoc as $l => $d) {
if (in_array(strtoupper($droit), $d)) {
$display[] = array(
'label' => $l,
'droit' => $droit,
);
}
}
}
$this->view->display = $display;
}
}

View File

@ -1,7 +0,0 @@
<?php
class Zend_View_Helper_DocComplement extends Zend_View_Helper_Abstract
{
public function docComplement($method)
{
}
}

View File

@ -1,8 +0,0 @@
<?php
class Zend_View_Helper_DocDescription extends Zend_View_Helper_Abstract
{
public function docDescription($method)
{
return $method['desc'];
}
}

View File

@ -1,31 +0,0 @@
<?php
class Zend_View_Helper_DocExemple extends Zend_View_Helper_Abstract
{
public function docExemple($method)
{
$exemple = '';
$langages = array(
'php' => 'PHP',
'java' => 'Java',
'perl' => 'Perl',
'python' => 'Python',
'csharp' => 'C#'
);
foreach ($langages as $langage => $lib) {
$fichier = 'assets/code/'.$method.'-'.$langage.'.txt';
if (file_exists($fichier)) {
$url = $this->view->url(
array(
'controller' => 'documentation',
'action' => 'code',
'langage' => $langage,
'element' => $method,
), null, true);
$exemple.= '<a href="'.$url.'">' . $lib . '</a>';
$exemple.= '&nbsp;';
}
}
return $exemple;
}
}

View File

@ -1,59 +0,0 @@
<?php
class Zend_View_Helper_DocMethod extends Zend_View_Helper_Abstract
{
protected $_transcodeType = array(
'str' => 'string',
'bool' => 'boolean',
'integer' => 'int',
);
public function docMethod($method)
{
$output = '';
$returnType = $method['return'];
$methodName = $method['name'];
$cptParameters = 0;
$parameters = '';
foreach ($method['params'] as $param) {
if (isset($param['optional'])) {
$parameters.= '[';
}
$parameters.= '<i>' . $this->transcodeType($param['type']) . '</i>';
$parameters.= '&nbsp;';
$parameters.= '<b>' . $param['name'] . '</b>';
if (isset($param['optional'])) {
if (isset($param['defaultValue'])) {
$parameters.= ' = ';
if (is_bool($param['defaultValue'])) {
$parameters.= ($param['defaultValue'] === false) ? 'false' : 'true' ;
} elseif (is_string($param['defaultValue']) && $param['defaultValue']=='') {
$parameters.= "''";
} else {
$parameters.= $param['defaultValue'];
}
}
$parameters.= ']';
}
$cptParameters++;
if ($cptParameters < count($method['params'])) {
$parameters.= ', ';
}
}
$output = '<i>' . $this->transcodeType($returnType) . '</i>';
$output.= ' ';
$output.= '<b>' . $methodName . '</b>' . ' <b>(</b> ' . $parameters . ' <b>)</b>';
return $output;
}
private function transcodeType($type)
{
if (array_key_exists($type, $this->_transcodeType)) {
return $this->_transcodeType[$type];
} else {
return $type;
}
}
}

View File

@ -1,80 +0,0 @@
<?php
class Zend_View_Helper_DocParameter extends Zend_View_Helper_Abstract
{
protected $serviceTypes;
protected $types = array(
'string', 'str',
'boolean', 'bool',
'int', 'integer', 'long',
'float', 'double',
'array', 'object', 'mixed'
);
protected $_transcodeType = array(
'str' => 'string',
'bool' => 'boolean',
'integer' => 'int',
);
public function docParameter($params, $serviceTypes)
{
$this->serviceTypes = $serviceTypes;
$output = '';
if (count($params)>0) {
$output.= '<ul>';
foreach ($params as $param) {
$output.= $this->formatParam($param);
}
$output.= '</ul>';
}
return $output;
}
private function parseType($type)
{
$output = '';
$type = str_replace('[]', '', $type);
if (array_key_exists($type, $this->serviceTypes)) {
$types = $this->serviceTypes[$type];
$output.= '<ul>';
foreach ($types as $param) {
$output.= $this->formatParam($param);
}
$output.= '</ul>';
} elseif (in_array($type, $this->types)) {
$output.= '';
} elseif ($type == 'void') {
$output.= 'Void';
} else {
$output.= ' => <b>Type '.$type.' inconnu</b>';
}
return $output;
}
private function formatParam($param)
{
$output = '';
$output.= '<li>';
$output.= '<i>' . $this->transcodeType($param['type']) . '</i>';
$output.= ' ';
$output.= '<b>' . $param['name'] . '</b>';
if (isset($param['description']) && !empty($param['description'])) {
$output.= ' - '.$param['description'];
}
if (!in_array($param['type'], $this->types)) {
$output.= $this->parseType($param['type']);
}
$output.= '</li>';
return $output;
}
private function transcodeType($type)
{
if (array_key_exists($type, $this->_transcodeType)) {
return $this->_transcodeType[$type];
} else {
return $type;
}
}
}

View File

@ -1,73 +0,0 @@
<?php
class Zend_View_Helper_DocReturn extends Zend_View_Helper_Abstract
{
protected $serviceTypes;
protected $types = array(
'string', 'str',
'boolean', 'bool',
'integer', 'int', 'long',
'float', 'double',
'array', 'object', 'mixed'
);
protected $_transcodeType = array(
'str' => 'string',
'bool' => 'boolean',
'integer' => 'int',
);
public function docReturn($type, $serviceTypes)
{
$this->serviceTypes = $serviceTypes;
return $this->parseType($type);
}
private function parseType($type)
{
$output = '';
$type = str_replace('[]', '', $type);
if (array_key_exists($type, $this->serviceTypes)) {
$types = $this->serviceTypes[$type];
$output.= '<ul>';
foreach ($types as $param) {
$output.= $this->formatParam($param);
}
$output.= '</ul>';
} elseif (in_array($type, $this->types)) {
$output.= '<i>' . $type . '</i> ';
} elseif ($type == 'void') {
$output.= 'Void';
} else {
$output.= ' => <b>Type '.$type.' inconnu</b>';
}
return $output;
}
private function formatParam($param)
{
$output = '';
$output.= '<li>';
$output.= '<i>' . $this->transcodeType($param['type']) . '</i>';
$output.= ' ';
$output.= '<b>'. $param['name'] . '</b>';
if (isset($param['description']) && !empty($param['description'])) {
$output.= ' - '.$param['description'];
}
$type = str_replace('[]', '', $param['type']);
if (!in_array($type, $this->types)) {
$output.= $this->parseType($param['type']);
}
$output.= '</li>';
return $output;
}
private function transcodeType($type)
{
if (array_key_exists($type, $this->_transcodeType)) {
return $this->_transcodeType[$type];
} else {
return $type;
}
}
}

View File

@ -1,17 +0,0 @@
<?php
class Zend_View_Helper_ProfileLink extends Zend_View_Helper_Abstract
{
public function profileLink()
{
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$username = $auth->getIdentity()->username;
$logoutUrl = $this->view->url(array(
'controller' => 'user',
'action' => 'logout'
), null, true);
return '<a href="'.$logoutUrl.'" title="Se déconnecter" class="navbar-link">Déconnexion : ' . $username . '</a>';
}
}
}

View File

@ -1,12 +0,0 @@
<h1>Démonstration - Liste des méthodes</h1>
<p class="bg-info">Uniquement disponible à titre d'information. Se référer à la documentation pour réaliser des tests.</p>
<ul>
<?php foreach($this->methods as $method){ ?>
<li>
<a href="<?php echo $method['url'];?>">
<?php echo $method['nom'];?></a>
</li>
<?php } ?>
</ul>

View File

@ -1,5 +0,0 @@
<h2><?php echo $this->method;?></h2>
<p><?php echo $this->message;?></p>
<div>
<?php echo $this->form;?>
</div>

View File

@ -1,20 +0,0 @@
<h2>SOAP</h2>
<p>Requete</p>
<textarea rows="10" cols="100" name="soap-requete">
<?php print_r($this->soap['requete']);?>
</textarea>
<p>Réponse</p>
<textarea rows="10" cols="100" name="soap-reponse">
<?php print_r($this->soap['reponse']);?>
</textarea>
<h2>XML</h2>
<p>Requete</p>
<textarea rows="10" cols="100" name="xml-requete">
<?php echo $this->xml['requete'];?>
</textarea>
<p>Réponse</p>
<textarea rows="10" cols="100" name="xml-reponse">
<?php echo $this->xml['reponse'];?>
</textarea>

View File

@ -1,42 +0,0 @@
<div id="wsdl">
<h1>WSDL</h1>
<p><a href="<?=$this->wsdl?>">Télécharger le WSDL</a></p>
<i>Le fichier est accessible sans authentification.</i>
</div>
<div class="op-list">
<h1>Liste des opérations :</h1>
<ol>
<?php foreach ($this->serviceMethods as $method) {?>
<li>
<b><?php echo $method['name'];?></b>
<a href="#<?php echo $method['name'];?>"><i>Détail</i></a>
</li>
<?php } ?>
</ol>
</div>
<div class="op-detail">
<h1>Détails :</h1>
<?php foreach ($this->serviceMethods as $method) {?>
<div class="function">
<a name="<?php echo $method['name'];?>">&nbsp;</a>
<h2><?php echo $method['name'];?></h2>
<div><u>Description : </u></div>
<div class="description"><?=$this->docDescription($method)?></div>
<div class="complement"><?=$this->docComplement($method)?></div>
<div class="function-detail" id="<?=$method['name']?>">
<p><?php echo $this->docMethod($method);?></p>
<div><u>Paramètres : </u></div>
<div class="parameters">
<?php echo $this->docParameter($method['params'], $this->serviceTypes);?>
</div>
<div><u>Retour : </u></div>
<div class="return">
<?php echo $this->docReturn($method['return'], $this->serviceTypes);?>
</div>
</div>
<p>Exemple : <?php echo $this->docExemple($method['name']);?></p>
</div>
<?php } ?>
</div>

View File

@ -1,2 +0,0 @@
<h2><?=$this->langage?></h2>
<?=$this->code?>

View File

@ -1,10 +0,0 @@
<div>
<h1>Liste des code erreurs/messages :</h1>
<ul>
<?php foreach ($this->erreurs as $code => $message) {?>
<li>
<b><?php echo $code?></b> : <?php echo $message?>
</li>
<?php } ?>
</ul>
</div>

View File

@ -1,2 +0,0 @@
<h2>Liste des exemples</h2>

View File

@ -1,48 +0,0 @@
<div class="page-header"><h1>Authentification</h1></div>
<p>
Le WebService utilise une authentification http basic.
Il s'agit donc de transmettre comme paramètres d'authentification
</p>
<p><code>http://{login}:{password}@url</code></p>
<p>
- <code>{password}</code> est une chaine construite de cette façon md5({login}|{pass}) <br/>
- <code>{login}</code> est l'identifiant fournit <br/>
- <code>{pass}</code> le mot de passe fournit.
</p>
<div class="bs-callout bs-callout-warning">
Authentification basic<br/>
<br/>
Le client HTTP envoi une requête avec l'en-tête HTTP "Authorization". Celui-ci doit contenir la méthode utilisée
(Basic) suivi de la représentation en Base64 du nom de l'utilisateur et du mot de passe séparés par
le caractère ":" (deux-points).<br/>
<br/>
Par exemple :<br/>
<br/>
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
</div>
<p>
Vous trouverez dans ces exemples les prérequis pour s'authentifier et suivant
les outils et langage la possibilité de générer le code à partir du WSDL.<br/>
Exemple : <?=$this->docExemple('authentication')?>
</p>
<div class="page-header"><h1>Compatibilité</h1></div>
<p>Notre service web a été testé avec ces langages/librairies</p>
<ul>
<li>C# : .Net Framework</li>
<li>PHP : PHP5 SOAP Extension</li>
<li>Perl : SOAP::Lite</li>
<li>Java : JAX-WS</li>
<li>Python : SOAPpy</li>
<li>VB.Net : .Net Framework</li>
<li>C++ : gSOAP</li>
</ul>
<br/>
<p>
Pour toutes remarques ou question merci d'adresser un email à
<a href="mailto:support@scores-decisions.com">support@scores-decisions.com</a>
</p>

View File

@ -1 +0,0 @@
Erreur

View File

@ -1,78 +0,0 @@
<div class="page-header"><h1>Service <?=$this->serviceName?> v<?=$this->serviceVersion?></h1></div>
<?php if ( $this->isDeprecated === true) {?>
<p class="bg-danger">Cette version est déprécié. Elle est désactivé.</p>
<?php }?>
<?php if ( $this->Info ) {?>
<p class="bg-info"><?=$this->Info?></p>
<?php }?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">WSDL</h3>
</div>
<div class="panel-body">
<p><a href="<?=$this->wsdl?>">Télécharger le WSDL</a></p>
<i>Le fichier est accessible sans authentification.</i>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Liste des opérations</h3>
</div>
<div class="panel-body">
<ol>
<?php foreach ($this->serviceMethods as $method) {?>
<li>
<b><?php echo $method['name'];?></b>
<a href="#<?php echo $method['name'];?>"><i>Détail</i></a>
</li>
<?php }?>
</ol>
</div>
</div>
<div class="page-header">
<h2>Détails</h2>
</div>
<?php foreach ($this->serviceMethods as $method) {?>
<div class="panel panel-default" id="<?=$method['name']?>">
<div class="panel-heading">
<h3 class="panel-title"><h4><?=$method['name']?></h4></h3>
</div>
<div class="panel-body">
<h5>Description</h5>
<div class="bs-callout bs-callout-php">
<h4><code><?=$this->docMethod($method)?></code></h4>
<p><?=$this->docComplement($method)?></p>
<p><?=$this->docDescription($method)?></p>
</div>
<h5>Paramètres</h5>
<div class="bs-callout bs-callout-php">
<?=$this->docParameter($method['params'], $this->serviceTypes);?>
</div>
<h5>Retour</h5>
<div class="bs-callout bs-callout-php">
<?php if ($method['returnDesc'] != '') {?><?=$method['returnDesc']?><br/><br/><?php }?>
<?=$this->docReturn($method['return'], $this->serviceTypes);?>
</div>
<?php $exemple = $this->docExemple($method['name'])?>
<?php if ( !empty($exemple) ) {?>
<h5>Exemple</h5>
<div class="bs-callout bs-callout-php">
<?=$exemple?>
</div>
<?php }?>
</div>
</div>
<?php } ?>

View File

@ -1,51 +0,0 @@
<div class="page-header"><h1>Liste des services disponibles</h1></div>
<p class="lead">Ci-dessous la liste des services disponibles, personnalisés ou standards.</code>.</p>
<?php foreach ($this->WsServices as $service => $params) {?>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<a href="<?=$this->url(array(
'controller'=>'documentation',
'action'=>'servicev',
'name'=>$service,
'type'=>$params['type']),null,true)?>">
<?=$params['name']?>
</a>
</div>
<div class="panel-body">
<p>Informations</p>
</div>
<?php if (isset($params['versions'])) { ?>
<ul class="list-group">
<?php foreach ($params['versions'] as $version => $versionElement) { ?>
<li class="list-group-item">
<a href="<?=$this->url(array(
'controller'=>'documentation',
'action'=>'service',
'name'=>$service,
'type'=>$params['type'],
'version'=>$version),null,true)?>">
Version <?=$version?></a>
<div class="pull-right">
<?php if ( $versionElement['defaut'] === true ) { ?>
<span class="label label-success">Actuel</span>
<?php } elseif ( $versionElement['defaut'] === false ) {?>
<span class="label label-danger">Déprécié</span>
<?php } elseif ( $versionElement['defaut'] == 'beta') {?>
<span class="label label-warning">Beta</span>
<?php }?>
<?php if ( $versionElement['actif'] === true ) { ?>
<span class="label label-info">Actif</span>
<?php } else {?>
<span class="label label-info">Inactif</span>
<?php }?>
</div>
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
<?php } ?>

View File

@ -1,40 +0,0 @@
<?php
$service = null;
if ( array_key_exists($this->key, $this->WsServices) ) {
$service = $this->WsServices[$this->key];
}
?>
<?php if ( $service === null ) {?>
<?php } else {?>
<div class="page-header"><h1>Versions du service <?=$service['name']?></h1></div>
<p class="lead">...</p>
<?php if (isset($service['versions'])) { ?>
<?php foreach ($service['versions'] as $version => $versionElement) { ?>
<div class="panel panel-default">
<div class="panel-heading">
<a href="<?=$this->url(array(
'controller'=>'documentation',
'action'=>'service',
'name'=>$this->key,
'type'=>$service['type'],
'version'=>$version))?>">
Version <?=$version?></a>
<?php if ( $versionElement['defaut'] === true ) { ?>
<span style="float:right;" class="label label-success">Défaut</span>
<?php } elseif ( $versionElement['defaut'] === false ) {?>
<span style="float:right;" class="label label-danger">Déprécié</span>
<?php } elseif ( $versionElement['defaut'] == 'beta') {?>
<span style="float:right;" class="label label-warning">Beta</span>
<?php }?>
</div>
<div class="panel-body">
<p>Information</p>
</div>
</div>
<?php }?>
<?php }?>
<?php } ?>

View File

@ -1,18 +0,0 @@
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>
<?php if (isset($this->exception)): ?>
<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>
<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>
<h3>Request Parameters:</h3>
<pre><?php echo var_export($this->request->getParams(), true) ?>
</pre>
<?php endif ?>

View File

@ -1,3 +0,0 @@
<div class="container">
<p class="text-muted credit"> &copy; <?=date('Y')?> <a href="http://www.scores-decisions.com">Scores & Décisions SAS</a>.</p>
</div>

View File

@ -1,38 +0,0 @@
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Web Service API</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<?php foreach ($this->navigation()->getContainer() as $page) {?>
<?php if ( $page->hasPages() ) {?>
<li class="dropdown<?php if ( $page->isActive(true) ) { echo ' active'; } ?>">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?=$page->label?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="<?=$page->getHref()?>">Accueil</a></li>
<li class="divider"></li>
<?php foreach ( $page->getPages() as $child ) {?>
<?php if ( $child->getHref() == '#') {?>
<li class="divider"></li>
<?php } else {?>
<li<?php if ( $child->isActive(true) ) { echo ' class="active"'; } ?>><a href="<?=$child->getHref()?>"><?=$child->label?></a></li>
<?php }?>
<?php }?>
</ul>
</li>
<?php } else {?>
<li<?php if ( $page->isActive(true) ) { echo ' class="active"'; } ?>><a href="<?=$page->getHref()?>"><?=$page->label?></a></li>
<?php }?>
<?php }?>
</ul>
<p class="navbar-text pull-right"><?=$this->profileLink()?></p>
</div><!--/.nav-collapse -->
</div>
</div>

View File

@ -1,53 +0,0 @@
<div>
<h2>Intégration d'un fichier</h2>
<p>Taille maximale d'un fichier : <?=$this->filesize?></p>
<form enctype="multipart/form-data" name="sendfile" action="<?=$this->url(array('controller'=>'import','action'=>'fileupload'))?>" method="post">
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="key" value="<?=uniqid()?>"/>
<input type="hidden" name="idClient" value="<?=$this->idClient?>" />
<input type="hidden" name="login" value="<?=$this->login?>" />
<div class="fieldgrp">
<label>Fichier</label>
<div class="field">
<input type="file" id="fichier" name="fichier"/>
<input type="submit" value="Envoi"/>
<div id="progressbar"></div>
<div id="output"></div>
</div>
</div>
</form>
</div>
<?=$this->inlineScript()?>
<script>
var timer;
$('form[name=sendfile]').ajaxForm({
beforeSubmit: function() {
timer = setInterval(checkProgress,200);
$('#progressbar').reportprogress(0);
$('#output').html('Envoi en cours...');
},
success: function(data) {
clearInterval(timer);
$('#progressbar').remove();
$('#output').html('<strong>' + data + '</strong>');
}
});
function checkProgress() {
$.get('<?=$this->url(array('controller'=>'import', 'action'=>'fileprogress'))?>',
{key: $('#key').val()}, function(data) {
var percent = data.current/data.total*100;
$('#progressbar').reportprogress(percent);
}, 'json');
}
</script>

View File

@ -1,6 +0,0 @@
<div class="page-header"><h1>Contact</h1></div>
<p class="lead"></p>
<p>Pour toutes questions concernant les paramètres techniques ou une explication des données, vous pouvez contactez
votre commercial ou le service support (<a href="mailto:support@scores-decisions.com">support@scores-decisions.com</a>).</p>
<p>Merci de rappeler pour référence le login utilisé pour l'accès au WebService.</p>

View File

@ -1,6 +0,0 @@
<div class="page-header"><h1>Contact</h1></div>
<p class="lead"></p>
<p>Pour toutes questions concernant les paramètres techniques ou une explication des données, vous pouvez contactez
votre commercial ou le service support (<a href="mailto:support@scores-decisions.com">support@scores-decisions.com</a>).</p>
<p>Merci de rappeler pour référence le login utilisé pour l'accès au WebService.</p>

View File

@ -1,7 +0,0 @@
<div class="page-header"><h1>Web Service API</h1></div>
<p class="lead">Scores & Décisions fournit un ensemble d'information sous la forme d'une API
compatible avec le protocole SOAP permettant la communication et l'échange de données avec vos
applications métier.
</p>
<p>La documentation vous fournira les éléments techniques relatifs aux <em>paramètres de connexion</em>,
<em>structure des données</em>, ...</p>

View File

@ -1,26 +0,0 @@
<?php echo $this->doctype(); ?>
<html>
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headStyle(); ?>
<?php echo $this->headLink(); ?>
<?php echo $this->headScript(); ?>
</head>
<body>
<div id="wrap">
<?php echo $this->render('header.phtml') ?>
<div class="container">
<?php echo $this->layout()->content; ?>
</div>
</div>
<div id="footer">
<?php echo $this->render('footer.phtml'); ?>
</div>
<?php echo $this->inlineScript(); ?>
</body>
</html>

View File

@ -1 +0,0 @@
<?= $this->message ?>

View File

@ -1 +0,0 @@
<?php

View File

@ -1 +0,0 @@
<?= $this->message ?>

View File

@ -1 +0,0 @@

View File

@ -1,33 +0,0 @@
<?php echo $this->doctype(); ?>
<html>
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headStyle(); ?>
<?php echo $this->headLink(); ?>
<?php echo $this->headScript(); ?>
</head>
<body>
<div id="wrap">
<div class="container">
<form class="form-signin" method="<?=$this->form->getMethod()?>" action="<?=$this->form->getAction()?>">
<h2 class="form-signin-heading">Web Service API</h2>
<div style="text-align:center;"><p class="text-danger"><span><?=$this->message?></span></p></div>
<input name="login" value="<?=$this->form->getValue('login')?>" type="text" class="form-control" placeholder="Identifiant" autofocus>
<input name="pass" value="<?=$this->form->getValue('pass')?>" type="password" class="form-control" placeholder="Mot de passe">
<button class="btn btn-lg btn-primary btn-block" type="submit">Connexion</button>
</form>
</div>
</div>
<div id="footer">
<?php echo $this->render('footer.phtml'); ?>
</div>
<?php echo $this->inlineScript(); ?>
</body>
</html>

View File

@ -1,24 +0,0 @@
<?php echo $this->doctype(); ?>
<html>
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headStyle(); ?>
<?php echo $this->headLink(); ?>
</head>
<body>
<div id="wrap">
<div class="container">
<p>Vous avez été déconnecté.</p>
</div>
</div>
<div id="footer">
<?php echo $this->render('footer.phtml'); ?>
</div>
</body>
</html>

View File

@ -1,36 +0,0 @@
<div class="page-header"><h1>Identifiant</h1></div>
<h2>Identité</h2>
<address>
<p>Login : <?=$this->login?></p>
<strong><?=$this->IdFullName?></strong><br>
<a href="mailto:#"><?=$this->IdEmail?></a>
</address>
<h2>Authorization Header</h2>
<div class="bs-callout bs-callout-warning">
Authorization: Basic <?=$this->authorizationHeader;?>
</div>
<div>
Base64("<?=$this->login?>:*****") = "<?=$this->authorizationHeader;?>"
</div>
<div class="page-header"><h1>Paramètres</h1></div>
<table class="table">
<thead>
<tr>
<th>Méthode</th>
<th>Droit</th>
</tr>
</thead>
<tbody>
<?php if ( count($this->display)>0 ) {?>
<?php foreach ( $this->display as $d ) {?>
<tr>
<td><?=$d['label']?></td>
<td><?=$d['droit']?></td>
</tr>
<?php }?>
<?php }?>
</tbody>
</table>

268
batch/calculRatios.php Normal file
View File

@ -0,0 +1,268 @@
#!/usr/bin/php -c/var/www/batch/config/php_batch_sd.ini
<?php
error_reporting(E_ALL & ~E_NOTICE);
include_once(FWK_PATH.'common/chiffres.php');
include_once(FWK_PATH.'common/dates.php');
include_once(INCLUDE_PATH.'insee/classMInsee.php');
include_once(INCLUDE_PATH.'partenaires/classMGreffes.php');
include_once(FWK_PATH.'common/dates.php');
include_once(INCLUDE_PATH.'partenaires/classMBilans.php');
include_once(FWK_PATH.'mail/sendMail.php');
$strInfoScript='Usage : '.basename($argv[0]). " [OPTION]
Calcul des ratios de toute la base entreprise S&D.
Options :
-t Calculer tous les ratios (*)
-i:XXX Reprendre à la ligne XXX
-c Mettre à jour le cache
-d:SSAAMMJJhhiiss Forcer la date de dernière MAJ à ...
(*) Option par défaut si aucun argument n'est passé.
";/* -e:X Calculer pour les X derniers exercices (3 par défaut)
-f Calculer les scores financiers
*/
$iDeb=0;
$updateCache=false;
for ($i=1; isset($argv[$i]); $i++) {
if (substr($argv[$i],0,1)=='-') {
switch (strtolower(substr($argv[$i],1,1))) {
case 't':
break;
case 'i':
$iDeb=substr($argv[$i],3)*1;
break;
case 'd':
$dateDeb=substr($argv[$i],3)*1;
break;
case 'c':
$updateCache=true;
break;
case '-':
case '?':
die($strInfoScript);
break;
default:
die('Option '. $argv[$i] . ' inconnue !'.EOL);
break;
}
}
}
//$iDbI=new WDB('insee');
$iDb=new WDB('jo');
$iDb2=new WDB('jo');
$iInsee=new MInsee();
if ($updateCache) {
include_once(INCLUDE_PATH.'scores/classMRatios.php');
if (genereCacheRatios())
echo date('Y/m/d - H:i:s') ." - Le cache des ratios a été généré avec succès !".EOL;
else
echo date('Y/m/d - H:i:s') ." - Erreur lors de la génération du cache des ratios !".EOL;
die();
}
echo date('Y/m/d - H:i:s') ." - DEBUT du programme de calcul des ratios...".EOL;
$tabLast=$iDb->select( 'ratios_formules',
'max(dateUpdate) AS lastUpdate, max(dateInsert) AS lastInsert',
'1');
$lastUpdate=$tabLast[0]['lastInsert'];
if ($tabLast[0]['lastUpdate']>$lastUpdate) $lastUpdate=$tabLast[0]['lastUpdate'];
/** On vérifie la présence du cache de calcul des ratios **/
if (!file_exists(INCLUDE_PATH.'tmp/configMRatios.php'))
die(date('Y/m/d - H:i:s') ." - ERREUR FATALE : Le cache des calculs de ratio n'existe pas !".EOL);
/** On vérifie qu'il n'y a pas de nouvelles formules à mettre dans le cache de calcul des ratios **/
elseif (strtr($lastUpdate, array(':'=>'','-'=>'', ' '=>''))>date('YmdHis',filectime(INCLUDE_PATH.'tmp/configMRatios.php'))) {
sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "ERREUR FATALE, le cache ratio n'est pas à jour !", date('Y/m/d - H:i:s') ." - ERREUR FATALE : Le cache des calculs de ratio n'est pas à jour (nouvelles formules ?). Relancer à l'option -c !");
die(date('Y/m/d - H:i:s') ." - ERREUR FATALE : Le cache des calculs de ratio n'est pas à jour (nouvelles formules ?). Relancer à l'option -c !".EOL);
}
/** On vérifie que le programme de MAJ du cache n'a pas été modifié **/
elseif (date('YmdHis',filectime(INCLUDE_PATH.'scores/classMRatios.php'))>date('YmdHis',filectime(INCLUDE_PATH.'tmp/configMRatios.php'))) // Le fichier de cache est déprécié
die(date('Y/m/d - H:i:s') ." - ERREUR FATALE : Le cache des calculs de ratio n'est pas à jour (programme modifié). Relancer à l'option -c !".EOL);
include_once(INCLUDE_PATH.'tmp/configMRatios.php');
echo date('Y/m/d - H:i:s') ." - Formules de calcul des ratios déjà en cache.".EOL;
/** Recherche de la dernière mise à jour des ratios secteurs **/
$tabLast=$iDb->select( 'ratios_secteurs',
'max(dateUpdate) AS lastUpdate, max(dateInsert) AS lastInsert',
'1');
$lastUpdate=$tabLast[0]['lastInsert'];
if ($tabLast[0]['lastUpdate']>$lastUpdate) $lastUpdate=$tabLast[0]['lastUpdate'];
if ($dateDeb>20000101123000) $lastUpdate=$dateDeb;
echo(date('Y/m/d - H:i:s') ." - La dernière mise à jour des ratios secteurs date du $lastUpdate...".EOL);
$nbRows=$iDb->select( 'ratios_tmp', 'siren, lastUpdate', "1", false, MYSQL_ASSOC, true);
if ($nbRows>0) {
$modeSuite=true;
echo date('Y/m/d - H:i:s') ." - Il reste $nbRows entreprises pour lesquels il faut mettre à jour les ratios secteurs...".EOL;
} else {
/** On met en table temporaire les siren en cas de plantage du script **/
$modeSuite=false;
// Date du dernier bilan inseré
$tabLast=$iDb->select( 'bilans',
'MAX(dateInsert) AS lastDateInsert',
"siren>100 AND dateInsert>='$lastUpdate' AND typeBilan IN ('N','',' ','A','B') ORDER BY dateInsert DESC");
$lastDateBilan=strtr($tabLast[0]['lastDateInsert'],array(' '=>'',':'=>'','-'=>''));
echo(date('Y/m/d - H:i:s') ." - Le dernier bilan inséré en base date du $lastDateBilan...".EOL);
// Liste des derniers Bilans insérés depuis le dernier calcul des ratios
$nbRows=$iDb->select( 'bilans', 'DISTINCT siren', "siren>100 AND dateInsert>='$lastUpdate' AND typeBilan IN ('N','',' ','A','B') ORDER BY dateInsert DESC", false, MYSQL_ASSOC, true);
$lastDate=strtr($lastUpdate,array(' '=>'',':'=>'','-'=>''));
echo date('Y/m/d - H:i:s') ." - Il y a $nbRows entreprises avec nouveaux bilans pour calcul des ratios secteurs...".EOL;
$iDb2->query('DROP TABLE IF EXISTS ratios_tmp;');
if (mysql_errno()>0) echo date('Y/m/d - H:i:s') .' - ERREUR SQL lors de la création de la table temporaires, n°'.mysql_errno().' : '.mysql_error().EOL;
$strSQL="CREATE TABLE IF NOT EXISTS ratios_tmp ( siren int(9) unsigned zerofill NOT NULL, lastUpdate bigint(14) unsigned zerofill NOT NULL, lastBilan bigint(14) unsigned zerofill NOT NULL, PRIMARY KEY(siren) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
$iDb2->query($strSQL);
if (mysql_errno()>0) echo date('Y/m/d - H:i:s') .' - ERREUR SQL lors de la création de la table temporaires, n°'.mysql_errno().' : '.mysql_error().EOL;
while($entrep=$iDb->fetch(MYSQL_ASSOC)) {
$iDb2->insert('ratios_tmp', array('siren'=>$entrep['siren'], 'lastUpdate'=>$lastDate, 'lastBilan'=>$lastDateBilan));
}
echo date('Y/m/d - H:i:s') ." - Les éléments ont été mis en table temporaire en cas de reprise sur erreur !".EOL;
$nbRows=$iDb->select( 'ratios_tmp', 'siren, lastUpdate, lastBilan', "1", false, MYSQL_ASSOC, true);
}
$k=0; // Compteur d'entreprises
$b=0; // Compteur total de bilans
while($entrep=$iDb->fetch(MYSQL_ASSOC)) {
if ($modeSuite && $k==0) $lastDate=$entrep['lastUpdate'];
$k++;
if ($k<$iDeb) continue;
$siren=$entrep['siren'];
if ($siren<100) continue;
// else echo "$siren\n";
$naf4=$naf5='';
unset($mBil);
$mBil=new MBilans($siren);
/** Récupération des informations Identitaires **/
$tabIdentite=@$iInsee->getIdentiteLight($siren);
$naf=$tabIdentite['NafEnt'];
$nafLib=$tabIdentite['NafEntLib'];
$efftr=$tabIdentite['Effectif'];
$fj=$tabIdentite['FJ'];
/** On Recherche le dernier Bilan mis à jour **/
$tabBilans=$mBil->listeBilans();
$nbBilansTot=count($tabBilans);
$tabBilans2=array();
foreach ($tabBilans as $mil=>$infosBilan) {
/** On vérifie s'il n'y a pas de Bilans vides **/
if ($infosBilan['dureeExercice']==0) {
print_r($infosBilan);
echo date('Y/m/d - H:i:s') ." - Erreur : Bilans vide en base pour le siren $siren !".EOL;
continue(2);
}
/** On ne garde que les Bilans dont la date de provenance est > à la date de dernière Mise à jour
** car les ratios secteurs des autres bilans on déjà été calculés ! **/
if ($infosBilan['dateInsert']>=$lastDate)
$tabBilans2[$mil]=$infosBilan;
}
$nbBilans=count($tabBilans2);
$tabBilan=$tabBil=array();
if ($nbBilans==0) {
print_r($tabBilans2);
echo date('Y/m/d - H:i:s') ." - Erreur : Aucun nouveau bilan en base pour le siren $siren sur les $nbBilansTot bilans !".EOL;
print_r($tabBilans);
//die();
continue;
}
$tabRatios=@calculRatios($tabBilans2, $tabIdentite, false);
if (strlen($naf)>4) $naf5=$naf; else $naf4=$naf;
if ($tabBilan[0]['CONSOLIDE']=='A') $naf4='ASSU';
elseif ($tabBilan[0]['CONSOLIDE']=='B') $naf4='BANQ';
if ($naf4=='ASSU' || $naf4=='BANQ') {
sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Calcul des ratios : Attention bilan de Banque ou Assurance", "Siren $siren, bilan $naf4".EOL.print_r($tabBilans));
}
foreach ($tabFormules as $f=>$formule) {
foreach ($tabRatios as $i=>$R) {
if ($f==0) $b++;
$id=$formule['id'];
// Si on n'est pas une banque/assurance, on ne calcul pas les ratios 700 à 799
if ($naf4<>'ASSU' && $naf4<>'BANQ' && $id>=700 && $id<800)
continue;
$annee=substr($tabBilan[$i]['DATE_CLOTURE'],0,4);
if ($R[$id]==='NS' || $R[$id]===false )
//echo "Le ratio n°$id est non significatif (".$R[$id].") pour le siren $siren et l'année $annee !".EOL;
continue;
/** Si c'est un ratio EUR, on le passe en K€ **/
if ($formule['unite']=='EUR') $mt=$R[$id]/1000;
else $mt=$R[$id];
/** On vérifie les bornes MIN et MAX **/
if ($formule['min']<>'' && $mt<$formule['min']) {
echo "Ratio n°$id, borne Mini non nulle (".$formule['min'].") et le montant est inférieur : $mt<".$formule['min']." pour le siren $siren et l'année $annee".EOL;
continue;
} elseif ($formule['max']<>'' && $mt>$formule['max']) {
echo "Ratio n°$id, borne Maxi non nulle (".$formule['max'].") et le montant est supérieur : $mt>".$formule['max']." pour le siren $siren et l'année $annee".EOL;
continue;
} //else
//echo "Ratio n°$id compris entre bornes ".$formule['min']." < $mt < ".$formule['max']." pour le siren $siren et l'année $annee".EOL;
/** Lecture des chiffres existants dans la table ratios_secteurs **/
$tabTmp=$iDb2->select( 'ratios_secteurs',
'montant, nombre, id, naf4, naf5, annee',
"id=$id AND naf4='$naf4' AND naf5='$naf5' AND annee=$annee",
false, MYSQL_ASSOC);
if (count($tabTmp)>0) {
$mt2=$mt+$tabTmp[0]['montant'];
$nb2=$tabTmp[0]['nombre'] + 1;
} else {
$mt2=$mt;
$nb2=1;
}
$tabUpdate=array( 'montant' => $mt2,
'nombre' => $nb2,
);
if (!$iDb2->update('ratios_secteurs', $tabUpdate, "id=$id AND naf4='$naf4' AND naf5='$naf5' AND annee=$annee") || $iDb2->getAffectedRows()==0 ) { // getAffectedRows ajouté le 14 mai 2009
$tabInsert=array_merge($tabUpdate, array( 'id'=>$id,
'naf4'=>$naf4,
'naf5'=>$naf5,
'annee'=>$annee,
'dateInsert'=>$lastDateBilan,
));
if (!$iDb2->insert('ratios_secteurs', $tabInsert) && mysql_errno()<>1062) {
$pct=round(($k/$nbRows)*100,2);
echo date('Y/m/d - H:i:s') ." - $k entreprises ($pct %) dont les ratios ont été calculés pour un total de $b bilans ($siren)...".EOL;
echo date('Y/m/d - H:i:s') .' - ERREUR SQL n°'.mysql_errno().' : '.mysql_error().EOL;
die();
}
}
if ($k%1000==0 && $f==0 && $i==0) {
$pct=round(($k/$nbRows)*100,2);
echo date('Y/m/d - H:i:s') ." - $k entreprises ($pct %) dont les ratios ont été calculés pour un total de $b bilans ($siren)...".EOL;
}
}
}
$iDb2->delete('ratios_tmp', "siren=$siren");
if (mysql_errno()>0) echo date('Y/m/d - H:i:s') .' - ERREUR SQL lors de la suppression des informations temporaires, n°'.mysql_errno().' : '.mysql_error().EOL;
}
echo date('Y/m/d - H:i:s') ." - Les ratios ont été mis à jour ; suppression des informations temporaires.".EOL;
$iDb2->query('DROP TABLE IF EXISTS jo.ratios_tmp;');
die(date('Y/m/d - H:i:s') ." - Fin du programme.".EOL);
?>

197
batch/setCacheTables.php Normal file
View File

@ -0,0 +1,197 @@
#!/usr/bin/php -c/var/www/batch/config/php_batch_sd.ini
<?php
function wsLog() {}
include_once(FWK_PATH.'common/chiffres.php');
include_once(FWK_PATH.'common/dates.php');
include_once(INCLUDE_PATH.'insee/classMInsee.php');
include_once(INCLUDE_PATH.'scores/classMRegression.php');
include_once('/var/www/html/ws2/WsEntreprise.php');
include_once(FWK_PATH.'mail/sendMail.php');
/*
for ($i=1; $i<=200; $i++) {
$date=date('H:i:s');
sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Mesage de test n°$i - $date", "Bonjour,
Voici le mail $i.
Cordialement,
YLN");//, '', array('kbis'=>'/tmp/kbis-518453394.pdf'));
}
die();
*/
$strInfoScript='Usage : '.basename($argv[0]). " <option> [FICHIERS]
Génération du cache des variables courantes si nécessaire.
Options :
-d Mode debug (Verbosité au maximum)
-f Forcer la re-Génération du cache
";
$modeDebug=$modeGeneration=false;
$argv=$_SERVER['argv'];
for ($i=1,$j=0; isset($argv[$i]); $i++) {
if (substr($argv[$i],0,1)=='-') {
switch (substr($argv[$i],1,1)) {
case 'd': $modeDebug=true; break;
case 'f': $modeGeneration=true; break;
case '-':
case '?': die($strInfoScript); break;
default: die('Option '. $argv[$i] . ' inconnue !'.EOL); break;
}
}// else $tabFichLigneCmd[]=$argv[$i];
}
$iDb=new WDB();
global $tabVariables;
$tdeb=microtime(true);
if (!$modeGeneration &&
file_exists('/var/www/html/ws2/data/tables/tables.bin') &&
file_exists('/var/www/html/ws2/data/tables/tables.ini') &&
filemtime('/var/www/html/ws2/data/tables/tables.bin')>filemtime("/var/www/html/ws2/data/tables/tables.ini")) {
if ($modeDebug) echo date('Y/m/d - H:i:s') ." - Lecture du cache...".EOL;
$tabVariables=unserialize(file_get_contents('/var/www/html/ws2/data/tables/tables.bin'));
$nb=count($tabVariables);
$duree=round((microtime(true)-$tdeb)*1000,1);
if ($modeDebug) {
$tailleM=round(memory_get_usage(true)/1024,1);
$tailleF=round(filesize('/var/www/html/ws2/data/tables/tables.bin')/1024,1);
$strFin=" (bin=$tailleF Ko, mem=$tailleM Ko).";
} else
$strFin='.';
echo date('Y/m/d - H:i:s') ." - Lecture du cache en $duree ms : $nb variables$strFin".EOL;
} else {
// Analyse avec les sections
$ini_array = parse_ini_file("/var/www/html/ws2/data/tables/tables.ini", TRUE);
$tabVariables=array();
foreach ($ini_array as $idVar => $tabVar) {
$idVar=strtoupper($idVar); // Nom= de la variable
$source=trim(strtoupper($tabVar['source']));
if ($modeDebug) echo date('Y/m/d - H:i:s') ." - [$idVar] Source='$source'...".EOL;
switch ($source) {
case 'SQL':
if (!isset($tabVar['sql'])) die("ERREUR : Requête SQL non définie pour [$idVar]");
$nbRecords=$iDb->query($tabVar['sql']);
if ($iDb->getLastErrorNum()>0) die("ERREUR : Requête SQL non fonctionnelle pour [$idVar] (".$iDb->getLastError().')');
if ($modeDebug) echo date('Y/m/d - H:i:s') ." - [$idVar] Source='$source' SQL: $nbRecords enregistrements...".EOL;
while ($ret=$iDb->fetch(MYSQL_ASSOC)) {
// Traitement de la zone libelle
if (strtoupper($ret['libelleCase'])=='MAJ')
$libelle=trim(ucfirst(strtolower($ret['libelle'])));
else
$libelle=trim($ret['libelle']);
// Traitement de la zone article
$article=trim($ret['article']);
if ($article=='') {
if (isset($tabVar['articles']) && strtolower($tabVar['articles'])=='auto') {
if (preg_match('/^(a|e|i|o|u|y)/i', $libelle))
$article='d\''.$libelle;
else
$article='de '.$libelle;
} else
$article=$libelle;
} elseif (preg_match('/^(.*)\$/', $article, $matches)) // en $
{ $article=trim(preg_replace('/ +/',' ', $matches[1].' '.$libelle));
$article=strtr($article, array("' "=>"'"));
}
$tabVariables[$idVar][trim($ret['code'])]=array('lib'=>$libelle,
'art'=>$article,
);
}
break;
default: // si <> de blanc, recopie de tableau existant
if ($source=='') die("ERREUR : Source non renseignée pour [$idVar]");
if (!isset($tabVariables[$source])) die("ERREUR : Source '$source' inexistante pour [$idVar]");
$tabVariables[$idVar]=$tabVariables[$source];
break;
}
}
$nb=count($tabVariables);
$duree=round((microtime(true)-$tdeb)*1000,1);
echo date('Y/m/d - H:i:s') ." - Génération du cache en $duree ms : $nb variables.".EOL;
if ($modeDebug) {
$tailleM=round(memory_get_usage(true)/1024,1);
$tailleF=round(filesize('/var/www/html/ws2/data/tables/tables.bin')/1024,1);
$strFin=" (bin=$tailleF Ko, mem=$tailleM Ko).";
} else
$strFin='.';
if (file_put_contents('/var/www/html/ws2/data/tables/tables.bin',serialize($tabVariables)))
echo date('Y/m/d - H:i:s') ." - Cache des tables associées généré$strFin".EOL;
}
//print_r($tabVariables);
die();
$R[6]=555;
$var='R[6]';
echo "'${${$var}}'";
die();
if (1==1 && 2==3 && (3==3 || 5==5 ))
echo 'Vrai';
else
echo 'Faux';
echo EOL;
die();
$siren=391032455;
//572014199;
//552144503;
$iWs=new WsEntreprise();
$tabRatios=@$iWs->getRatios($siren);
//print_r($tabRatios);
$iMax=count($tabRatios['result']['RatiosEntrep'])-1;
$r=$a=array();
for ($i=$iMax;$i>=0;$i--)
$r[]=$tabRatios['result']['RatiosEntrep'][$i]['r6']/1000;
for ($i=$iMax;$i>=0;$i--)
$a[]=substr($tabRatios['result']['BilansInfos'][$i]['dateCloture'],0,4)*1;
$y3=$r;//array(150, 155, 160, 165 ,170 ,175 ,180 ,185 ,190);
$x3=$a;//array(2000,2001,2002,2003,2004,2005,2006,2007,2008);
/*
$y3=array(150, 155, 160, 165 ,170 ,175 ,180 ,185 ,190);
$x3=array(2000,2001,2002,2003,2004,2005,2006,2007,2008);
*/
print("Années :".EOL);
print_r($a);
print("CA :".EOL);
print_r($r);
$oReg= new Regression($y3,$x3);
for ($i=0; $i<5; $i++) {
print("Meth $i".EOL);
print_r($oReg->OptMV($i));
print("Meth OPT".EOL);
print_r($oReg->GetOpt());
$an=3;
print("Projection à $an:".EOL);
print_r($oReg->GetProjection($an));
echo "Taux de Progression de ".$oReg->TauxProgression($an).EOL;
}
?>

View File

@ -1,50 +0,0 @@
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => "Aide.",
'path=s' => "{Service Name}/{version}",
));
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if ($optionsNb == 0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "\nType Service\n\n";
echo $opts->getUsageMessage();
exit;
}
$wsPath = APPLICATION_PATH . '/../library/WsScore/';
require_once $wsPath . $opts->path . '/Types.php';
$detect = new Zend_Reflection_File($wsPath . $opts->path . '/Types.php');
$result = $detect->getClasses();
$outPath = dirname($wsPath . $opts->path . '/Types.php');
$outFile = $outPath . '/Config.php';
if (count($result) > 0) {
file_put_contents($outFile, "<?php\n");
file_put_contents($outFile, "return array(\n", FILE_APPEND);
foreach ($result as $c) {
file_put_contents($outFile, "\t'". $c->name . "' => '" . $c->name ."',\n", FILE_APPEND);
}
file_put_contents($outFile, ");\n", FILE_APPEND);
}

View File

@ -1,60 +0,0 @@
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
error_reporting(E_ALL & ~E_NOTICE);
$typesFichier = array('csv', 'fichiers', 'clients', 'kbis');
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => 'Displays usage information.',
'all' => 'Execute toutes les actions (cron).',
'type=w' => 'Supprime uniquement les fichiers indiqués.',
));
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if ($optionsNb == 0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo $opts->getUsageMessage();
?>
Types de fichier disponibles : <?php echo join(', ', $typesFichier)?>
<?php
exit;
}
if ($opts->all || $opts->type)
{
foreach ($typesFichier as $dir)
{
if ($opts->all || $opts->type==$dir ){
removeFileInDir(LOG_PATH.'/'.$dir);
}
}
}
function removeFileInDir($dir)
{
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
unlink($dir . $file);
}
closedir($dh);
}
}
}

View File

@ -1,443 +0,0 @@
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => "Affiche l'aide.",
'list' => "Liste les actes en attente disponible sur le FTP et affiche les informations",
'get-s' => "Recupère seulement les actes du FTP (un seul document si la référence est spécifier G<NNN> )",
'send-s' => "Récupère les actes et envoi un mail à chaque client (un seul acte si la référence est spécifier G<NNN>)",
'type-s' => "Type de document : bilan, acte",
));
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if ($optionsNb == 0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Vérifie les actes numérisés reçus en provenance des Greffes.";
echo "\n\n";
echo $opts->getUsageMessage();
echo "\n";
exit;
}
$testMail = false;
$test = false;
if (isset($opts->list)){
$test = true;
}
$types = array('bi', 'ac');
// Configuration FTP
define ('ACTES_IGNUM_FTP_URL', 'ftp.scores-decisions.com');
define ('ACTES_IGNUM_FTP_USER', 'mpc2500');
define ('ACTES_IGNUM_FTP_PASS', 'passmpc78');
$pathIn = $c->profil->path->shared.'/files';
$report_email = $c->profil->mail->email->support;
$report_subject = 'Traitement des actes '.date('Y-m-d H:i:s');
$report_txt = '';
function sendMail($commande, $type){
$subject = "Actes ou Statuts disponible pour ".$commande->raisonSociale.' ('.$commande->siren.')';
$message = "Bonjour,\n\n";
$message.= "Le document commandé pour ".$commande->raisonSociale." (siren ".$commande->siren.") est disponible en téléchargement sur le site de Scores & Décisions.\r\n\r\n";
if ($commande->refClient!='') {
$message = "Votre référence : ".$commande->refClient."\r\n\r\n";
}
switch ( $type ) {
case 'BI':
$dateBilan = substr($commande->bilanCloture,8,2).'/'.substr($commande->bilanCloture,5,2).'/'.substr($commande->bilanCloture,0,4);
$message.= "Bilan cloturé le ".$dateBilan;
break;
case 'AC':
$dateActe = substr($commande->acteDate,8,2).'/'.substr($commande->acteDate,5,2).'/'.substr($commande->acteDate,0,4);
$dateDepot = substr($commande->depotDate,8,2).'/'.substr($commande->depotDate,5,2).'/'.substr($commande->depotDate,0,4);
$message.= "Acte n°".$commande->acteNum." du ".$dateActe." (Dépot n°".$commande->depotNum." du ".$dateDepot.") ";
break;
}
$message.= "\n\n";
$message.= "Consulter la fiche identité http://extranet.scores-decisions.com/identite/fiche/siret/".$commande->siren.", puis rubrique \"Pieces Officielles\"\n";
$message.= "ou directement depuis la page suivante http://extranet.scores-decisions.com/pieces";
switch ( $type ) {
case 'BI':
$message.= "/bilans/siret/".$commande->siren;
break;
case 'AC':
$message.= "/actes/siret/".$commande->siren;
break;
}
$message.= "\n\n";
$message.= "Bien cordialement, \n";
$message.= "Le service support.\n";
$message.= "\n";
$message.= "--";
$message.= "\n\n";
$message.= "SCORES & DECISIONS";
$message.= "\n";
$message.= "Service support";
$message.= "\n";
$message.= "1, rue de Clairefontaine - 78120 RAMBOUILLET";
$message.= "\n";
$message.= "tél : 0 811 261 216";
$message.= "\n";
$message.= "fax : 33 (0)1 75 43 85 74";
$message.= "\n";
$message.= "support@scores-decisions.com";
$message.= "\n";
$message.= "http://www.scores-decisions.com/";
$message.= "\n";
$message.= "Scores & Décisions est l'acteur nouvelle génération de l'information et de l'évaluation des entreprises";
$message.= "\n\n";
$message.= "Pensez à l'environnement avant d'imprimer ce message !";
$message.= "\n";
$message.= "Save paper - think before you print";
$message.= "\n";
$headers = 'From: support@scores-decisions.com' . "\r\n" .
'Reply-To: support@scores-decisions.com';
if ( mail(strtolower($commande->email), $subject, utf8_decode($message), $headers) ){
echo date ('Y/m/d - H:i:s').' - Un email a été envoyé à '.$commande->email." pour la commande ".$commande->id.".\n";
return true;
} else {
echo date ('Y/m/d - H:i:s').' - ERREUR : Impossible d\'envoyer l\'email à '.$commande->email." pour la commande ".$commande->id.".\n";
return false;
}
}
/**
* Liste des commandes non traités depuis la base de données
*/
$tabCommandes = array();
if (in_array('ac', $types)) {
$sql = "SELECT * FROM sdv1.greffe_commandes_ac WHERE mode=:mode AND dateCommande!=:commande AND dateEnvoi=:envoi";
$stmt = $conn->prepare($sql);
$stmt->bindValue('mode', 'C');
$stmt->bindValue('commande', '0000-00-00 00:00:00');
$stmt->bindValue('envoi', '0000-00-00 00:00:00');
$stmt->execute();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(\PDO::FETCH_OBJ)) {
$tabCommandes['G-AC-'.$row->id] = $row;
}
}
}
if (in_array('bi', $types)) {
$sql = "SELECT * FROM sdv1.greffe_commandes_bi WHERE mode=:mode AND dateCommande!=:commande AND dateEnvoi=:envoi";
$stmt = $conn->prepare($sql);
$stmt->bindValue('mode', 'C');
$stmt->bindValue('commande', '0000-00-00 00:00:00');
$stmt->bindValue('envoi', '0000-00-00 00:00:00');
$stmt->execute();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(\PDO::FETCH_OBJ)) {
$tabCommandes['G-BI-'.$row->id] = $row;
}
}
}
$nbCommandes = count($tabCommandes);
echo date('Y/m/d - H:i:s') ." - Il y a $nbCommandes commandes en attente de réception courrier ou numérisation !\n";
/**
* Connexion au site FTP pour la récupération de la liste des fichiers au format pdf
*/
$conn_id = ftp_connect(ACTES_IGNUM_FTP_URL);
if (!$conn_id) {
echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de se connecter au serveur FTP (".ACTES_IGNUM_FTP_URL.") !\n";
exit;
}
$login_result = ftp_login($conn_id, ACTES_IGNUM_FTP_USER, ACTES_IGNUM_FTP_PASS);
if (!$login_result) {
echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de s'authentifier sur le serveur FTP (".ACTES_IGNUM_FTP_URL.")!\n";
exit;
}
ftp_pasv($conn_id, true);
$contents = ftp_nlist($conn_id, "*.pdf");
if ($contents === false) {
echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de se connecter au serveur FTP (".ACTES_IGNUM_FTP_URL.") !\n";
exit;
}
/**
* Liste de tout les fichiers disponible dans le repertoire
* et associe une clé pour faciliter le tri
*/
$tabFichiersFtp = array();
foreach ($contents as $filename){
$indice = 0;
$f = strtolower($filename);
if (preg_match('/g-(ac|bi)-[0-9]+\.pdf/', $f)
|| preg_match('/g-(ac|bi)-[0-9]+-[0-9]{1,2}\.pdf/', $f)) {
$part = substr(str_replace('.pdf', '', $f), 5);
$p = strpos($part, '-');
if ( $p === false ) {
$ref = substr($f, 0, 5) . $part;
$indice = 0;
} else {
$ref = substr($f, 0, 5) . substr($part, 0, $p);
$indice = substr($part, $p+1);
}
$tabFichiersFtp[strtoupper($ref).'-'.$indice] = $filename;
}
// Fichiers en anomalies
else {
if ($test) {
echo "Erreur : Anomalie fichier numérisé $filename\n";
} else {
$subject = "Erreur : Anomalie fichier numérisé";
$message = "Le fichier $filename a été trouvé et ne correspond pas au format attendu";
$headers = 'From: supportdev@scores-decisions.com' . "\r\n" .
'Reply-To: supportdev@scores-decisions.com';
mail('supportdev@scores-decisions.com', $subject, $message, $headers);
}
}
}
/**
* Tri des fichiers par ordre décroissant
* Les noms des fichiers sont incrémenté par 1
*/
krsort($tabFichiersFtp);
/**
* Dans le cas ou il y a eu une erreur de scan, la production passe a nouveau le
* document dans le scanner et le fichier est envoyé sur le ftp
* Le document est nommé G[ref],G[ref]-1,G[ref]-2,.....pdf.
* On garde donc le dernier document scanné.
*/
$lastRef = '';
$tabFichiersTemp = array();
foreach($tabFichiersFtp as $k => $val) {
$part = substr($k, 5);
$p = strpos($part, '-');
if ($p === false) {
$ref = substr($k, 0, 5) . $part;
} else {
$ref = substr($k, 0, 5) . substr($part, 0, $p);
}
if( $lastRef != $ref ) {
$tabFichiersTemp[$ref] = $val;
}
$lastRef = $ref;
}
$tabFichiers = $tabFichiersTemp;
unset($tabFichiersTemp);
/**
* Pour chaque commande, test de la présence d'un fichier associé
* Si le fichier correspond téléchargement du fichier
*/
foreach ($tabCommandes as $ref => $commande) {
foreach ($tabFichiers as $refAssocie => $fichier) {
if ($ref == $refAssocie) {
echo date ('Y/m/d - H:i:s')." - Traitement de la commande $ref\n";
if ($test) {
echo date ('Y/m/d - H:i:s')." - Fichier $fichier \n";
} else {
// Récupération du fichier depuis le FTP (s'il n'existe pas déjà)
if (!file_exists($pathIn.'/'.$fichier)) {
if (ftp_get($conn_id, $pathIn.'/'.$fichier, $fichier, FTP_BINARY, 0)) {
echo date ('Y/m/d - H:i:s')." - Fichier $fichier téléchargé depuis le serveur FTP.\n";
} else {
echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de télécharger le fichier $fichier !\n";
}
}
switch (substr($ref,2,2)) {
case 'BI':
$infogreffe = new Metier_Infogreffe_DocBI();
$infogreffe->setSiren($commande->siren);
//Format date cloture
$dateCloture = substr($commande->bilanCloture,0,4) . '-' .
substr($commande->bilanCloture,5,2) . '-' .
substr($commande->bilanCloture,8,2);
$path = $infogreffe->getFilePath($commande->bilanType, $dateCloture);
$nomCible = $infogreffe->getFileName($commande->bilanType, $dateCloture);
$fileOut = $c->profil->infogreffe->storage->path.'/'.$path.'/'.$nomCible;
$isFileOnStorage = false;
if (file_exists($fileOut)) {
$isFileOnStorage = true;
echo date ('Y/m/d - H:i:s')." - Fichier ".$pathIn.'/'.$fichier." déjà présent en ".$fileOut.".\n";
} else {
if (copy($pathIn.'/'.$fichier, $fileOut)) {
$isFileOnStorage = true;
echo date ('Y/m/d - H:i:s')." - Fichier ".$pathIn.'/'.$fichier." déplacé en ".$fileOut.".\n";
} else {
echo date ('Y/m/d - H:i:s')." ERREUR - Impossible de déplacer ".$pathIn.'/'.$fichier." en ".$fileOut." !\n";
}
}
// --- Lecture présence référence bilan
if ($commande->bilanType=='sociaux') {
$sql = "SELECT * FROM jo.greffes_bilans WHERE siren=:siren AND date_cloture=:cloture AND type_comptes='' OR type_comptes='sociaux'";
} else {
$sql = "SELECT * FROM jo.greffes_bilans WHERE siren=:siren AND date_cloture=:cloture AND type_comptes='consolides'";
}
$stmt = $conn->prepare($sql);
$stmt->bindValue('siren', $commande->siren);
$stmt->bindValue('cloture', $dateCloture);
$stmt->execute();
$item = $stmt->fetch(\PDO::FETCH_OBJ);
// --- Enregistrement
if ($isFileOnStorage && $item->pdfDate == '0000-00-00') {
$infos = $infogreffe->pdfInfos($fileOut);
if (false !== $infos) {
$data = array(
'pdfLink' => $nomCible,
'pdfSize' => $infos['size'],
'pdfPage' => $infos['pages'],
'pdfVer' => $infos['version'],
'pdfDate' => date('Ymd'),
);
try {
$conn->update('jo.greffes_bilans', $data, array('id' => $item->id));
} catch(\Doctrine\DBAL\DBALException $e) {
echo $e->getMessage();
}
}
}
break;
case 'AC':
$sql = "SELECT id, siren, numRC, LPAD(numGreffe,4,0) AS numGreffe, pdfLink,
pdfSize, pdfPage, pdfDate, num_depot, date_depot, date_acte,
LPAD(num_acte,2,0) AS num_acte, type_acte, type_acte_libelle,
nbpages_acte, decision_nature, decision_libelle FROM jo.greffes_actes
WHERE siren=:siren AND num_depot=:depot AND num_acte=:acte AND type_acte=:type";
$stmt = $conn->prepare($sql);
$stmt->bindValue('siren', $commande->siren);
$stmt->bindValue('depot', $commande->depotNum);
$stmt->bindValue('acte', $commande->acteNum);
$stmt->bindValue('type', $commande->acteType);
$stmt->execute();
$item = $stmt->fetch(\PDO::FETCH_OBJ);
$infogreffe = new Metier_Infogreffe_DocAC();
$infogreffe->setSiren($commande->siren);
$date = $commande->acteDate;
if ($date == '0000-00-00') {
$date = $commande->depotDate;
}
$path = $infogreffe->getFilePath($date);
//(Numéro du Greffe)-(dossier_millesime)-(dossier_statut)-(dossier_chrono)-(num_depot)
$options = $item->numGreffe . '-' . substr($item->numRC,0,2) . '-' . substr($item->numRC,2,1) . '-' . substr($item->numRC,3) . '-' . $item->num_depot;
$nomCible = $infogreffe->getFileName($date, $commande->acteNum, $commande->acteType, $options);
$fileOut = $c->profil->infogreffe->storage->path.'/'.$path.'/'.$nomCible;
$isFileOnStorage = false;
if (file_exists($fileOut)) {
$isFileOnStorage = true;
echo date ('Y/m/d - H:i:s')." - Fichier ".$pathIn.'/'.$fichier." déjà présent en ".$fileOut.".\n";
} else {
if (copy($pathIn.'/'.$fichier, $fileOut)) {
$isFileOnStorage = true;
echo date ('Y/m/d - H:i:s')." - Fichier ".$pathIn.'/'.$fichier." déplacé en ".$fileOut.".\n";
} else {
echo date ('Y/m/d - H:i:s')." ERREUR - Impossible de déplacer ".$pathIn.'/'.$fichier." en ".$fileOut." !\n";
}
}
if ($isFileOnStorage && $item->pdfDate == '0000-00-00') {
$infos = $infogreffe->pdfInfos($fileOut);
if ( false !== $infos ) {
$data = array(
'pdfLink' => $nomCible,
'pdfSize' => $infos['size'],
'pdfPage' => $infos['pages'],
'pdfVer' => $infos['version'],
'pdfDate' => date('Ymd'),
);
try {
$conn->update('jo.greffes_actes', $data, array('id' => $item->id));
echo " = enregistrement.\n";
} catch(\Doctrine\DBAL\DBALException $e) {
echo $e->getMessage();
}
}
}
break;
}
// Envoi du mail et Mise à jour de la commande
if (file_exists($fileOut)) {
if ( $testMail ) {
echo "Envoi fichier $nomCible ($ref) à ".$commande->email;
} else {
$report_txt.= "$ref intégré à l'extranet";
$isMailSent = false;
if (trim($commande->email)!=''){
$isMailSent = sendMail($commande, substr($ref,2,2));
} else {
$isMailSent = true;
}
if ( $isMailSent ) {
$data = array( 'dateEnvoi' => date('YmdHis'));
switch ( substr($ref,2,2) ) {
case 'BI':
$conn->update('sdv1.greffe_commandes_bi', $data, array('id' => $commande->id));
break;
case 'AC':
$conn->update('sdv1.greffe_commandes_ac', $data, array('id' => $commande->id));
break;
}
echo date ('Y/m/d - H:i:s')." - Commande $ref mise à jour\n";
$report_txt.= ' - Email envoyé à '.$commande->email;
} else {
$report_txt.= ' - Email non envoyé !';
echo date ('Y/m/d - H:i:s')." ERREUR - Email non envoyé et commande $ref non mise à jour\n";
}
$report_txt.= "\n";
}
} // Fin envoi mail
}
} // Fin condition ref
}
}
ftp_close($conn_id);
if (empty($report_txt)) {
$report_txt = "Aucun envoi.";
}
//Envoi du mail de rapport
if (!$test && !$testMail){
$headers = 'From: supportdev@scores-decisions.com';
if (mail($report_email, $report_subject, utf8_decode($report_txt))){
echo date ('Y/m/d - H:i:s')." - Rapport envoyé.\n";
} else {
echo date ('Y/m/d - H:i:s')." - Erreur lors de l'envoir du rapport !\n";
}
}
?>

View File

@ -1,599 +0,0 @@
#!/usr/bin/php
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(
//Options
array(
'help|?' => "Affiche l'aide.",
'siren=s' => "Commander un kbis",
'commandes' => "Liste les commandes passees (Reference), si reference alors recupere le kbis",
'visu=s' => "Telechargement du kbis avec une reference (--commandes obligatoire)",
'debug' => "Mode debug",
)
);
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if ($optionsNb == 0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Telecharge le kbis chez infogreffe.";
echo "\n\n";
echo $opts->getUsageMessage();
echo "\n";
exit;
}
if ( isset($opts->debug) ) {
define('DEBUG', true);
} else {
define('DEBUG', false);
}
function getPageHeader($start,$end,$header)
{
$pattern = '/'. $start .'(.*)'. $end .'/';
if (preg_match($pattern, $header, $result)) {
return $result[1];
} else {
return false;
}
}
function getPage($url, $curl_data = '', $override = null)
{
global $ckfile;
//$user_agent = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1';
//$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)';
$verbose = false;
$post = false;
$fields = '';
if (is_array($curl_data) && count($curl_data)>0) {
foreach($curl_data as $key=>$value) {
$fields .= $key.'='.$value.'&';
}
rtrim($fields,'&');
$post = true;
}
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => false, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => $user_agent, // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POST => $post, // i am sending post data
CURLOPT_POSTFIELDS => $fields, // this are my post vars
CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
CURLOPT_SSL_VERIFYPEER => false, //
CURLOPT_VERBOSE => $verbose , //
//CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEFILE => $ckfile,
CURLOPT_COOKIEJAR => $ckfile, // Stockage du cookie de session
);
//Override define CURL option
if (is_array($override) && count($override)>0 ) {
$options = $override + $options;
}
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch) ;
$header = curl_getinfo($ch);
curl_close($ch);
//Rewrite encoding to UTF-8
//text/html; charset=ISO-8859-1
//$encoding = getPageHeader('text\/html; charset=', '', $header['content_type']);
//$encoding = 'ISO-8859-1';
//$content = iconv($encoding, 'UTF-8//TRANSLIT', $content);
// $header['errno'] = $err;
// $header['errmsg'] = $errmsg;
// $header['content'] = $content;
return array('header'=>$header, 'content'=>$content);
}
/**
* Retourne l'url après une page 302
* @param string $content
* @return string|boolean
*/
function getUrl302($content)
{
$url = false;
preg_match('/\<title\>(.*)\<\/title\>/', $content, $matches);
if ($matches[1]=='302 Moved Temporarily') {
preg_match('/\<a href="(.*)"\>/', $content, $matches);
$url = $matches[1];
}
return $url;
}
//Define Main URL
$siteUrl = "https://www2.infogreffe.fr";
function infogreffeConnexion()
{
global $siteUrl;
$url = $siteUrl . "/infogreffe/index.jsp";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis-connexion1.html', $result['content']);
$url = $siteUrl . "/infogreffe/popupLog.jsp?type=0&url=index.jsp";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis-connexion2.html', $result['content']);
$url = $siteUrl . "/infogreffe/login.do?redirect=index.jsp";
// 302 Moved Temporarily
// => http://www.infogreffe.fr/infogreffe/index.jsp
$data = array(
'codeAbo'=>'2559',
'codeClt'=>'0041',
'log'=>'',
'pwd'=>'69873',
);
$result = getPage($url, $data);
if (DEBUG) file_put_contents('kbis-connexion3.html', $result['content']);
/*
We need to have
<div style="margin-top:2px; *margin-top:0px;" class="identBar">
<span class="name">Abonn&eacute;</span> |
<a href="/infogreffe/jsp/information/monCompte.jsp">Mon compte</a> |
<a href="/infogreffe/afficherMesAchats.do?refCde=N">Documents Command&eacute;s</a>
| <a href="/infogreffe/deconnexion.do">Se d&eacute;connecter</a>
</div>
*/
}
function infogreffeKbis($ref)
{
global $siteUrl;
/**************************************************
afficheProduit
**************************************************/
$url = $siteUrl . "/infogreffe/chargement.jsp?oups=".$ref."_0_V_0_";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis-afficheproduit.html', $result['content']);
//Redirection javascript qui fait patienter
sleep(1);
/**************************************************
serviceProduit
**************************************************/
$url = $siteUrl . "/infogreffe/serviceProduit.do?cdePro=".$ref."_0_V_0_";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis-serviceproduit.html', $result['content']);
$output = $result['content'];
//Modification du code HTML pour impression
$output = removeTag('script', $output, true, true);
$output = str_replace('/infogreffe/styles/infogreffe_base.css', '../styles/infogreffe_base.css', $output);
$output = str_replace('/infogreffe/styles/infogreffe.css', '../styles/infogreffe.css', $output);
$output = preg_replace(
'/\<body onload="adapterDimensions(\'conteneur\');" class="simple preventSelection" style="background-color: rgb(241, 241, 241);">/',
'<body class="simple preventSelection" style="background-color: rgb(241, 241, 241);">',
$output
);
//Récupération des informations dans le kbis
//<td align="left" valign="top" class="label">Numéro d'identification :</td><td>509 536 371 R.C.S. PONTOISE</td>
preg_match('/([0-9]{3}\s[0-9]{3}\s[0-9]{3})\sR\.C\.S\./', $output, $matches);
if (count($matches)>1){
$identifiant = str_replace(' ', '',$matches[1]);
} else {
$identifiant = 'unknown';
}
$fichier = $identifiant . '-' . $ref . '.html';
global $c;
$dir = realpath($c->profil->path->shared).'/datafile/kbis/'.date('Ymd');
if (!file_exists($dir)) mkdir($dir);
file_put_contents($dir . '/' . $fichier, $output);
return ($identifiant!='unknown') ? $identifiant : false;
}
function removeTag($balise, $content, $endOfTag = true, $removeContent = true)
{
if( $endOfTag )
{
if( $removeContent)
$output = preg_replace(
'@<'.$balise.'[^>]*?>.*?</'.$balise.'>@si',
'',
$content
);
else
$output = preg_replace(
array('@<'.$balise.'[^>]*?>@', '@</'.$balise.'>@'),
'',
$content
);
}
else
{
$output = preg_replace(
'@<'.$balise.'[^>]*?>@',
'',
$content
);
}
return $output;
}
function parseRef($document)
{
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($document);
$xpath = new DOMXpath($doc);
//Recherche des infos de la première commande
$nodelist = $xpath->query("//a/img[@alt='visualiser']");
foreach ($nodelist as $n){
$href = $n->parentNode->getAttribute('href');
preg_match("/javascript:afficheProduit\(\'(.*)_0_V_0_\'/", $href, $matches);
$ref = $matches[1];
}
//Recherche Raison Sociale
$nodelist = $xpath->query("//span[@class='text-company']/a");
foreach ($nodelist as $n){
$rs = $n->nodeValue;
break;
}
//Recherche RCS
$nodelist = $xpath->query("//span[@class='text-rcs']");
foreach ($nodelist as $n){
$rcs = $n->nodeValue;
break;
}
return array(
'ref' => $ref,
'rs' => $rs,
'rcs' => $rcs,
);
}
//Define cookie file for storage
//@todo : Faire en sorte d'utiliser le cookie pendant un temps déterminé, ou nouvelle session à chaque fois
$ckfile = __DIR__.'/'.uniqid('cookie-');
if (file_exists($ckfile)) unlink($ckfile);
// Récupération de la liste des commandes et
if ( $opts->commandes )
{
$referer = '';
/**************************************************
Connexion
**************************************************/
infogreffeConnexion();
$url = $siteUrl . "/infogreffe/jsp/information/monCompte.jsp";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis-moncompte.html', $result['content']);
/**************************************************
Documents commandés
**************************************************/
$url = $siteUrl . "/infogreffe/afficherMesAchats.do?refCde=N";
$result = getPage($url);
if (DEBUG) file_put_contents('documents.html', $result['content']);
//On parse le document pour trouver les références de commandes
$refs = array();
$tmp = parseRef($result['content']);
$refs[] = $tmp;
//Liste des commandes
$nodelist = $xpath->query("//a[@class='folded-fond-gris']");
foreach ($nodelist as $n){
$href = $n->getAttribute('href');
preg_match("/javascript:reveal\(\'(.*)\'\)/", $href, $matches);
$refs[] = array( 'ref' => $matches[1] );
}
$listeRef = array();
foreach($refs as $item){
$listeRef[] = $item['ref'];
}
if ( $opts->visu && in_array($opts->visu, $listeRef) )
{
//Pour toutes les commandes en dehors de la toute dernière
if ( array_search($opts->visu, $listeRef)!=0 ){
$url = $siteUrl . "/infogreffe/chargerContenuCommande.do?refCde=".$opts->visu."&_=";
$result = getPage($url);
if (DEBUG) file_put_contents('documents-'.$ref['ref'].'.html', $result['content']);
}
echo "Téléchargement du kbis...\n";
infogreffeKbis($opts->visu);
} elseif ( !$opts->visu ) {
/**************************************************
Reveal : Ajax pour mettre à jour le div
**************************************************/
// Parcourir le fichier précédent et relevé toute les références de commandes
// http://www.infogreffe.fr/infogreffe/chargerContenuCommande.do?refCde=XNDAE&_=
// Dans javascript la requete est réalisé en GET
$i = 0;
foreach ( $refs as $ref )
{
if ($i!=0){
$url = $siteUrl . "/infogreffe/chargerContenuCommande.do?refCde=".$ref['ref']."&_=";
$result = getPage($url);
if (DEBUG) file_put_contents('documents-'.$ref['ref'].'.html', $result['content']);
//@todo : Recup des informations
$info = array();
$info = parseRef($document);
}
echo $ref['ref'];
if ( $info['ref']==$ref['ref'] ) {
if ( !empty($info['rs']) ) echo " ".$info['rs'];
if ( !empty($info['rcs']) ) echo " ".$info['rcs'];
}
echo "\n";
$i++;
}
}
}
// Commande d'un kbis
if ( $opts->siren )
{
//Vérification du siren
if (strlen($opts->siren)!=9 && strlen($opts->siren)!=14) {
echo "Erreur SIREN invalide\n"; exit;
}
$referer = '';
/**************************************************
Connexion
**************************************************/
infogreffeConnexion();
/**************************************************
Affichage formulaire
**************************************************/
$url = $siteUrl . "/infogreffe/index.jsp";
$result = getPage($url);
if (DEBUG) file_put_contents('kbis1.html', $result['content']);
/**************************************************
Soumission formulaire
**************************************************/
$fields = array(
'commune' => '',
'denomination' => '',
'departement' => '',
//'elargirSecondaire' => 'on',
'elargirRadie' => 'on',
'siren' => $opts->siren,
);
$url = $siteUrl . "/infogreffe/newRechercheEntreprise.xml";
$result = getPage($url, $fields);
if (DEBUG) file_put_contents('kbis2.html', $result['content']);
// 302 Moved Temporarily - But we always use this URL
$url = $siteUrl . '/infogreffe/entrepRech.do';
/**************************************************
Affichage identite entreprise
**************************************************/
//url defini plus haut
$result = getPage($url, '', array(CURLOPT_FOLLOWLOCATION => true));
if (DEBUG) file_put_contents('kbis3.html', $result['content']);
/*
* !! Attention !! Elargir aux radiés peut retourner plusieurs résultats
*/
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($result['content']);
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("//div[@id='includeEntrepListe']");
if ($nodelist->length>0) {
$entries = $xpath->query("//a[@class='company']");
foreach ($entries as $n) {
$url = $siteUrl . $n->getAttribute('href');
break;
}
$result = getPage($url);
}
/*
* Try to detect we can pass an order, else send message and exit
*
* Si la recherche a fonctionné
* div[@id="libelleRcsGreffe"], nodeValue = "552 144 503 R.C.S. PARIS"
*
* Si pas de résultats lors de la recherche alors
* table[@class='liste-res-rech']/tbody/tr[1]/td[1]/div/span[1]
*/
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($result['content']);
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("//div[@id='libelleRcsGreffe']");
if ($nodelist->length==0) {
$entries = $xpath->query("//table[@class='liste-res-rech']/tbody/tr[1]/td[1]/div/span");
if ($entries->length>0) {
echo trim($entries->item(0)->nodeValue);
} else {
echo "ERREUR";
}
if (file_exists($ckfile)) unlink($ckfile);
exit;
}
/*
* Si les documents sont disponibles
* <a onclick="reveal('kbis');return false" href="#" id="a_kbis" class="folded">Extrait RCS (Kbis)</a>
*
* Sinon rechercher la valeur du message
* "//div[@id='conteneur']/table/tbody/tr/td/table/tbody/tr[2]/td/table[2]/tbody/tr[last()-2]/td";
*/
$nodelist = $xpath->query("//a[@id='a_kbis']");
if ($nodelist->length==0) {
$div = $xpath->query("//div[@id='conteneur']");
$context = $div->item(0);
$entries = $xpath->query("table/tbody/tr/td/table/tbody/tr[2]/td/table[2]/tbody/tr[9]/td", $context);
if ($entries->length!=0) {
$message = $entries->item(0)->nodeValue;
echo trim($message);
} else {
$entries = $xpath->query("//span[@class='texte-standard']", $context);
if ($entries->length!=0) {
$message = $entries->item(0)->nodeValue;
echo trim($message);
}
}
if (file_exists($ckfile)) unlink($ckfile);
exit;
}
// 302 Moved Temporarily
//http://www.infogreffe.fr/infogreffe/entrepListe.do?index=rcs
if ( $result['header']['http_code']=='302' && array_key_exists('redirect_url', $result['header']) ) {
$url = $result['header']['redirect_url'];
$result = getPage($url);
if (DEBUG) file_put_contents('kbis3-1.html', $result['content']);
// => /infogreffe/getEntrepDetail.do?docId=780308B042410000
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($result['content']);
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("//a[@class='company']");
foreach ($nodelist as $n) {
$url = $siteUrl . $n->getAttribute('href');
break;
}
$result = getPage($url);
if (DEBUG) file_put_contents('kbis3-2.html', $result['content']);
} elseif ( $result['header']['http_code']=='302' ) {
$url = $siteUrl . '/weblogic/infogreffe/entrepListe.do?index=rcs';
$result = getPage($url);
if (DEBUG) file_put_contents('kbis3-1.html', print_r($result,1));
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($result['content']);
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("//a[@class='company']");
foreach ($nodelist as $n) {
$url = $siteUrl . $n->getAttribute('href');
break;
}
$result = getPage($url);
if (DEBUG) file_put_contents('kbis3-2.html', $result['content']);
}
$fields = array();
//Recherche des infos pour la validation du formulaire
$doc = new DOMDocument();
$doc->strictErrorChecking = false;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($result['content']);
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("//form[@name='FicheEntrepriseForm']/div[@id='conteneur']/input[@type='hidden']");
foreach ($nodelist as $n) {
$key = $n->getAttribute('name');
$value = $n->getAttribute('value');
$fields[$key] = $value;
}
$fields['montantTotalSelection'] = '5.44'; // 3.11 + 2.33
$fields['extraitForm.visualisation'] = 'on'; // => Définit par javascript
$fields['extraitForm.formVisible'] = 'true';
$fields['extraitForm.envoiPeriodiqueForm.periodicite'] = '1';
$fields['extraitForm.envoiPeriodiqueForm.duree'] = '12';
$fields['etatEndettementForm.formVisible'] = 'true';
$fields['etatEndettementForm.etatComplet'] = 'false';
$fields['listeActesForm.formVisible'] = 'true';
$fields['historiqueModificationsForm.formVisible'] = 'true';
$fields['historiqueModificationsForm.tri'] = '0';
$fields['procedureCollectiveForm.formVisible'] = 'true';
$fields['dossierCompletForm.formVisible'] = 'true';
if (DEBUG) print_r($fields);
/**************************************************
Validation de la selection
**************************************************/
$url = $siteUrl . "/infogreffe/validerSelectionFicheEntreprise.xml";
$result = getPage($url, $fields);
if (DEBUG) file_put_contents('kbis4.html', print_r($result,1));
/**************************************************
Valider la commande
**************************************************/
$url = $siteUrl . "/infogreffe/validerPanierAbonne.do?forcerSaisieCoordonnees=false";
$fields = array();
$result = getPage($url, $fields);
if (DEBUG) file_put_contents('kbis5.html', $result['content']);
/**************************************************
Afficher mes achats et prendre la première commande
**************************************************/
$url = $siteUrl . "/infogreffe/afficherMesAchats.do?refCde=N&pageAppel=validerPanier";
$fields = array();
$result = getPage($url, $fields);
if (DEBUG) file_put_contents('kbis6.html', $result['content']);
$info = parseRef($result['content']);
$ref = $info['ref'];
/**************************************************
Visualiser
**************************************************/
$identifiant = infogreffeKbis($ref);
//Suppression fichier
if (file_exists($ckfile)) unlink($ckfile);
if ($identifiant===false || $identifiant!=substr($opts->siren,0,9)) {
echo "ERREUR";
exit;
}
echo $identifiant.'-'.$ref.'.html';
}

View File

@ -1,378 +0,0 @@
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
/**
* User-Agent
* IE 11.0 : Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
*
*
*
*/
try {
$opts = new Zend_Console_Getopt(
//Options
array(
'help|?' => "Affiche l'aide.",
'siren=s' => "Commander un kbis",
'commandes' => "Liste les commandes passees (Reference), si reference alors recupere le kbis",
'visu=s' => "Telechargement du kbis avec une reference (--commandes obligatoire)",
'debug' => "Mode debug",
)
);
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
echo $e->getUsageMessage();
exit;
}
// --- Aide / Options
if ($optionsNb == 0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Telecharge le kbis chez infogreffe.";
echo "\n\n";
echo $opts->getUsageMessage();
echo "\n";
exit;
}
if ( isset($opts->debug) ) {
define('DEBUG', true);
} else {
define('DEBUG', false);
}
/*
338 437 189
552 144 503
https://www.infogreffe.fr/societes/
Se connecter
Form
Var client : 0041
Var utilisateur : 2559
Var password : 69873
1 - GET https://www.infogreffe.fr/societes/
2 - POST https://www.infogreffe.fr/sso/identity/authenticate
password 69873
uri realm=abonnes
username 00412559
token.id=AQIC5wM2LY4Sfcy_Nc7YNNc2BtJVjZr-CrTMfnMxDw1iSvw.*AAJTSQACMDIAAlMxAAIwNA..*
3 - GET https://www.infogreffe.fr/societes/
4 - GET https://www.infogreffe.fr/services/entreprise/rest/recherche/parPhrase?nbIdRetournes=100&surveillanceVisible=true&miseAuPanierVisible=true&typeProduitMisEnAvant=EXTRAIT&phrase=338437189
miseAuPanierVisible true
nbIdRetournes 100
phrase 338437189
surveillanceVisible true
typeProduitMisEnAvant EXTRAIT
{"critereRecherchePrincipal":"338437189","critereRecherche":null,"entrepRechInfosComplementaires":null
,"entrepRCSStoreResponse":{"success":true,"identifier":"id","label":"deno","loadedAttr":"numeroDossier"
,"idRecherche":"ENTREP_RCS_ACTIF","nbTotalResultats":1,"items":[{"id":8143039,"numeroDossier":"130586B20094"
,"etablissementChrono":"0000","libelleEntreprise":{"denomination":"PROVENCE PLOMBERIE","denominationEirl"
:null,"enseigne":"PROVENCE PLOMBERIE","nomCommercial":null,"sigle":null},"siren":338437189,"nic":"00016"
,"adresse":{"lignes":["QUARTIER LA MARIANNE "],"codePostal":"13560","bureauDistributeur":"SÉNAS"},"codePaysRegistreEtranger"
:null,"greffe":{"numero":"1305","nom":"TARASCON","codeGroupement":"05","codeEDI":"G1305","nomGreffeMin"
:null},"typeEtab":"SIE","produitAuPanier":"AJOUTABLE","typeInscription":1,"sourceDonnees":"GTC","radie"
:false,"dateRadiation":null,"nbEtablissements":1,"activite":{"codeNAF":"4322A","libelleNAF":"Travaux
d'installation d'eau et de gaz en tous locaux"},"etatSurveillance":"SURVEILLABLE"}],"typeProduitMisEnAvant"
:"EXTRAIT","critereRecherchePrincipal":null,"entrepRechInfosComplementaires":null},"entrepMultiStoreResponse"
:{"success":true,"identifier":"id","label":"deno","loadedAttr":"numeroDossier","idRecherche":null,"nbTotalResultats"
:0,"items":null,"typeProduitMisEnAvant":"EXTRAIT","critereRecherchePrincipal":null,"entrepRechInfosComplementaires"
:null},"entrepRadieeStoreResponse":null,"entrepHorsRCSStoreResponse":{"success":true,"identifier":"id"
,"label":"deno","loadedAttr":"numeroDossier","idRecherche":"ENTREP_HORS_RCS_ACTIFS","nbTotalResultats"
:0,"items":[],"typeProduitMisEnAvant":"EXTRAIT","critereRecherchePrincipal":null,"entrepRechInfosComplementaires"
:null},"reprStoreResponse":{"success":true,"identifier":"id","label":"deno","loadedAttr":"numeroDossier"
,"idRecherche":"REPRESENTANT","nbTotalResultats":0,"items":[],"typeProduitMisEnAvant":"EXTRAIT","critereRecherchePrincipal"
:"338437189","critereRecherche":null,"entrepRechInfosComplementaires":null},"typeProduitMisEnAvant":"EXTRAIT"
}
5 - GET https://www.infogreffe.fr/societes/entreprise-societe/338437189-provence-plomberie-130586B200940000.html?typeProduitOnglet=EXTRAIT&afficherretour=false
afficherretour false
typeProduitOnglet EXTRAIT
<title>PROVENCE PLOMBERIE à SÉNAS (338437189) - Infogreffe</title>
5 - GET https://www.infogreffe.fr/services/produits/rest/catalogue/dossier/130586B20094/0000
{"ordrePresentationParProduit":{"BILAN_SAISI":6,"EXTRAIT":1,"ETAT_ENDETEMENT":2,"DOSSIER_COMPLET":9,"HISTO_MODIFS_RCS"
:7,"CERTIF_PROC_COLLECTIVE":8,"ACTE":5},"cataloguePrix":{"ETAT_ENDETEMENT":{"typeProduit":"ETAT_ENDETEMENT"
,"prixBaseTTC":46.8,"prixFraisEnvoiPostalTTC":1.42,"prixFraisEnvoiElectroniqueTTC":2.34,"prixBaseTTCParTypeInscription"
:3.12,"prixFraisEnvoiPostalTTCParTypeInscription":0.89},"BILAN_SAISI":{"typeProduit":"BILAN_SAISI","prixBaseTTC"
:3.6,"prixFraisEnvoiPostalTTC":0.0,"prixFraisEnvoiElectroniqueTTC":2.34},"STATUT_A_JOUR":{"typeProduit"
:"STATUT_A_JOUR","prixBaseTTC":9.36,"prixFraisEnvoiPostalTTC":2.15,"prixFraisEnvoiElectroniqueTTC":2
.34},"HISTO_MODIFS_RCS":{"typeProduit":"HISTO_MODIFS_RCS","prixBaseTTC":7.8,"prixFraisEnvoiPostalTTC"
:0.0,"prixFraisEnvoiElectroniqueTTC":2.34},"BILAN_COMPLET":{"typeProduit":"BILAN_COMPLET","prixBaseTTC"
:9.36,"prixFraisEnvoiPostalTTC":2.15,"prixFraisEnvoiElectroniqueTTC":2.34},"EXTRAIT":{"typeProduit":"EXTRAIT"
,"prixBaseTTC":3.12,"prixFraisEnvoiPostalTTC":0.89,"prixFraisEnvoiElectroniqueTTC":0.78},"DOSSIER_COMPLET"
:{"typeProduit":"DOSSIER_COMPLET","prixBaseTTC":70.19999999999999,"prixFraisEnvoiPostalTTC":7.499999999999999
,"prixFraisEnvoiElectroniqueTTC":2.34},"ACTE":{"typeProduit":"ACTE","prixBaseTTC":9.36,"prixFraisEnvoiPostalTTC"
:2.15,"prixFraisEnvoiElectroniqueTTC":2.34},"CERTIF_PROC_COLLECTIVE":{"typeProduit":"CERTIF_PROC_COLLECTIVE"
,"prixBaseTTC":1.56,"prixFraisEnvoiPostalTTC":0.89,"prixFraisEnvoiElectroniqueTTC":2.34}},"produits"
:[{"modesDeDiffusionDispos":["V","C","M","T"],"produit":{"typeProduit":"EXTRAIT","modifiable":true,"identifiant"
:{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"},"kbisPeriodique"
:true},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C"],"produit":{"typeProduit":"ETAT_ENDETEMENT"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094"},"categoriesInscription":[{"code":"C1","libelle":"Catégorie 1","typesInscription":[{"code":"PRIV_SECU"
,"libelle":"Privilège de la sécurité sociale et des régimes complémentaires"},{"code":"PRIV_TRESOR","libelle"
:"Privilège du Trésor Public"},{"code":"PROTET","libelle":"Protêts"},{"code":"PRIV_ANAEM","libelle":"Agence
Nationale de l'Accueil des Etrangers et des Migrations"}]},{"code":"C2","libelle":"Catégorie 2","typesInscription"
:[{"code":"NAN_FOND_COMM","libelle":"Nantissements du fonds de commerce"},{"code":"PRIV_VENDEUR","libelle"
:"Privilèges du vendeur de fonds de commerce et d'action résolutoire"},{"code":"NAN_OUTIL","libelle"
:"Nantissements de l'outillage, matériel et équipement"},{"code":"DECL_CREANCES","libelle":"Déclaration
de créance"}]},{"code":"C3","libelle":"Catégorie 3","typesInscription":[{"code":"OP_CREDIT_BAIL","libelle"
:"Opérations de crédit-bail en matière mobilière"},{"code":"PUB_CONTRAT_LOC","libelle":"Publicité de
contrats de location"},{"code":"PUB_RESEV_PROPR","libelle":"Publicité de clauses de réserve de propri
été"}]},{"code":"C4","libelle":"Catégorie 4","typesInscription":[{"code":"GAGE_STOCKS","libelle":"Gage
des stocks"},{"code":"WARRANTS_CAT","libelle":"Warrants"}]},{"code":"C5","libelle":"Catégorie 5","typesInscription"
:[{"code":"PRETS_DELAIS","libelle":"Prêts et délais"},{"code":"BIENS_INALIENABLES","libelle":"Biens inali
énables"}]}]},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"STATUT_A_JOUR"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","depotActeNumero":4,"acteChrono":2},"dateActe":1418770800000,"typeActe":{"code":"STAJh","libelle"
:"Statuts mis à jour"},"nbPages":16,"decisions":[],"depot":{"numeroDepot":"4","numeroDepotManu":3459
,"dateDepot":1419980400000}},"miseAuPanier":null},{"modesDeDiffusionDispos":["C"],"produit":{"typeProduit"
:"ACTE","modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut"
:"B","dossierChrono":"20094","depotActeNumero":1,"acteChrono":1},"dateActe":652485600000,"typeActe":
{"code":"ORDPREh","libelle":"Ordonnance du président"},"nbPages":0,"decisions":[{"natureDecision":{"code"
:"AGPRh","libelle":"Prorogation du délai de réunion de l'A.G. chargée d'approuver les comptes"},"libelle"
:null}],"depot":{"numeroDepot":"1","numeroDepotManu":16,"dateDepot":655686000000}},"miseAuPanier":null
},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"ACTE","modifiable":true,"identifiant"
:{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","depotActeNumero"
:2,"acteChrono":1},"dateActe":807832800000,"typeActe":{"code":"PVAh","libelle":"Procès-verbal d'assembl
ée"},"nbPages":19,"decisions":[],"depot":{"numeroDepot":"2","numeroDepotManu":814,"dateDepot":812156400000
}},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"ACTE","modifiable"
:true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","depotActeNumero":2,"acteChrono":2},"dateActe":807832800000,"typeActe":{"code":"STAJh","libelle"
:"Statuts mis à jour"},"nbPages":19,"decisions":[],"depot":{"numeroDepot":"2","numeroDepotManu":814,"dateDepot"
:812156400000}},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit"
:"ACTE","modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut"
:"B","dossierChrono":"20094","depotActeNumero":2,"acteChrono":3},"dateActe":807832800000,"typeActe":
{"code":"DIVERSh","libelle":"Divers"},"nbPages":19,"decisions":[{"natureDecision":{"code":"ZDIVh","libelle"
:"Divers"},"libelle":"EXTENSION OBJET SOCIAL & ACTIVITE"}],"depot":{"numeroDepot":"2","numeroDepotManu"
:814,"dateDepot":812156400000}},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit"
:{"typeProduit":"ACTE","modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut"
:"B","dossierChrono":"20094","depotActeNumero":3,"acteChrono":1},"dateActe":1216072800000,"typeActe"
:{"code":"PVAh","libelle":"Procès-verbal d'assemblée"},"nbPages":4,"decisions":[{"natureDecision":{"code"
:"ZDIVh","libelle":"Divers"},"libelle":"MODIFICATION DE L'AFFECTATION DU RESULTAT - EXERCICE CLOS LE
31.12.2007"}],"depot":{"numeroDepot":"3","numeroDepotManu":1373,"dateDepot":1219960800000}},"miseAuPanier"
:null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"ACTE","modifiable":true,"identifiant"
:{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","depotActeNumero"
:4,"acteChrono":1},"dateActe":1418770800000,"typeActe":{"code":"PVAGEXh","libelle":"Procès-verbal d'assembl
ée générale extraordinaire"},"nbPages":3,"decisions":[{"natureDecision":{"code":"EXCLOTh","libelle":"Changement
relatif à la date de clôture de l'exercice social"},"libelle":null}],"depot":{"numeroDepot":"4","numeroDepotManu"
:3459,"dateDepot":1419980400000}},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","M","T"],"produit"
:{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime"
:"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2013,"bilanNumero":1427},"type":"BS"
,"sousCode":"SP","dateClotureExercice":1388444400000,"denominationEIRL":null,"disponibleXbrl":false}
,"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2013,"bilanNumero":1427},"type":"BS","sousCode":"BL","dateClotureExercice"
:1388444400000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2012,"bilanNumero"
:2537},"type":"BS","sousCode":"SP","dateClotureExercice":1356908400000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2012,"bilanNumero":2537},"type":"BS","sousCode":"BL","dateClotureExercice"
:1356908400000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2011,"bilanNumero"
:1672},"type":"BS","sousCode":"SP","dateClotureExercice":1325286000000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2011,"bilanNumero":1672},"type":"BS","sousCode":"BL","dateClotureExercice"
:1325286000000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2010,"bilanNumero"
:2196},"type":"BS","sousCode":"SP","dateClotureExercice":1293750000000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2010,"bilanNumero":2196},"type":"BS","sousCode":"BL","dateClotureExercice"
:1293750000000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2009,"bilanNumero"
:969},"type":"BS","sousCode":"SP","dateClotureExercice":1262214000000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2009,"bilanNumero":969},"type":"BS","sousCode":"BL","dateClotureExercice":1262214000000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2008,"bilanNumero"
:1427},"type":"BS","sousCode":"SP","dateClotureExercice":1230678000000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2008,"bilanNumero":1427},"type":"BS","sousCode":"BL","dateClotureExercice"
:1230678000000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2007,"bilanNumero"
:902},"type":"BS","sousCode":"SP","dateClotureExercice":1199055600000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2007,"bilanNumero":902},"type":"BS","sousCode":"BL","dateClotureExercice":1199055600000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2006,"bilanNumero"
:891},"type":"BS","sousCode":"SP","dateClotureExercice":1167519600000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2006,"bilanNumero":891},"type":"BS","sousCode":"BL","dateClotureExercice":1167519600000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2005,"bilanNumero"
:769},"type":"BS","sousCode":"SP","dateClotureExercice":1135983600000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","C","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2005,"bilanNumero":769},"type":"BS","sousCode":"BL","dateClotureExercice":1135983600000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2004,"bilanNumero"
:704},"type":"BS","sousCode":"SP","dateClotureExercice":1104447600000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2004,"bilanNumero":704},"type":"BS","sousCode":"BL","dateClotureExercice":1104447600000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2003,"bilanNumero"
:850},"type":"BS","sousCode":"SP","dateClotureExercice":1072825200000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2003,"bilanNumero":850},"type":"BS","sousCode":"BL","dateClotureExercice":1072825200000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2002,"bilanNumero"
:959},"type":"BS","sousCode":"SP","dateClotureExercice":1041289200000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2002,"bilanNumero":959},"type":"BS","sousCode":"BL","dateClotureExercice":1041289200000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2001,"bilanNumero"
:561},"type":"BS","sousCode":"SP","dateClotureExercice":1009753200000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2001,"bilanNumero":561},"type":"BS","sousCode":"BL","dateClotureExercice":1009753200000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"M","T"],"produit":{"typeProduit":"BILAN_SAISI","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":2000,"bilanNumero"
:644},"type":"BS","sousCode":"SP","dateClotureExercice":978217200000,"denominationEIRL":null,"disponibleXbrl"
:false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET"
,"modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094","bilanMillesime":2000,"bilanNumero":644},"type":"BS","sousCode":"BL","dateClotureExercice":978217200000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"T"],"produit":{"typeProduit":"BILAN_COMPLET","modifiable":true,"identifiant":{"codeGreffe":"1305","dossierMillesime"
:"86","dossierStatut":"B","dossierChrono":"20094","bilanMillesime":1999,"bilanNumero":986},"type":"BS"
,"sousCode":"BL","dateClotureExercice":946594800000,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier"
:null},{"modesDeDiffusionDispos":["V","T"],"produit":{"typeProduit":"BILAN_COMPLET","modifiable":true
,"identifiant":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"
,"bilanMillesime":1998,"bilanNumero":614},"type":"BS","sousCode":"BL","dateClotureExercice":915058800000
,"denominationEIRL":null,"disponibleXbrl":false},"miseAuPanier":null},{"modesDeDiffusionDispos":["V"
,"T"],"produit":{"typeProduit":"HISTO_MODIFS_RCS","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"}},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","C"],"produit":{"typeProduit":"CERTIF_PROC_COLLECTIVE","modifiable":true,"identifiant":{"codeGreffe"
:"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"}},"miseAuPanier":null},{"modesDeDiffusionDispos"
:["V","C"],"produit":{"typeProduit":"DOSSIER_COMPLET","modifiable":true,"identifiant":{"codeGreffe":"1305"
,"dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"},"detailProduits":[{"typeProduit"
:"EXTRAIT","modesDeDiffusionDispos":["V","C","M","T"]},{"typeProduit":"ETAT_ENDETEMENT","modesDeDiffusionDispos"
:["V","C"]},{"typeProduit":"BILAN_COMPLET","modesDeDiffusionDispos":["V","C","T"],"dateClotureExercice"
:1388444400000},{"typeProduit":"STATUT_A_JOUR","modesDeDiffusionDispos":["V","C","T"]},{"typeProduit"
:"CERTIF_PROC_COLLECTIVE","modesDeDiffusionDispos":["V","C"]}]},"miseAuPanier":null}]}
ordrePresentationParProduit.EXTRAIT = 1 (+ cataloguePrix)
6 - POST AJAX https://www.infogreffe.fr/services/produits/rest/panier/extrait
idDossier 130586B20094
modesDeDiffusion V
modesDeDiffusion T
nbExemplaires 0
{"nbDocuments":1,"nbDocumentsParTypeProduit":1,"total":3.9,"totalReduit":3.9,"hasCourrier":false,"cartoucheTotal"
:3.9,"cartoucheReduitTotal":3.9,"produitTotal":3.9,"produitReduitTotal":3.9}
7 - https://www.infogreffe.fr/services/produits/rest/panier
{"panier":{"panierCartouches":[{"prixCartouche":{"totalTtc":3.9},"identite":{"dossier":{"idDossier":
{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"},"nomGreffeImmat"
:"TARASCON","siren":338437189,"denomination":"PROVENCE PLOMBERIE","etatposeSurveillance":null},"debiteur"
:null,"listeEntreprises":null,"affaire":null,"nomGreffeImmat":"TARASCON"},"ordrePresentationParProduit"
:{"EXTRAIT":1},"produits":[{"produit":{"typeProduit":"EXTRAIT","modifiable":true,"identifiant":{"codeGreffe"
:"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono":"20094"},"kbisPeriodique":true},"miseAuPanier"
:{"prixProduit":{"totalTtc":3.9},"modesDeDiffusionSelectionnes":["V","T"],"nbExemplaires":null,"envoiPeriodique"
:{"periodicite":0,"duree":0},"modifiable":true},"libelleProduit":"Extrait RCS (K bis)"}],"prixTotalActes"
:0.0,"prixTotalDap":0.0}],"prixTotal":{"totalTtc":3.9},"hasCourrier":false}}
8 - https://www.infogreffe.fr/services/produits/rest/panier/resume
{"nbDocuments":1,"nbDocumentsParTypeProduit":0,"total":3.9,"totalReduit":3.9,"hasCourrier":false}
9 - GET https://www.infogreffe.fr/services/achatclient/rest/achat/createCmdAbonne
{"numCommande":"173829445","modeDiffusionCourrier":false}
10 - GET https://www.infogreffe.fr/services/commandeclient/rest/client/recapCommande?numeroCommande=173829445
numeroCommande 173829445
{"commande":{"idCommande":"173829445","date":1433493693000,"totalTTC":3.9,"totalTVA":0.65,"totalHT":null
,"refCommande":"YGWJN","moyenPaiement":"COMPTE_ABONNE","numeroCartePrepayee":null,"cartouches":[{"intitule"
:{"dossier":{"idDossier":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094"},"nomGreffeImmat":"TARASCON","siren":338437189,"denomination":"PROVENCE PLOMBERIE","etatposeSurveillance"
:"SURVEILLABLE"},"debiteur":null,"listeEntreprises":null,"affaire":null,"nomGreffeImmat":"TARASCON"}
,"produitsEntreprise":[{"ligneCommande":1,"document":"EXCP","produitTTC":3.9000000000000004,"produitHT"
:0.0,"fraisDePortHT":0.0,"documentsProduit":[{"modeDiffusion":"V","nbExemplaires":1,"urlTelechargement"
:null,"codeSuiviLivraison":null},{"modeDiffusion":"T","nbExemplaires":1,"urlTelechargement":null,"codeSuiviLivraison"
:null}],"inDossierComplet":null,"envoiPeriodique":{"periodicite":0,"duree":0},"refEnvoiPeriodique":null
}]}],"refCommandeClient":null,"refEnvoiPeriodique":null,"denominationSociete":null,"nomClient":"SCORES
ET DECISIONS SAS","abNume":"0041","abAbonne":"2559","email":"CONTACT@SCORES-DECISIONS.COM","solde":null
,"nbDocuments":null,"fraisDePortHT":0.0}}
11 - GET https://www.infogreffe.fr/services/commandeclient/rest/client/recapCommande?numeroCommande=173829445
numeroCommande 173829445
{"commande":{"idCommande":"173829445","date":1433493693000,"totalTTC":3.9,"totalTVA":0.65,"totalHT":null
,"refCommande":"YGWJN","moyenPaiement":"COMPTE_ABONNE","numeroCartePrepayee":null,"cartouches":[{"intitule"
:{"dossier":{"idDossier":{"codeGreffe":"1305","dossierMillesime":"86","dossierStatut":"B","dossierChrono"
:"20094"},"nomGreffeImmat":"TARASCON","siren":338437189,"denomination":"PROVENCE PLOMBERIE","etatposeSurveillance"
:"SURVEILLABLE"},"debiteur":null,"listeEntreprises":null,"affaire":null,"nomGreffeImmat":"TARASCON"}
,"produitsEntreprise":[{"ligneCommande":1,"document":"EXCP","produitTTC":3.9000000000000004,"produitHT"
:0.0,"fraisDePortHT":0.0,"documentsProduit":[{"modeDiffusion":"V","nbExemplaires":1,"urlTelechargement"
:null,"codeSuiviLivraison":null},{"modeDiffusion":"T","nbExemplaires":1,"urlTelechargement":null,"codeSuiviLivraison"
:null}],"inDossierComplet":null,"envoiPeriodique":{"periodicite":0,"duree":0},"refEnvoiPeriodique":null
}]}],"refCommandeClient":null,"refEnvoiPeriodique":null,"denominationSociete":null,"nomClient":"SCORES
ET DECISIONS SAS","abNume":"0041","abAbonne":"2559","email":"CONTACT@SCORES-DECISIONS.COM","solde":null
,"nbDocuments":null,"fraisDePortHT":0.0}}
12 - GET https://www.infogreffe.fr/societes/panier/confirmation?numCommande=173829445&typeClient=AB&etapeCoord=false
etapeCoord false
numCommande 173829445
typeClient AB
=> HTML
Téléchargement du KBIS
<tbody class="commandeDocs">
<a href="javascript:void(0);" class="voirRouge" style="color: red;">Télécharger</a>
https://www.infogreffe.fr/services/commandeclient/rest/client/visupdf?numeroCommande=173829445&ligneCommande=1&visualisation=undefined
13 - GET https://www.infogreffe.fr/services/commandeclient/rest/client/recapCommande?numeroCommande=173829445
=> Voir 10
14 -
*/

View File

@ -1,56 +0,0 @@
<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => "Displays usage information.",
'sqlfile=s' => "",
'csvfile=s' => "",
));
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if (count($opts->getOptions())==0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Génération d'un fichier CSV à partir d'un fichier SQL.\n";
echo $opts->getUsageMessage();
exit;
}
use League\Csv\Writer;
$sql = file_get_contents($opts->sqlfile);
//we fetch the info from a DB using a PDO object
$stmt = $conn->executeQuery($sql);
if ($stmt->rowCount() == 0) {
file_put_contents($opts->csvfile, "");
}
else {
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// Create the CSV
$csv = Writer::createFromPath($opts->csvfile.'.tmp', 'w');
$csv->setNewline("\r\n");
$csv->setOutputBOM(Writer::BOM_UTF8);
// Insert the CSV header
$csv->insertOne(array_keys($rows[0]));
// Insert all data
$csv->insertAll($rows);
// Set the real name of file
rename($opts->csvfile.'.tmp', $opts->csvfile);
}

View File

@ -1,33 +0,0 @@
{
"name": "scores/webservice",
"description": "Webservice API",
"require": {
"zendframework/zendframework1": "^1.12",
"geshi/geshi": "dev-master",
"league/csv": "^8.1",
"doctrine/dbal": "^2.5",
"mikehaertl/phpwkhtmltopdf": "^2.2",
"guzzlehttp/guzzle": "^6.2",
"monolog/monolog": "^1.22",
"scores/library": "dev-develop"
},
"repositories": [
{
"type": "git",
"url": "git@gitlab.factory.insight.doubletrade.com:scores/library.git"
}
],
"include-path": ["library/"],
"autoload": {
"classmap": [
"application/",
"library/Application/"
]
},
"authors": [
{
"name": "Scores et Decisions",
"email": "supportdev@scores-decisions.com"
}
]
}

View File

@ -1,33 +0,0 @@
{
"name": "scores/webservice",
"description": "Webservice API",
"require": {
"zendframework/zendframework1": "^1.12",
"geshi/geshi": "dev-master",
"league/csv": "^8.1",
"doctrine/dbal": "^2.5",
"mikehaertl/phpwkhtmltopdf": "^2.2",
"guzzlehttp/guzzle": "^6.2",
"monolog/monolog": "^1.22",
"scores/library": "dev-master"
},
"repositories": [
{
"type": "git",
"url": "git@gitlab.factory.insight.doubletrade.com:scores/library.git"
}
],
"include-path": ["library/"],
"autoload": {
"classmap": [
"application/",
"library/Application/"
]
},
"authors": [
{
"name": "Scores et Decisions",
"email": "supportdev@scores-decisions.com"
}
]
}

1151
composer.lock generated

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,55 +0,0 @@
Le fichier Zend/Soap/Wsdl/Strategy/DefaultComplexType.php a été modifié pour
générer la documentation automatiquement.
/**
* Traitement éléments de documentation à placer dans le WSDL
* Supprime les retours chariots.
* Récupére les éléments de documentation
*/
$comment = '';
$docBlock = preg_replace('/\n/', '', $property->getDocComment() );
if (preg_match('/\/\*\*(.+) \* @var\s+[^\s]+\s+(?:\*|@)/m', $docBlock, $docBlockMatches)) {
$comment.= preg_replace(
array('/\r/', '/\t\s\*/'),
array('', ''), $docBlockMatches[1]
);
}
/**
* Ajout des éléments de documentation au WSDL
*/
if (!empty($comment)){
$annotation = $dom->createElement('xsd:annotation');
$documentation = $dom->createElement('xsd:documentation', trim($comment));
$annotation->appendChild($documentation);
$element->appendChild($annotation);
}
===============================================================================>
Le fichier Zend/Soap/AutoDiscover.php a été modifié
function _addFunctionToWsdl
$sequenceElement = array(
'name' => $param->getName(),
'type' => $wsdl->getType($param->getType()),
'desc' => $param->getDescription()
);
===============================================================================>
Le fichier Zend/Soap/Wsdl.php a été modifié
function _parseElement
} elseif ($key == 'desc') {
if (!empty($value)) {
$annotation = $this->_dom->createElement('xsd:annotation');
$documentation = $this->_dom->createElement('xsd:documentation', trim($value));
$annotation->appendChild($documentation);
$elementXml->appendChild($annotation);
}
} else {

View File

@ -1,163 +0,0 @@
WebService
==========
- Créer le vhost, voir le fichier VHOST pour les exemples
<VirtualHost *:80>
ServerName webservice.sd.dev
AddDefaultCharset utf-8
<IfModule mod_xsendfile.c>
XSendFile On
XSendFilePath /home/vhosts/webservice/shared
</IfModule>
DocumentRoot /home/vhosts/webservice/public
<Directory /home/vhosts/webservice/public/>
EnableSendfile Off
AllowOverride none
Require all granted
<Files ~ "^\.user.ini">
Order allow,deny
Deny from all
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/favicon.ico$ [OR]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</IfModule>
</Directory>
<Directory /home/vhosts/webservice/public/assets/>
<IfModule mod_rewrite.c>
RewriteEngine Off
</IfModule>
</Directory>
# Possible values include: debug, info, notice, warn, error, crit, alert, emerg.
LogLevel error
ErrorLog ${APACHE_LOG_DIR}/webservice-error.log
CustomLog ${APACHE_LOG_DIR}/webservice-access.log combined
</VirtualHost>
- Installer les librairies avec composer
$ composer install
- Configurer l'application
La config (fichier application.ini) est à placer dans "application/configs/"
Exemple de la config dans "docs/config/application.ini" (Modifier selon les besoins)
- APPLICATION_ENV
Différent niveau peuvent être utilisé dans l'application pour gérer les erreurs et le comportement.
production
staging
development
testing
Cette variable est accessible dans PHP.
. mod_php
Add in <VirtualHost/>
SetEnv APPLICATION_ENV "development"
. php-fpm
Add a file in document root path (public/) a file .user.ini
env[APPLICATION_ENV] = "development"
See the .user.ini file
- Créer les repertoires de données nécessaires
[WORKSPACE]/data/webservice/
- cache
- logs
- sessions
- wsdl
- files
- greffes
Fonctionnement
==============
Obtenir les WSDL
Pour le service Entreprise
- En mode développement : http://hostname/entreprise/version?wsdl-auto
- Générer le WSDL : http://hostname/entreprise/version?wsdl-generate
- Utiliser le WSDL généré : http://hostname/entreprise/version?wsdl
Pour le service Interne
http://hostname/interne/version?wsdl
Pour les clients
http://hostname/clients/nom_du_client/version?wsdl
N.B : Le fichier WSDL est généré automatiquement en appelant
http://hostname/service?wsdl afin de ne pas provoquer d'erreur
après une mise en production
Pour définir le mode (vhost d'apache)
SetEnv APPLICATION_ENV "development"
SetEnv APPLICATION_ENV "production"
SetEnv APPLICATION_ENV "staging"
En appelant l'url http://hostname/service, le contoller de l'application,
"service" est automatiquement utiliser.
Tout ce qui est visible dans la class est utilisé par le controller et se
retrouve visible dans le service (wsdl, requête)
Si des fonctions ne doivent pas être rendu visible il faut donc les séparer
dans un autre controller utilisant une autre class.
Documentation des méthodes et ajout spécial
===========================================
La documentation est géneré en automatique.
Voici comment définir simplement la documentation d'une méthode
/**
* Retourne les informations identitaires de l'entreprise ou de l'établissement demandé
* @param string $key Siren de l'entreprise ou siret de l'établissement
* @return Identite
*/
public function test($key)
{
}
Attention ces informations servent aussi pour la structure du WSDL
Pour spécifier un lien vers un fichier ou pour générer un fichier depuis une
requête SQL à partir de la documentation du service.
Ajouter dans le docblock :
- Pour un fichier
@ref fichier:libellé:{nom_du_fichier.ext}
- Pour une requête SQL
@ref mysql:libellé:{nom_du_fichier.sql}
Les fichiers a télécharger sont à placer dans le répértoire public/fichier et
les fichiers sql dans public/sql
Pour spécifier des éléments de taille (non pris en compte sur le WSDL)
@xsd minLength=9
@xsd maxLength=15

View File

@ -1,9 +0,0 @@
upload_max_filesize=513M
post_max_size=513M
memory_limit=512M
mbstring.func_overload=0
always_populate_raw_post_data=-1
default_charset='UTF-8'
date.timezone='Europe/Paris'
soap.wsdl_cache_enabled=0
env[APPLICATION_ENV] = "development"

View File

@ -1,74 +0,0 @@
[production]
phpSettings.soap.wsdl_cache_dir = "PROJECT_DIR/shared/sessions/wsdl"
phpSettings.date.timezone = "Europe/Paris"
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.session.save_path = "PROJECT_DIR/shared/sessions"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.plugins.Auth = "Application_Controller_Plugin_Auth"
resources.frontController.plugins.Services = "Application_Controller_Plugin_Services"
resources.frontController.plugins.Menu = "Application_Controller_Plugin_Menu"
resources.frontController.params.displayExceptions = 0
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/views"
resources.view.basePath = APPLICATION_PATH "/views"
; Scores configuration
profil.server.name = development
profil.mail.method = smtp
profil.mail.host = smtp.free.fr
profil.mail.email.support = supportdev@scores-decisions.com
profil.mail.email.supportdev = supportdev@scores-decisions.com
profil.mail.email.contact = supportdev@scores-decisions.com
profil.mail.email.production = supportdev@scores-decisions.com
profil.wkhtmltopdf.path = "/usr/local/bin/wkhtmltopdf"
profil.path.shared = "PROJECT_DIR/shared"
; Metier - Infogreffe
profil.infogreffe.wsdl = "infogreffe.wsdl"
profil.infogreffe.url = "https://webservices.infogreffe.fr/WSContextInfogreffe/INFOGREFFE"
profil.infogreffe.uri = "https://webservices.infogreffe.fr/"
profil.infogreffe.user = 85000109
profil.infogreffe.password = 166
profil.infogreffe.cache.path = "PROJECT_DIR/shared/cache"
profil.infogreffe.cache.time = 8
profil.infogreffe.storage.path = "PROJECT_DIR/shared/datafile/greffes"
; Sphinx configuration
profil.sphinx.ent.host = "172.18.8.5"
profil.sphinx.ent.port = 9312
profil.sphinx.ent.version = "2.2.10"
profil.sphinx.dir.host = "172.18.8.5"
profil.sphinx.dir.port = 9312
profil.sphinx.dir.version = "2.2.10"
profil.sphinx.act.host = "172.18.8.5"
profil.sphinx.act.port = 9312
profil.sphinx.act.version = "2.2.10"
profil.sphinx.histo.host = "172.18.8.5"
profil.sphinx.histo.port = 9312
profil.sphinx.histo.version = "2.2.10"
; For old configuration - see Configure.php
profil.db.metier.adapter=mysqli
profil.db.metier.params.host=172.18.8.5
profil.db.metier.params.username=wsuser
profil.db.metier.params.password=scores
profil.db.metier.params.dbname=sdv1
profil.db.metier.params.driver_options.MYSQLI_INIT_COMMAND = "SET NAMES utf8mb4"
[staging : production]
phpSettings.soap.wsdl_cache_enabled = 0
resources.frontController.params.displayExceptions = 1
[development : production]
phpSettings.soap.wsdl_cache_enabled = 0
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 0
resources.frontController.params.displayExceptions = 1
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

View File

@ -1,8 +0,0 @@
Créer un fichier "webservice" dans /etc/logrotate.d
/var/log/webservice/*.log {
weekly
missingok
compress
notifempty
}

View File

@ -0,0 +1,763 @@
<?
class WChiffes {
private static $tabChiffresEnLEttres = array( 0=>'zéro',
1=>'un',
2=>'deux',
3=>'trois',
4=>'quatre',
5=>'cinq',
6=>'six',
7=>'sept',
8=>'huit',
9=>'neuf',
10=>'dix',
11=>'onze',
12=>'douze',
13=>'treize',
14=>'quatorze',
15=>'quinze',
16=>'seize',
17=>'dix sept',
18=>'dix huit',
19=>'dix neuf',
20=>'vingt',
21=>'vingt et un',
22=>'vingt deux',
23=>'vingt trois',
24=>'vingt quatre',
25=>'vingt cinq',
26=>'vingt six',
27=>'vingt sept',
28=>'vingt huit',
29=>'vingt neuf',
30=>'trente',
40=>'quarante',
50=>'cinquante',
60=>'soixante',
70=>'soixante dix',
80=>'quatre vingt',
90=>'quatre vingt dix');
public function ChiffresEnLettres($chiffre) {
return array_search($chiffre, self::$tabChiffresEnLEttres);
}
}
/*
define('NEL_SEPTANTE', 0x0001);
define('NEL_HUITANTE', 0x0002);
define('NEL_OCTANTE', 0x0004);
define('NEL_NONANTE', 0x0008);
define('NEL_BELGIQUE', NEL_SEPTANTE|NEL_NONANTE);
define('NEL_VVF', NEL_SEPTANTE|NEL_HUITANTE|NEL_NONANTE);
define('NEL_ARCHAIQUE', NEL_SEPTANTE|NEL_OCTANTE|NEL_NONANTE);
define('NEL_SANS_MILLIARD', 0x0010);
define('NEL_AVEC_ZILLIARD', 0x0020);
define('NEL_TOUS_ZILLIONS', 0x0040);
define('NEL_RECTIF_1990', 0x0100);
define('NEL_ORDINAL', 0x0200);
define('NEL_NIEME', 0x0400);
# Le tableau associatif $NEL contient toutes les variables utilisées
# de façon globale dans ce module. ATTENTION : ce nom est assez court,
# et cela pourrait poser des problèmes de collision avec une autre
# variable si plusieurs modules sont inclus dans le même programme.
$NEL = array(
'1-99' => array(
# 0-19
'', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept',
'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze',
'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf',
# 20-29
'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois',
'vingt-quatre', 'vingt-cinq', 'vingt-six',
'vingt-sept', 'vingt-huit', 'vingt-neuf',
# 30-39
'trente', 'trente et un', 'trente-deux', 'trente-trois',
'trente-quatre', 'trente-cinq', 'trente-six',
'trente-sept', 'trente-huit', 'trente-neuf',
# 40-49
'quarante', 'quarante et un', 'quarante-deux', 'quarante-trois',
'quarante-quatre', 'quarante-cinq', 'quarante-six',
'quarante-sept', 'quarante-huit', 'quarante-neuf',
# 50-59
'cinquante', 'cinquante et un', 'cinquante-deux', 'cinquante-trois',
'cinquante-quatre', 'cinquante-cinq', 'cinquante-six',
'cinquante-sept', 'cinquante-huit', 'cinquante-neuf',
# 60-69
'soixante', 'soixante et un', 'soixante-deux', 'soixante-trois',
'soixante-quatre', 'soixante-cinq', 'soixante-six',
'soixante-sept', 'soixante-huit', 'soixante-neuf',
# 70-79
'septante', 'septante et un', 'septante-deux', 'septante-trois',
'septante-quatre', 'septante-cinq', 'septante-six',
'septante-sept', 'septante-huit', 'septante-neuf',
# 80-89
'huitante', 'huitante et un', 'huitante-deux', 'huitante-trois',
'huitante-quatre', 'huitante-cinq', 'huitante-six',
'huitante-sept', 'huitante-huit', 'huitante-neuf',
# 90-99
'nonante', 'nonante et un', 'nonante-deux', 'nonante-trois',
'nonante-quatre', 'nonante-cinq', 'nonante-six',
'nonante-sept', 'nonante-huit', 'nonante-neuf'
),
'illi' => array('', 'm', 'b', 'tr', 'quatr', 'quint', 'sext'),
'maxilli' => 0, # voir plus loin
'de_maxillions' => '', # voir plus loin
'septante' => false, # valeurs possibles : (false|true)
'huitante' => false, # valeurs possibles : (false|true|'octante')
'nonante' => false, # valeurs possibles : (false|true)
'zillions' => false, # valeurs possibles : (false|true)
'zilliard' => 1, # valeurs possibles : (0|1|2)
'rectif' => false, # valeurs possibles : (false|true)
'ordinal' => false, # valeurs possibles : (false|true|'nieme')
'separateur' => ' '
);
# Si le tableau $NEL['illi'] s'arrête à 'sext', alors les deux valeurs
# suivantes sont respectivement '6' et ' de sextillions'.
$NEL['maxilli'] = count($NEL['illi']) - 1;
$NEL['de_maxillions'] = " de {$NEL['illi'][$NEL['maxilli']]}illions";
function enlettres_options($options, $separateur=NULL)
{
global $NEL;
if ($options !== NULL) {
$NEL['septante'] = ($options & NEL_SEPTANTE) ? true : false;
$NEL['huitante'] =
($options & NEL_OCTANTE) ? 'octante' :
(($options & NEL_HUITANTE) ? true : false);
$NEL['nonante'] = ($options & NEL_NONANTE) ? true : false;
$NEL['zillions'] = ($options & NEL_TOUS_ZILLIONS) ? true : false;
$NEL['zilliard'] =
($options & NEL_AVEC_ZILLIARD) ? 2 :
(($options & NEL_SANS_MILLIARD) ? 0 : 1);
$NEL['rectif'] = ($options & NEL_RECTIF_1990) ? true : false;
$NEL['ordinal'] =
($options & NEL_NIEME) ? 'nieme' :
(($options & NEL_ORDINAL) ? true : false);
}
if ($separateur !== NULL) {
$NEL['separateur'] = $separateur;
}
}
function enlettres_par3($par3)
{
global $NEL;
if ($par3 == 0) return '';
$centaine = floor($par3 / 100);
$par2 = $par3 % 100;
$dizaine = floor($par2 / 10);
# On traite à part les particularités du français de référence
# 'soixante-dix', 'quatre-vingts' et 'quatre-vingt-dix'.
$nom_par2 = NULL;
switch ($dizaine) {
case 7:
if ($NEL['septante'] === false) {
if ($par2 == 71) $nom_par2 = 'soixante et onze';
else $nom_par2 = 'soixante-' . $NEL['1-99'][$par2 - 60];
}
break;
case 8:
if ($NEL['huitante'] === false) {
if ($par2 == 80) $nom_par2 = 'quatre-vingts';
else $nom_par2 = 'quatre-vingt-' . $NEL['1-99'][$par2 - 80];
}
break;
case 9:
if ($NEL['nonante'] === false) {
$nom_par2 = 'quatre-vingt-' . $NEL['1-99'][$par2 - 80];
}
break;
}
if ($nom_par2 === NULL) {
$nom_par2 = $NEL['1-99'][$par2];
if (($dizaine == 8) and ($NEL['huitante'] === 'octante')) {
$nom_par2 = str_replace('huitante', 'octante', $nom_par2);
}
}
# Après les dizaines et les unités, il reste à voir les centaines
switch ($centaine) {
case 0: return $nom_par2;
case 1: return rtrim("cent {$nom_par2}");
}
# Assertion : $centaine = 2 .. 9
$nom_centaine = $NEL['1-99'][$centaine];
if ($par2 == 0) return "{$nom_centaine} cents";
return "{$nom_centaine} cent {$nom_par2}";
}
function enlettres_zilli($idx)
{
# Noms des 0ème à 9ème zillions
static $petit = array(
'n', 'm', 'b', 'tr', 'quatr', 'quint', 'sext', 'sept', 'oct', 'non'
);
# Composantes des 10ème à 999ème zillions
static $unite = array(
'<', 'un<', 'duo<', 'tre<sé',
'quattuor<', 'quin<', 'se<xsé',
'septe<mné', 'octo<', 'nove<mné'
);
static $dizaine = array(
'', 'né>déci<', 'ms>viginti<', 'ns>triginta<',
'ns>quadraginta<', 'ns>quinquaginta<', 'né>sexaginta<',
'né>septuaginta<', 'mxs>octoginta<', 'é>nonaginta<'
);
static $centaine = array(
'>', 'nxs>cent', 'né>ducent', 'ns>trécent',
'ns>quadringent', 'ns>quingent', 'né>sescent',
'né>septingent', 'mxs>octingent', 'é>nongent'
);
# Règles d'assimilation aux préfixes latins, modifiées pour accentuer
# un éventuel 'é' de fin de préfixe.
# (1) Si on trouve une lettre deux fois entre < > on la garde.
# S'il y a plusieurs lettres dans ce cas, on garde la première.
# (2) Sinon on efface tout ce qui est entre < >.
# (3) On remplace "treé" par "tré", "seé" par "sé", "septeé" par "septé"
# et "noveé" par "nové".
# (4) En cas de dizaine sans centaine, on supprime la voyelle en trop.
# Par exemple "déciilli" devient "décilli" et "trigintailli" devient
# "trigintilli".
#
# Il est à noter que ces règles PERL (en particulier la première qui
# est la plus complexe) sont *très* fortement inspirées du programme
# de Nicolas Graner. On pourrait même parler de plagiat s'il n'avait
# pas été au courant que je reprenais son code.
# Voir <http://www.graner.net/nicolas/nombres/nom.php>
# et <http://www.graner.net/nicolas/nombres/nom-exp.php>
#
static $recherche = array(
'/<[a-zé]*?([a-zé])[a-zé]*\1[a-zé]*>/', # (1)
'/<[a-zé]*>/', # (2)
'/eé/', # (3)
'/[ai]illi/' # (4)
);
static $remplace = array(
'\\1', # (1)
'', # (2)
'é', # (3)
'illi' # (4)
);
$nom = '';
while ($idx > 0) {
$p = $idx % 1000;
$idx = floor($idx/1000);
if ($p < 10) {
$nom = $petit[$p] . 'illi' . $nom;
} else {
$nom = $unite[$p % 10] . $dizaine[floor($p/10) % 10]
. $centaine[floor($p/100)] . 'illi' . $nom;
}
}
return preg_replace($recherche, $remplace, $nom);
}
function enlettres_illions($idx)
{
global $NEL;
if ($idx == 0) {
return '';
}
if ($NEL['zillions']) {
return enlettres_zilli($idx) . 'ons';
}
$suffixe = '';
while ($idx > $NEL['maxilli']) {
$idx -= $NEL['maxilli'];
$suffixe .= $NEL['de_maxillions'];
}
return "{$NEL['illi'][$idx]}illions{$suffixe}";
}
function enlettres_avec_illiards($idx)
{
global $NEL;
if ($idx == 0) return false;
switch ($NEL['zilliard']) {
case 0: return false;
case 2: return true;
}
return ($idx == 1);
}
function enlettres($nombre, $options=NULL, $separateur=NULL)
{
global $NEL;
if ($options !== NULL or $separateur !== NULL) {
$NELsave = $NEL;
enlettres_options($options, $separateur);
$nom = enlettres($nombre);
$NEL = $NELsave;
return $nom;
}
# On ne garde que les chiffres, puis on supprime les 0 du début
$nombre = preg_replace('/[^0-9]/', '', $nombre);
$nombre = ltrim($nombre, '0');
if ($nombre == '') {
if ($NEL['ordinal'] === 'nieme') return 'zéroïème';
else return 'zéro';
}
$table_noms = array();
for ($idx = 0; $nombre != ''; $idx++) {
$par6 = (int)((strlen($nombre) < 6) ? $nombre : substr($nombre, -6));
$nombre = substr($nombre, 0, -6);
if ($par6 == 0) continue;
$nom_par3_sup = enlettres_par3(floor($par6 / 1000));
$nom_par3_inf = enlettres_par3($par6 % 1000);
$illions = enlettres_illions($idx);
if (enlettres_avec_illiards($idx)) {
if ($nom_par3_inf != '') {
$table_noms[$illions] = $nom_par3_inf;
}
if ($nom_par3_sup != '') {
$illiards = preg_replace('/illion/', 'illiard', $illions, 1);
$table_noms[$illiards] = $nom_par3_sup;
}
} else {
switch($nom_par3_sup) {
case '':
$nom_par6 = $nom_par3_inf;
break;
case 'un':
$nom_par6 = rtrim("mille {$nom_par3_inf}");
break;
default:
$nom_par3_sup = preg_replace('/(vingt|cent)s/', '\\1', $nom_par3_sup);
$nom_par6 = rtrim("{$nom_par3_sup} mille {$nom_par3_inf}");
break;
}
$table_noms[$illions] = $nom_par6;
}
}
$nom_enlettres = '';
foreach ($table_noms as $nom => $nombre) {
##
# $nombre est compris entre 'un' et
# 'neuf cent nonante-neuf mille neuf cent nonante-neuf'
# (ou variante avec 'quatre-vingt-dix-neuf')
##
# $nom peut valoir '', 'millions', 'milliards', 'billions', ...
# 'sextillions', 'sextilliards', 'millions de sextillions',
# 'millions de sextilliards', etc.
##
# Rectifications orthographiques de 1990
if ($NEL['rectif']) {
$nombre = str_replace(' ', '-', $nombre);
}
# Nom (éventuel) et accord (éventuel) des substantifs
$nom = rtrim("{$nombre} {$nom}");
if ($nombre == 'un') {
# Un seul million, milliard, etc., donc au singulier
# noter la limite de 1 remplacement, pour ne supprimer que le premier 's'
# dans 'billions de sextillions de sextillions'
$nom = preg_replace('/(illion|illiard)s/', '\\1', $nom, 1);
}
# Ajout d'un séparateur entre chaque partie
if ($nom_enlettres == '') {
$nom_enlettres = $nom;
} else {
$nom_enlettres = $nom . $NEL['separateur'] . $nom_enlettres;
}
}
if ($NEL['ordinal'] === false) {
# Nombre cardinal : le traitement est fini
return $nom_enlettres;
}
# Aucun pluriel dans les ordinaux
$nom_enlettres =
preg_replace('/(cent|vingt|illion|illiard)s/', '\\1', $nom_enlettres);
if ($NEL['ordinal'] !== 'nieme') {
# Nombre ordinal simple (sans '-ième')
return $nom_enlettres;
}
if ($nom_enlettres === 'un') {
# Le féminin n'est pas traité ici. On fait la supposition
# qu'il est plus facile de traiter ce cas à part plutôt
# que de rajouter une option rien que pour ça.
return 'premier';
}
switch (substr($nom_enlettres, -1)) {
case 'e':
# quatre, onze à seize, trente à nonante, mille
# exemple : quatre -> quatrième
return substr($nom_enlettres, 0, -1) . 'ième';
case 'f':
# neuf -> neuvième
return substr($nom_enlettres, 0, -1) . 'vième';
case 'q':
# cinq -> cinquième
return $nom_enlettres . 'uième';
}
# Tous les autres cas.
# Exemples: deuxième, troisième, vingtième, trente et unième,
# neuf centième, un millionième, quatre-vingt milliardième.
return $nom_enlettres . 'ième';
}
function enchiffres_petit($mot)
{
static $petit = array(
# 1-16
'un' => 1,
'deux' => 2,
'trois' => 3,
'quatre' => 4,
'cinq' => 5,
'six' => 6,
'sept' => 7,
'huit' => 8,
'neuf' => 9,
'dix' => 10,
'onze' => 11,
'douze' => 12,
'treize' => 13,
'quatorze' => 14,
'quinze' => 15,
'seize' => 16,
# 20-90
'vingt' => 20,
'vingts' => 20,
'trente' => 30,
'quarante' => 40,
'cinquante' => 50,
'soixante' => 60,
'septante' => 70,
'huitante' => 80,
'octante' => 80,
'nonante' => 90,
# 100, 1000
'cent' => 100,
'cents' => 100,
'mil' => 1000,
'mille' => 1000
);
if (! isset($petit[$mot]))
return false;
return $petit[$mot];
}
function enchiffres_zilli($mot)
{
# Noms des 0ème à 9ème zillions
static $petits = array(
'n', 'm', 'b', 'tr', 'quadr', 'quint', 'sext', 'sept', 'oct', 'non'
);
# Composantes des 10ème à 999ème zillions
static $unites = array(
'', 'un', 'duo', 'tre', 'quattuor', 'quin', 'se', 'septe', 'octo', 'nove'
);
static $dizaines = array(
'', 'dec', 'vigint', 'trigint', 'quadragint',
'quinquagint', 'sexagint', 'septuagint', 'octogint', 'nonagint'
);
static $centaines = array(
'', 'cent', 'ducent', 'trecent', 'quadringent',
'quingent', 'sescent', 'septingent', 'octingent', 'nongent'
);
# Expressions rationnelles pour extraire les composantes
static $um =
'(|un|duo|tre(?!c)|quattuor|quin|se(?!p)(?!sc)|septe|octo|nove)[mnsx]?';
static $dm =
'(|dec|(?:v|tr|quadr|quinqu|sex|septu|oct|non)[aio]gint)[ai]?';
static $cm =
'(|(?:|du|tre|ses)cent|(?:quadri|qui|septi|octi|no)ngent)';
$u = array_search($mot, $petits);
if ($u !== false) {
return '00' . $u;
}
if (preg_match('/^'.$um.$dm.$cm.'$/', $mot, $resultat) < 1) {
return false;
}
$u = array_search($resultat[1], $unites);
$d = array_search($resultat[2], $dizaines);
$c = array_search($resultat[3], $centaines);
if ($u === false or $d === false or $c === false) {
return false;
}
return $c.$d.$u;
}
function enchiffres_grand($mot)
{
# Quelques remplacements initiaux pour simplifier (les 'é' ont déjà
# été tous transformés en 'e').
# (1) Je supprime le 's' final de '-illions' ou '-illiards' pour ne
# tester que '-illion' ou '-illiard'.
# (2) Les deux orthographes étant possibles pour quadrillion ou
# quatrillion, je teste les deux. Noter que j'aurais pu changer
# 'quadr' en 'quatr' au lieu de l'inverse, mais alors cela aurait
# aussi changé 'quadragintillion' en 'quatragintillion', ce qui
# n'est pas franchement le but recherché.
# (3) En latin, on trouve parfois 'quatuor' au lieu de 'quattuor'. De même,
# avec google on trouve quelques 'quatuordecillions' au milieu des
# 'quattuordecillions' (environ 1 sur 10).
# (4) La règle de John Conway et Allan Wechsler préconisait le préfixe
# 'quinqua' au lieu de 'quin' que j'ai choisi. Pour accepter les deux,
# je remplace 'quinqua' par 'quin', sauf dans 'quinquaginta' (50)
# et dans 'quinquadraginta' (45).
static $recherche = array(
'/s$/', # (1)
'/quatr/', # (2)
'/quatuor/', # (3)
'/quinqua(?!(dra)?gint)/' # (4)
);
static $remplace = array(
'', # (1)
'quadr', # (2)
'quattuor', # (3)
'quin' # (4)
);
$mot = preg_replace($recherche, $remplace, $mot);
if ($mot == 'millier') return 1;
if ($mot == 'millinillion') return 2000;
$prefixes = explode('illi', $mot);
if (count($prefixes) < 2) {
# Il faut au moins un 'illi' dans le nom
return false;
}
switch (array_pop($prefixes)) {
case 'on':
# zillion : nombre pair de milliers
$ard = 0;
break;
case 'ard':
# zilliard : nombre impair de milliers
$ard = 1;
break;
default:
# Ce n'est ni un zillion, ni un zilliard
return false;
}
$nombre = '';
foreach ($prefixes as $prefixe) {
$par3 = enchiffres_zilli($prefixe);
if ($par3 === false) return false;
$nombre .= $par3;
}
if (strlen($nombre) > 3) {
# On n'accepte que les nombres inférieurs au millinillion
# pour limiter le temps de calcul
return 0;
}
return 2*$nombre + $ard;
}
class enchiffres_struct
{
var $valeur;
var $discr;
function enchiffres_struct($mul, $val)
{
$this->valeur = $this->discr = $val;
if ($mul != 0) {
$this->valeur *= $mul;
}
}
}
function enchiffres_ajouter_petit(&$table_petits, $petit)
{
$somme = 0;
while (($elem = array_pop($table_petits)) !== NULL) {
if ($elem->discr > $petit) {
array_push($table_petits, $elem);
break;
}
$somme += $elem->valeur;
}
$elem = new enchiffres_struct($somme, $petit);
array_push($table_petits, $elem);
}
function enchiffres_somme_petits($table_petits)
{
$somme = 0;
foreach ($table_petits as $elem) {
$somme += $elem->valeur;
}
return $somme;
}
function enchiffres_ajouter_grand(&$table_grands, $mantisse, $exposant)
{
while ($mantisse > 0) {
if (isset($table_grands[$exposant])) {
$mantisse += $table_grands[$exposant];
}
$table_grands[$exposant] = $mantisse % 1000;
$mantisse = floor($mantisse / 1000);
$exposant++;
}
}
function enchiffres($nom)
{
$nom = preg_replace('/[éèÉÈ]/', 'e', $nom);
$nom = strtolower($nom);
$table_mots = preg_split('/[^a-z]+/', $nom);
$table_petits = array();
$mantisse = $exposant = 0;
$table_grands = array();
foreach ($table_mots as $mot) {
$petit = enchiffres_petit($mot);
if ($petit !== false) {
if ($mantisse != 0) {
enchiffres_ajouter_grand($table_grands, $mantisse, $exposant);
$mantisse = $exposant = 0;
}
enchiffres_ajouter_petit($table_petits, $petit);
continue;
}
$grand = enchiffres_grand($mot);
if ($grand === false) {
# Ce n'est pas un nombre
continue;
}
if ($grand == 0) {
# Ce nombre était trop grand (millinillion et plus) : on annule le
# tout pour limiter le temps de calcul.
$mantisse = 0;
$exposant = 0;
$table_petits = array();
} else {
if (count($table_petits) > 0) {
$mantisse = enchiffres_somme_petits($table_petits);
$exposant = 0;
$table_petits = array();
}
if ($mantisse != 0) {
$exposant += $grand;
}
}
}
if (count($table_petits) > 0) {
$mantisse = enchiffres_somme_petits($table_petits);
$exposant = 0;
}
if ($mantisse != 0) {
enchiffres_ajouter_grand($table_grands, $mantisse, $exposant);
}
$nombre = "";
for ($exposant = 0; count($table_grands) > 0; $exposant++) {
if (isset($table_grands[$exposant])) {
$par3 = $table_grands[$exposant];
unset($table_grands[$exposant]);
} else {
$par3 = 0;
}
$nombre = sprintf("%03d", $par3) . $nombre;
}
$nombre = ltrim($nombre, '0');
if ($nombre === '') $nombre = '0';
return $nombre;
}
function enchiffres_aerer($nombre, $blanc=' ', $virgule=',', $tranche=3)
{
# Si c'est un nombre à virgule, on traite séparément les deux parties
if ($virgule !== NULL) {
$ent_dec = preg_split("/$virgule/", $nombre);
if (count($ent_dec) >= 2) {
$ent = enchiffres_aerer($ent_dec[0], $blanc, NULL, $tranche);
$dec = enchiffres_aerer($ent_dec[1], $blanc, NULL, -$tranche);
return $ent . $virgule . $dec;
}
}
# On ne garde que les chiffres
$nombre = preg_replace('/[^0-9]/', '', $nombre);
# Il est plus logique d'avoir un nombre positif pour les entiers,
# donc négatif pour la partie décimale, mais plus pratique de
# faire le contraire pour les substr().
$tranche = - (int)$tranche;
if ($tranche == 0) {
# on voulait juste supprimer les caractères en trop, pas en rajouter
return $nombre;
}
$nombre_aere = '';
if ($tranche < 0) {
# entier, ou partie entière d'un nombre décimal
while ($nombre != '') {
$par3 = substr($nombre, $tranche);
$nombre = substr($nombre, 0, $tranche);
if ($nombre_aere == '') {
$nombre_aere = $par3;
} else {
$nombre_aere = $par3 . $blanc . $nombre_aere;
}
}
} else {
# partie décimale
while ($nombre != '') {
$par3 = substr($nombre, 0, $tranche);
$nombre = substr($nombre, $tranche);
if ($nombre_aere == '') {
$nombre_aere = $par3;
} else {
$nombre_aere .= $blanc . $par3;
}
}
}
return $nombre_aere;
}
*/
?>

572
framework/common/curl.php Normal file
View File

@ -0,0 +1,572 @@
<?
//include_once('/var/www/default/_includes/timer.php');
/** Parse une page Html et retourne son contenu dans un tableau :
** "code" => Code réponse Serveur
** "header" => Headers du serveur
** "body" => Page HTML
**/
function parse_response($this_response) {
// Split response into header and body sections
list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
$response_header_lines = explode("\r\n", $response_headers);
// First line of headers is the HTTP response code
$http_response_line = array_shift($response_header_lines);
if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }
// put the rest of the headers in an array
$response_header_array = array();
$nbRMID=0;
foreach($response_header_lines as $header_line)
{
list($header,$value) = explode(': ', $header_line, 2);
if ($header=='Set-cookie' && substr($value,0,5)=='RMID=' && $nbRMID<5)//{
$nbRMID++;
// echo ("Je gicle le RMID n°$nbRMID\r\n");}
else
@$response_header_array[$header] .= $value."\n";
}
return array('code' => $response_code, 'header' => $response_header_array, 'body' => $response_body);
}
/** Récupère une page HTML en fonction des paramètres :
** $url Url distante de la page à récupérer
** $strCookies Chaine de caractère contenant les cookies
** $postData Tableau des données à passer en POST uniquement
** $referer Referer à indiquer lors de l'appel de la page
** $debug Activer le débogage (True/False)
**
** ... et retourne son contenu dans un tableau :
** "code" => Code réponse Serveur
** "header" => Headers du serveur
** "body" => Page HTML
**/
function getUrl($url, $strCookies='', $postData='', $referer='', $debug=false, $host='', $proxy='', $timeout=0, $nbRetry=0) {
$ch = curl_init();
if ($host=='')
$this_header = array('Host: '. parse_url($url, PHP_URL_HOST));
else
$this_header = array('Host: '. $host);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
if ($proxy<>'') curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'username:password'); // Pas nécessaire en authentification NT
if (((int)$timeout)<>0) {
curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int)$timeout);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // New
//curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
/* curl_setopt($ch, CURLOPT_WRITEFUNCTION, receiveResponse);
function receiveResponse($curlHandle,$xmldata)
{
$this->responseString = $xmldata;
$this->responseXML .= $this->responseString;
$this->length = strlen($xmldata);
$this->size += $this->length;
return $this->length;
}
*/
if (preg_match('/^https/i',$url))
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_REFERER, $referer);
// Add each cookie that has been returned in the response
// If cookies need to be added/deleted or value changed, then add code here
if ($strCookies!='') {
//die('"'.$strCookies.'"');
//echo $strCookies."\r\n";
$cookies = explode("\n", $strCookies);
// Create the basic header
foreach($cookies as $this_cookie) {
if (trim($this_cookie)<>'')
array_push($this_header, 'Cookie: '.$this_cookie);
}
}
if ($postData!='') {
if (is_array($postData))
$post_data=$postData;
$o="";
foreach ($post_data as $k=>$v)
{
$o.= "$k=".utf8_encode($v)."&";
}
$post_data=substr($o,0,-1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//if in_array('',$this_header
/*array_push($this_header, "Content-type: application/x-www-form-urlencoded");
array_push($this_header, "Content-Length: 44");*/
}
/* curl_setopt($ch, CURLOPT_STDERR, '/var/www/log/curlerror.log');
curl_setopt($ch, CURLOPT_VERBOSE, true);
*/
curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
//print_r($this_header);
if ($nbRetry==0) {
$page=curl_exec($ch);
if($page === false) {
if (curl_errno($ch) == 28) //TIMEOUT
$response=array('code' =>408, 'header' =>array('curl_errno'=>curl_errno($ch),'curl_error'=>curl_error($ch)), 'body' =>'Connexion impossible au site du partenaire/Timeout');
else
$response=array('code' =>400, 'header' =>array('curl_errno'=>curl_errno($ch),'curl_error'=>curl_error($ch)), 'body' =>'Erreur Curl : ' . curl_error($ch));
} else
$response = parse_response($page);
} else {
$numTry=0;
while($numTry<=$nbRetry) {
$page=curl_exec($ch);
if($page === false) {
if (curl_errno($ch) == 28) //TIMEOUT
$response=array('code' =>408, 'header' =>array('curl_errno'=>curl_errno($ch),'curl_error'=>curl_error($ch)), 'body' =>'Connexion impossible au site du partenaire');
else
$response=array('code' =>400, 'header' =>array('curl_errno'=>curl_errno($ch),'curl_error'=>curl_error($ch)), 'body' =>'Erreur Curl : ' . curl_error($ch));
} else {
$response = parse_response($page);
break;
}
}
}
if ($debug){
$url2=str_replace('http://', '', $url);
$url2=str_replace('/', '_', $url2);
$url2=str_replace('?', '(param)', $url2);
$url2=str_replace('&', '(et)', $url2);
$fp=fopen('/tmp/curl-'. date('Ymd-His') .'-'. microtime_float(true) .'-'. $url2 . '.html', 'a');
fwrite($fp, $url."\r\n");
fwrite($fp, $page);
fclose($fp);
//echo strip_tags(html_entity_decode($response['body']), '<td>');
}
//print_r(curl_getinfo($ch));
curl_close($ch);
return $response;
}
/** Recherche un texte dans une page HTML
**
**/
function getTextInHtml($pageHtml, $strToFind, $strDeb, $strEnd, $include_strDeb=false, $include_strEnd=false, $ltrim=true, $rtrim=true, &$fin, $nbOcc=1) {
$tabRet=array();
$deb=$nbOccTrouve=0;
while( is_int(($deb=strpos($pageHtml,$strToFind,$fin))) ) {
$deb++;
$deb2 = strpos($pageHtml,$strDeb, $deb);
$fin = strpos($pageHtml,$strEnd, $deb2);
if (!$include_strDeb)
$deb2+=strlen($strDeb);
$s_temp = substr($pageHtml, $deb2, ($fin-$deb2));
if ($ltrim) $s_temp=ltrim($s_temp);
if ($rtrim) $s_temp=rtrim($s_temp);
if ($nbOcc==1) return $s_temp;
//echo $s_temp."\r\n";
//$a_temp = explode('" class="basic">', $s_temp);
$tabUrl[$nbOccTrouve]=$s_temp;
$nbOccTrouve++;
if ($nbOcc==$nbOccTrouve) {
// echo "j'ai trouvé le nb demandé, je sort\r\n";
break;
};
}
return $tabUrl;
/*<span class="mongrasvert">
<li>Le type de voie a été modifié<br>
<li>L'orthographe du mot directeur a été modifiée<br>
<li>Le code postal a été forcé à partir du département et de la localité<br> </span>
*/
}
function simpleWhois($domain, $tdl, $debug=false) {
// Fonction de traitement
// -----------------------------------------------
// 0 => Info, le nom est pris
// 1 => Info, le nom est libre
// 2 => Info, le nom est en pending
// 3 => Avertissement, trop de requêtes
// 4 => Erreur, il faut spécifier une chaine à rechercher (regexp)
// 5 => Erreur, la requête retournée était vide
// -----------------------------------------------
// Informations spécifiques aux extensions
$info = array(
'fr' => array(
'host' => 'whois.nic.fr',
'regexp' => 'No[s]*entries[s]*found',
'pending' => 'status[s]*:[s]*REDEMPTION'
),
'com' => array(
'host' => 'whois.crsnic.net',
'regexp' => 'No[s]*match[s]*for'
),
'net' => array(
'host' => 'whois.crsnic.net',
'regexp' => 'No[s]*match[s]*for'
),
);
// Initialisation de la sortie
$output = '';
// Initialisation de la requête
$req = fsockopen($info[$tdl]['host'], 43, $errno, $errstr, 5); // le 5 permet de stopper la requete si aucune réponse au bout de 5 secondes
// Récupération de la requête
if($req){
fputs($req, $domain.'.'.$tdl."rn");
while(!feof($req)) $output .= fgets($req, 4096);
fclose($req);
}else unset($req);
// mode debug
if($debug) return $output;
// Sortie vide
if(empty($output)) return 5;
// Trop de requêtes
if(preg_match("/(Too[s]+many[s]+requests|Your[s]+connection[s]+limit[s]+exceeded|daily[s]+whois[s]+limit[s]+exceeded|Maximum[s]+queries|WHOIS[s]+LIMIT[s]+EXCEEDED|referral[s]+host[s]+not[s]+responding|Excessive[s]+querying)/i", $output)) return 3;
// Pending
if(isset($info[$tdl]['pending']) && !empty($info[$tdl]['pending']) && preg_match("/".$info[$tdl]['pending']."/i", $output)) return 2;
// Info de recheche manquant
if(!isset($info[$tdl]['regexp']) || empty($info[$tdl]['regexp'])) return 4;
// Libre
if(preg_match("/".$info[$tdl]['regexp']."/i", $output)) return 1;
// Pris
return 0;
}
/*** Fonction PDF ***/
function getPdfInfo($f){
$tabInfo=array( 'file'=>$f,
'fileName'=>basename($f));
$handle = @fopen($f, 'r');
if ($handle) {
//echo '1'.EOL;
$i=$nbPages=$buffer=0;
while (!feof($handle)) {
$prev_buffer=$buffer;
$buffer = fgets($handle, 4096);
if ($i==0 && preg_match("/^\%PDF\-(.*)\s/U", $buffer, $matches))
$tabInfo['version']=$matches[1];
elseif (preg_match("/Type\s*\/Page[^s]/", $buffer) )
++$nbPages;
$i++;
}
//echo '2'.EOL;
if (preg_match("/\%\%EOF$/", $prev_buffer) || preg_match("/\%\%EOF/", $prev_buffer) || preg_match("/\%\%EOF/", $buffer)) {
//echo '3'.EOL;
$tabInfo['pdfEOF']=true;
} else {
/*echo '4 prev:'.$prev_buffer.EOL;
echo '4 last:'.$buffer.EOL;*/
$tabInfo['debugBuffer']=$prev_buffer;
return false;
}
fclose($handle);
} else {
//echo '5'.EOL;
return false;
}
$tabInfo['pdfSize']=filesize($f);
$tabInfo['nbPages']=0+$nbPages;
$tabInfo['nbCar']=strlen(pdf2text($f));
//$tabInfo['debugBuffer']=$prev_buffer;
return $tabInfo;
}
/** @link : http://webcheatsheet.com/php/reading_clean_text_from_pdf.php
*/
function decodeAsciiHex($input) {
$output = '';
$isOdd = true;
$isComment = false;
for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
switch($c) {
case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
case '%':
$isComment = true;
break;
default:
$code = hexdec($c);
if($code === 0 && $c != '0') return '';
if($isOdd) $codeHigh = $code;
else $output .= chr($codeHigh * 16 + $code);
$isOdd = !$isOdd;
break;
}
}
if($input[$i] != '>') return '';
if($isOdd) $output .= chr($codeHigh * 16);
return $output;
}
function decodeAscii85($input) {
$output = '';
$isComment = false;
$ords = array();
for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ') continue;
if ($c == '%') {
$isComment = true;
continue;
}
if ($c == 'z' && $state === 0) {
$output .= str_repeat(chr(0), 4);
continue;
}
if ($c < '!' || $c > 'u') return '';
$code = ord($input[$i]) & 0xff;
$ords[$state++] = $code - ord('!');
if ($state == 5) {
$state = 0;
for ($sum = 0, $j = 0; $j < 5; $j++)
$sum = $sum * 85 + $ords[$j];
for ($j = 3; $j >= 0; $j--)
$output .= chr($sum >> ($j * 8));
}
}
if ($state === 1) return '';
elseif ($state > 1) {
for ($i = 0, $sum = 0; $i < $state; $i++)
$sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
for ($i = 0; $i < $state - 1; $i++)
$ouput .= chr($sum >> ((3 - $i) * 8));
}
return $output;
}
function decodeFlate($input) {
return @gzuncompress($input);
}
function getObjectOptions($object) {
$options = array();
if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
$options = explode("/", $options[1]);
@array_shift($options);
$o = array();
for ($j = 0; $j < @count($options); $j++) {
$options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
if (strpos($options[$j], " ") !== false) {
$parts = explode(" ", $options[$j]);
$o[$parts[0]] = $parts[1];
} else
$o[$options[$j]] = true;
}
$options = $o;
unset($o);
}
return $options;
}
function getDecodedStream($stream, $options) {
$data = '';
if (empty($options["Filter"]))
$data = $stream;
else {
$length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
$_stream = substr($stream, 0, $length);
foreach ($options as $key => $value) {
if ($key == "ASCIIHexDecode") $_stream = decodeAsciiHex($_stream);
if ($key == "ASCII85Decode") $_stream = decodeAscii85($_stream);
if ($key == "FlateDecode") $_stream = decodeFlate($_stream);
}
$data = $_stream;
}
return $data;
}
function getDirtyTexts(&$texts, $textContainers) {
for ($j = 0; $j < count($textContainers); $j++) {
if (preg_match_all("#\[(.*)\]\s*TJ#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, @$parts[1]);
elseif(preg_match_all("#Td\s*(\(.*\))\s*Tj#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, @$parts[1]);
}
}
function getCharTransformations(&$transformations, $stream) {
preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
for ($j = 0; $j < count($chars); $j++) {
$count = $chars[$j][1];
$current = explode("\n", trim($chars[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
$transformations[str_pad($map[1], 4, "0")] = $map[2];
}
}
for ($j = 0; $j < count($ranges); $j++) {
$count = $ranges[$j][1];
$current = explode("\n", trim($ranges[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$_from = hexdec($map[3]);
for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
} elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$parts = preg_split("#\s+#", trim($map[3]));
for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
}
}
}
}
function getTextUsingTransformations($texts, $transformations) {
$document = '';
for ($i = 0; $i < count($texts); $i++) {
$isHex = false;
$isPlain = false;
$hex = '';
$plain = '';
for ($j = 0; $j < strlen($texts[$i]); $j++) {
$c = $texts[$i][$j];
switch($c) {
case "<":
$hex = "";
$isHex = true;
break;
case ">":
$hexs = str_split($hex, 4);
for ($k = 0; $k < count($hexs); $k++) {
$chex = str_pad($hexs[$k], 4, "0");
if (isset($transformations[$chex]))
$chex = $transformations[$chex];
$document .= html_entity_decode("&#x".$chex.";");
}
$isHex = false;
break;
case "(":
$plain = "";
$isPlain = true;
break;
case ")":
$document .= $plain;
$isPlain = false;
break;
case "\\":
$c2 = $texts[$i][$j + 1];
if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
elseif ($c2 == "n") $plain .= '\n';
elseif ($c2 == "r") $plain .= '\r';
elseif ($c2 == "t") $plain .= '\t';
elseif ($c2 == "b") $plain .= '\b';
elseif ($c2 == "f") $plain .= '\f';
elseif ($c2 >= '0' && $c2 <= '9') {
$oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
$j += strlen($oct) - 1;
$plain .= html_entity_decode("&#".octdec($oct).";");
}
$j++;
break;
default:
if ($isHex) $hex .= $c;
if ($isPlain) $plain .= $c;
break;
}
}
$document .= "\n";
}
return $document;
}
function pdf2text($filename) {
$infile = @file_get_contents($filename, FILE_BINARY);
if (empty($infile)) return '';
$transformations = array();
$texts = array();
preg_match_all("#obj(.*)endobj#ismU", $infile, $objects);
$objects = @$objects[1];
for ($i = 0; $i < count($objects); $i++) {
$currentObject = $objects[$i];
if (preg_match("#stream(.*)endstream#ismU", $currentObject, $stream)) {
$stream = ltrim($stream[1]);
$options = getObjectOptions($currentObject);
if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"]))) continue;
$data = getDecodedStream($stream, $options);
if (strlen($data)) {
if (preg_match_all("#BT(.*)ET#ismU", $data, $textContainers)) {
$textContainers = @$textContainers[1];
getDirtyTexts($texts, $textContainers);
} else
getCharTransformations($transformations, $data);
}
}
}
return getTextUsingTransformations($texts, $transformations);
}
?>

249
framework/common/dates.php Normal file
View File

@ -0,0 +1,249 @@
<?
include_once('chiffres.php');
/**
* Classe de gestion des méthodes relatives à la date et à l'heure
*
* <p>détail de la classe</p>
*
* @name nom de la classe
* @author Nom de l'auteur <adresse@Email.dom>
* @link
* @copyright Prénom Nom Année
* @version 1.0.0
* @package Nom du package
*/
class WDate {
private static $tabMoisEnLettres = array( 1=>'Janvier',
2=>'Février',
3=>'Mars',
4=>'Avril',
5=>'Mai',
6=>'Juin',
7=>'Juillet',
8=>'Août',
9=>'Septembre',
10=>'Octobre',
11=>'Novembre',
12=>'Décembre');
private static $tabMoisEnLettresC = array( 1=>'Jan',
2=>'Fév',
3=>'Mar',
4=>'Avr',
5=>'Mai',
6=>'Juin',
7=>'Juil',
8=>'Août',
9=>'Sep',
10=>'Oct',
11=>'Nov',
12=>'Déc');
private static $tabMoisEnLettresEn = array( 1=>'Jan',
2=>'Feb',
3=>'Mar',
4=>'Apr',
5=>'May',
6=>'Jun',
7=>'Jul',
8=>'Aou',
9=>'Sep',
10=>'Oct',
11=>'Nov',
12=>'Dec');
/** Retourne le numéro du mois donné au format texte (janvier, mars, etc...)
* @param string Mois en toute lettres (janvier, mars, etc...)
* @return string Mois en Chiffe (1, 3, 12) / false en cas d'erreur
*/
public function getNumMois($moisEnLettres, $lang='fr', $court=false) {
if ($lang=='fr' && !$court) {
foreach (self::$tabMoisEnLettres as $num=>$mois)
$tabMoisSansAccents[$num]=strtr($mois, 'ééûÉÉÛ','eeueeu');
} elseif ($lang=='fr' && $court) {
foreach (self::$tabMoisEnLettresC as $num=>$mois)
$tabMoisSansAccents[$num]=strtr($mois, 'ééûÉÉÛ','eeueeu');
} elseif ($lang=='en') {
foreach (self::$tabMoisEnLettresEn as $num=>$mois)
$tabMoisSansAccents[$num]=strtr($mois, 'ééûÉÉÛ','eeueeu');
}
return array_search(ucfirst(strtolower(strtr($moisEnLettres, 'ééûÉÉÛ','eeuEEU'))), $tabMoisSansAccents);
}
/** Retourne le libellé nu numéro du mois passé en paramètre
* @param int $moisEnChiffre
* @return string Libellé du mois / false si le mois passé en paramètre est invalide
*/
public function getLibelleMois($moisEnChiffre) {
if ($moisEnChiffre>0 && $moisEnChiffre<13)
return self::$tabMoisEnLettres[$moisEnChiffre];
return false;
}
/** Retourne le nombre de mois entre 2 dates au format Ymd
**
** @param int $dateDeb Date de début au format Ymd
** @param int $dateFin Date de fin (ultérieur à la date de début) au format Ymd
** @return int Nombre de mois
**/
function nbMoisEntre($dateDeb, $dateFin=TODAY) {
$dDeb=explode('-', Wdate::dateT('Ymd','Y-m-d', $dateDeb));
$dFin=explode('-', Wdate::dateT('Ymd','Y-m-d', $dateFin));
return ($dFin[0]*12+$dFin[1])-($dDeb[0]*12+$dDeb[1]);
}
/**
* Conversion de formats de dates selon les formats de dates définits en php
* @param string Format de la date d'entrée
* @param string Format de la date de sortie
* @param string Date d'entrée
* @return string Date formatée
*/
public function dateT($formatIN, $formatOUT, $date) {
$M='';
switch ($formatIN) {
case 'd M Y': $tmp=explode(' ', $date); $d=str_replace('1er', '1', $tmp[0]); $m=self::getNumMois($tmp[1],'fr'); $Y=$tmp[2]; break;
case 'd-M-Y': $tmp=explode('-', $date); $d=str_replace('1er', '1', $tmp[0]); $m=self::getNumMois($tmp[1],'fr'); $Y=$tmp[2]; break;
case 'd-Mc-Y': $tmp=explode('-', $date); $d=str_replace('1er', '1', $tmp[0]); $m=self::getNumMois($tmp[1],'fr',1); $Y=$tmp[2]; break;
case 'd Men Y': $tmp=explode(' ', $date); $d=str_replace('1st', '1', $tmp[0]); $m=self::getNumMois($tmp[1],'en'); $Y=$tmp[2]; break;
case 'dMY': $Y=substr($date,-4);
if (substr($date,0,3)=='1er') { $d=1; $posM=3; }
elseif (is_numeric(substr($date,1,1))) { $d=substr($date,0,2); $posM=2; }
else { $d=substr($date,0,1); $posM=1; }
$M=trim(substr($date, $posM, strlen($date)-4-$posM));
//echo "$date:$posM:$M".EOL;
$m=self::getNumMois($M);
break;
case 'Ymd': $d=substr($date,6,2); $m=substr($date,4,2); $Y=substr($date,0,4); break;
case 'ymd': $d=substr($date,4,2); $m=substr($date,2,2); $Y=substr($date,0,2);
if ($Y<50) $Y='20'.$Y; else $Y='19'.$Y; break;
case 'Y-m-d': $d=substr($date,8,2); $m=substr($date,5,2); $Y=substr($date,0,4); break;
case 'Y-m': $d=1; $m=substr($date,5,2); $Y=substr($date,0,4); break;
case 'd/m/Y': $tmp=explode('/', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
case 'd.m.Y': $tmp=explode('.', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
case 'd/m/y': $tmp=explode('/', $date); $d=$tmp[0]; $m=$tmp[1];
if ($tmp[2]<date('y')) $Y='20'.$tmp[2]; else $Y='19'.$tmp[2]; break;
case 'd-m-Y': $tmp=explode('-', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
case 'm/d/Y': $tmp=explode('/', $date); $d=$tmp[1]; $m=$tmp[0]; $Y=$tmp[2]; break;
case 'dmY': $d=substr($date,0,2); $m=substr($date,2,2); $Y=substr($date,4,4); break;
case 'dmy': $d=substr($date,0,2); $m=substr($date,2,2); $Y=substr($date,4,2);
if ($Y<50) $Y='20'.$Y; else $Y='19'.$Y; break;
default: return $date;
}
if ($m*1>0 && $m*1<10) $m='0'.($m*1); if ($d*1>0 && $d*1<10) $d='0'.($d*1);
/* echo "d=$d".EOL;
echo "m=$m".EOL;
echo "Y=$Y".EOL;
*/
switch ($formatOUT) {
case 'd/m/Y': return $d.'/'.$m.'/'.$Y; break;
case 'dmY': return $d.''.$m.''.$Y; break;
case 'm/Y': return $m.'/'.$Y; break;
case 'd M Y': return $d.' '.self::$tabMoisEnLettres[$m*1].' '.$Y; break;
case 'M Y': return self::$tabMoisEnLettres[$m*1].' '.$Y; break;
case 'Y': return $Y; break;
case 'm': return $m; break;
case 'd': return $d; break;
case 'Ym': return $Y.''.$m; break;
case 'Ymd': return $Y.''.$m.''.$d; break;
case 'Y-m-d': return $Y.'-'.$m.'-'.$d; break;
case 'Y/m/d': return $Y.'/'.$m.'/'.$d; break;
default: return $date;
}
}
/** Calcul de la date après application de la période textuelle (deux ans, six mois, quinze jours, etc...)
* @todo Fonction ne fonctionnant qu'avec un chiffre en un seul mot du genre dix mais pas quatre vingt dix !!!
* @param date $dateIN au format Ymd
* @param string $period (ex : cinq mois, six ans, un jour, 3 mois)
* @return date
*/
function period2Days($dateIN, $period, $inThePast=false) {
$dateV=self::dateT('Ymd', 'Ymd', $dateIN);
if ($dateV<>$dateIN) return NULL;
$d=substr($dateIN,6,2);
$m=substr($dateIN,4,2);
$Y=substr($dateIN,0,4);
$period=strtolower(trim(strtr($period, "-.,", ' ')));
if ($period=='') return NULL;
$tabP=explode(' ', $period);
if ($tabP[0]*1>0) $chiffre=$tabP[0]*1*1;
else $chiffre=WChiffes::ChiffresEnLettres($tabP[0]);
if ($inThePast) $chiffre=-1*$chiffre;
switch (end($tabP)) {
case 'mois': $dateOUT=date('Ymd', mktime(0, 0, 0, $m+$chiffre, $d, $Y)); break;
case 'an':
case 'ans': $dateOUT=date('Ymd', mktime(0, 0, 0, $m, $d, $Y+$chiffre)); break;
case 'jour':
case 'jours': $dateOUT=date('Ymd', mktime(0, 0, 0, $m, $d+$chiffre, $Y)); break;
default: $dateOUT=NULL;
}
return $dateOUT;
}
function getNextDate($dateCour, $nbJours=7) {
$nextDate=date('Ymd', mktime(0, 0, 0, WDate::dateT('Ymd','m', $dateCour), WDate::dateT('Ymd','d', $dateCour)+$nbJours, WDate::dateT('Ymd','Y', $dateCour)));
return $nextDate;
}
/** le jour est il ferié
* @param date $date Date au format SSAA-MM-JJ ou SSAAMMJJ
* @param bool $weekend Considérer les WeekEnd comme feriés ? 1=Oui
* @return bool
**/
function jourFerie($date, $weekend=false) {
$date =str_replace('-','',strtr($date, '/.:','---'));
$jour =self::dateT('Ymd', 'd', $date);
$mois =self::dateT('Ymd', 'm', $date);
$annee=self::dateT('Ymd', 'Y', $date);
$ferie=false;
// Jours feriées fixes
if($jour == 1 && $mois == 1) $ferie = true; // 1er janvier
if($jour == 1 && $mois == 5) $ferie = true; // 1er mai
if($jour == 8 && $mois == 5) $ferie = true; // 8 mai
if($jour == 14 && $mois == 7) $ferie = true; // 14 juillet
if($jour == 15 && $mois == 8) $ferie = true; // 15 aout
if($jour == 1 && $mois == 11) $ferie = true; // 1 novembre
if($jour == 11 && $mois == 11) $ferie = true; // 11 novembre
if($jour == 25 && $mois == 12) $ferie = true; // 25 décembre
// fêtes religieuses mobiles
$pak = @easter_date($annee);
$jp = date("d", $pak);
$mp = date("m", $pak);
if($jp == $jour && $mp == $mois){ $ferie = true;} // Pâques
$lpk = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) +1, date("Y", $pak) );
$jp = date("d", $lpk);
$mp = date("m", $lpk);
if($jp == $jour && $mp == $mois){ $ferie = true; }// Lundi de Pâques
$asc = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 39, date("Y", $pak) );
$jp = date("d", $asc);
$mp = date("m", $asc);
if($jp == $jour && $mp == $mois){ $ferie = true;}//ascension
$pe = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 49, date("Y", $pak) );
$jp = date("d", $pe);
$mp = date("m", $pe);
if($jp == $jour && $mp == $mois) {$ferie = true;}// Pentecôte
$lp = mktime(date("H", $asc), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 50, date("Y", $pak) );
$jp = date("d", $lp);
$mp = date("m", $lp);
if($jp == $jour && $mp == $mois) {$ferie = true;}// lundi Pentecôte
// Samedis et Dimanches
if ($weekend) {
$jour_sem = date('N',mktime(0,0,0, $mois, $jour, $annee));
if($jour_sem>5) $ferie = true;
}
return $ferie;
}
}
?>

135
framework/common/ftp.php Normal file
View File

@ -0,0 +1,135 @@
<?php
function ftp_mget($ftp_url, $ftp_user, $ftp_pass, $ftp_dir, $local_dir, $debug=null) {
$conn_id = @ftp_connect($ftp_url);
if (!$conn_id) {
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de se connecter au serveur FTP ($ftp_url) !".EOL;
return false;
}
$login_result = @ftp_login($conn_id, $ftp_user, $ftp_pass);
if (!$login_result) {
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de s'authentifier sur le serveur FTP (user=$ftp_user)!".EOL;
return false;
}
// Récupération du contenu d'un dossier
$contents = ftp_nlist($conn_id, $ftp_dir);
// print_r($contents);
// print_r(ftp_rawlist($conn_id, $ftp_dir));
$nbFic=0; // Nombre de fichiers récupérés
if (is_array($contents))
foreach($contents as $k => $server_file) {
$tailleDist = ftp_size($conn_id, $server_file);
$dateDist = ftp_mdtm($conn_id, $server_file);
$tailleLoc=0;
if ($dateDist != -1) {
$tabFichiers[$server_file]['dateDispo']=date('Y-m-d H:i:s', $dateDist);
// echo date ('Y/m/d - H:i:s') ." - Le fichier distant $server_file a été modifié le ".date("d/m/Y à H:i:s.",$dateDist)."\n";
} else {
$tabFichiers[$server_file]['dateDispo']=NULL;
// echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de récupérer l'heure de modification du fichier distant $server_file !\n";
}
$tabFichiers[$server_file]['taille']=$tailleDist;
if ($tailleDist != -1) {
//echo date ('Y/m/d - H:i:s') ." - Taille du fichier distant $server_file est de $tailleDist octets\n";
}
if (file_exists($local_dir . $server_file)) {
$dateLoc=filemtime($local_dir . $server_file);
$tabFichiers[$server_file]['dateDownload']=date('Y-m-d H:i:s', $dateLoc);
$tailleLoc=filesize($local_dir . $server_file);
//echo date ('Y/m/d - H:i:s') ." - Taille du fichier local $server_file = $tailleLoc octets\n";
}
if ($tailleDist<>$tailleLoc) {
if (ftp_get($conn_id, $local_dir. $server_file, $server_file, FTP_BINARY))
//echo date ('Y/m/d - H:i:s')." - Fichier distant $server_file téléchargé avec succès".EOL;
$nbFic++;
else {
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Fichier distant $server_file non téléchargé !".EOL;
// return false;
}
}
}
// Fermeture de la connexion
ftp_close($conn_id);
return $nbFic;
}
/**
* ftpRecursiveFileListing
*
* Get a recursive listing of all files in all subfolders given an ftp handle and path
*
* @param resource $ftpConnection the ftp connection handle
* @param string $path the folder/directory path
* @return array $allFiles the list of files in the format: directory => $filename
*/
/*function ftp_rlist($conn_id, $path) {
static $allFiles = array();
$contents = ftp_nlist($conn_id, $path);
foreach($contents as $currentFile) {
// assuming its a folder if there's no dot in the name
echo $currentFile.EOL;
//if (strpos($currentFile, '.') === false) {
if(ftp_is_dir($conn_id, $currentFile)) {
ftp_rlist($conn_id, $path.'/'.$currentFile);
}
$allFiles[$path][] = substr($currentFile, strlen($path) + 1);
}
return $allFiles;
}
*/
//identify directories
function ftp_is_dir($conn_id, $dir) {
if (@ftp_chdir($conn_id, $dir)) {
ftp_chdir($conn_id, '../');
return true;
} else {
return false;
}
}
/*
function list_all_files($conn_id, $path){
$buff = ftp_rawlist($conn_id, $path);
$res = parse_rawlist( $buff) ;
static $flist = array();
if(count($res)>0){
foreach($res as $result){
// verify if is dir , if not add to the list of files
if($result['size']== 0){
// recursively call the function if this file is a folder
list_all_files($conn_id, $path.'/'.$result['name']);
}
else{
// this is a file, add to final list
$flist[] = $result;
}
}
}
return $flist;
}*/
function ftp_rlist($conn_id, $path, $suffixes=array('gif','png','jpeg','pdf','php','txt','csv'), $files=array()) {
ftp_pasv($conn_id, true);
// = explode(",", $suffix);
$list = ftp_rawlist($conn_id, $path);
$anzlist = count($list);
$i = 0;
while ($i < $anzlist):
$split = preg_split("/[\s]+/", $list[$i], 9, PREG_SPLIT_NO_EMPTY);
$ItemName = $split[8];
$endung = strtolower(substr(strrchr($ItemName,"."),1));
$path = "$path/$ItemName";
if (substr($list[$i],0,1) === "d" AND substr($ItemName,0,1) != "."):
// array_push($files, $path); # write directory in array if desired
ftp_rlist($conn_id,$path, $suffixes, $files);
elseif (substr($ItemName,0,2) != "._" AND in_array($endung,$suffixes)):
array_push($files, $path);
endif;
$i++;
endwhile;
return $files;
}
?>

View File

@ -0,0 +1,3 @@
<?php
include_once(FWK_PATH.'mail/htmlMimeMail5.php');
?>

241
framework/common/mysql.php Normal file
View File

@ -0,0 +1,241 @@
<?php
class WDB {
private $host;
private $database;
private $user;
private $password;
private $con_id; // Connection ID with MySQL
private $result;
public function __construct($database='', $host='', $user='', $password='') {
if ($host=='') $this->host=MYSQL_HOST;
else $this->host=$host;
if ($user=='') $this->user=MYSQL_USER;
else $this->user=$user;
if ($password=='') $this->password=MYSQL_PASS;
else $this->password=$password;
if ($database=='') $this->database=MYSQL_DEFAULT_DB;
else $this->database=$database;
$this->con_id = mysql_pconnect($this->host, $this->user, $this->password);
if (!($this->con_id === false)) {
if (mysql_select_db($this->database, $this->con_id) === false) {
echo date('Y/m/d - H:i:s') ." - ERREUR ".mysql_errno()." : Connection à la base de données impossible !".EOL;
echo date ('Y/m/d - H:i:s'). mysql_error();
die();
}
}
return mysql_query("SET NAMES 'latin1';", $this->con_id);
}
public function setCharSet($charSet) {
return (mysql_query("SET CHARACTER SET $charSet;", $this->con_id));
}
private function setDB() {
return (mysql_query("USE $this->database;", $this->con_id));
}
/** INSERTION d'un tableau dans une table.
** Les index doivent avoir les mêmes noms que les champs.
** @param string Table
** @param array Valeurs insérer
** @return int Dernière valeur de l'auto-incrément, 1 si pas d'auto-incrément et 0 si erreur
**/
public function insert($table, $toAdd, $debug=false, $low_priority=false){
$this->setDB();
$fields = implode(array_keys($toAdd), '`,`');
foreach (array_values($toAdd) as $key=>$array_values)
$tmp[$key]=checkaddslashes($array_values);
$values = "'".implode(array_values($tmp), "','")."'"; # better
$values = str_replace("'NULL'", 'NULL', $values);
if ($low_priority)
$query = 'INSERT DELAYED INTO `'.$table.'` (`'.$fields.'`) VALUES ('.$values.');';
else
$query = 'INSERT INTO `'.$table.'` (`'.$fields.'`) VALUES ('.$values.');';
if ($debug) $tdeb=microtime_float();
$res = mysql_query($query, $this->con_id);
if ($res!==false)
{
if (mysql_insert_id($this->con_id)>0)
$res=mysql_insert_id($this->con_id);
else
$res=true;
}
if ($debug) $this->trace($query, $res, $tdeb);
return $res;
}
public function update($table, $update, $where, $debug=false, $limit=0, $low_priority=false){
$this->setDB();
$fields = array_keys($update);
$values = array_values($update);
$i=0;
if ($low_priority)
$query='UPDATE LOW_PRIORITY `'.$table.'` SET ';
else
$query='UPDATE `'.$table.'` SET ';
while(isset($fields[$i])){
if($i>0) { $query.=', '; }
$query.=' `'.$fields[$i]."`='".checkaddslashes($values[$i])."'";
$i++;
}
$query = str_replace("'NULL'", 'NULL', $query);
$query.=' WHERE '.$where;
if ($limit>0) $query.=" LIMIT $limit";
if ($debug) $tdeb=microtime_float();
$res=mysql_query($query, $this->con_id);
if ($debug) $this->trace($query, $res, $tdeb);
return $res;
}
public function delete($table, $where, $debug=false, $low_priority=false) {
$this->setDB();
if ($low_priority)
$query='DELETE LOW_PRIORITY QUICK FROM `'.$table.'` WHERE '.$where.' LIMIT 1;';
else
$query='DELETE FROM `'.$table.'` WHERE '.$where.' LIMIT 1;';
if ($debug) $tdeb=microtime_float();
$res=mysql_query($query, $this->con_id);
if ($debug) $this->trace($query, $res, $tdeb);
return $res;
}
public function deleteAll($table, $where, $debug=false, $low_priority=false) {
$this->setDB();
if ($low_priority)
$query='DELETE LOW_PRIORITY QUICK FROM `'.$table.'` WHERE '.$where.';';
else
$query='DELETE FROM `'.$table.'` WHERE '.$where.';';
if ($debug) $tdeb=microtime_float();
$res=mysql_query($query, $this->con_id);
if ($debug) $this->trace($query, $res, $tdeb);
return $res;
}
public function select($table, $fields, $where, $debug=false, $assoc=MYSQL_BOTH, $huge=false) {
$this->setDB();
if (mysql_select_db($this->database, $this->con_id) === false) {
echo date('Y/m/d - H:i:s') ." - ERREUR ".mysql_errno()." : Connection à la base de données impossible !".EOL;
echo date ('Y/m/d - H:i:s'). mysql_error();
die();
}
$query="SELECT $fields FROM $table WHERE $where;";
if ($debug) $tdeb=microtime_float();
$this->result=mysql_query($query, $this->con_id);// or die(mysql_error());
if (mysql_errno()) {
$fpErr=fopen('/var/www/log/sqlerror.log','a');
fwrite($fpErr, date('YmdHis'). ' - '.$query .EOL);
fwrite($fpErr, date('YmdHis'). ' - '.mysql_errno() .' - '. mysql_error().EOL);
return false;
}
// echo ;
if (!$huge) {
$tab=array();
while ($ligne = mysql_fetch_array($this->result, $assoc))
$tab[]=$ligne;
if ($debug) $this->trace($query, sizeof($tab), $tdeb);
return $tab;
} else {
$nbRows=mysql_num_rows($this->result);
if ($debug) $this->trace($query, $nbRows, $tdeb);
return $nbRows;
}
}
public function fetch($assoc=MYSQL_BOTH) {
return mysql_fetch_array($this->result, $assoc);
}
public function trace($query, $res='', $tdeb=-1) {
if (!$fp=fopen('mysql_insert.log', 'a'))
return false;
$errnum=mysql_errno($this->con_id);
if ($tdeb>-1) $duree=substr(''.microtime_float()-$tdeb, 0, 5);
else $duree='N/D';
if (!fwrite($fp, date('Y/m/d - H:i:s') ." - $errnum - $res - $duree - $query\n"))
return false;
if (!fclose($fp))
return false;
return true;
}
/** Exécute la requête passé en paramètre **/
public function query($query, $debug=false){
$this->setDB();
$this->result=mysql_query($query, $this->con_id);
return $this->result;
}
/** Retourne le nombre de records de la dernière requête de sélection **/
public function getNumRows() {
//return mysql_num_rows($this->con_id);
return mysql_num_rows($this->result);
}
/** Retourne le libellé de la dernière erreur **/
public function getLastErrorMsg() {
return mysql_error($this->con_id);
}
/** Retourne le numéro de la dernière erreur **/
public function getLastErrorNum() {
return mysql_errno($this->con_id);
}
/** Retourne le libellé et le numéro de la dernière erreur **/
public function getLastError() {
return mysql_error($this->con_id).' ('.mysql_errno($this->con_id).')';
}
/** Retourne le nombre de lignes modifiées par la dernière requête **/
public function getAffectedRows() {
return mysql_affected_rows($this->con_id);
}
/** Génère le fichier CSV pour la requete SQL
**
** @param string $query
** @param string $fileCsv
** @return bool
*/
public function exportCSV($query, $fileCsv, $sep=',', $eol=EOL) {
$i=$c=0;
$fp = fopen($fileCsv, 'w');
if (!$fp) return false;
$res=$this->query($query);
$nbLignes=mysql_num_rows($res);
while ($ligne=$this->fetch(MYSQL_ASSOC)) {
if ($i==0) {
$nbCols=count($ligne);
foreach ($ligne as $libCol=>$col) {
$c++;
if ($c<$nbCols) fwrite($fp, str_replace($sep,' ', $libCol).$sep);
else fwrite($fp, str_replace($sep,' ', $libCol));
}
fwrite($fp, $eol);
}
$c=0;
foreach ($ligne as $libCol=>$col) {
$c++;
if ($c<$nbCols) fwrite($fp, str_replace($sep,' ', $col).$sep);
else fwrite($fp, str_replace($sep,' ', $col));
}
fwrite($fp, $eol);
$i++;
}
fclose($fp);
return $nbLignes;//$this->getAffectedRows();
}
}
?>

215
framework/common/rss.php Normal file
View File

@ -0,0 +1,215 @@
<?php
/*
Atom and RSS Extractor and Displayer
(c) 2007 Scriptol.com - Licence Mozilla 1.1.
commonlib.php
*/
class atomRss {
public $codeErreurHttp=0;
private $Common_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$y["title"] = $item->getElementsByTagName("title")->item(0)->firstChild->data;
$y["link"] = $item->getElementsByTagName("link")->item(0)->firstChild->data;
$y["description"] = $item->getElementsByTagName("description")->item(0)->firstChild->data;
$tnl = $item->getElementsByTagName("pubDate");
if($tnl->length == 0)
{
$tnl = $item->getElementsByTagName("lastBuildDate");
}
if($tnl->length != 0)
{
$tnl =$tnl->item(0)->firstChild->data;
}
else
$tnl = false;
$y["updated"] = $tnl;
$y["type"] = $type;
array_push($this->Common_Content, $y);
}
function RSS_Channel($channel)
{
$items = $channel->getElementsByTagName("item");
// Processing channel
$this->RSS_Tags($channel, 0); // get description of channel, type 0
// Processing articles
foreach($items as $item)
{
$this->RSS_Tags($item, 1); // get description of article, type 1
}
}
function RSS_Retrieve($url)
{
$doc = new DOMDocument();
$ret = $doc->load($url);
if ($ret===false) {
$page=getUrl($url,'','','',false,'','',3);
$this->codeErreurHttp=$page['code'];
if ($this->codeErreurHttp==302) {
$url=$page['header']['Location'];
$ret = $doc->load($url);
}
}
$channels = $doc->getElementsByTagName("channel");
$this->Common_Content = array();
foreach($channels as $channel)
{
$this->RSS_Channel($channel);
}
return ( count($this->Common_Content) > 0);
}
function Atom_Tags($item)
{
$y = array();
$y["title"] = $item->getElementsByTagName("title")->item(0)->firstChild->data;
$y["link"] = $item->getElementsByTagName("link")->item(0)->getAttribute("href");
$y["description"] = $item->getElementsByTagName("summary")->item(0)->firstChild->data;
$y["updated"] = $item->getElementsByTagName("updated")->item(0)->firstChild->data;
$y["type"] = 1;
array_push($this->Common_Content, $y);
}
function Atom_Feed($doc)
{
$entries = $doc->getElementsByTagName("entry");
if($entries->length == 0) return false;
// Processing feed
$y = array();
$y["title"] = $doc->getElementsByTagName("title")->item(0)->firstChild->data;
$y["link"] = $doc->getElementsByTagName("link")->item(0)->getAttribute("href");
$y["description"] = $doc->getElementsByTagName("subtitle")->item(0)->firstChild->data;
$y["updated"] = $doc->getElementsByTagName("updated")->item(0)->firstChild->data;
$y["type"] = 0;
array_push($this->Common_Content, $y);
// Processing articles
foreach($entries as $entry)
{
$this->Atom_Tags($entry); // get description of article, type 1
}
return true;
}
function Atom_Retrieve($url)
{
$doc = new DOMDocument();
$doc->load($url);
$this->Common_Content = array();
return $this->Atom_Feed($doc);
}
function loadRss($url, $size=200, $chanopt=true, $descopt=true, $dateopt=true)
{
$opened = false;
$page = "";
if($this->Atom_Retrieve($url) === false)
{
if($this->RSS_Retrieve($url) === false)
{
return false;
}
}
if($size > 0)
{
$size += 1; // add one for the channel
$recents = array_slice($this->Common_Content, 0, $size);
}
//$tabFlux=array();
return $recents;
/*
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($chanopt != true) continue;
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
//$page .="<b>";
}
else
{
if($opened == false && $chanopt == true)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$page .= "<".$Common_Style."><a href=\"$link\">$title</a>";
if($descopt != false)
{
$description = $article["description"];
if($description != false)
{
$page .= "<br>$description";
}
}
if($dateopt != false)
{
$updated = $article["updated"];
if($updated != false)
{
$page .= "<br /><font $Common_Date_Font>$updated</font>";
}
}
$page .= "</".$Common_Style.">\n";
/*
if($type == 0)
{
$page .="<br />";
}
*
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
*/
}
}
?>

View File

@ -0,0 +1,455 @@
<?
define ('BEFORE', 0);
define ('AFTER', 1);
define ('BOTH', 2);
define ('ALIGN_LEFT', 0);
define ('ALIGN_RIGHT', 1);
/**Initialisation d'une chaîne de caractère
*
* @param string $chaine Chaîne de caractère initiale
* @param int $taille Taille de la chaîne de caractère à initialiser
* @param string $caractere_pour_combler Caractère à utiliser pour combler la chaîne de caractère (espace par défaut)
* @param string $align Aligner la chaîne de caractère à droite (right) ou à gauche (left, par défaut)
* @return string
*/
function initstr($chaine, $taille, $caractere_pour_combler=' ', $align=ALIGN_LEFT) {
if ($align==ALIGN_RIGHT) {
$str2='';
for ($i=0;$i<($taille-strlen($chaine));$i++)
$str2.=$caractere_pour_combler;
$str=$str2.$chaine;
} else {
if (strlen($chaine)>=$taille)
return substr($chaine,0,$taille);
$str=$chaine;
for ($i=strlen($chaine);$i<$taille;$i++)
$str = $str . $caractere_pour_combler;
}
return $str;
}
/**
* Ajout d'anti-slashs s'il y a lieu en vu d'une insertion en BDD
*
* @param string $str Chaine de caractère
* @return unknown
*/
function checkaddslashes($str){
return addslashes(preg_replace('/\\[^nrt\']/i', '\\', $str));
}
function checkaddslashes2($str){
if(strpos(str_replace("\'",''," $str"),"'")!=false)
return addslashes($str);
else
return $str;
}
function trimAccent ($strWithAccent) {
$strWithAccent = htmlentities(strtolower($strWithAccent ));
$strWithAccent = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $strWithAccent );
$strWithAccent = preg_replace("/([^a-z0-9]+)/", " ", html_entity_decode($strWithAccent ));
$strWithAccent = trim($strWithAccent , "-");
return $strWithAccent;
}
//function SRSaufVoyelle ($strIn, $mot1, $mot2) {
function str_replace_except_voy($mot1, $mot2, $strIn, $rule=0) {
$Voyelle=array('a','e','i','o','u','y', '1', '2', '3', '4');
if ($mot1==$mot2) return $strIn;
if (strpos($mot2,$mot1)===false)
{
//foreach ($Voyelle as $k => $voy)
$posMot1=strpos($strIn, $mot1);
while ($posMot1!==false) {
$lettreAV=$strIn[$posMot1-1];
$lettreAP=$strIn[$posMot1+strlen($mot1)];
//echo "Lettre AV=$lettreAV<br/>";
//echo "Lettre AP=$lettreAP<br/>";
if ( ( $rule==0 && !in_array($lettreAV, $Voyelle) ) ||
( $rule==1 && !in_array($lettreAP, $Voyelle) ) ||
( $rule==2 && !in_array($lettreAV, $Voyelle) && !in_array($lettreAP, $Voyelle) ))
$strIn=substr($strIn,0,$posMot1) . $mot2 . substr($strIn,$posMot1+strlen($mot1),strlen($strIn));
//echo "Le Mot devient : $strIn<br/>";
$posMot1=strpos($strIn, $mot1, $posMot1+strlen($mot1));
}
return $strIn;
}
//echo "Erreur : $mot2 contient $mot1 !<br>";
return $strIn;
}
/** Retourne le phonex d'un mot
**/
function phonex($strIn) {
if ($strIn=='') return 0.0;
$tabSonAIA=array('aina', 'eina', 'aima', 'eima');
$tabSonAIE=array('ainr', 'eine', 'aime', 'eime');
$tabSonAII=array('aini', 'eini', 'aimi', 'eimi');
$tabSonAIO=array('aino', 'eino', 'aimo', 'eimo');
$tabSonAIU=array('ainu', 'einu', 'aimu', 'eimu');
$tabCarPhon=array('1', '2', '3', '4', '5', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'n', 'o', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z');
/** On traite tout en minuscule **/
$strIn=strtolower($strIn);
/** On remplace les 'Y' par des 'I' **/
$strIn=str_replace('y', 'i', $strIn);
/** On supprime les accents **/
$strIn=trimAccent($strIn);
/** On retire les 'H' muets sauf ceux précédés par 'C' ou 'S' **/
$strIn = preg_replace ('/(?<![CS])H/', '', $strIn);
/** On remplace les 'PH' par des 'F' **/
$strIn=str_replace('ph', 'f', $strIn);
/** On remplace les 'G' par des 'K' devant AN AM AIN AIM **/
$strIn=str_replace('gan', 'kan', $strIn);
$strIn=str_replace('gain', 'kain', $strIn);
$strIn=str_replace('gam', 'kam4', $strIn);
$strIn=str_replace('gaim', 'kaim', $strIn);
/** On remplace le son AI **/
for ($i=0; $i>4; $i++) {
$strIn=str_replace($tabSonAIA[$i], 'yna', $strIn);
$strIn=str_replace($tabSonAIE[$i], 'yne', $strIn);
$strIn=str_replace($tabSonAII[$i], 'yni', $strIn);
$strIn=str_replace($tabSonAIO[$i], 'yno', $strIn);
$strIn=str_replace($tabSonAIU[$i], 'ynu', $strIn);
}
/** Remplacement des groupes de 3 lettres **/
$strIn=str_replace('eau', 'o', $strIn);
$strIn=str_replace('oua', '2', $strIn);
$strIn=str_replace('ein', '4', $strIn);
$strIn=str_replace('ain', '4', $strIn);
/** Remplacement du son 'é' **/
$strIn=str_replace('ai', 'y', $strIn);
$strIn=str_replace('ei', 'y', $strIn);
$strIn=str_replace('er', 'yr', $strIn);
$strIn=str_replace('ess', 'yss', $strIn);
$strIn=str_replace('et', 'yt', $strIn);
$strIn=str_replace('ez', 'yz', $strIn);
/** Remplacement des groupes de 2 lettres sauf si voyelle ou son (1 à 4) AVANT **/
$strIn=str_replace_except_voy('an', '1', $strIn, BEFORE);
$strIn=str_replace_except_voy('am', '1', $strIn, BEFORE);
$strIn=str_replace_except_voy('en', '1', $strIn, BEFORE);
$strIn=str_replace_except_voy('em', '1', $strIn, BEFORE);
$strIn=str_replace_except_voy('in', '4', $strIn, BEFORE);
/** Remplacement du son 'SCH' **/
$strIn=str_replace('sch', '5', $strIn);
/** Remplacement du 'S' sauf si voyelle ou son (1 à 4) avant ou après **/
$strIn=str_replace_except_voy('in', '4', $strIn, BOTH);
/** Remplacement de groupe de 2 lettres diverses **/
$strIn=str_replace('oe', 'e', $strIn);
$strIn=str_replace('eu', 'e', $strIn);
$strIn=str_replace('au', 'o', $strIn);
$strIn=str_replace('oi', '2', $strIn);
$strIn=str_replace('oy', '2', $strIn);
$strIn=str_replace('ou', '3', $strIn);
$strIn=str_replace('ch', '5', $strIn);
$strIn=str_replace('sh', '5', $strIn);
$strIn=str_replace('ss', 's', $strIn);
$strIn=str_replace('sc', 's', $strIn);
/** Remplacement du 'C' par 'S' s'il est suivi d'un 'E' ou d'un 'I' **/
$strIn=str_replace('ce', 'se', $strIn);
$strIn=str_replace('ci', 'si', $strIn);
/** Remplacement divers **/
$strIn=str_replace('c', 'k', $strIn);
$strIn=str_replace('q', 'k', $strIn);
$strIn=str_replace('qu', 'k', $strIn);
$strIn=str_replace('ga', 'ka', $strIn);
$strIn=str_replace('go', 'ko', $strIn);
$strIn=str_replace('gu', 'ku', $strIn);
$strIn=str_replace('gy', 'ky', $strIn);
$strIn=str_replace('g2', 'k2', $strIn);
$strIn=str_replace('g1', 'k1', $strIn);
$strIn=str_replace('g3', 'k3', $strIn);
$strIn=str_replace('a', 'o', $strIn);
$strIn=str_replace('d', 't', $strIn);
$strIn=str_replace('p', 't', $strIn);
$strIn=str_replace('j', 'g', $strIn);
$strIn=str_replace('b', 'f', $strIn);
$strIn=str_replace('v', 'f', $strIn);
$strIn=str_replace('m', 'n', $strIn);
/** Supression des lettres dupliquées **/
$let=$strIn[0];
$strIn2=$let;
for ($i=1; $i<strlen($strIn); $i++)
{ if ($strIn==$let)
continue;
else {
$let=$strIn[$i];
$strIn2.=$strIn[$i];
}
}
$strIn=$strIn2;
/** Supression des terminaisons **/
$strIn2=substr($strIn,-1);
if ($strIn2=='t' || $strIn2=='k' || $strIn2=='s' || $strIn2=='z')
$strIn=substr($strIn,0,-1);
/** Supression des caractères non autorisés **/
$j=10;
$sout=array();
for ($i=0; $i<strlen($strIn); $i++)
{
if ($j<1) break;
for ($k=0; $k<22; $k++)
{
if ($strIn[$i]==$tabCarPhon[$k])
{
$sout[$j]=$k;
$j--;
}
}
}
print_r($tabCarPhon);
/** Couversion en flottant **/
$result=0.0;
for ($j=10; $j>0; $j--)
$result+=$sout[$j]*pow($j-1,10);
return $result;
}
/**
* CLASS soundex2
* soundex2 French version
* based on the algorithm described here : http://sqlpro.developpez.com/cours/soundex/ by Frédéric BROUARD
*
* author Johan Barbier <barbier_johan@hotmail.com>
*/
class csoundex2 {
/**
* public sString
* main string we work on
*/
var $sString = '';
/**
* vowels replacement array
*/
var $aReplaceVoy1 = array (
'E' => 'A',
'I' => 'A',
'O' => 'A',
'U' => 'A'
);
/**
* consonnants replacement array
*/
var $aReplaceGrp1 = array (
'GUI' => 'KI',
'GUE' => 'KE',
'GA' => 'KA',
'GO' => 'KO',
'GU' => 'K',
'CA' => 'KA',
'CO' => 'KO',
'CU' => 'KU',
'Q' => 'K',
'CC' => 'K',
'CK' => 'K'
);
/**
* other replacement array
*/
var $aReplaceGrp2 = array (
'ASA' => 'AZA',
'KN' => 'NN',
'PF' => 'FF',
'PH' => 'FF',
'SCH' => 'SSS'
);
/**
* endings replacement array
*/
var $aEnd = array (
'A',
'T',
'D',
'S'
);
/**
* public function build
* core function of the class, go through the whole process
* @Param string sString : the string we want to check
*/
function build ($sString) {
/**
* let's check it's a real string...
*/
if (is_string ($sString) && !empty ($sString)) {
$this -> sString = $sString;
} else {
trigger_error ('Parameter string must not be empty', E_USER_ERROR);
}
/**
* remove starting and ending spaces
*/
$this -> sString = trim ($this -> sString);
/**
* remove special french characters
*/
$this -> trimAccent ();
/**
* string to upper case
*/
$this -> sString = strtoupper ($this -> sString );
/**
* let's remove every space in the string
*/
$this -> sString = str_replace (' ', '', $this -> sString);
/**
* let's remove every '-' in the string
*/
$this -> sString = str_replace ('-', '', $this -> sString);
/**
* let's process through the first replacement array
*/
$this -> arrReplace ($this -> aReplaceGrp1);
/**
* let's process through th vowels replacement
*/
$sChar = substr ($this -> sString, 0, 1);
$this -> sString = substr ($this -> sString, 1, strlen ($this -> sString) - 1);
$this -> arrReplace ($this -> aReplaceVoy1);
$this -> sString = $sChar.$this -> sString;
/**
* let's process through the second replacement array
*/
$this -> arrReplace ($this -> aReplaceGrp2, true);
/**
* let's remove every 'H' but those prededed by a 'C' or an 'S'
*/
$this -> sString = preg_replace ('/(?<![CS])H/', '', $this -> sString);
/**
* let's remove every 'Y' but those preceded by an 'A'
*/
$this -> sString = preg_replace ('/(?<!A)Y/', '', $this -> sString);
/**
* remove endings in aEnd
*/
$length = strlen ($this -> sString) - 1;
if (in_array ($this -> sString{$length}, $this -> aEnd)) {
$this -> sString = substr ($this -> sString, 0, $length);
}
/**
* let's remove every 'A', but the one at the beginning of the string, if any.
*/
$sChar = '';
if ($this -> sString{0} === 'A') {
$sChar = 'A';
}
$this -> sString = str_replace ('A', '', $this -> sString);
$this -> sString = $sChar.$this -> sString;
/**
* let's have only 1 occurence of each letter
*/
$this -> sString = preg_replace( '/(.)\1/', '$1', $this -> sString );
/**
* let's have the final code : a 4 letters string
*/
$this -> getFinal ();
}
/**
* private function getFinal
* gets the first 4 letters, pads the string with white space if the string length < 4
*/
function getFinal () {
if (strlen ($this -> sString) < 4) {
$this -> sString = str_pad ($this -> sString, 4, ' ', STR_PAD_RIGHT);
} else {
$this -> sString = substr ($this -> sString, 0, 4);
}
}
/**
* private function trimAccent
* remove every special French letters
*/
function trimAccent () {
$this -> sString = htmlentities(strtolower($this -> sString ));
$this -> sString = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $this -> sString );
$this -> sString = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($this -> sString ));
$this -> sString = trim($this -> sString , "-");
}
/**
* private function arrReplace
* replacement method, given an array
* @Param array tab : the replacement array to be used
* @Param bool pref : if false, just replace keys by values; if true, do the same but only with prefix
*/
function arrReplace (array $tab, $pref = false) {
$fromRep = array_keys ($tab);
$toRep = array_values ($tab);
if (false === $pref) {
$this -> sString = str_replace ($fromRep, $toRep, $this -> sString);
} else {
foreach ($fromRep as $clef => $val) {
$length = strlen ($val);
if (substr ($this -> sString, 0, $length) === $val) {
$this -> sString = substr_replace ($this -> sString, $toRep[$clef], 0, $length);
}
}
}
}
}
function soundex2($str) {
$soundex2 = new csoundex2();
$soundex2 -> build ($str);
return $soundex2 -> sString;
}
function htm2txt($str) {
return trim(strip_tags( str_replace(chr(160), ' ',
str_replace('&#156;', 'oe',
str_replace('&#146;', '\'', html_entity_decode($str, ENT_QUOTES))))));
}
function html2array($body, $tabZones) {
foreach ($tabZones as $zone=>$regex) {
$posDeb=strpos($zone, '[');
if ($posDeb && strpos($zone, ']')) {
$tabSZones=explode(',',substr($zone,$posDeb+1,strlen($zone)-$posDeb-2));
$zone=preg_replace('/\[.*\]/','',$zone);
if (preg_match_all('/'.str_replace("/","\/",$regex)."/Uis", $body, $matches)) {
foreach ($matches as $j=>$tmp) {
if ($j==0) continue;
foreach ($tmp as $k=>$tmp2) {
$tabInsert[$zone][$tabSZones[$j-1]][$k]=utf8_decode(html_entity_decode(trim(str_replace('&nbsp;',' ',strip_tags($tmp2)))));
}
}
}
// On retri le tableau
if (isset($tabInsert[$zone]) && is_array($tabInsert[$zone]))
foreach ($tabInsert[$zone] as $zone2=>$tData2) {
foreach ($tData2 as $i=>$tData) {
//$tabInsert2[$i]['id']=$tabInsert['id'];
//$tabInsert2[$i]['num']=$i;
$tabInsert2[$i][$zone2]=$tData;
}
}
if (isset($tabInsert2) && is_array($tabInsert2))
$tabInsert[$zone]=@$tabInsert2;
} elseif (preg_match('/'.str_replace("/","\/",$regex)."/Uis", $body, $matches))
$tabInsert[$zone]=utf8_decode(html_entity_decode(trim(str_replace('&nbsp;',' ',strip_tags($matches[1])))));
}
return $tabInsert;
}
?>

View File

@ -0,0 +1,111 @@
<?php
/*
XML Parser Class
by Eric Rosebrock
http://www.phpfreaks.com
Class originated from: kris@h3x.com AT: http://www.devdump.com/phpxml.php
Usage:
<?php
include 'clsParseXML.php';
$xmlparse = &new ParseXML;
$xml = $xmlparse->GetXMLTree('/path/to/xmlfile.xml');
echo "<pre>";
print_r($xml);
echo "</pre>";
?>
The path to the XML file may be a local file or a URL.
Returns the elements of the XML file into an array with
it's subelements as keys and subarrays.
*/
class ParseXML{
function GetChildren($vals, &$i) {
$children = array(); // Contains node data
if (isset($vals[$i]['value'])){
$children['VALUE'] = $vals[$i]['value'];
}
while (++$i < count($vals)){
switch ($vals[$i]['type']){
case 'cdata':
if (isset($children['VALUE'])){
$children['VALUE'] .= $vals[$i]['value'];
} else {
$children['VALUE'] = $vals[$i]['value'];
}
break;
case 'complete':
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
if (isset($vals[$i]['value'])){
$children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
} else {
$children[$vals[$i]['tag']][$index]['VALUE'] = '';
}
} else {
if (isset($vals[$i]['value'])){
$children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
} else {
$children[$vals[$i]['tag']][]['VALUE'] = '';
}
}
break;
case 'open':
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
$children[$vals[$i]['tag']][$index] = array_merge($children[$vals[$i]['tag']][$index],$this->GetChildren($vals, $i));
} else {
$children[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
}
break;
case 'close':
return $children;
}
}
}
function GetXMLTree($xmlloc){
if (file_exists($xmlloc)){
$data = implode('', file($xmlloc));
} else {
$fp = fopen($xmlloc,'r');
while(!feof($fp)){
$data = $data . fread($fp, 1024);
}
fclose($fp);
}
$parser = xml_parser_create('ISO-8859-1');
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $vals, $index);
xml_parser_free($parser);
$tree = array();
$i = 0;
if (isset($vals[$i]['attributes'])) {
$tree[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($tree[$vals[$i]['tag']])-1;
$tree[$vals[$i]['tag']][$index] = array_merge($tree[$vals[$i]['tag']][$index], $this->GetChildren($vals, $i));
} else {
$tree[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
}
return $tree;
}
}

281
framework/fwk.php Normal file
View File

@ -0,0 +1,281 @@
<?
define('FWK_PATH', '/var/www/framework/');
include_once(FWK_PATH.'common/mysql.php');
include_once(FWK_PATH.'common/strings.php');
//include_once(FWK_PATH.'common/dates.php');
define ('REP_TEMP', '/tmp/');
// Environnement : DEV ou PRD
define ('ENV', 'DEV');
define ('EOL', "\n");
define ('MODE_CLI', 1);
define ('MODE_WWW', 2);
define ('MODE_WS', 3);
if (@$_SERVER['argc']>0) define('MODE_EXEC', MODE_CLI);
else define('MODE_EXEC', MODE_WS);
/** @todo Gérer la distinction du mode WWW du WS
else define('MODE_EXEC', MODE_WWW);
*/
/** TimeStamp Unix
** Si $onlyMiliSec=true, retourne juste les milisec du timestamp
**/
function microtime_float($onlyMiliSec=false) {
list($usec, $sec) = explode(' ', microtime());
if (!$onlyMiliSec)
return ((float)$usec + (float)$sec);
else
return $usec;
}
/** Fait une pause aléatoire entre 0 et 15 secondes par défaut
**/
function randsleep($min_sec=0, $max_sec=15) {
sleep(rand($min_sec, $max_sec));
}
/** Retourne la factorielle d'un nombre : 4! = 1*2*3*4 = 24
**/
function factorielle($nbr) {
if($nbr === 0) // condition d'arret
return 1;
else
return $nbr*factorielle($nbr-1);
}
/** Vérification que la variable demandé respecte bien les règles passées en paramètres
* @param mixed Variable à tester
* @param int Longueur minimum en caractère de la variable
* @param int Longueur mximum
* @param char(1) Type de variable <b>A</b>:Alphanumérique / <b>N</b>:Numérique
* @param mixed Message textuel d'erreur à afficher en cas d'erreur ou false
* @return mixed true, false ou Message d'erreur passé en paramètre
*/
function valideData($variable, $taille_min, $taille_max, $type_variable, $erreur=false){
if ( strlen((string)$variable) < $taille_min )
return $erreur;
if ( strlen((string)$variable) > $taille_max )
return $erreur;
if ( $type_variable == 'A' )
if ( is_string($variable) == true )
return true;
else
return $erreur;
elseif ( $type_variable == 'N')
{
for ($i=0; $i < strlen((string)$variable); $i++)
{
$car = substr((string)$variable,$i,1);
if ($car<'0' || $car>'9')
return $erreur;
}
return true;
}
return $erreur;
}
function adapteOCtets($size) {
$kb = 1024; // Kilobyte
$mb = 1024 * $kb; // Megabyte
$gb = 1024 * $mb; // Gigabyte
$tb = 1024 * $gb; // Terabyte
if($size==0) return '0';
else if($size < $kb) return $size.'o';
else if($size < $mb) return round($size/$kb,2).'ko';
else if($size < $gb) return round($size/$mb,2).'Mo';
else if($size < $tb) return round($size/$gb,2).'Go';
else return round($size/$tb,2).'To';
}
/**
** Enregistrer une information dans la log
**
** @param string $debugLevel E=Error, W=Warning, N=Notice, I=Info, D=Debug
** @param string $message Message d'erreur à inscrire dans la log
** @param integer $line __LINE__
** @param string $file __FILE__
** @param string $function __FUNCTION__
** @param string $class __CLASS___
**/
function debugLog($debugLevel, $message, $line, $file, $function, $class) {
if (!file_exists('/var/www/log/debug.log')) {
$fp=@fopen('/var/www/log/debug.log', 'a');
@fwrite($fp, 'Date/Heure;Niveau;Script;Login;Password;Adresse IP;Action SOAP;Ligne;Fichier;Fonction;Classe;Domaine;POST DATA;Memory;Message'.EOL);
} else
$fp=@fopen('/var/www/log/debug.log', 'a');
@fwrite($fp, date('Y/m/d-H:i:s') .';'. $debugLevel .';'. $_SERVER['PHP_SELF'] .';'. $_SERVER['PHP_AUTH_USER'] .';'. $_SERVER['PHP_AUTH_PW'] .';'.
$_SERVER['REMOTE_ADDR'] .';'. $_SERVER['HTTP_SOAPACTION'] .';'.$line.';'. $file.';'. $function.';'. $class .';'.
@gethostbyaddr($_SERVER['REMOTE_ADDR']) .';'. $HTTP_RAW_POST_DATA .';'. @memory_get_usage().';'. $message . EOL);
@fclose($fp);
if ($debugLevel=='E'){
if (!file_exists('/var/www/log/debugError.log')) {
$fp=@fopen('/var/www/log/debugError.log', 'a');
@fwrite($fp, 'Date/Heure;Niveau;Script;Login;Password;Adresse IP;Action SOAP;Ligne;Fichier;Fonction;Classe;Domaine;POST DATA;Message'.EOL);
} else
$fp=@fopen('/var/www/log/debugError.log', 'a');
@fwrite($fp, date('Y/m/d-H:i:s') .';'. $debugLevel .';'. $_SERVER['PHP_SELF'] .';'. $_SERVER['PHP_AUTH_USER'] .';'. $_SERVER['PHP_AUTH_PW'] .';'.
$_SERVER['REMOTE_ADDR'] .';'. $_SERVER['HTTP_SOAPACTION'] .';'.$line.';'. $file.';'. $function.';'. $class .';'.
@gethostbyaddr($_SERVER['REMOTE_ADDR']) .';'. $HTTP_RAW_POST_DATA .';'. @memory_get_usage().';'. $message . EOL);
@fclose($fp);
//die($message);
}
}
function prepareString($str) {
$tabReplace=array();
for($c=0;$c<32; $c++)
$tabReplace[''.chr($c)]='';
for($c=127;$c<256; $c++)
$tabReplace[''.chr($c)]='';
return strtr(
strtr(htmlentities(utf8_decode(strtr(strtr($str, 'àáâãäåæçèéêëìíîïðñòóôõöùúûüýÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝŸ…‘‹',
"aaaaaaaceeeeiiiionooooouuuuyyAAAAAAACEEEEIIIIONOOOOOUUUUYY.''"), array('œ'=>'oe'))), ENT_QUOTES, 'ISO-8859-1'),array('€'=>'&euro;',''=>'"')),
$tabReplace);
//return */
//return utf8_encode($str);
}
/**
** Déplacement d'un fichier. Retourne false en cas d'erreur.
**
** @param string $from
** @param string $to
** @return bool
**/
function move($from, $to) {
return (copy($from, $to) and unlink($from));
}
/** Converti une IP en nombre
**
** @param string $ip Adresse IP
** @return integer
**/
function getIpNumber($ip) {
$tab=explode('.', $ip);
return (($tab[0]*256*256*256) + ($tab[1]*256*256) + ($tab[2]*256) + ($tab[3]));
}
/** Vérifie si une IP est dans une plage du type 192.168.3.1-192.168.3.10
**
** @param string $plage_1 Plage IP de début
** @param string $plage_2 Plage IP de fin
** @param string $ip Adresse IP à tester
** @return boolean
**/
function in_plage($plage_1,$plage_2,$ip){
$ip2=getIpNumber($ip);
if ($ip2>=getIpNumber($plage_1) && $ip2<=getIpNumber($plage_2))
return true;
else
return false;
}
/** Controle si une adresse IP est dans une liste des IP communiquées sous la forme 192.168.3.5-192.68.3.10;192.168.3.*;192.168.3.10
**
** @param string $strPlageIP La plage d'adresses IP
** @param string $adresseIP L'adresse IP à tester
** @return boolean
**/
function checkPlagesIp($strPlageIP, $adresseIP) {
$connected=false;
$tabIpAllowed=explode(';', trim($strPlageIP));
if (count($tabIpAllowed)==1 && $tabIpAllowed[0]=='')
$tabIpAllowed=array();
foreach ($tabIpAllowed as $ip) {
$tabPlages=explode('-', $ip);
// C'est une plage d'adresse '-'
if (isset($tabPlages[1]))
$connected=in_plage($tabPlages[0],$tabPlages[1],$adresseIP);
else {
// C'est une adresse avec ou sans masque '*'
if (preg_match('/^'.str_replace('*','.*',str_replace('.','\.',$ip)).'$/', $adresseIP) )
$connected=true;
}
if ($connected) break;
}
if (count($tabIpAllowed)==0) return false;
elseif (!$connected) {
return false;
}
return true;
}
/**
* @return bool
* @param string $in
* @param string $out
* @desc compressing the file with the bzip2-extension
*/
function bzip2 ($in, $out)
{
if (!file_exists ($in) || !is_readable ($in))
return false;
if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
return false;
$in_file = fopen ($in, 'rb');
$out_file = bzopen ($out.'.bz2', 'wb');
while (!feof ($in_file)) {
$buffer = fgets ($in_file, 4096);
bzwrite ($out_file, $buffer, 4096);
}
fclose ($in_file);
bzclose ($out_file);
return true;
}
/**
* @return bool
* @param string $in
* @param string $out
* @desc uncompressing the file with the bzip2-extension
*/
function bunzip2 ($in, $out)
{
if (!file_exists ($in) || !is_readable ($in))
return false;
if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
return false;
$in_file = bzopen ($in, "rb");
$out_file = fopen ($out, "wb");
while ($buffer = bzread ($in_file, 4096)) {
fwrite ($out_file, $buffer, 4096);
}
bzclose ($in_file);
fclose ($out_file);
return true;
}
class DomDocument2 extends DOMDocument {
function getValueFromTag($tagName) {
$items=$this->getElementsByTagName($tagName);
foreach ($items as $item) {
return utf8_decode($item->nodeValue);
}
}
}
?>

878
framework/mail/RFC822.php Normal file
View File

@ -0,0 +1,878 @@
<?php
/**
) o------------------------------------------------------------------------------o
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
* | If you use the code commercially (or if you don't want to be restricted by |
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
* o------------------------------------------------------------------------------o
*
* © Copyright 2005 Richard Heyes
*/
/**
* RFC 822 Email address list validation Utility
*
* What is it?
*
* This class will take an address string, and parse it into it's consituent
* parts, be that either addresses, groups, or combinations. Nested groups
* are not supported. The structure it returns is pretty straight forward,
* and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
* print_r() to view the structure.
*
* How do I use it?
*
* $address_string = 'My Group: "Richard Heyes" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
* $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', TRUE)
* print_r($structure);
*/
class Mail_RFC822
{
/**
* The address being parsed by the RFC822 object.
* @private string $address
*/
private $address = '';
/**
* The default domain to use for unqualified addresses.
* @private string $default_domain
*/
private $default_domain = 'localhost';
/**
* Should we return a nested array showing groups, or flatten everything?
* @private boolean $nestGroups
*/
private $nestGroups = true;
/**
* Whether or not to validate atoms for non-ascii characters.
* @private boolean $validate
*/
private $validate = true;
/**
* The array of raw addresses built up as we parse.
* @private array $addresses
*/
private $addresses = array();
/**
* The final array of parsed address information that we build up.
* @private array $structure
*/
private $structure = array();
/**
* The current error message, if any.
* @private string $error
*/
private $error = null;
/**
* An internal counter/pointer.
* @private integer $index
*/
private $index = null;
/**
* The number of groups that have been found in the address list.
* @private integer $num_groups
* @access public
*/
private $num_groups = 0;
/**
* A variable so that we can tell whether or not we're inside a
* Mail_RFC822 object.
* @private boolean $mailRFC822
*/
private $mailRFC822 = true;
/**
* A limit after which processing stops
* @private int $limit
*/
private $limit = null;
/**
* Sets up the object. The address must either be set here or when
* calling parseAddressList(). One or the other.
*
* @access public
* @param string $address The address(es) to validate.
* @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
*
* @return object Mail_RFC822 A new Mail_RFC822 object.
*/
function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
}
/**
* Starts the whole process. The address must either be set here
* or when creating the object. One or the other.
*
* @access public
* @param string $address The address(es) to validate.
* @param string $default_domain Default domain/host etc.
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
*
* @return array A structured array of addresses.
*/
function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (!isset($this->mailRFC822)) {
$obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
return $obj->parseAddressList();
}
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
$this->structure = array();
$this->addresses = array();
$this->error = null;
$this->index = null;
while ($this->address = $this->_splitAddresses($this->address)) {
continue;
}
if ($this->address === false || isset($this->error)) {
return false;
}
// Reset timer since large amounts of addresses can take a long time to
// get here
set_time_limit(30);
// Loop through all the addresses
for ($i = 0; $i < count($this->addresses); $i++){
if (($return = $this->_validateAddress($this->addresses[$i])) === false
|| isset($this->error)) {
return false;
}
if (!$this->nestGroups) {
$this->structure = array_merge($this->structure, $return);
} else {
$this->structure[] = $return;
}
}
return $this->structure;
}
/**
* Splits an address into seperate addresses.
*
* @access private
* @param string $address The addresses to split.
* @return boolean Success or failure.
*/
function _splitAddresses($address)
{
if (!empty($this->limit) AND count($this->addresses) == $this->limit) {
return '';
}
if ($this->_isGroup($address) && !isset($this->error)) {
$split_char = ';';
$is_group = true;
} elseif (!isset($this->error)) {
$split_char = ',';
$is_group = false;
} elseif (isset($this->error)) {
return false;
}
// Split the string based on the above ten or so lines.
$parts = explode($split_char, $address);
$string = $this->_splitCheck($parts, $split_char);
// If a group...
if ($is_group) {
// If $string does not contain a colon outside of
// brackets/quotes etc then something's fubar.
// First check there's a colon at all:
if (strpos($string, ':') === false) {
$this->error = 'Invalid address: ' . $string;
return false;
}
// Now check it's outside of brackets/quotes:
if (!$this->_splitCheck(explode(':', $string), ':'))
return false;
// We must have a group at this point, so increase the counter:
$this->num_groups++;
}
// $string now contains the first full address/group.
// Add to the addresses array.
$this->addresses[] = array(
'address' => trim($string),
'group' => $is_group
);
// Remove the now stored address from the initial line, the +1
// is to account for the explode character.
$address = trim(substr($address, strlen($string) + 1));
// If the next char is a comma and this was a group, then
// there are more addresses, otherwise, if there are any more
// chars, then there is another address.
if ($is_group && substr($address, 0, 1) == ','){
$address = trim(substr($address, 1));
return $address;
} elseif (strlen($address) > 0) {
return $address;
} else {
return '';
}
// If you got here then something's off
return false;
}
/**
* Checks for a group at the start of the string.
*
* @access private
* @param string $address The address to check.
* @return boolean Whether or not there is a group at the start of the string.
*/
function _isGroup($address)
{
// First comma not in quotes, angles or escaped:
$parts = explode(',', $address);
$string = $this->_splitCheck($parts, ',');
// Now we have the first address, we can reliably check for a
// group by searching for a colon that's not escaped or in
// quotes or angle brackets.
if (count($parts = explode(':', $string)) > 1) {
$string2 = $this->_splitCheck($parts, ':');
return ($string2 !== $string);
} else {
return false;
}
}
/**
* A common function that will check an exploded string.
*
* @access private
* @param array $parts The exloded string.
* @param string $char The char that was exploded on.
* @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
*/
function _splitCheck($parts, $char)
{
$string = $parts[0];
for ($i = 0; $i < count($parts); $i++) {
if ($this->_hasUnclosedQuotes($string)
|| $this->_hasUnclosedBrackets($string, '<>')
|| $this->_hasUnclosedBrackets($string, '[]')
|| $this->_hasUnclosedBrackets($string, '()')
|| substr($string, -1) == '\\') {
if (isset($parts[$i + 1])) {
$string = $string . $char . $parts[$i + 1];
} else {
$this->error = 'Invalid address spec. Unclosed bracket or quotes';
return false;
}
} else {
$this->index = $i;
break;
}
}
return $string;
}
/**
* Checks if a string has an unclosed quotes or not.
*
* @access private
* @param string $string The string to check.
* @return boolean True if there are unclosed quotes inside the string, false otherwise.
*/
function _hasUnclosedQuotes($string)
{
$string = explode('"', $string);
$string_cnt = count($string);
for ($i = 0; $i < (count($string) - 1); $i++)
if (substr($string[$i], -1) == '\\')
$string_cnt--;
return ($string_cnt % 2 === 0);
}
/**
* Checks if a string has an unclosed brackets or not. IMPORTANT:
* This function handles both angle brackets and square brackets;
*
* @access private
* @param string $string The string to check.
* @param string $chars The characters to check for.
* @return boolean True if there are unclosed brackets inside the string, false otherwise.
*/
function _hasUnclosedBrackets($string, $chars)
{
$num_angle_start = substr_count($string, $chars[0]);
$num_angle_end = substr_count($string, $chars[1]);
$this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
$this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
if ($num_angle_start < $num_angle_end) {
$this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
return false;
} else {
return ($num_angle_start > $num_angle_end);
}
}
/**
* Sub function that is used only by hasUnclosedBrackets().
*
* @access private
* @param string $string The string to check.
* @param integer &$num The number of occurences.
* @param string $char The character to count.
* @return integer The number of occurences of $char in $string, adjusted for backslashes.
*/
function _hasUnclosedBracketsSub($string, &$num, $char)
{
$parts = explode($char, $string);
for ($i = 0; $i < count($parts); $i++){
if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
$num--;
if (isset($parts[$i + 1]))
$parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
}
return $num;
}
/**
* Function to begin checking the address.
*
* @access private
* @param string $address The address to validate.
* @return mixed False on failure, or a structured array of address information on success.
*/
function _validateAddress($address)
{
$is_group = false;
if ($address['group']) {
$is_group = true;
// Get the group part of the name
$parts = explode(':', $address['address']);
$groupname = $this->_splitCheck($parts, ':');
$structure = array();
// And validate the group part of the name.
if (!$this->_validatePhrase($groupname)){
$this->error = 'Group name did not validate.';
return false;
} else {
// Don't include groups if we are not nesting
// them. This avoids returning invalid addresses.
if ($this->nestGroups) {
$structure = new stdClass;
$structure->groupname = $groupname;
}
}
$address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
}
// If a group then split on comma and put into an array.
// Otherwise, Just put the whole address in an array.
if ($is_group) {
while (strlen($address['address']) > 0) {
$parts = explode(',', $address['address']);
$addresses[] = $this->_splitCheck($parts, ',');
$address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
}
} else {
$addresses[] = $address['address'];
}
// Check that $addresses is set, if address like this:
// Groupname:;
// Then errors were appearing.
if (!isset($addresses)){
$this->error = 'Empty group.';
return false;
}
for ($i = 0; $i < count($addresses); $i++) {
$addresses[$i] = trim($addresses[$i]);
}
// Validate each mailbox.
// Format could be one of: name <geezer@domain.com>
// geezer@domain.com
// geezer
// ... or any other format valid by RFC 822.
array_walk($addresses, array($this, 'validateMailbox'));
// Nested format
if ($this->nestGroups) {
if ($is_group) {
$structure->addresses = $addresses;
} else {
$structure = $addresses[0];
}
// Flat format
} else {
if ($is_group) {
$structure = array_merge($structure, $addresses);
} else {
$structure = $addresses;
}
}
return $structure;
}
/**
* Function to validate a phrase.
*
* @access private
* @param string $phrase The phrase to check.
* @return boolean Success or failure.
*/
function _validatePhrase($phrase)
{
// Splits on one or more Tab or space.
$parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
$phrase_parts = array();
while (count($parts) > 0){
$phrase_parts[] = $this->_splitCheck($parts, ' ');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($parts);
}
for ($i = 0; $i < count($phrase_parts); $i++) {
// If quoted string:
if (substr($phrase_parts[$i], 0, 1) == '"') {
if (!$this->_validateQuotedString($phrase_parts[$i]))
return false;
continue;
}
// Otherwise it's an atom:
if (!$this->_validateAtom($phrase_parts[$i])) return false;
}
return true;
}
/**
* Function to validate an atom which from rfc822 is:
* atom = 1*<any CHAR except specials, SPACE and CTLs>
*
* If validation ($this->validate) has been turned off, then
* validateAtom() doesn't actually check anything. This is so that you
* can split a list of addresses up before encoding personal names
* (umlauts, etc.), for example.
*
* @access private
* @param string $atom The string to check.
* @return boolean Success or failure.
*/
function _validateAtom($atom)
{
if (!$this->validate) {
// Validation has been turned off; assume the atom is okay.
return true;
}
// Check for any char from ASCII 0 - ASCII 127
if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
return false;
}
// Check for specials:
if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
return false;
}
// Check for control characters (ASCII 0-31):
if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
return false;
}
return true;
}
/**
* Function to validate quoted string, which is:
* quoted-string = <"> *(qtext/quoted-pair) <">
*
* @access private
* @param string $qstring The string to check
* @return boolean Success or failure.
*/
function _validateQuotedString($qstring)
{
// Leading and trailing "
$qstring = substr($qstring, 1, -1);
// Perform check.
return !(preg_match('/(.)[\x0D\\\\"]/', $qstring, $matches) && $matches[1] != '\\');
}
/**
* Function to validate a mailbox, which is:
* mailbox = addr-spec ; simple address
* / phrase route-addr ; name and route-addr
*
* @access public
* @param string &$mailbox The string to check.
* @return boolean Success or failure.
*/
function validateMailbox(&$mailbox)
{
// A couple of defaults.
$phrase = '';
$comment = '';
// Catch any RFC822 comments and store them separately
$_mailbox = $mailbox;
while (strlen(trim($_mailbox)) > 0) {
$parts = explode('(', $_mailbox);
$before_comment = $this->_splitCheck($parts, '(');
if ($before_comment != $_mailbox) {
// First char should be a (
$comment = substr(str_replace($before_comment, '', $_mailbox), 1);
$parts = explode(')', $comment);
$comment = $this->_splitCheck($parts, ')');
$comments[] = $comment;
// +1 is for the trailing )
$_mailbox = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1);
} else {
break;
}
}
for($i=0; $i<count(@$comments); $i++){
$mailbox = str_replace('('.$comments[$i].')', '', $mailbox);
}
$mailbox = trim($mailbox);
// Check for name + route-addr
if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
$parts = explode('<', $mailbox);
$name = $this->_splitCheck($parts, '<');
$phrase = trim($name);
$route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false)
return false;
// Only got addr-spec
} else {
// First snip angle brackets if present.
if (substr($mailbox,0,1) == '<' && substr($mailbox,-1) == '>')
$addr_spec = substr($mailbox,1,-1);
else
$addr_spec = $mailbox;
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false)
return false;
}
// Construct the object that will be returned.
$mbox = new stdClass();
// Add the phrase (even if empty) and comments
$mbox->personal = $phrase;
$mbox->comment = isset($comments) ? $comments : array();
if (isset($route_addr)) {
$mbox->mailbox = $route_addr['local_part'];
$mbox->host = $route_addr['domain'];
$route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
} else {
$mbox->mailbox = $addr_spec['local_part'];
$mbox->host = $addr_spec['domain'];
}
$mailbox = $mbox;
return true;
}
/**
* This function validates a route-addr which is:
* route-addr = "<" [route] addr-spec ">"
*
* Angle brackets have already been removed at the point of
* getting to this function.
*
* @access private
* @param string $route_addr The string to check.
* @return mixed False on failure, or an array containing validated address/route information on success.
*/
function _validateRouteAddr($route_addr)
{
// Check for colon.
if (strpos($route_addr, ':') !== false) {
$parts = explode(':', $route_addr);
$route = $this->_splitCheck($parts, ':');
} else {
$route = $route_addr;
}
// If $route is same as $route_addr then the colon was in
// quotes or brackets or, of course, non existent.
if ($route === $route_addr){
unset($route);
$addr_spec = $route_addr;
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
} else {
// Validate route part.
if (($route = $this->_validateRoute($route)) === false) {
return false;
}
$addr_spec = substr($route_addr, strlen($route . ':'));
// Validate addr-spec part.
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
if (isset($route)) {
$return['adl'] = $route;
} else {
$return['adl'] = '';
}
$return = array_merge($return, $addr_spec);
return $return;
}
/**
* Function to validate a route, which is:
* route = 1#("@" domain) ":"
*
* @access private
* @param string $route The string to check.
* @return mixed False on failure, or the validated $route on success.
*/
function _validateRoute($route)
{
// Split on comma.
$domains = explode(',', trim($route));
for ($i = 0; $i < count($domains); $i++) {
$domains[$i] = str_replace('@', '', trim($domains[$i]));
if (!$this->_validateDomain($domains[$i])) return false;
}
return $route;
}
/**
* Function to validate a domain, though this is not quite what
* you expect of a strict internet domain.
*
* domain = sub-domain *("." sub-domain)
*
* @access private
* @param string $domain The string to check.
* @return mixed False on failure, or the validated domain on success.
*/
function _validateDomain($domain)
{
// Note the different use of $subdomains and $sub_domains
$subdomains = explode('.', $domain);
while (count($subdomains) > 0) {
$sub_domains[] = $this->_splitCheck($subdomains, '.');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($subdomains);
}
for ($i = 0; $i < count($sub_domains); $i++) {
if (!$this->_validateSubdomain(trim($sub_domains[$i])))
return false;
}
// Managed to get here, so return input.
return $domain;
}
/**
* Function to validate a subdomain:
* subdomain = domain-ref / domain-literal
*
* @access private
* @param string $subdomain The string to check.
* @return boolean Success or failure.
*/
function _validateSubdomain($subdomain)
{
if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
if (!$this->_validateDliteral($arr[1])) return false;
} else {
if (!$this->_validateAtom($subdomain)) return false;
}
// Got here, so return successful.
return true;
}
/**
* Function to validate a domain literal:
* domain-literal = "[" *(dtext / quoted-pair) "]"
*
* @access private
* @param string $dliteral The string to check.
* @return boolean Success or failure.
*/
function _validateDliteral($dliteral)
{
return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
}
/**
* Function to validate an addr-spec.
*
* addr-spec = local-part "@" domain
*
* @access private
* @param string $addr_spec The string to check.
* @return mixed False on failure, or the validated addr-spec on success.
*/
function _validateAddrSpec($addr_spec)
{
$addr_spec = trim($addr_spec);
// Split on @ sign if there is one.
if (strpos($addr_spec, '@') !== false) {
$parts = explode('@', $addr_spec);
$local_part = $this->_splitCheck($parts, '@');
$domain = substr($addr_spec, strlen($local_part . '@'));
// No @ sign so assume the default domain.
} else {
$local_part = $addr_spec;
$domain = $this->default_domain;
}
if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
if (($domain = $this->_validateDomain($domain)) === false) return false;
// Got here so return successful.
return array('local_part' => $local_part, 'domain' => $domain);
}
/**
* Function to validate the local part of an address:
* local-part = word *("." word)
*
* @access private
* @param string $local_part
* @return mixed False on failure, or the validated local part on success.
*/
function _validateLocalPart($local_part)
{
$parts = explode('.', $local_part);
// Split the local_part into words.
while (count($parts) > 0){
$words[] = $this->_splitCheck($parts, '.');
for ($i = 0; $i < $this->index + 1; $i++) {
array_shift($parts);
}
}
// Validate each word.
for ($i = 0; $i < count($words); $i++) {
if ($this->_validatePhrase(trim($words[$i])) === false) return false;
}
// Managed to get here, so return the input.
return $local_part;
}
/**
* Returns an approximate count of how many addresses are
* in the given string. This is APPROXIMATE as it only splits
* based on a comma which has no preceding backslash. Could be
* useful as large amounts of addresses will end up producing
* *large* structures when used with parseAddressList().
*
* @param string $data Addresses to count
* @return int Approximate count
*/
function approximateCount($data)
{
return count(preg_split('/(?<!\\\\),/', $data));
}
/**
* This is a email validating function seperate to the rest
* of the class. It simply validates whether an email is of
* the common internet form: <user>@<domain>. This can be
* sufficient for most people. Optional stricter mode can
* be utilised which restricts mailbox characters allowed
* to alphanumeric, full stop, hyphen and underscore.
*
* @param string $data Address to check
* @param boolean $strict Optional stricter mode
* @return mixed False if it fails, an indexed array
* username/domain if it matches
*/
function isValidInetAddress($data, $strict = false)
{
$regex = $strict ? '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i';
if (preg_match($regex, trim($data), $matches)) {
return array($matches[1], $matches[2]);
} else {
return false;
}
}
}
?>

File diff suppressed because it is too large Load Diff

311
framework/mail/mimePart.php Normal file
View File

@ -0,0 +1,311 @@
<?php
/**
* o------------------------------------------------------------------------------o
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
* | If you use the code commercially (or if you don't want to be restricted by |
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
* o------------------------------------------------------------------------------o
*
* © Copyright Richard Heyes
*/
/**
*
* Raw mime encoding class
*
* What is it?
* This class enables you to manipulate and build
* a mime email from the ground up.
*
* Why use this instead of mime.php?
* mime.php is a userfriendly api to this class for
* people who aren't interested in the internals of
* mime mail. This class however allows full control
* over the email.
*
* Eg.
*
* // Since multipart/mixed has no real body, (the body is
* // the subpart), we set the body argument to blank.
*
* $params['content_type'] = 'multipart/mixed';
* $email = new Mail_mimePart('', $params);
*
* // Here we add a text part to the multipart we have
* // already. Assume $body contains plain text.
*
* $params['content_type'] = 'text/plain';
* $params['encoding'] = '7bit';
* $text = $email->addSubPart($body, $params);
*
* // Now add an attachment. Assume $attach is
* the contents of the attachment
*
* $params['content_type'] = 'application/zip';
* $params['encoding'] = 'base64';
* $params['disposition'] = 'attachment';
* $params['dfilename'] = 'example.zip';
* $attach =& $email->addSubPart($body, $params);
*
* // Now build the email. Note that the encode
* // function returns an associative array containing two
* // elements, body and headers. You will need to add extra
* // headers, (eg. Mime-Version) before sending.
*
* $email = $message->encode();
* $email['headers'][] = 'Mime-Version: 1.0';
*
*
* Further examples are available at http://www.phpguru.org
*
* TODO:
* - Set encode() to return the $obj->encoded if encode()
* has already been run. Unless a flag is passed to specifically
* re-build the message.
*
* @author Richard Heyes <richard@phpguru.org>
* @version $Revision: 1.3 $
* @package Mail
*/
class Mail_MIMEPart
{
/**
* The encoding type of this part
* @var string
*/
private $encoding;
/**
* An array of subparts
* @var array
*/
private $subparts;
/**
* The output of this part after being built
* @var string
*/
private $encoded;
/**
* Headers for this part
* @var array
*/
private $headers;
/**
* The body of this part (not encoded)
* @var string
*/
private $body;
/**
* Constructor.
*
* Sets up the object.
*
* @param $body - The body of the mime part if any.
* @param $params - An associative array of parameters:
* content_type - The content type for this part eg multipart/mixed
* encoding - The encoding to use, 7bit, 8bit, base64, or quoted-printable
* cid - Content ID to apply
* disposition - Content disposition, inline or attachment
* dfilename - Optional filename parameter for content disposition
* description - Content description
* charset - Character set to use
* @access public
*/
public function __construct($body = '', $params = array())
{
if (!defined('MAIL_MIMEPART_CRLF')) {
define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", true);
}
foreach ($params as $key => $value) {
switch ($key) {
case 'content_type':
$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
break;
case 'encoding':
$this->encoding = $value;
$headers['Content-Transfer-Encoding'] = $value;
break;
case 'cid':
$headers['Content-ID'] = '<' . $value . '>';
break;
case 'disposition':
$headers['Content-Disposition'] = $value . (isset($dfilename) ? '; filename="' . $dfilename . '"' : '');
break;
case 'dfilename':
if (isset($headers['Content-Disposition'])) {
$headers['Content-Disposition'] .= '; filename="' . $value . '"';
} else {
$dfilename = $value;
}
break;
case 'description':
$headers['Content-Description'] = $value;
break;
case 'charset':
if (isset($headers['Content-Type'])) {
$headers['Content-Type'] .= '; charset="' . $value . '"';
} else {
$charset = $value;
}
break;
}
}
// Default content-type
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'text/plain';
}
// Default encoding
if (!isset($this->encoding)) {
$this->encoding = '7bit';
}
// Assign stuff to member variables
$this->encoded = array();
$this->headers = $headers;
$this->body = $body;
}
/**
* Encodes and returns the email. Also stores
* it in the encoded member variable
*
* @return An associative array containing two elements,
* body and headers. The headers element is itself
* an indexed array.
*/
public function encode()
{
$encoded =& $this->encoded;
if (!empty($this->subparts)) {
srand((double)microtime()*1000000);
$boundary = '=_' . md5(uniqid(rand()) . microtime());
$this->headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
// Add body parts to $subparts
for ($i = 0; $i < count($this->subparts); $i++) {
$headers = array();
$tmp = $this->subparts[$i]->encode();
foreach ($tmp['headers'] as $key => $value) {
$headers[] = $key . ': ' . $value;
}
$subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'];
}
$encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF .
implode('--' . $boundary . MAIL_MIMEPART_CRLF, $subparts) .
'--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
} else {
$encoded['body'] = $this->getEncodedData($this->body, $this->encoding) . MAIL_MIMEPART_CRLF;
}
// Add headers to $encoded
$encoded['headers'] =& $this->headers;
return $encoded;
}
/**
* Adds a subpart to current mime part and returns
* a reference to it
*
* @param $body The body of the subpart, if any.
* @param $params The parameters for the subpart, same
* as the $params argument for constructor.
* @return A reference to the part you just added.
*/
public function addSubPart($body, $params)
{
$this->subparts[] = new Mail_MIMEPart($body, $params);
return $this->subparts[count($this->subparts) - 1];
}
/**
* Returns encoded data based upon encoding passed to it
*
* @param $data The data to encode.
* @param $encoding The encoding type to use, 7bit, base64,
* or quoted-printable.
*/
private function getEncodedData($data, $encoding)
{
switch ($encoding) {
case '8bit':
case '7bit':
return $data;
break;
case 'quoted-printable':
return $this->quotedPrintableEncode($data);
break;
case 'base64':
return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
break;
default:
return $data;
}
}
/**
* Encodes data to quoted-printable standard.
*
* @param $input The data to encode
* @param $line_max Optional max line length. Should
* not be more than 76 chars
*/
private function quotedPrintableEncode($input , $line_max = 76)
{
$lines = preg_split("/\r?\n/", $input);
$eol = MAIL_MIMEPART_CRLF;
$escape = '=';
$output = '';
while(list(, $line) = each($lines)){
$linlen = strlen($line);
$newline = '';
for ($i = 0; $i < $linlen; $i++) {
$char = substr($line, $i, 1);
$dec = ord($char);
if (($dec == 32) AND ($i == ($linlen - 1))){ // convert space at eol only
$char = '=20';
} elseif($dec == 9) {
; // Do nothing if a tab.
} elseif(($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
$char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
}
if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted
$output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay
$newline = '';
}
$newline .= $char;
} // end of for
$output .= $newline . $eol;
}
$output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
return $output;
}
} // End of class
?>

103
framework/mail/sendMail.php Normal file
View File

@ -0,0 +1,103 @@
<?
function sendMail($from, $to, $subject, $text='', $html='', /*$priority='high', $tabImgFiles=array(), */$tabAttachedFiles=array())
{
//return true;
$to=preg_split("/[\s,;]+/", $to);
//die(print_r($to));
require_once('Mail.php');
require_once('Mail/mime.php');
$headers=array( 'From'=>$from,
'To'=>$to,
'Subject'=>$subject,
// 'Reply-To'=>$from,
// 'Return-Path'=>$from,
'Content-Transfer-Encoding'=>'8bit',
'MIME-Version'=>'1.0',
'Date'=>date('D, d M Y H:i:s O'),
'Message-ID'=>'<'.md5(date('YmdHis')).'@mail.scores-decisions.com>',
'X-Priority'=>3,
'X-Mailer'=>'PHP v'.phpversion(),
);
/*
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= ''.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";
*/
$mime = new Mail_mime();
$footer="";/*
_______________________________________________________________________
Ce message et toutes les pièces jointes (ci-après le \"message\") sont établis a l'intention exclusive de ses destinataires.Si vous recevez ce message par erreur, merci de le détruire et d'en avertir immédiatement l'expéditeur par e-mail. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. Les communications sur Internet n'étant pas sécurisées, SCORES & DECISIONS S.A.S. informe qu'elle ne peut accepter aucune responsabilite quant au contenu de ce message.
This mail message and attachments (the \"message\") are solely intended for the addressees. It is confidential in nature . If you receive this message in error, please delete it and immediately notify the sender by e-mail. Any use other than its intended purpose, dissemination or disclosure, either whole or partial, is prohibited except if formal approval is granted. As communication on the Internet is not secure, SCORES & DECISIONS S.A.S. does not accept responsability for the content of this message.
";*/
if ($text<>'') $mime->setTXTBody($text.$footer);
if ($html<>'') $mime->setHTMLBody($html);
foreach ($tabAttachedFiles as $file)
$mime->addAttachment($file);
//do not ever try to call these lines in reverse order
$body = $mime->get();
$headers = $mime->headers($headers);
$params=array( 'host'=>'smtpauth.online.net', // SMTP_HOST
'port'=>25, //SMTP_PORT,
);
$params=array( 'host'=>SMTP_HOST,
'port'=>SMTP_PORT,
//'debug'=>true,
//'persist'=>true,
);
if (SMTP_USER=='' && SMTP_PASS=='')
$params['auth'] = false;
else {
$params['username'] = SMTP_USER;
$params['password'] = SMTP_PASS;
}/*
$params['auth'] = true;
$params['username'] = 'buzuk@scores-decisions.com';
$params['password'] = 'catsysyo92';
*/
$nbEssais=0;
while (1) {
// Create the mail object using the Mail::factory method
$mail_object = Mail::factory('smtp', $params);
// Trying to send the mail
$send = $mail_object->send($to, $headers, $body);
$nbEssais++;
if (PEAR::isError($send)) {
/** @todo tester les différents codes erreur **/
echo date('Y-m-d H:i:s'). " sendMail.php - essai #$nbEssais : ".$send->getMessage().EOL;
if (preg_match('/too many connections|421/i', $send->getMessage()))
sleep($nbEssais);
else {
$strTo=implode(';', $to);
file_put_contents( '/var/www/log/sendMailError.log',
date('Y-m-d H:i:s')."\t#$nbEssais\t$strTo\t".$send->getMessage().EOL,
FILE_APPEND);
break;
}
} else {
/** Si nous sommes en mode CLI, alors on fait en sorte de ne pas atteindre
la limite des 25 mails par minute (ramené à 100 / minute)
**/
if (MODE_EXEC==MODE_CLI) usleep(500000);
break;
}
}
return true;
}
?>

View File

@ -0,0 +1,33 @@
<?
function sendMail($from, $to, $subject, $text='', $html='', $priority='high', $tabImgFiles=array(), $tabAttachedFiles=array())
{
require_once("Mail.php");
$headers["From"] = $from;
$headers["To"] = $to;
$headers["Subject"] = $subject;
$body = $text;
$params["host"] = SMTP_HOST;
$params["port"] = SMTP_PORT;
if (SMTP_USER=='' && SMTP_PASS=='')
$params["auth"] = false;
else {
$params["username"] = SMTP_USER;
$params["password"] = SMTP_PASS;
}
// Create the mail object using the Mail::factory method
$mail_object = Mail::factory("smtp", $params);
$mail_object->send($to, $headers, $body);
if (PEAR::isError($mail_object))
return $mail_object->getMessage();
return true;
}
?>

369
framework/mail/smtp.php Normal file
View File

@ -0,0 +1,369 @@
<?php
/**
) o------------------------------------------------------------------------------o
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
* | If you use the code commercially (or if you don't want to be restricted by |
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
* o------------------------------------------------------------------------------o
*
* © Copyright 2005 Richard Heyes
*/
define('SMTP_STATUS_NOT_CONNECTED', 1, true);
define('SMTP_STATUS_CONNECTED', 2, true);
class smtp
{
private $authenticated;
private $connection;
private $recipients;
private $headers;
private $timeout;
private $errors;
private $status;
private $body;
private $from;
private $host;
private $port;
private $helo;
private $auth;
private $user;
private $pass;
/**
* Constructor function. Arguments:
* $params - An assoc array of parameters:
*
* host - The hostname of the smtp server Default: localhost
* port - The port the smtp server runs on Default: 25
* helo - What to send as the HELO command Default: localhost
* (typically the hostname of the
* machine this script runs on)
* auth - Whether to use basic authentication Default: FALSE
* user - Username for authentication Default: <blank>
* pass - Password for authentication Default: <blank>
* timeout - The timeout in seconds for the call Default: 5
* to fsockopen()
*/
public function __construct($params = array())
{
if(!defined('CRLF'))
define('CRLF', "\r\n", TRUE);
$this->authenticated = FALSE;
$this->timeout = 5;
$this->status = SMTP_STATUS_NOT_CONNECTED;
$this->host = 'smtp.free.fr';
$this->port = 25;
$this->helo = 'srvsd01';
$this->auth = FALSE;
$this->user = '';
$this->pass = '';
$this->errors = array();
foreach($params as $key => $value){
$this->$key = $value;
}
}
/**
* Connect function. This will, when called
* statically, create a new smtp object,
* call the connect function (ie this function)
* and return it. When not called statically,
* it will connect to the server and send
* the HELO command.
*/
public function connect($params = array())
{
if (!isset($this->status)) {
$obj = new smtp($params);
if($obj->connect()){
$obj->status = SMTP_STATUS_CONNECTED;
}
return $obj;
} else {
$this->connection = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if (function_exists('socket_set_timeout')) {
@socket_set_timeout($this->connection, 5, 0);
}
$greeting = $this->get_data();
if (is_resource($this->connection)) {
return $this->auth ? $this->ehlo() : $this->helo();
} else {
$this->errors[] = 'Failed to connect to server: '.$errstr;
return FALSE;
}
}
}
/**
* Function which handles sending the mail.
* Arguments:
* $params - Optional assoc array of parameters.
* Can contain:
* recipients - Indexed array of recipients
* from - The from address. (used in MAIL FROM:),
* this will be the return path
* headers - Indexed array of headers, one header per array entry
* body - The body of the email
* It can also contain any of the parameters from the connect()
* function
*/
public function send($params = array())
{
foreach ($params as $key => $value) {
$this->set($key, $value);
}
if ($this->is_connected()) {
// Do we auth or not? Note the distinction between the auth variable and auth() function
if ($this->auth AND !$this->authenticated) {
if(!$this->auth())
return false;
}
$this->mail($this->from);
if (is_array($this->recipients)) {
foreach ($this->recipients as $value) {
$this->rcpt($value);
}
} else {
$this->rcpt($this->recipients);
}
if (!$this->data()) {
return false;
}
// Transparency
$headers = str_replace(CRLF.'.', CRLF.'..', trim(implode(CRLF, $this->headers)));
$body = str_replace(CRLF.'.', CRLF.'..', $this->body);
$body = substr($body, 0, 1) == '.' ? '.'.$body : $body;
$this->send_data($headers);
$this->send_data('');
$this->send_data($body);
$this->send_data('.');
$result = (substr(trim($this->get_data()), 0, 3) === '250');
//$this->rset();
return $result;
} else {
$this->errors[] = 'Not connected!';
return FALSE;
}
}
/**
* Function to implement HELO cmd
*/
private function helo()
{
if(is_resource($this->connection)
AND $this->send_data('HELO '.$this->helo)
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
return true;
} else {
$this->errors[] = 'HELO command failed, output: ' . trim(substr(trim($error),3));
return false;
}
}
/**
* Function to implement EHLO cmd
*/
private function ehlo()
{
if (is_resource($this->connection)
AND $this->send_data('EHLO '.$this->helo)
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
return true;
} else {
$this->errors[] = 'EHLO command failed, output: ' . trim(substr(trim($error),3));
return false;
}
}
/**
* Function to implement RSET cmd
*/
private function rset()
{
if (is_resource($this->connection)
AND $this->send_data('RSET')
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
return true;
} else {
$this->errors[] = 'RSET command failed, output: ' . trim(substr(trim($error),3));
return false;
}
}
/**
* Function to implement QUIT cmd
*/
private function quit()
{
if(is_resource($this->connection)
AND $this->send_data('QUIT')
AND substr(trim($error = $this->get_data()), 0, 3) === '221' ){
fclose($this->connection);
$this->status = SMTP_STATUS_NOT_CONNECTED;
return true;
} else {
$this->errors[] = 'QUIT command failed, output: ' . trim(substr(trim($error),3));
return false;
}
}
/**
* Function to implement AUTH cmd
*/
private function auth()
{
if (is_resource($this->connection)
AND $this->send_data('AUTH LOGIN')
AND substr(trim($error = $this->get_data()), 0, 3) === '334'
AND $this->send_data(base64_encode($this->user)) // Send username
AND substr(trim($error = $this->get_data()),0,3) === '334'
AND $this->send_data(base64_encode($this->pass)) // Send password
AND substr(trim($error = $this->get_data()),0,3) === '235' ){
$this->authenticated = true;
return true;
} else {
$this->errors[] = 'AUTH command failed: ' . trim(substr(trim($error),3));
return false;
}
}
/**
* Function that handles the MAIL FROM: cmd
*/
private function mail($from)
{
if ($this->is_connected()
AND $this->send_data('MAIL FROM:<'.$from.'>')
AND substr(trim($this->get_data()), 0, 2) === '250' ) {
return true;
} else {
return false;
}
}
/**
* Function that handles the RCPT TO: cmd
*/
private function rcpt($to)
{
if($this->is_connected()
AND $this->send_data('RCPT TO:<'.$to.'>')
AND substr(trim($error = $this->get_data()), 0, 2) === '25' ){
return true;
} else {
$this->errors[] = trim(substr(trim($error), 3));
return false;
}
}
/**
* Function that sends the DATA cmd
*/
private function data()
{
if($this->is_connected()
AND $this->send_data('DATA')
AND substr(trim($error = $this->get_data()), 0, 3) === '354' ) {
return true;
} else {
$this->errors[] = trim(substr(trim($error), 3));
return false;
}
}
/**
* Function to determine if this object
* is connected to the server or not.
*/
private function is_connected()
{
return (is_resource($this->connection) AND ($this->status === SMTP_STATUS_CONNECTED));
}
/**
* Function to send a bit of data
*/
private function send_data($data)
{
if(is_resource($this->connection)){
return fwrite($this->connection, $data.CRLF, strlen($data)+2);
} else {
return false;
}
}
/**
* Function to get data.
*/
private function get_data()
{
$return = '';
$line = '';
$loops = 0;
if(is_resource($this->connection)){
while((strpos($return, CRLF) === FALSE OR substr($line,3,1) !== ' ') AND $loops < 100){
$line = fgets($this->connection, 512);
$return .= $line;
$loops++;
}
return $return;
}else
return false;
}
/**
* Sets a variable
*/
public function set($var, $value)
{
$this->$var = $value;
return true;
}
/**
* Function to return the errors array
*/
public function getErrors()
{
return $this->errors;
}
} // End of class
?>

View File

@ -0,0 +1,247 @@
<?php
ini_set('soap.wsdl_cache_enabled', 0);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
class mantisWsdlClient
{
private $mtSrvClient;
private $mtSrvUser='';
private $mtSrvPass='';
public function __construct($mtSrvWsdlUrl, $mtSrvUser, $mtSrvPass)
{
$this->mtSrvUser=$mtSrvUser;
$this->mtSrvPass=$mtSrvPass;
try {
$this->mtSrvClient = new soapclient($mtSrvWsdlUrl);
} catch(Soapfault $e) {
echo "Erreur : URL Soap WSDL Mantis invalide";
exit();
}
}
/** Ajout d'une note
* @param unknown_type $issue_id
* @param unknown_type $reporter_id
* @param unknown_type $notes
*/
public function add_issue_note($issue_id,$reporter_id,$notes)
{
$view_state = new StdClass;
$view_state->id =1;
$note = new StdClass;
$note->id =$issue_id;
$note->reporter =$reporter_id;
$note->text =$notes;
$note->view_state=$view_state;
$note->date_submitted =date('d-m-Y');
$note->last_modified =date('d-m-Y');
try{
$this->mtSrvClient->mc_issue_note_add($this->mtSrvUser,$this->mtSrvPass,$issue_id,$note);
} catch (SoapFault $exception) {
// handle the fault
print_r($exception);
//var_dump(libxml_get_last_error());
echo "Problem occured when adding issue for the planner title: ".$summary."<br>";
}
}
// Add issue function
// parameter @projectid
public function addissue($projecId,$reporterid,$summary,$description,$priority=0)
{
//$client = new soapclient(WSDL_URL);
$issue = new StdClass;
$project = new StdClass;
$project->id =$projecId;// 15;
$reporter = new StdClass;
$reporter->id =$reporterid;// 24;
/*$handler = new StdClass;
if(trim($handlerid)=="" or trim($handlerid)=="0" )
$handler->id =$reporterid;// 24;
else
$handler->id =$handlerid;// 24;
// echo "HAND: ".$handler->id."<br><br>";
*/
$issue->project = $project;
$issue->reporter = $reporter;
//$issue->handler = $handler;
$issue->summary = $summary;//"testiing subject";
$issue->description =$description;//"testiing";
if($priority*1==0)
$issue->priority = 30;
else
$issue->priority = $prority;
/*if($eta=="" or $eta=="0" )
$issue->eta = 10;
else
$issue->eta = $eta;
*/
$issue->severity = 50;
$issue->status = 10;
$issue->reproducibility = 70;//10;
//$issue->resolution = 10;
$issue->projection = 10;
$issue->view_state = 10;
$issue->category = "";
$issue->additional_information =date('d-m-Y: H:i:s');
try {
$response_issue_id=$this->mtSrvClient->mc_issue_add($this->mtSrvUser,$this->mtSrvPass,$issue); // add Task
return $response_issue_id;
} catch (SoapFault $exception) {
// handle the fault
print_r($exception);
//var_dump(libxml_get_last_error());
echo "Problem occured when adding issue for the planner title: ".$summary."<br>";
}
/*POSTDATA =
name="bug_report_token"
name="m_id" 0
name="project_id" 37
name="category"
name="reproducibility" 70
name="severity" 50
name="priority" 30
name="profile_id"
name="platform"
name="os"
name="os_build"
name="build"
name="handler_id" 0
name="summary" Siren 450175179 Bilan du 31/12/2009
name="description" Poste DO non saisit
name="steps_to_reproduce"
name="additional_info"
name="max_file_size" 2000000
name="file"; filename="" Content-Type: application/octet-stream
name="view_state" 10
*/
}
function getProjectIssues($projecId) {
if ($this->checkProjectid($projecId)) {
try {
$resfound=$this->mtSrvClient->mc_project_get_issues($this->mtSrvUser,$this->mtSrvPass,$projecId);
} catch(Exception $e) {
echo "<br>Invalid Login credentials (wsdl_config.php) or ProjectID .<br>";
return false;
}
return $resfound;
}
return false;
}
//Function accpets username as argument and returns userid if exists
/*
public function checkUserid($username)
{
$result = mysql_query("SELECT * FROM mantis_user_table where username='".$username."'") or die(mysql_error());
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
if(sizeof($row>0))
return $row['id'];
else
return 0;
}*/
//insert custom fields startdate,finsihdate,percentage complete
/*
public function mantis_insert_customfield($field_id,$bug_id,$value)
{
$sql="insert into mantis_custom_field_string_table (field_id,bug_id,value) values ('".$field_id."','".$bug_id."','".$value."')";
mysql_query($sql);
}
*/
//update ETA field
/*
public function mantis_update_bugfield($bug_id,$bugfield,$bugvalue)
{
$sql="update mantis_bug_table set ".$bugfield."='".$bugvalue."' where id=".$bug_id;
//echo $sql;
mysql_query($sql);
}
*/
/** Le projet existe t il dans Mantis ?
**
** @param $projecId
**/
public function checkProjectid($projecId)
{
try {
$resfound=$this->mtSrvClient->mc_project_get_categories($this->mtSrvUser,$this->mtSrvPass, $projecId );
}
catch(Exception $e)
{
echo "<br>Invalid Login credentials (wsdl_config.php) or ProjectID .<br>";
return false;
}
// print_r($resfound);
return true;
}
public function addirelationship($relationType,$issue_id,$target_id)
{
//relation object class---------------START
$relation = new StdClass;
if($relationType=="p")
{
//parent of
$relation->id = 2;
$relation->name = "parent of";
}
else
{
//child of
$relation->id = 3;
$relation->name = "child of";
}
//relation object class---------------END
//relationship object class-----------------------START
$relationship = new StdClass;
$relationship->id= 3;
$relationship->type=$relation;
$relationship->target_id= $target_id;
//relationship object class-----------------------END
//$response_issue_id=56;
try{
$response=$this->mtSrvClient->mc_issue_relationship_add($this->mtSrvUser,$this->mtSrvPass,$issue_id,$relationship); // add relationshiip
} catch (SoapFault $exception) {
//print_r($exception);
// handle the fault
//echo "Problem occured when configuring relationship for the Ticket id: ".$issue_id."<br>";
}
}
}
?>

View File

@ -0,0 +1,215 @@
<?
include_once(FWK_PATH.'common/strings.php');
include_once(FWK_PATH.'sphinx/sphinxapi2.php');
function search($index, $findMe, $tabFiltres=array(), $deb=0, $nbRep=20, $max=200, $any=false) {
$deb=$deb*1;
$nbRep=$nbRep*1;
$max=$max*1;
debugLog('I',"Search Sphinx dans $index de $findMe ($deb, $nbRep, $max) avec ".implode(',',$tabFiltres),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$iDb=new WDB();
/*
$cl = new SphinxClient ();
$cl->SetServer ( $host, $port );
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $mode );
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
$res = $cl->Query ( $q, $index );
*/
//$any = false; // si false $index='xxx'
$cl = new SphinxClient ();
$cl->SetServer (SPHINX_HOST, SPHINX_PORT);
$cl->SetConnectTimeout ( 1 );
$cl->SetLimits ($deb, $nbRep, $max);//0, $nbRep*10);
//$cl->SetSortMode(SPH_SORT_ATTR_DESC, 'actif');//siege');
if (substr($index,0,4)=='etab')
$cl->SetSortMode(SPH_SORT_EXTENDED, 'rang DESC, actif DESC, siege DESC');//, nic DESC
//$cl->SetWeights ( array ( 100, 1 ) );
//$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
$cl->SetMatchMode (SPH_MATCH_EXTENDED);
foreach ($tabFiltres as $nomFiltre => $valFiltre)
$cl->SetFilter($nomFiltre, array(0=>$valFiltre));
$cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );
//$cl->SetArrayResult ( true );
$res = $cl->Query ( $findMe, $index );
if ($res===false) {
debugLog('I',"Search Sphinx : Pas de réponse pour $findMe avec ".implode(',',$tabFiltres).' ('.$cl->GetLastError() .')',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
return array( 'results'=>false,
'nbRet'=>0,
'nbTot'=>0,
'duration'=>$res[time]);//return false;
} else { // Le moteur est opérationel
if ( $cl->GetLastWarning() ) {
debugLog('I',"Search Sphinx : Warning pour $findMe - ".$cl->GetLastWarning(),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
}
/* print "Query '$findMe' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
print "Query stats :\n";
if ( is_array($res["words"]) )
foreach ( $res["words"] as $word => $info )
print " - '$word' found $info[hits] times in $info[docs] documents\n";
print "\n";*/
debugLog('I',"'Search Sphinx dans $index de $findMe (Filtre=".implode(',',$tabFiltres)."), Deb=$deb, nbRep=$nbRep, max=$max, any=$any",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
// debugLog('I',"Search Sphinx dans $index ". print_r($tabFiltres, true));
$tabRet=array();
if ( @is_array($res['matches'])) { // il y a des données à renvoyer
if (substr($index,0,4)=='etab') { // Recherche par étab
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne
$listeEtab=$iDb->select('etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, e.actif",
"id=$doc LIMIT 0,1", true);
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
//'NafEtabLib'=>$etab['LibNafEt'],
'NafEnt'=>$etab['ape_entrep'], // Entreprise
//'NafEntLib'=>$etab['LibNafEt'],
);
}
} else { // Recherche par dirigeant
$findMe4=trim(substr($findMe,0,4));
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne dirigeant
/*$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
"d.dateEffet, d.fonction, d.depart, e.actif",
"d.id=$doc AND d.id=b.id AND b.siren=e.siren AND (d.nom LIKE '%$findMe4%' OR d.prenom LIKE '%$findMe4%' OR d.nomUsage LIKE '%$findMe4%' OR d.rs LIKE '%$findMe4%') LIMIT 0,1", true);
if (count($listeEtab)==0)
$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
"d.dateEffet, d.fonction, d.depart, e.actif",
"d.id=$doc AND d.id=b.id AND b.siren=e.siren LIMIT 0,1", true);
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
'NafEnt'=>$etab['ape_entrep'], // Entreprise
'rs'=>$etab['rs'],
'nomD'=>$etab['nom'],
'prenom'=>$etab['prenom'],
'nomUsage'=>$etab['nomUsage'],
'dateEffet'=>$etab['dateEffet'],
'fonction'=>$etab['fonction'],
'depart'=>$etab['depart'],
);
}
*/
//print_r($tabRet);
//die();
$listeEtab=$iDb->select('rncs_dirigeants d, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, /*d.rs,*/ d.nom, d.prenom, /*d.nomUsage,*/ d.naissance_date, d.naissance_lieu, ".
"d.fonction_lib, /*d.depart,*/ e.actif",
"d.id=$doc AND d.siren=e.siren AND e.siege=1 ORDER BY e.actif DESC LIMIT 0,1", true);
//die(print_r($listeEtab));
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
'NafEnt'=>$etab['ape_entrep'], // Entreprise
'rs'=>'',//$etab['rs'],
'nomD'=>$etab['nom'],
'prenom'=>$etab['prenom'],
'nomUsage'=>'',//$etab['nomUsage'],
'dateEffet'=>'',//$etab['dateEffet'],
'fonction'=>$etab['fonction_lib'],
'depart'=>0,//$etab['depart'],
);
}
}
}
}
debugLog('I','Search Sphinx : Retourne '. $res[total].'/'. $res[total_found] .' en '.$res[time] .'secondes',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
return array( 'results'=>$tabRet,
'nbRet'=>$res[total],
'nbTot'=>$res[total_found],
'duration'=>$res[time],
);
}
?>

View File

@ -0,0 +1,327 @@
<?
include_once(FWK_PATH.'common/strings.php');
//include_once(FWK_PATH.'sphinx/sphinxapi2.php');
function search2($index, $findMe, $tabFiltres=array(), $deb=0, $nbRep=20, $max=200, $any=false) {
$deb=$deb*1;
$nbRep=$nbRep*1;
$max=$max*1;
debugLog('I',"Search Sphinx dans $index de $findMe ($deb, $nbRep, $max) avec ".implode(',',$tabFiltres),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$iDb=new WDB();
/*
$cl = new SphinxClient ();
$cl->SetServer ( $host, $port );
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $mode );
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
$res = $cl->Query ( $q, $index );
*/
//$any = false; // si false $index='xxx'
$cl = new SphinxClient();
if ($index == 'histo'){
$cl->SetServer (SPHINX_HISTO_HOST, SPHINX_HISTO_PORT);
} else {
$cl->SetServer (SPHINX_HOST, SPHINX_PORT);
}
$cl->SetConnectTimeout ( 1 );
$cl->SetLimits ($deb, $nbRep, $max);//0, $nbRep*10);
//$cl->SetSortMode(SPH_SORT_ATTR_DESC, 'actif');//siege');
if (substr($index,0,4)=='etab')
$cl->SetSortMode(SPH_SORT_EXTENDED, 'rang DESC, actif DESC, siege DESC');//, nic DESC
//$cl->SetWeights ( array ( 100, 1 ) );
//$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
$cl->SetMatchMode (SPH_MATCH_EXTENDED);
foreach ($tabFiltres as $nomFiltre => $valFiltre)
$cl->SetFilter($nomFiltre, array(0=>$valFiltre));
$cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );
//$cl->SetArrayResult ( true );
$res = $cl->Query ( $findMe, $index );
//@sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Debug", print_r($res,true)) ;
if ($res===false) {
debugLog('I',"Search Sphinx : Pas de réponse pour $findMe avec ".implode(',',$tabFiltres).' ('.$cl->GetLastError() .')',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
return array( 'results'=>false,
'nbRet'=>0,
'nbTot'=>0,
'error'=>$cl->GetLastError(),
'warning'=>$cl->GetLastWarning(),
'duration'=>$res[time]);//return false;
} else { // Le moteur est opérationel
if ( $cl->GetLastWarning() ) {
debugLog('I',"Search Sphinx : Warning pour $findMe - ".$cl->GetLastWarning(),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
}
/* print "Query '$findMe' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
print "Query stats :\n";
if ( is_array($res["words"]) )
foreach ( $res["words"] as $word => $info )
print " - '$word' found $info[hits] times in $info[docs] documents\n";
print "\n";*/
debugLog('I',"'Search Sphinx dans $index de $findMe (Filtre=".implode(',',$tabFiltres)."), Deb=$deb, nbRep=$nbRep, max=$max, any=$any",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
// debugLog('I',"Search Sphinx dans $index ". print_r($tabFiltres, true));
$tabRet=array();
if ( @is_array($res['matches'])) { // il y a des données à renvoyer
if (substr($index,0,4)=='etab') { // Recherche par étab
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne
$listeEtab=$iDb->select('etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, e.actif",
"id=$doc LIMIT 0,1", true);
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
//'NafEtabLib'=>$etab['LibNafEt'],
'NafEnt'=>$etab['ape_entrep'], // Entreprise
//'NafEntLib'=>$etab['LibNafEt'],
);
}
} elseif ($index=='histo') {
foreach ( $res['matches'] as $doc => $docinfo ) {
$listeEtab=$iDb->select('histobodacc.bodacc_ocr',
"'Histo' as Loc, id, nomFichier, annee1, bod, texte",
"id=$doc");
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Fichier'=>$etab['nomFichier'],
'Annee'=>$etab['annee1'],
'Code'=>$etab['bod'],
'Texte'=>$etab['texte'],
);
}
} else { // Recherche par dirigeant
$findMe4=trim(substr($findMe,0,4));
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne dirigeant
/*$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
"d.dateEffet, d.fonction, d.depart, e.actif",
"d.id=$doc AND d.id=b.id AND b.siren=e.siren AND (d.nom LIKE '%$findMe4%' OR d.prenom LIKE '%$findMe4%' OR d.nomUsage LIKE '%$findMe4%' OR d.rs LIKE '%$findMe4%') LIMIT 0,1", true);
if (count($listeEtab)==0)
$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
"d.dateEffet, d.fonction, d.depart, e.actif",
"d.id=$doc AND d.id=b.id AND b.siren=e.siren LIMIT 0,1", true);
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
'NafEnt'=>$etab['ape_entrep'], // Entreprise
'rs'=>$etab['rs'],
'nomD'=>$etab['nom'],
'prenom'=>$etab['prenom'],
'nomUsage'=>$etab['nomUsage'],
'dateEffet'=>$etab['dateEffet'],
'fonction'=>$etab['fonction'],
'depart'=>$etab['depart'],
);
}
*/
//print_r($tabRet);
//die();
$listeEtab=$iDb->select('rncs_dirigeants d, etablissements e',
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
"CONCAT(e.siren, e.nic) as siret, /*d.rs,*/ d.nom, d.prenom, /*d.nomUsage,*/ d.naissance_date, d.naissance_lieu, ".
"d.fonction_lib, /*d.depart,*/ e.actif",
"d.id=$doc AND d.siren=e.siren AND e.siege=1 ORDER BY e.actif DESC LIMIT 0,1", true);
//die(print_r($listeEtab));
$etab=$listeEtab[0];
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
'id'=>$doc,
'Pertinence'=>$docinfo['weight'],
'Siret'=>$etab['siret'],
'Siege'=>$etab['siege'],
'Nom'=>$etab['raisonSociale'],
'Sigle'=>$etab['sigle'],
'Enseigne'=>$etab['enseigne'],
'Adresse'=>trim($etab['adr_num'] .' '.
$etab['adr_btq'] .' '.
$etab['adr_typeVoie'] .' '.
$etab['adr_libVoie'] .' '.
$etab['adr_comp']),
'CP'=>$etab['adr_cp'],
'Ville'=>$etab['adr_ville'],
'Tel'=>$etab['tel'],
'Fax'=>$etab['fax'],
'FJ'=>$etab['cj'],
'Siren'=>$etab['siren'],
'Nic'=>$etab['nic'],
'Actif'=>$etab['actif'],
'NafEtab'=>$etab['ape_etab'], // Etablissement
'NafEnt'=>$etab['ape_entrep'], // Entreprise
'rs'=>'',//$etab['rs'],
'nomD'=>$etab['nom'],
'prenom'=>$etab['prenom'],
'nomUsage'=>'',//$etab['nomUsage'],
'dateEffet'=>'',//$etab['dateEffet'],
'fonction'=>$etab['fonction_lib'],
'depart'=>0,//$etab['depart'],
);
}
}
}
}
debugLog('I','Search Sphinx : Retourne '. $res[total].'/'. $res[total_found] .' en '.$res[time] .'secondes',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
return array( 'results'=>$tabRet,
'nbRet'=>$res[total],
'nbTot'=>$res[total_found],
'duration'=>$res[time],
'words'=>$res['words'],
);
}
/*
<nafen>7020z<
*/
function comptage($findMe, $tabFiltres=array(), $deb=0, $nbRep=20, $max=1000, $any=false, $fichierCsv=false) {
$deb=$deb*1;
$nbRep=$nbRep*1;
$max=$max*1;
$index='comptage';
$iDb=new WDB();
/*
$cl = new SphinxClient ();
$cl->SetServer ( $host, $port );
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $mode );
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
$res = $cl->Query ( $q, $index );
*/
$cl = new SphinxClient ();
$cl->SetServer ('192.168.3.24', 3312);
$cl->SetConnectTimeout(1);
$cl->SetLimits ($deb, $nbRep, $max);
// if (substr($index,0,4)=='etab')
// $cl->SetSortMode(SPH_SORT_EXTENDED, 'rang DESC, actif DESC, siege DESC');//, nic DESC
//$cl->SetWeights ( array ( 100, 1 ) );
//$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
$cl->SetMatchMode (SPH_MATCH_EXTENDED);
foreach ($tabFiltres as $nomFiltre => $valFiltre)
$cl->SetFilter($nomFiltre, $valFiltre);
/*8.4.3. SetFilterRange
Prototype: function SetFilterRange ( $attribute, $min, $max, $exclude=false )
Adds new integer range filter. */
$cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );
//$cl->SetArrayResult ( true );
$res = $cl->Query ( $findMe, $index );
if ($res===false) {
// debugLog('I',"Search Sphinx : Pas de réponse pour $findMe avec ".implode(',',$tabFiltres).' ('.$cl->GetLastError() .')',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
return array( 'results'=>false,
'nbRet'=>0,
'nbTot'=>0,
'error'=>$cl->GetLastError(),
'warning'=>$cl->GetLastWarning(),
'durationCpt'=>$res[time],
'durationExp'=>0);//return false;);//return false;
} else { // Le moteur est opérationel
$tdeb=microtime(1);
if ( $cl->GetLastWarning() ) {
//debugLog('I',"Search Sphinx : Warning pour $findMe - ".$cl->GetLastWarning(),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
}
$tabRet=array();
if ( @is_array($res['matches'])) { // il y a des données à renvoyer
$tabIdDoc=array();
foreach ( $res['matches'] as $doc => $docinfo ) //{ // On balaye chaque ligne
$tabIdDoc[]=$doc;
$strDoc='('.implode(',',$tabIdDoc).')';
$tabTmp=$iDb->select( 'etablissements_act',
'id,ape_etab,ape_entrep,source,siren,nic,actif,siege,adr_cp,adr_dep,adr_com,tel,fax,cj,capital,age_entrep,age_etab,tca,tcaexp,teff_entrep,teff_etab,rang,dateCrea_etab,eff_entrep,eff_etab,nbEtab,bilType,bilAnnee,bilTca,bilCA,bilCAexp,bilRN',
"id IN $strDoc", false, MYSQL_ASSOC);
if ($fichierCsv) {
$fp=fopen($fichierCsv, 'w');
foreach ($tabTmp as $iTmp=>$tmp) {
$tabRet[]=$tmp;
fwrite($fp, implode("\t", $tmp).EOL);
}
fclose($fp);
}
}
}
return array( 'results'=>$tabRet,
'nbRet'=>$res[total],
'nbTot'=>$res[total_found],
'durationCpt'=>$res[time],
'durationExp'=>round(microtime(1)-$tdeb,3),
'error'=>$cl->GetLastError(),
'warning'=>$cl->GetLastWarning(),
'words'=>$res['words'],
);
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,187 @@
<?
if (!isset($_REQUEST['typeRecherche']) || ( $_REQUEST['typeRecherche']<>'exacte' &&
$_REQUEST['typeRecherche']<>'approx') )
$_REQUEST['typeRecherche']='exacte';
if (!isset($_REQUEST['nbRep']) || $_REQUEST['nbRep']<25 || $_REQUEST['nbRep']>200 )
$_REQUEST['nbRep']=25;
if (!isset($_REQUEST['nom'])) $_REQUEST['nom']='';
if (!isset($_REQUEST['prenom'])) $_REQUEST['prenom']='';
if (!isset($_REQUEST['codePostal'])) $_REQUEST['codePostal']='';
?>
<form action="./?action=rechercher" method="POST">
<input type="hidden" name="submitted" value="1">
<table>
<tr><td><i>Informations sur la personne</i></td><td>&nbsp;</td></tr>
<tr><td><b>NOM *</b></td><td><input type="text" name="nom" value="<?=$_REQUEST['nom']?>"></td></tr>
<tr><td>Pr&eacute;nom *</td><td><input type="text" name="prenom" value="<?=$_REQUEST['prenom']?>"></td></tr>
<tr><td>D&eacute;partement ou Code Postal de r&eacute;sidence *</td><td><input type="text" name="codePostal" value="<?=$_REQUEST['codePostal']?>"></td></tr>
<tr><td>Civilit&eacute;</td><td><input type="radio" name="civilite" value="Mlle"> Mlle
<input type="radio" name="civilite" value="Mme"> Mme
<input type="radio" name="civilite" value="M"> M</td></tr>
<tr><td>Date de Naissance *</td><td><input type="text" name="naissJJ" size="3" maxlength="2">&nbsp;/&nbsp;<input type="text" name="naissMM" size="3" maxlength="2">&nbsp;/&nbsp;<input type="text" name="naissAA" size="5" maxlength="4"></td></tr>
<tr><td>Ville de Naissance</td><td><input type="text" name="naissVille"></td></tr>
<tr><td>D&eacute;partement de Naissance</td><td><input type="text" name="naissDept"></td></tr>
<tr><td>Pays de Naissance</td><td><input type="text" name="naissPays"></td></tr>
<tr><td>Adresse de r&eacute;sidence *</td><td><input type="text" name="adresse"></td></tr>
<tr><td>Ville de r&eacute;sidence *</td><td><input type="text" name="adresseVille"></td></tr>
<tr><td>Montant du cr&eacute;dit demand&eacute; *</td><td><input type="text" name="creditDemande"></td></tr>
<tr><td>SIREN si entrepreneur individuel</td><td><input type="text" name="siren"></td></tr>
<tr><td>RIB</td><td><input type="text" name="siren"></td></tr>
<tr><td>T&eacute;l&eacute;phone Domicile</td><td><input type="text" name="telephoneMaison">&nbsp;<i>Liste rouge <input type="radio" name="listeRouge" value="Oui"> Oui&nbsp;&nbsp;&nbsp;<input type="radio" name="listeRouge" value="Non"> Non</td></tr>
<tr><td>T&eacute;l&eacute;phone Professionel</td><td><input type="text" name="telephonePro"></td></tr>
<tr><td>T&eacute;l&eacute;phone Portable</td><td><input type="text" name="telephonePort"></td></tr>
<tr><td><i>Informations compl&eacute;mentaires</i></td><td>&nbsp;</td></tr>
<tr><td>Nom de l'employeur</td><td><input type="text" name="employeurNom"></td></tr>
<tr><td>Adresse de l'employeur</td><td><input type="text" name="employeurAdresse"></td></tr>
<tr><td>Code Postal de l'employeur</td><td><input type="text" name="employeurCP"></td></tr>
<tr><td>Ville de l'employeur</td><td><input type="text" name="employeurVille"></td></tr>
<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td>Type de recherche</td><td><input type="radio" <?if ($_REQUEST['typeRecherche']=='exacte') echo 'CHECKED';?> name="typeRecherche" value="exacte">Exacte&nbsp;&nbsp;<input type="radio" <?if ($_REQUEST['typeRecherche']=='approx') echo 'CHECKED';?> name="typeRecherche" value="approx">Approchante</td></tr>
<tr><td>Nombre de r&eacute;sultats</td><td><select name="nbRep"><option value="25">25</option><option value="50">50</option><option value="100">100</option><option value="200">200</option></select></td></tr>
</table>
<input type="submit" value="Valider">&nbsp;&nbsp;&nbsp;<input type="reset" value="RAZ">
</form>
<?php
include_once('/var/www/includes/mysql.php');
$con = mysql_pconnect('localhost', 'root', 'bzh4231*');
if (!($con === false)) {
if (mysql_select_db('npaipp', $con) === false)
die('Could not select database: ' . mysql_error());
}
require ( "sphinxapi.php" );
//die ( "usage: php -f test.php [--any] <word [word [word [...]]]> [--group <group>] [-p <port>] [-i <index>]\n" );
$q = $_REQUEST['nom'].' '.$_REQUEST['prenom'];
$any = false; // si false $index='xxx'
$port = 3312;
if ($_REQUEST['typeRecherche']=='exacte')
$index="annuaire_pp";
else
$index="annuaire_pp_shx";
$nbRep=$_REQUEST['nbRep'];
////////////
// do query
////////////
$cl = new SphinxClient ();
$cl->SetServer ( "localhost", $port );
$cl->SetLimits (0, $nbRep);
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
if ( isset($_REQUEST['codePostal']) && $_REQUEST['codePostal']<>'' ) {
$tailleCP=strlen($_REQUEST['codePostal']);
if ($tailleCP>1 && $tailleCP<4) $cl->SetFilter("departement", array(0=>$_REQUEST['codePostal']));
elseif ($tailleCP==5) $cl->SetFilter("codepostal", array(0=>$_REQUEST['codePostal']));
}
if ( isset($_REQUEST['telephoneMaison']) && $_REQUEST['telephoneMaison']<>'' ) {
$cl->SetFilter("tel", array(0=>$_REQUEST['telephoneMaison']));
}
$res = $cl->Query ( $q, $index );
////////////////
// print me out
////////////////
if ( $res===false )
{
print "Query failed: " . $cl->GetLastError() . ".\n";
} else
{
if ( $cl->GetLastWarning() )
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.<br/>";
print "<h3>Query stats</h3><ul>";
if ( is_array($res["words"]) )
foreach ( $res["words"] as $word => $info )
print "<li>'$word' found $info[hits] times in $info[docs] documents</li>";
print "</ul>";
if ( is_array($res["matches"]) )
{
$n = 1;
print "<h3>Reponses :</h3><ul>";
foreach ( $res["matches"] as $doc => $docinfo )
{
// print "<li>$n. doc_id=$doc, weight=$docinfo[weight]<br/>";
// foreach ( $res["attrs"] as $attrname => $attrtype )
// {
$info=mysql_select('particuliers', 'Nom, Adresse, CodePostal, Ville, Tel, Fax', "id=$doc");
$personne=$info[0];
echo '<li><i>'. $n .'.</i> '. $personne['Nom'] .' ('. $docinfo[weight] .' %)<br/>';
echo $personne['Adresse'] .'<br/>';
echo $personne['CodePostal'] .' '. $personne['Ville'] .'<br/>';
if ($personne['Tel']<>'') echo 'T&eacute;l : '.$personne['Tel'].'<br/>';
if ($personne['Fax']<>'') echo 'Fax : '.$personne['Fax'].'<br/>';
echo "</li>\n";
$n++;
/* $value = $docinfo["attrs"][$attrname];
if ( $attrtype==SPH_ATTR_TIMESTAMP )
$value = date ( "Y-m-d H:i:s", $value );
print ", $attrname=$value";
}
print "</li>";*/
//$n++;
}
print "</ul>";
}
echo '<!--';
print_r($res);
echo '-->';
if ($_POST['submitted']) {
print_r($_POST);
/* Actions à effectuer :
// 1. Vérification de l'existance du NOM, Prénom et Adresse dans Annuaire (/30 points)
1.1. Si NOM+Prénom à l'adresse ==> OK 30 points
1.2. Si NOM sans prénom à l'adresse ==> OK 25 points
1.3. Si quelqu'un dans annuaire à l'adresse 10 points
1.4. Si pas d'adresse 0 point
// Si 1.2 ==> 2
// Si 1.3 ==> 2 + 3
// Si 1.4 ==> 2 + 3 + 4
// 2. Vérifier si le prénom existe dans la table des prénoms (/ 3 points)
2.1. Si le prénom existe OK 2 points
2.2. Sinon valeur approchante 1 point
2.3. Sinon ?????????? 0 point
// 3. Vérifier si le nom existe dans la table des noms (/ 3 points)
1.1. Si le nom existe OK 2 points
1.2. Sinon valeur approchante 1 point
1.3. Sinon 0 point
// 4. Recherche de l'existance de l'adresse / ville (/ 5 points)
2.1. Si adresse complète existe 5 points
2.2. Si adresse sans 3 points
2.3. Si approchant 2 points
2.4. Si ville sans l'adresse 0 point
//10. Vérifier si le prénom est logique avec les l'age moyen des personnes portant ce prénom (/ 3 points)
2.4.1. Si logique OK 2 points
2.4.2. Si approchant 1 point
2.4.3. Sinon 0 point
3.3.1 Vérification dans le pages blanches
// 3. Si un téléphone est communiqué et qu'absence de liste rouge : (30 points)
3.1. Vérifier la concordance NOM, Prénom, Adresse, Téléphonesi OK 30 point
Enregistrer chaque requête
et les informations communqiuées par le client
*/
}
}
?>

View File

@ -0,0 +1,157 @@
<?php
//
// $Id: test.php 1103 2008-01-24 18:42:57Z shodan $
//
require ( "sphinxapi.php" );
//////////////////////
// parse command line
//////////////////////
// for very old PHP versions, like at my home test server
if ( is_array($argv) && !isset($_SERVER["argv"]) )
$_SERVER["argv"] = $argv;
unset ( $_SERVER["argv"][0] );
// build query
if ( !is_array($_SERVER["argv"]) || empty($_SERVER["argv"]) )
{
print ( "Usage: php -f test.php [OPTIONS] query words\n\n" );
print ( "Options are:\n" );
print ( "-h, --host <HOST>\tconnect to searchd at host HOST\n" );
print ( "-p, --port\t\tconnect to searchd at port PORT\n" );
print ( "-i, --index <IDX>\tsearch through index(es) specified by IDX\n" );
print ( "-s, --sortby <CLAUSE>\tsort matches by 'CLAUSE' in sort_extended mode\n" );
print ( "-S, --sortexpr <EXPR>\tsort matches by 'EXPR' DESC in sort_expr mode\n" );
print ( "-a, --any\t\tuse 'match any word' matching mode\n" );
print ( "-b, --boolean\t\tuse 'boolean query' matching mode\n" );
print ( "-e, --extended\t\tuse 'extended query' matching mode\n" );
print ( "-ph,--phrase\t\tuse 'exact phrase' matching mode\n" );
print ( "-f, --filter <ATTR>\tfilter by attribute 'ATTR' (default is 'group_id')\n" );
print ( "-v, --value <VAL>\tadd VAL to allowed 'group_id' values list\n" );
print ( "-g, --groupby <EXPR>\tgroup matches by 'EXPR'\n" );
print ( "-gs,--groupsort <EXPR>\tsort groups by 'EXPR'\n" );
print ( "-d, --distinct <ATTR>\tcount distinct values of 'ATTR''\n" );
print ( "-l, --limit <COUNT>\tretrieve COUNT matches (default: 20)\n" );
exit;
}
$args = array();
foreach ( $_SERVER["argv"] as $arg )
$args[] = $arg;
$q = "";
$mode = SPH_MATCH_ALL;
$host = "localhost";
$port = 3312;
$index = "*";
$groupby = "";
$groupsort = "@group desc";
$filter = "group_id";
$filtervals = array();
$distinct = "";
$sortby = "";
$limit = 20;
$ranker = SPH_RANK_PROXIMITY_BM25;
for ( $i=0; $i<count($args); $i++ )
{
$arg = $args[$i];
if ( $arg=="-h" || $arg=="--host" ) $host = $args[++$i];
else if ( $arg=="-p" || $arg=="--port" ) $port = (int)$args[++$i];
else if ( $arg=="-i" || $arg=="--index" ) $index = $args[++$i];
else if ( $arg=="-s" || $arg=="--sortby" ) { $sortby = $args[++$i]; $sortexpr = ""; }
else if ( $arg=="-S" || $arg=="--sortexpr" ) { $sortexpr = $args[++$i]; $sortby = ""; }
else if ( $arg=="-a" || $arg=="--any" ) $mode = SPH_MATCH_ANY;
else if ( $arg=="-b" || $arg=="--boolean" ) $mode = SPH_MATCH_BOOLEAN;
else if ( $arg=="-e" || $arg=="--extended" ) $mode = SPH_MATCH_EXTENDED;
else if ( $arg=="-e2" ) $mode = SPH_MATCH_EXTENDED2;
else if ( $arg=="-ph"|| $arg=="--phrase" ) $mode = SPH_MATCH_PHRASE;
else if ( $arg=="-f" || $arg=="--filter" ) $filter = $args[++$i];
else if ( $arg=="-v" || $arg=="--value" ) $filtervals[] = $args[++$i];
else if ( $arg=="-g" || $arg=="--groupby" ) $groupby = $args[++$i];
else if ( $arg=="-gs"|| $arg=="--groupsort" ) $groupsort = $args[++$i];
else if ( $arg=="-d" || $arg=="--distinct" ) $distinct = $args[++$i];
else if ( $arg=="-l" || $arg=="--limit" ) $limit = (int)$args[++$i];
else if ( $arg=="-r" )
{
$arg = strtolower($args[++$i]);
if ( $arg=="bm25" ) $ranker = SPH_RANK_BM25;
if ( $arg=="none" ) $ranker = SPH_RANK_NONE;
if ( $arg=="wordcount" )$ranker = SPH_RANK_WORDCOUNT;
}
else
$q .= $args[$i] . " ";
}
////////////
// do query
////////////
$cl = new SphinxClient ();
$cl->SetServer ( $host, $port );
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $mode );
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
$cl->SetRankingMode ( $ranker );
$cl->SetArrayResult ( true );
$res = $cl->Query ( $q, $index );
////////////////
// print me out
////////////////
if ( $res===false )
{
print "Query failed: " . $cl->GetLastError() . ".\n";
} else
{
if ( $cl->GetLastWarning() )
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
print "Query stats:\n";
if ( is_array($res["words"]) )
foreach ( $res["words"] as $word => $info )
print " '$word' found $info[hits] times in $info[docs] documents\n";
print "\n";
if ( is_array($res["matches"]) )
{
$n = 1;
print "Matches:\n";
foreach ( $res["matches"] as $docinfo )
{
print "$n. doc_id=$docinfo[id], weight=$docinfo[weight]";
foreach ( $res["attrs"] as $attrname => $attrtype )
{
$value = $docinfo["attrs"][$attrname];
if ( $attrtype & SPH_ATTR_MULTI )
{
$value = "(" . join ( ",", $value ) .")";
} else
{
if ( $attrtype==SPH_ATTR_TIMESTAMP )
$value = date ( "Y-m-d H:i:s", $value );
}
print ", $attrname=$value";
}
print "\n";
$n++;
}
}
}
//
// $Id: test.php 1103 2008-01-24 18:42:57Z shodan $
//
?>

View File

@ -0,0 +1,53 @@
<?php
//
// $Id: test2.php 910 2007-11-16 11:43:46Z shodan $
//
require ( "sphinxapi.php" );
$docs = array
(
"this is my test text to be highlighted, and for the sake of the testing we need to pump its length somewhat",
"another test text to be highlighted, below limit",
"test number three, without phrase match",
"final test, not only without phrase match, but also above limit and with swapped phrase text test as well",
);
$words = "test text";
$index = "test1";
$opts = array
(
"before_match" => "<b>",
"after_match" => "</b>",
"chunk_separator" => " ... ",
"limit" => 60,
"around" => 3,
);
foreach ( array(0,1) as $exact )
{
$opts["exact_phrase"] = $exact;
print "exact_phrase=$exact\n";
$cl = new SphinxClient ();
$res = $cl->BuildExcerpts ( $docs, $index, $words, $opts );
if ( !$res )
{
die ( "ERROR: " . $cl->GetLastError() . ".\n" );
} else
{
$n = 0;
foreach ( $res as $entry )
{
$n++;
print "n=$n, res=$entry\n";
}
print "\n";
}
}
//
// $Id: test2.php 910 2007-11-16 11:43:46Z shodan $
//
?>

View File

@ -0,0 +1,44 @@
<?php
//
// $Id: test2.php,v 1.4 2006/11/26 12:24:21 shodan Exp $
//
require ( "sphinxapi.php" );
$docs = array
(
"this is my test text to be highlighted",
"this is another test text to be highlighted",
);
$words = "test text";
$index = "test1";
$opts = array
(
"before_match" => "<b>",
"after_match" => "</b>",
"chunk_separator" => " ... ",
"limit" => 400,
"around" => 15
);
$cl = new SphinxClient ();
$res = $cl->BuildExcerpts ( $docs, $index, $words, $opts );
if ( !$res )
{
die ( "ERROR: " . $cl->GetLastError() . ".\n" );
} else
{
foreach ( $res as $entry )
{
$n++;
print "n=$n, res=$entry\n";
}
}
//
// $Id: test2.php,v 1.4 2006/11/26 12:24:21 shodan Exp $
//
?>

View File

@ -0,0 +1,108 @@
#!/usr/bin/php -q
<?php
//
// $Id: test.php,v 1.12 2006/11/26 12:24:21 shodan Exp $
//
require ( "sphinxapi.php" );
//////////////////////
// parse command line
//////////////////////
// for very old PHP versions, like at my home test server
if ( is_array($argv) && !isset($_SERVER["argv"]) )
$_SERVER["argv"] = $argv;
unset ( $_SERVER["argv"][0] );
// build query
if ( !is_array($_SERVER["argv"]) || empty($_SERVER["argv"]) )
die ( "usage: php -f test.php [--any] <word [word [word [...]]]> [--group <group>] [-p <port>] [-i <index>]\n" );
$args = array();
foreach ( $_SERVER["argv"] as $arg )
$args[] = $arg;
$q = "";
$any = false;
$groups = array();
$port = 3312;
$index = "*";
for ( $i=0; $i<count($args); $i++ )
{
if ( $args[$i]=="--any" )
{
$any = true;
} else if ( $args[$i]=="--group" )
{
$groups[] = (int)$args[++$i];
} else if ( $args[$i]=="-p" )
{
$port = (int)$args[++$i];
} else if ( $args[$i]=="-i" )
{
$index = $args[++$i];
} else
{
$q .= $args[$i] . " ";
}
}
////////////
// do query
////////////
$cl = new SphinxClient ();
$cl->SetServer ( "localhost", $port );
$cl->SetWeights ( array ( 100, 1 ) );
$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
if ( count($groups) )
$cl->SetFilter ( "group_id", $groups );
$res = $cl->Query ( $q, $index );
////////////////
// print me out
////////////////
if ( $res===false )
{
print "Query failed: " . $cl->GetLastError() . ".\n";
} else
{
if ( $cl->GetLastWarning() )
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
print "Query stats:\n";
if ( is_array($res["words"]) )
foreach ( $res["words"] as $word => $info )
print " '$word' found $info[hits] times in $info[docs] documents\n";
print "\n";
if ( is_array($res["matches"]) )
{
$n = 1;
print "Matches:\n";
foreach ( $res["matches"] as $doc => $docinfo )
{
print "$n. doc_id=$doc, weight=$docinfo[weight]";
foreach ( $res["attrs"] as $attrname => $attrtype )
{
$value = $docinfo["attrs"][$attrname];
if ( $attrtype==SPH_ATTR_TIMESTAMP )
$value = date ( "Y-m-d H:i:s", $value );
print ", $attrname=$value";
}
print "\n";
$n++;
}
}
}
//
// $Id: test.php,v 1.12 2006/11/26 12:24:21 shodan Exp $
//
?>

20
html/afnic/.htaccess Normal file
View File

@ -0,0 +1,20 @@
#php_value include_path ".:/var/www/framework:/var/www/site_extranet/includes:/usr/share/php"
php_value auto_prepend_file "/var/www/includes/auto_prepend.php"
#php_value auto_append_file "/var/www/site_extranet/config/append.php"
#ErrorDocument 400 /error.php?errtyp=400
#ErrorDocument 401 /error.php?errtyp=401
#ErrorDocument 402 /error.php?errtyp=402
#ErrorDocument 403 /error.php?errtyp=403
#ErrorDocument 404 /error.php?errtyp=404
#ErrorDocument 500 /error.php?errtyp=500
#ErrorDocument 501 /error.php?errtyp=501
#ErrorDocument 502 /error.php?errtyp=502
#Options +FollowSymlinks
RewriteEngine on
#RewriteRule ^(.*).htm$ http://www2.scores-decisions.com/index.php?page=$1 [nc]
#RewriteRule !(index\.php|test\.php|^documents/pdf/courriers(.*)|\.html|\.htm|\.gif|\.css|\.jpg|\.png|\.jar|\.js|\.ico|\.pdf)$ /index.php [L]
#RewriteRule ^img/(.*) /img/$1 [L]
#RewriteRule ^js/(.*) /scripts/$1 [L]
#RewriteRule ^css/(.*) /design/stylesheets/$1 [L]
#RewriteRule ^etatspdf/(.*) /documents/pdf/etats/$1 [L]
#RewriteRule ^(.*)\.htm$ /html/$1.html [L]

753
html/afnic/WsEntreprise.php Normal file
View File

@ -0,0 +1,753 @@
<?php
ini_set('soap.wsdl_cache_enabled', 0);
include_once(INCLUDE_PATH.'insee/classMInsee.php');
include_once(INCLUDE_PATH.'insee/classMSirene.php');
include_once(INCLUDE_PATH.'partenaires/classMBilans.php');
include_once(INCLUDE_PATH.'partenaires/classMBourse.php');
include_once(INCLUDE_PATH.'partenaires/classMLiens.php');
include_once(INCLUDE_PATH.'scores/classMFinancier.php');
include_once(INCLUDE_PATH.'scores/classMSolvabilite.php');
include_once(INCLUDE_PATH.'partenaires/classMTva.php');
include_once(INCLUDE_PATH.'partenaires/classMGreffes.php');
include_once(FWK_PATH.'mail/sendMail.php');
class WsEntreprise {
var $iInsee;
/** Constructeur de la classe
** @nodoc
**/
function __construct(){
$this->iInsee=new MInsee();
}
/** Obtention automatique d'un nouveau login pour un client
** @nodoc
**/
function getNextLogin($login) {
global $iDbCrm;
global $tabInfoUser;
if ($tabInfoUser['profil']=='Administrateur') {
/** Un administrateur veut créer un nouveau login **/
$rep=$iDbCrm->select('utilisateurs u, clients c', 'u.idClient, c.racineLogin', "u.login='$login' AND u.idClient=c.id");
$racine=$rep[0]['racineLogin'];
$idClient=$rep[0]['idClient'];
$rep=$iDbCrm->select('utilisateurs', 'login, length(login) as taille', "login like '$racine%' group by login order by taille desc, login desc LIMIT 0,1");
if (count($rep)==0) $racine.='1';
else {
$last_i=preg_replace("/\D/", '',$rep[0]['login'])*1;
$racine.=$last_i+1;
}
return array('error'=>array('errnum'=>$errnum, 'errmsg'=>$errmsg), 'result'=>array('racine'=>$racine, 'idClient'=>$idClient));
}
}
/** Récupère les informations du profil connecté
** @nodoc
**/
function getInfosLogin($login, $ipUtilisateur) {
global $iDbCrm;
global $tabInfoUser;
if ($tabInfoUser['login']<>$login && $tabInfoUser['profil']=='Administrateur') {
/** Un administrateur veut il des infos sur un login ? **/
$rep=$iDbCrm->select('utilisateurs', 'login, id, email, password, idClient, typeCompte, actif, filtre_ip, civilite, nom, prenom, tel, fax, mobile, profil, raisonSociale, siret, adrNum, adrIndRep, adrTypeVoie, adrLibVoie, adrCp, adrVille, adrComp, tel, fax, mobile, pref, profil, dateInscription, dateValidation, nombreConnexions, dateDerniereConnexion, droits, referenceParDefaut, nbReponses, formatMail, dateDebutCompte, dateFinCompte, maxFicheId', "login='$login' AND deleted=0", true, MYSQL_ASSOC);
$tabRep=$rep[0];
if (count($rep)>0) {
$rep=array('login'=> $login,
'id'=> $tabRep['id'],
'email'=> $tabRep['email'],
'typeCompte'=> $tabRep['typeCompte'],
'idClient'=> $tabRep['idClient'],
'filtre_ip'=> $tabRep['filtre_ip'],
'civilite'=> $tabRep['civilite'],
'nom'=> prepareString($tabRep['nom']),
'prenom'=> prepareString($tabRep['prenom']),
'raisonSociale'=> prepareString($tabRep['raisonSociale']),
'siret'=> $tabRep['siret'],
'adrNum'=> $tabRep['adrNum'],
'adrIndRep'=> $tabRep['adrIndRep'],
'adrTypeVoie'=> $tabRep['adrTypeVoie'],
'adrLibVoie'=> prepareString($tabRep['adrLibVoie']),
'adrCp'=> $tabRep['adrCp'],
'adrVille'=> prepareString($tabRep['adrVille']),
'adrComp'=> prepareString($tabRep['adrComp']),
'tel'=> $tabRep['tel'],
'fax'=> $tabRep['fax'],
'mobile'=> $tabRep['mobile'],
'pref'=> $tabRep['pref'],
'profil'=> prepareString($tabRep['profil']),
'dateInscription'=> $tabRep['dateInscription'],
'dateValidation'=> $tabRep['dateValidation'],
'nombreConnexions'=> $tabRep['nombreConnexions'],
'dateDerniereConnexion'=> $tabRep['dateDerniereConnexion'],
'droits'=> $tabRep['droits'],
'nbReponses'=> $tabRep['nbReponses'],
'formatMail'=> $tabRep['formatMail'],
'reference'=> $tabRep['referenceParDefaut'],
'dateDebutCompte'=> $tabRep['dateDebutCompte'],
'dateFinCompte'=> $tabRep['dateFinCompte'],
'maxFicheId'=> $tabRep['maxFicheId'],
);
}
return array('error'=>array('errnum'=>$errnum, 'errmsg'=>$errmsg), 'result'=>$rep);
}
$connected=false;
$tabIpAllowed=explode(';', trim($tabInfoUser['filtre_ip']));
if (count($tabIpAllowed)==1 && $tabIpAllowed[0]=='')
$tabIpAllowed=array();
//debugLog('I',"getInfosLogin : \$tabIpAllowed : ".print_r($tabIpAllowed,true),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
foreach ($tabIpAllowed as $ip) {
if (preg_match('/^'.str_replace('*','.*',str_replace('.','\.',$ip)).'$/', $ipUtilisateur) )
$connected=true;
}
if (count($tabIpAllowed)==0) $connected=true;
elseif (!$connected) {
$errnum=10818;
$errmsg='Adresse IP non declaree pour ce compte. Contactez votre administrateur !';
}
$rep=array( 'connected'=> $connected,
'login'=> $tabInfoUser['login'],
'id'=> $tabInfoUser['id'],
'idClient'=> $tabInfoUser['idClient'],
'email'=> $tabInfoUser['email'],
'typeCompte'=> $tabInfoUser['typeCompte'],
'filtre_ip'=> $tabInfoUser['filtre_ip'],
'ipPasserelle'=> $tabInfoUser['ipConnexion'],
'ipConnexion'=> $ipUtilisateur,
'civilite'=> $tabInfoUser['civilite'],
'nom'=> prepareString($tabInfoUser['nom']),
'prenom'=> prepareString($tabInfoUser['prenom']),
'raisonSociale'=> prepareString($tabInfoUser['raisonSociale']),
'siret'=> $tabInfoUser['siret'],
'adrNum'=> $tabInfoUser['adrNum'],
'adrIndRep'=> $tabInfoUser['adrIndRep'],
'adrTypeVoie'=> $tabInfoUser['adrTypeVoie'],
'adrLibVoie'=> prepareString($tabInfoUser['adrLibVoie']),
'adrCp'=> $tabInfoUser['adrCp'],
'adrVille'=> prepareString($tabInfoUser['adrVille']),
'adrComp'=> prepareString($tabInfoUser['adrComp']),
'tel'=> $tabInfoUser['tel'],
'fax'=> $tabInfoUser['fax'],
'mobile'=> $tabInfoUser['mobile'],
'pref'=> $tabInfoUser['pref'],
'profil'=> prepareString($tabInfoUser['profil']),
'dateInscription'=> $tabInfoUser['dateInscription'],
'dateValidation'=> $tabInfoUser['dateValidation'],
'nombreConnexions'=> $tabInfoUser['nombreConnexions'],
'dateDerniereConnexion'=> $tabInfoUser['dateDerniereConnexion'],
'droits'=> $tabInfoUser['droits'],
'nbReponses'=> $tabInfoUser['nbReponses'],
'formatMail'=> $tabInfoUser['formatMail'],
'reference'=> $tabInfoUser['referenceParDefaut'],
'dateDebutCompte'=> $tabInfoUser['dateDebutCompte'],
'dateFinCompte'=> $tabInfoUser['dateFinCompte'],
'maxFicheId'=> $tabInfoUser['maxFicheId'],
);
return array('error'=>array('errnum'=>$errnum, 'errmsg'=>$errmsg), 'result'=>$rep);
}
/** Récupère les informations du profil connecté
** @nodoc
**/
function getListeUtilisateurs($login, $idClient=0) {
global $iDbCrm;
global $tabInfoUser;
if ($tabInfoUser['profil']<>'Administrateur')
return array('error'=>array('errnum'=>987684351, 'errmsg'=>'Profil non administrateur'), 'result'=>array());
$rep=$iDbCrm->select('utilisateurs', 'idClient', "login='$login'");
$idClient=$rep[0][0];
if ($idClient==0)
return array('error'=>array('errnum'=>98684351, 'errmsg'=>'idClient=0'), 'result'=>$rep);
$rep=$iDbCrm->select('utilisateurs', 'id, idClient, login, email, actif, nom, prenom', "idClient='$idClient' AND deleted=0 ORDER BY login ASC", true, MYSQL_ASSOC);
$tabRet=array();
foreach ($rep as $uti)
$tabRet[]=array( 'idUti'=>$uti['id'],
'idClient'=>$uti['idClient'],
'login'=>$uti['login'],
'email'=>$uti['email'],
'actif'=>$uti['actif'],
'nom'=>prepareString($uti['nom']),
'prenom'=>prepareString($uti['prenom']),
);
return array('error'=>array('errnum'=>$errnum, 'errmsg'=>$errmsg), 'results'=>$tabRet);
}
/** Mise à jour des informations du profil connecté
** @nodoc
**/
function setInfosLogin($login, $tabInfoUserWS) {
global $iDbCrm;
global $tabInfoUser;
if ($tabInfoUserWS['delete']==1 && $tabInfoUser['profil']=='Administrateur')
$tabUpdate=array('deleted'=>1);
elseif (isset($tabInfoUserWS['actif']) && $tabInfoUserWS['actif']==0 && $tabInfoUser['profil']=='Administrateur')
$tabUpdate=array('actif'=>0);
elseif (isset($tabInfoUserWS['actif']) && $tabInfoUserWS['actif']==1 && $tabInfoUser['profil']=='Administrateur')
$tabUpdate=array('actif'=>1);
else {
$strPrefs=@implode(' ',$tabInfoUserWS['pref']);
$strDroits=@implode(' ',$tabInfoUserWS['droits']);
$tabUpdate=array();
if (isset($tabInfoUserWS['email'])) $tabUpdate['email']=stripslashes($tabInfoUserWS['email']);
if (isset($tabInfoUserWS['tel_fix'])) $tabUpdate['tel']=stripslashes($tabInfoUserWS['tel_fix']);
if (isset($tabInfoUserWS['tel_fax'])) $tabUpdate['fax']=stripslashes($tabInfoUserWS['tel_fax']);
if (isset($tabInfoUserWS['tel_mob'])) $tabUpdate['mobile']=stripslashes($tabInfoUserWS['tel_mob']);
if (isset($tabInfoUserWS['rech_nbrep'])) $tabUpdate['nbReponses']=$tabInfoUserWS['rech_nbrep'];
if (isset($tabInfoUserWS['formatMail'])) $tabUpdate['formatMail']=$tabInfoUserWS['formatMail'];
if (isset($tabInfoUserWS['pref'])) $tabUpdate['pref']=$strPrefs;
if (isset($tabInfoUserWS['changepwd']) && $tabInfoUserWS['changepwd']==1 &&
isset($tabInfoUserWS['password']) && trim($tabInfoUserWS['password'])<>'')
$tabUpdate['password']=stripslashes($tabInfoUserWS['password']);
if ($tabInfoUser['profil']=='Administrateur') {
$tabUpdate['droits']=$strDroits;
if (isset($tabInfoUserWS['nom'])) $tabUpdate['nom']=stripslashes($tabInfoUserWS['nom']);
if (isset($tabInfoUserWS['prenom'])) $tabUpdate['prenom']=stripslashes($tabInfoUserWS['prenom']);
if (isset($tabInfoUserWS['reference'])) $tabUpdate['referenceParDefaut']=stripslashes($tabInfoUserWS['reference']);
}
}
if ($tabInfoUserWS['action']=='new') {
$tabUpdate['login']=$login;
$tabUpdate['idClient']=$tabInfoUserWS['idClient'];
if ($iDbCrm->insert('utilisateurs', $tabUpdate))
return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'result'=>1);
else
return array('error'=>array('errnum'=>76841, 'errmsg'=>'Création impossible'), 'result'=>0);
}
if ($iDbCrm->update('utilisateurs', $tabUpdate, "login='$login'"))
return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'result'=>1);
else
return array('error'=>array('errnum'=>76840, 'errmsg'=>'Mise a jour impossible'), 'result'=>0);
/*
[rech_limites] => Array
(
[0] => assocs
[1] => actifs
[2] => radies
[3] => sieges
)
'typeCompte'=> $tabRep['typeCompte'],
'filtre_ip'=> $tabRep['filtre_ip'],
'civilite'=> $tabRep['civilite'],
'raisonSociale'=> $tabRep['raisonSociale'],
'siret'=> $tabRep['siret'],
'adrNum'=> $tabRep['adrNum'],
'adrIndRep'=> $tabRep['adrIndRep'],
'adrTypeVoie'=> $tabRep['adrTypeVoie'],
'adrLibVoie'=> $tabRep['adrLibVoie'],
'adrCp'=> $tabRep['adrCp'],
'adrVille'=> $tabRep['adrVille'],
'adrComp'=> $tabRep['adrComp'],
'profil'=> $tabRep['profil'],
'dateInscription'=> $tabRep['dateInscription'],
'dateValidation'=> $tabRep['dateValidation'],
'nombreConnexions'=> $tabRep['nombreConnexions'],
'dateDerniereConnexion'=> $tabRep['dateDerniereConnexion'],
'droits'=> $tabRep['droits'],
'referenceParDefaut'=> $tabRep['referenceParDefaut'],
'dateDebutCompte'=> $tabRep['dateDebutCompte'],
'dateFinCompte'=> $tabRep['dateFinCompte'],
'maxFicheId'=> $tabRep['maxFicheId'],
*/
}
/** Recherche d'une entreprise ou d'un établissement par sa raison sociale, son enseigne, son sigle, son adresse .
** @nodoc
** @param string $raisonSociale Raison Sociale ou Enseigne ou Sigle
** @param string $adresse Adresse de l'entreprise, du type : 3 rue des Plantes
** @param string $codePostal Code postal (ex: 75014)
** @param string $ville Ville
** @param bool $siege Limitation de la recherche au sièges (si true)
** @param bool $actif Limitation aux établissements actifs (si true)
** @param integer $deb Position du curseur dans la liste des réponses (0 par défaut)
** @param integer $nbRep Nombre de réponses retournées au maximum par cette requete (20 par défaut)
** @param integer $maxRep Nombre de réponses recherchées au maximum (200 par défaut)
** @param bool $pertinence Recherche orthographique stricte sur le nom, l'adresse et la ville (si true)
** @param bool $avecSiren Ne proposer que les entités sirénées
** @return Tableau d'entreprises ou d'établissements
**/
function searchNomAdr($raisonSociale, $adresse='', $codePostal='', $ville='', $siege='', $actif='', $deb=0, $nbRep=20, $maxRep=200, $pertinence=false, $avecSiren=false, $ape_etab='') {
debugLog('I',"Recherche Entreprise de $raisonSociale, $adresse, $codePostal $ville (Siège=$siege / Max Rep=$nbRep)",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$etabs=$this->iInsee->rechercheEtab($raisonSociale, $adresse, $codePostal, $ville, $siege, $actif, $deb, $nbRep, $maxRep, $pertinence, $avecSiren, $ape_etab);
$tabRet2=array();
foreach ($etabs['reponses'] as $etab)
$tabRet2[]=array( 'id'=>$etab['id'],
'Pertinence'=>$etab['Pertinence'],
'Siret'=>$etab['Siret'],
'Siege'=>$etab['Siege'],
'Nom'=>prepareString(strtr($etab['Nom'],'/*',' ')),
'Nom2'=>prepareString($etab['Nom2']),
'Sigle'=>prepareString($etab['Sigle']),
'Enseigne'=>prepareString($etab['Enseigne']),
'Adresse'=>prepareString($etab['Adresse']),
'CP'=>$etab['CP'],
'Ville'=>prepareString($etab['Ville']),
'Tel'=>$etab['Tel'],
'Fax'=>$etab['Fax'],
'FJ'=>$etab['FJ'],
'FJLib'=>prepareString($etab['FJLib']),
'Siren'=>$etab['Siren'],
'Nic'=>$etab['Nic'],
'Actif'=>$etab['Actif'],
'NafEtab'=>$etab['NafEtab'], // Etablissement
'NafEtabLib'=>prepareString($etab['NafEtabLib']), // Etablissement
'NafEnt'=>$etab['NafEnt'], // Entreprise
'NafEntLib'=>prepareString($etab['NafEntLib']),
);
$tabRet=$etabs;
$tabRet['reponses']=$tabRet2;
if ($tabRet['nbReponses']==0) {
debugLog('W', "Aucun résultat pour cette recherche !", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>100, 'errmsg'=>'Pas de reponse'), 'results'=>$tabRet);
}
else return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'results'=>$tabRet);
}
/** Recherche d'entreprise ou d'établissement par leur identifiant SIREN ou SIRET
** @nodoc
** @param integer $siret Siren ou Siret de l'entreprise ou de l'établissement sur 9 ou 14 chiffres significatifs
** @param integer $deb Position du curseur dans la liste des réponses (0 par défaut)
** @param integer $nbRep Nombre de réponses retournées au maximum par cette requete (20 par défaut)
** @param integer $maxRep Nombre de réponses recherchées au maximum (200 par défaut)
** @param integer $dep Département
** @return Liste d'établissements
**/
function searchSiren($siret, $deb=0, $nbRep=20, $maxRep=200, $dep=0) {
$tabRet=array();
debugLog('I',"Recherche par Siret de $siret (dep=$dep) avec un maximum de $maxRep réponses pour la tranche $deb à $nbRep",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
if (strlen($siret)==14) $nic=substr(''.$siret,9,5);
elseif (strlen($siret)== 9) $nic='';
else {
debugLog('W', "Siren/Siret $siret incorrect", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren Siret inexistant'), 'results'=>$tabRet);
}
$siren=substr(''.$siret,0,9);
$rep=$this->iInsee->getEtablissements($siren, $nic, $deb, $nbRep, $maxRep, $dep);
$etabs=$rep['reponses'];
foreach ($etabs as $nb=>$etab) {
$tabRet[]=array( 'id' => $etab['id'],
'Pertinence'=> $etab['Pertinence'],
'Siret' => $etab['Siret'],
'Siege' => $etab['Siege'],
'Nom' => prepareString(strtr($etab['Nom'],'/*',' ')),
'Nom2' => prepareString($etab['Nom2']),
'Sigle' => prepareString($etab['Sigle']),
'Enseigne' => prepareString($etab['Enseigne']),
'Adresse' => prepareString($etab['Adresse']),
'Adresse2' => prepareString($etab['Adresse2']),
'CP' => $etab['CP'],
'Ville' => prepareString($etab['Ville']),
'Tel' => $etab['Tel'],
'Fax' => $etab['Fax'],
'FJ' => $etab['FJ'],
'FJLib' => prepareString($etab['FJLib']),
'Siren' => $etab['Siren'],
'Nic' => $etab['Nic'],
'Actif' => $etab['Actif'],
'NafEtab' => $etab['NafEtab'], // Etablissement
'NafEtabLib'=> prepareString($etab['NafEtabLib']), // Etablissement
'NafEnt' => $etab['NafEnt'], // Entreprise
'NafEntLib' => prepareString($etab['NafEntLib']),
);
}
$rep['reponses']=$tabRet;
/** Si le siren est valide, on part chez Infogreffe **/
if (count($tabRet)==0 && $this->iInsee->valideSiren($siren)) {
$iGeffes=new MGreffes();
$etab=$iGeffes->getIdentite($siren);
if ($etab) {
$tabRet[]=array( 'id' => $etab['id'],
'Pertinence'=> $etab['Pertinence'],
'Siret' => $etab['Siret'],
'Siege' => $etab['Siege'],
'Nom' => prepareString($etab['Nom']),
'Nom2' => prepareString($etab['Nom2']),
'Sigle' => prepareString($etab['Sigle']),
'Enseigne' => prepareString($etab['Enseigne']),
'Adresse' => prepareString($etab['Adresse']),
'Adresse2' => prepareString($etab['Adresse2']),
'CP' => $etab['CP'],
'Ville' => prepareString($etab['Ville']),
'Tel' => $etab['Tel'],
'Fax' => $etab['Fax'],
'FJ' => $etab['FJ'],
'FJLib' => prepareString($etab['FJLib']),
'Siren' => $etab['Siren'],
'Nic' => $etab['Nic'],
'Actif' => $etab['Actif'],
'NafEtab' => $etab['NafEtab'],
'NafEtabLib'=> prepareString($etab['NafEtabLib']),
'NafEnt' => $etab['NafEnt'],
'NafEntLib' => prepareString($etab['NafEntLib']),
);
$rep=array( 'criteres'=>array('siren'=>$siren, 'nic'=>$nic, 'dep'=>$dep),
'nbReponses'=>1,
'nbReponsesTotal'=>1,
'reponses'=>$tabRet);
} else
$rep=array( 'criteres'=>array('siren'=>$siren, 'nic'=>$nic, 'dep'=>$dep),
'nbReponses'=>0,
'nbReponsesTotal'=>0,
'reponses'=>array());
}
return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'results'=>$rep);
}
/** Recherche d'entreprise ou d'établissement par un autre Identifiant
**
** @param integer $typeId I=Code Isin, W=N°Waldec (Associations) ou R=N°RC (Registre Greffe)
** @param integer $identifiant Identifiant recherché
** @param integer $deb Position du curseur dans la liste des réponses (0 par défaut)
** @param integer $nbRep Nombre de réponses retournées au maximum par cette requete (20 par défaut)
** @param integer $maxRep Nombre de réponses recherchées au maximum (200 par défaut)
** @return Liste d'établissements
**/
function getIdentite($params) {
$siret=$params->siret;
$dep=$params->dept;
$id=$params->id;
$waldec=strtoupper($params->waldec);
/**sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Afnic $siret/$waldec ($dep)", "Siret $siret
Waldec $waldec
Département $dep
Id=$id");
*/
$forceVerif=false;
if ($waldec<>'' && substr($waldec,0,1)=='W' && $siret*1==0) {
debugLog('I',"AFNIC Recherche par identifiant Waldec $waldec (Siren=$siret, Dept=$dep, Id=$id)",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$rep=$this->iInsee->getEtablissementsParId('AUTRE', $waldec, 0, 20, 20);
$etabs=$rep['reponses'];
if ($rep['nbReponses']>0) {
foreach ($etabs as $nb=>$etab) {
$siret=$etab['Siret'];
$id=$etab['id'];
break;
}
} else {
debugLog('W', "Waldec $waldec non présent en base", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>108, 'errmsg'=>'Waldec inconnu'), 'result'=>$tabRet);
}
}
$tabRet=array();
$siret=trim($siret);
$len=strlen($siret);
$id=trim($id)*1;
if ($len==14) $nic=substr(''.$siret,9,5)*1;
elseif ($len== 9) $nic='';
elseif ($len== 0) { $siren=0; $nic=''; }
else {
debugLog('W', "Siren/Siret $siren incorrect", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren Siret inexistant'), 'result'=>$tabRet);
}
$siren=substr(''.$siret,0,9)*1;
if ($siren==0 && $id==0) {
debugLog('W', "Siren $siren inexistant", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren inexistant'), 'result'=>$tabRet);
}
if ($id==0 && !$this->iInsee->valideSiren($siren, $nic)) {
debugLog('W', "Siren $siren/$nic invalide (105)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>105, 'errmsg'=>'Siren invalide'), 'result'=>$tabRet);
}
$tabTmp=$this->searchSiren($siret);
if ($tabTmp['results']['nbReponses']==0 && $id==0) {
debugLog('W', "Siren $siren inexistant", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>106, 'errmsg'=>'Siren inconnu'), 'result'=>$tabRet);
}
if ($dep==974) {
debugLog('I',"AFNIC Recherche par Siren/Dept (Waldec=$waldec, Siren=$siret, Dept=$dep, Id=$id)",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$rep=$this->iInsee->getEtablissements($siren, $nic, 0, 20, 20, $dep);
$etabs=$rep['reponses'];
if ($rep['nbReponses']>0) {
foreach ($etabs as $nb=>$etab) {
$siren=$etab['siren'];
$nic=$etab['nic'];
$id=$etab['id'];
break;
}
} else {
debugLog('W', "Siren $siren/Waldec $waldec non présent en base", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>107, 'errmsg'=>'Entreprise ou Association non présente dans le département demandé'), 'result'=>$tabRet);
}
}
debugLog('I',"AFNIC Identités demandée pour siret ".strtr(print_r($siret, true),array("\r"=>'',"\n"=>'')). " (id=$id)",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
debugLog('I', "Avant getIdentiteEntreprise($siren, $nic, $id)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
$entrep=$this->iInsee->getIdentiteEntreprise($siren, $nic, $id, $forceVerif);
debugLog('I', "Après getIdentiteEntreprise($siren, $nic, $id)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
if (empty($entrep)) {
debugLog('W', "Siren $siren non présent en base", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren inexistant'), 'result'=>$tabRet);
}
$autreId=$entrep['AutreId'];
if ($params->siret>0 && $waldec<>'')
$autreId=$waldec;
$tabRet=array( 'id' =>$entrep['id'],
'Siret' =>$entrep['Siret'],
'SiretSiege' =>$entrep['SiretSiege'],
'Siege' =>$entrep['Siege'],
'Actif' =>$entrep['Actif'],
'AutreId' =>$autreId,
'idSd' =>$entrep['Source'].'-'.$entrep['SourceId'],
'Nom' =>prepareString(strtr($entrep['Nom'],'/*',' ')),
'Nom2' =>prepareString($entrep['Nom2']),
'Sigle' =>prepareString($entrep['Sigle']),
'Enseigne' =>prepareString($entrep['Enseigne']),
'Adresse' =>prepareString($entrep['Adresse']),
'Adresse2' =>prepareString($entrep['Adresse2']),
'AdresseNum' =>prepareString($entrep['AdresseNum']),
'AdresseBtq' =>prepareString($entrep['AdresseBtq']),
'AdresseVoie' =>prepareString($entrep['AdresseVoie']),
'AdresseRue' =>prepareString($entrep['AdresseRue']),
'CP' =>$entrep['CP'],
'Ville' =>prepareString($entrep['Ville']),
'Pays' =>prepareString($entrep['Pays']), // Ajouté le 18 02 2008
'Civilite' =>$entrep['Civilite'],
'NbEtab' =>$entrep['NbEtab'],
'Tel' =>prepareString($entrep['Tel']),
'Fax' =>prepareString($entrep['Fax']),
'Web' =>prepareString($entrep['Web']),
'Mail' =>prepareString($entrep['Mail']),
'FJ' =>$entrep['FJ'],
'FJ_lib' =>prepareString($entrep['FJ_lib']),
'Siren' =>$entrep['Siren'],
'Nic' =>$entrep['Nic'],
'NafEnt' =>$entrep['NafEnt'],
'NafEntLib' =>prepareString($entrep['NafEntLib']),
'Capital' =>$entrep['Capital'],
'CapitalDev' =>$entrep['CapitalDev'],
'CapitalLib' =>prepareString($entrep['CapitalLib']), // Ajouté le 18 02 2008
'DateCreaEt' =>$entrep['DateCreaEt'],
'DateCreaEn' =>$entrep['DateCreaEn'],
'DateClotEn' =>$entrep['DateClotEn'],
'EffEnTr' =>prepareString($entrep['EffEnTr']),
'EffEnTrLib' =>prepareString($entrep['EffEnTrLib']),
'Effectif' =>prepareString($entrep['Effectif']),
'Dept' =>$entrep['Dept'],
'codeCommune' =>prepareString($entrep['codeCommune']),
'TrancheCA' =>prepareString($entrep['TrancheCA']),
'TrancheCALib' =>prepareString($entrep['TrancheCALib']),
'dir1Titre' =>prepareString($entrep['dir1Titre']),//utf8
'dir1NomPrenom' =>prepareString($entrep['dir1NomPrenom']),
'dir1DateFct' =>prepareString($entrep['dir1DateFct']),
'SituationJuridique'=>$entrep['SituationJuridique'],
);
global $tabInfoUser;
if (preg_match('/NAF4/i', $tabInfoUser['pref'])) {
$entrep2=$this->iInsee->getNaf4($siren, $nic, $id);
$tabRet['Naf4Ent'] = $entrep2['apen4'];
$tabRet['Naf4Etab'] = $entrep2['apet4'];
$tabRet['Naf4EntLib'] = prepareString($entrep2['apen4_lib']);
$tabRet['Naf4EtabLib'] = prepareString($entrep2['apet4_lib']);
}
/*$tabRet=$entrep;
$tabRet['Bourse']=array('placeCotation'=>$bourse['placeCotation'],
'nombreTitres'=>$bourse['nombreTitres'],
'capitalisation'=>$bourse['close']*$bourse['nombreTitres'],
'derCoursDate'=>$bourse['date'],
'derCoursCloture'=>$bourse['close']);*/
//$tabRet=$entrep;
debugLog('I', 'Etablissement retourné = '. $entrep['Nom'], __LINE__, __FILE__, __FUNCTION__, __CLASS__);
wsLog('identite',$siret,$id);
return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'result'=>$tabRet);
}
/** Retourne les informations identitaires de l'entreprise ou de l'établissement demandé
** @nodoc
** @param integer $siret Siren de l'entreprise ou siret de l'établissement
** @param integer $id Identifiant S&D de l'établissement
** @return array Fiche d'identité de l'établissement
**/
/*function getIdentite($params) {
//function getIdentite($siret, $id = 0) {
/* $login, $page, $siret, $ip, $host, $resolution, $nbcolors, $user_agent, $referer, $date_login, $date_last_action, $request) {
if (!file_exists('/var/www/site_extranet/log/actions.log')) {
$fp=fopen('/var/www/site_extranet/log/actions.log', 'a');
fwrite($fp, 'Date et Heure;Login;Page;Siret;Ip;Host;Resolution;Nbcolors;User Agent;Referer;Date login;Date last action;Request'."\n");
} else {
$fp=fopen('/var/www/site_extranet/log/actions.log', 'a');
}
fwrite($fp, date('Y/m/d H:i:s').";$login;$page;$siret;$ip;$host;$resolution;$nbcolors;$user_agent;$referer;$date_login;$date_last_action;$request\n");
fclose($fp);
}**
$siret=$params->siret;
$id=$params->id;
$forceVerif=false;
debugLog('I',"AFNIC Identités demandée pour siret ".strtr(print_r($siret, true),array("\r"=>'',"\n"=>'')). " (id=$id)",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
$tabRet=array();
$siret=trim($siret);
$len=strlen($siret);
$id=trim($id)*1;
if ($len==14) $nic=substr(''.$siret,9,5)*1;
elseif ($len== 9) $nic='';
elseif ($len== 0) { $siren=0; $nic=''; }
else {
debugLog('W', "Siren/Siret $siren incorrect", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren Siret inexistant'), 'result'=>$tabRet);
}
$siren=substr(''.$siret,0,9)*1;
if ($siren==0 && $id==0) {
debugLog('W', "Siren $siren inexistant", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren inexistant'), 'result'=>$tabRet);
}
if (!$this->iInsee->valideSiren($siren, $nic)) {
debugLog('W', "Siren $siren/$nic invalide (105)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>105, 'errmsg'=>'Siren invalide'), 'result'=>$tabRet);
}
$tabTmp=$this->searchSiren($siret);
if ($tabTmp['results']['nbReponses']==0) {
debugLog('W', "Siren $siren inexistant", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>106, 'errmsg'=>'Siren inconnu'), 'result'=>$tabRet);
}
debugLog('I', "Avant getIdentiteEntreprise($siren, $nic, $id)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
$entrep=$this->iInsee->getIdentiteEntreprise($siren, $nic, $id, $forceVerif);
debugLog('I', "Après getIdentiteEntreprise($siren, $nic, $id)", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
if (empty($entrep)) {
debugLog('W', "Siren $siren non présent en base", __LINE__, __FILE__, __FUNCTION__, __CLASS__);
return array('error'=>array('errnum'=>102, 'errmsg'=>'Siren inexistant'), 'result'=>$tabRet);
}
$iBourse=new MBourse($siren);
$bourse=$iBourse->getInfosBourse($siren);
$tabRet=array( 'id' =>$entrep['id'],
'Siret' =>$entrep['Siret'],
'SiretSiege' =>$entrep['SiretSiege'],
'Siege' =>$entrep['Siege'],
'Actif' =>$entrep['Actif'],
'AutreId' =>$entrep['AutreId'],
'idSd' =>$entrep['Source'].'-'.$entrep['SourceId'],
// 'Source' =>$entrep['Source'],
// 'SourceId' =>$entrep['SourceId'],
// 'Isin' =>$entrep['Isin'],
'Nom' =>prepareString(strtr($entrep['Nom'],'/*',' ')),
'Nom2' =>prepareString($entrep['Nom2']),
// 'Siret' =>$entrep['Siret'],
'Sigle' =>prepareString($entrep['Sigle']),
'Enseigne' =>prepareString($entrep['Enseigne']),
'Adresse' =>prepareString($entrep['Adresse']),
'Adresse2' =>prepareString($entrep['Adresse2']),
'AdresseNum' =>prepareString($entrep['AdresseNum']),
'AdresseBtq' =>prepareString($entrep['AdresseBtq']),
'AdresseVoie' =>prepareString($entrep['AdresseVoie']),
'AdresseRue' =>prepareString($entrep['AdresseRue']),
'CP' =>$entrep['CP'],
'Ville' =>prepareString($entrep['Ville']),
'Pays' =>prepareString($entrep['Pays']), // Ajouté le 18 02 2008
'Civilite' =>$entrep['Civilite'],
'NbEtab' =>$entrep['NbEtab'],
'Tel' =>prepareString($entrep['Tel']),
'Fax' =>prepareString($entrep['Fax']),
'Web' =>prepareString($entrep['Web']),
'Mail' =>prepareString($entrep['Mail']),
/*
'GeoLat' =>$entrep['GeoLat'],
'GeoLon' =>$entrep['GeoLon'],
'GeoPrecis' =>$entrep['GeoPrecis'],
'GeoInfos' =>$entrep['GeoInfos'],
'TvaNumero' =>$entrep['TvaNumero'],
'TvaAttribue' =>$entrep['TvaAttribue'],
** 'FJ' =>$entrep['FJ'],
'FJ_lib' =>prepareString($entrep['FJ_lib']),
'Siren' =>$entrep['Siren'],
'Nic' =>$entrep['Nic'],
'NafEnt' =>$entrep['NafEnt'],
'NafEntLib' =>prepareString($entrep['NafEntLib']),
// 'NafEtab' =>$entrep['NafEtab'],
// 'NafEtabLib' =>prepareString($entrep['NafEtabLib']),
// 'Activite' =>prepareString($entrep['Activite']),
'Capital' =>$entrep['Capital'],
'CapitalDev' =>$entrep['CapitalDev'],
'CapitalLib' =>prepareString($entrep['CapitalLib']), // Ajouté le 18 02 2008
'DateCreaEt' =>$entrep['DateCreaEt'],
'DateCreaEn' =>$entrep['DateCreaEn'],
'DateClotEn' =>$entrep['DateClotEn'],
'EffEnTr' =>prepareString($entrep['EffEnTr']),
'EffEnTrLib' =>prepareString($entrep['EffEnTrLib']),
'Effectif' =>prepareString($entrep['Effectif']),
'Dept' =>$entrep['Dept'],
'codeCommune' =>prepareString($entrep['codeCommune']),
'TrancheCA' =>prepareString($entrep['TrancheCA']),
'TrancheCALib' =>prepareString($entrep['TrancheCALib']),
'dir1Titre' =>prepareString($entrep['dir1Titre']),//utf8
'dir1NomPrenom' =>prepareString($entrep['dir1NomPrenom']),
'dir1DateFct' =>prepareString($entrep['dir1DateFct']),
/* 'dir2Titre' =>prepareString($entrep['dir2Titre']),
'dir2NomPrenom' =>prepareString($entrep['dir2NomPrenom']),
'dir2DateFct' =>prepareString($entrep['dir2DateFct']),
'Rivoli' =>$entrep['Rivoli'],
'NatureActivite' =>$entrep['NatureActivite'], // Nature de l'activité
'OrigineCreation' =>$entrep['OrigineCreation'], // Origine de la création
'Auxiliaire' =>$entrep['Auxiliaire'], // 1=Auxiliaire / 0=Non auxiliaire
'Saisonnalite' =>$entrep['Saisonnalite'], // P=Activité permanente / S=Activité saisonnière
** 'SituationJuridique'=>$entrep['SituationJuridique'],
/* 'Bourse' =>array('placeCotation'=>$bourse['placeCotation'],
'nombreTitres'=>$bourse['nombreTitres'],
'capitalisation'=>$bourse['close']*$bourse['nombreTitres'],
'derCoursDate'=>$bourse['date'],
'derCoursCloture'=>$bourse['close']),**
//'importExport' =>$entrep['importExport'],
);
global $tabInfoUser;
if (preg_match('/NAF4/i', $tabInfoUser['pref'])) {
$entrep2=$this->iInsee->getNaf4($siren, $nic, $id);
$tabRet['Naf4Ent'] = $entrep2['apen4'];
$tabRet['Naf4Etab'] = $entrep2['apet4'];
$tabRet['Naf4EntLib'] = prepareString($entrep2['apen4_lib']);
$tabRet['Naf4EtabLib'] = prepareString($entrep2['apet4_lib']);
}
/*$tabRet=$entrep;
$tabRet['Bourse']=array('placeCotation'=>$bourse['placeCotation'],
'nombreTitres'=>$bourse['nombreTitres'],
'capitalisation'=>$bourse['close']*$bourse['nombreTitres'],
'derCoursDate'=>$bourse['date'],
'derCoursCloture'=>$bourse['close']);**
//$tabRet=$entrep;
debugLog('I', 'Etablissement retourné = '. $entrep['Nom'], __LINE__, __FILE__, __FUNCTION__, __CLASS__);
wsLog('identite',$siret,$id);
return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'result'=>$tabRet);
}
*/
}
?>

View File

@ -0,0 +1,109 @@
<?xml version='1.0' encoding='UTF-8'?>
<definitions name="entreprises" targetNamespace="urn:entreprises" xmlns:typens="urn:entreprises" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:entreprises">
<xsd:complexType name="EntrepElement">
<xsd:all>
<xsd:element name="id" type="xsd:integer"/>
<xsd:element name="Siret" type="xsd:string"/>
<xsd:element name="SiretSiege" type="xsd:string"/>
<xsd:element name="Siege" type="xsd:integer"/>
<xsd:element name="Actif" type="xsd:integer"/>
<xsd:element name="AutreId" type="xsd:string"/>
<xsd:element name="Nom" type="xsd:string"/>
<xsd:element name="Nom2" type="xsd:string"/>
<xsd:element name="Sigle" type="xsd:string"/>
<xsd:element name="Enseigne" type="xsd:string"/>
<xsd:element name="Adresse" type="xsd:string"/>
<xsd:element name="Adresse2" type="xsd:string"/>
<xsd:element name="AdresseNum" type="xsd:integer"/>
<xsd:element name="AdresseBtq" type="xsd:string"/>
<xsd:element name="AdresseVoie" type="xsd:string"/>
<xsd:element name="AdresseRue" type="xsd:string"/>
<xsd:element name="CP" type="xsd:integer"/>
<xsd:element name="Ville" type="xsd:string"/>
<xsd:element name="Pays" type="xsd:string"/>
<xsd:element name="Civilite" type="xsd:string"/>
<xsd:element name="NbEtab" type="xsd:integer"/>
<xsd:element name="Tel" type="xsd:string"/>
<xsd:element name="Fax" type="xsd:string"/>
<xsd:element name="Web" type="xsd:string"/>
<xsd:element name="Mail" type="xsd:string"/>
<xsd:element name="FJ" type="xsd:integer"/>
<xsd:element name="FJ_lib" type="xsd:string"/>
<xsd:element name="Siren" type="xsd:integer"/>
<xsd:element name="Nic" type="xsd:integer"/>
<xsd:element name="NafEnt" type="xsd:string"/>
<xsd:element name="NafEntLib" type="xsd:string"/>
<xsd:element name="Capital" type="xsd:integer"/>
<xsd:element name="CapitalDev" type="xsd:string"/>
<xsd:element name="CapitalLib" type="xsd:string"/>
<xsd:element name="DateCreaEt" type="xsd:integer"/>
<xsd:element name="DateCreaEn" type="xsd:integer"/>
<xsd:element name="DateClotEn" type="xsd:integer"/>
<xsd:element name="EffEnTr" type="xsd:string"/>
<xsd:element name="EffEnTrLib" type="xsd:string"/>
<xsd:element name="Effectif" type="xsd:string"/>
<xsd:element name="Dept" type="xsd:string"/>
<xsd:element name="codeCommune" type="xsd:integer"/>
<xsd:element name="TrancheCA" type="xsd:string"/>
<xsd:element name="TrancheCALib" type="xsd:string"/>
<xsd:element name="dir1Titre" type="xsd:string"/>
<xsd:element name="dir1NomPrenom" type="xsd:string"/>
<xsd:element name="dir1DateFct" type="xsd:string"/>
<xsd:element name="SituationJuridique" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="ErrorElement">
<xsd:all>
<xsd:element name="errnum" type="xsd:integer"/>
<xsd:element name="errmsg" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="EntrepResult">
<xsd:all>
<xsd:element name="error" type="typens:ErrorElement"/>
<xsd:element name="result" type="typens:EntrepElement"/>
</xsd:all>
</xsd:complexType>
</xsd:schema>
</types>
<message name="getIdentite">
<part name="siret" type="xsd:integer"/>
<part name="id" type="xsd:integer"/>
</message>
<message name="getIdentiteResponse">
<part name="identiteEntrepReturn" type="typens:EntrepResult"/>
</message>
<portType name="SdWsEntreprisesPortType">
<operation name="getIdentite">
<documentation>
Retourne une fiche identite entreprise
</documentation>
<input message="typens:getIdentite"/>
<output message="typens:getIdentiteResponse"/>
</operation>
</portType>
<binding name="SdWsEntreprisesBinding" type="typens:SdWsEntreprisesPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="getIdentite">
<soap:operation soapAction="urn:SdWsEntreprisesAction"/>
<input>
<soap:body namespace="urn:entreprises" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body namespace="urn:entreprises" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
</binding>
<service name="entreprisesService">
<port name="SdWsEntreprisesPort" binding="typens:SdWsEntreprisesBinding">
<soap:address location="http://saulnier.scores-decisions.com/afnic/"/>
</port>
</service>
</definitions>

View File

@ -0,0 +1,129 @@
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions name="WsEntreprises"
targetNamespace="urn:WsEntreprises"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:wsdlns="urn:WsEntreprises"
xmlns:typens="urn:WsEntreprises"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
>
<wsdl:types>
<xsd:schema elementFormDefault='qualified' xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:WsEntreprises">
<xsd:complexType name="EntrepStruct">
<xsd:sequence>
<xsd:element name="id" type="xsd:int" nillable="true" />
<xsd:element name="Siret" type="xsd:string" nillable="true" />
<xsd:element name="SiretSiege" type="xsd:string" nillable="true" />
<xsd:element name="Siege" type="xsd:int" nillable="true" />
<xsd:element name="Actif" type="xsd:int" nillable="true" />
<xsd:element name="AutreId" type="xsd:string" nillable="true" />
<xsd:element name="Nom" type="xsd:string" nillable="true" />
<xsd:element name="Nom2" type="xsd:string" nillable="true" />
<xsd:element name="Sigle" type="xsd:string" nillable="true" />
<xsd:element name="Enseigne" type="xsd:string" nillable="true" />
<xsd:element name="Adresse" type="xsd:string" nillable="true" />
<xsd:element name="Adresse2" type="xsd:string" nillable="true" />
<xsd:element name="AdresseNum" type="xsd:int" nillable="true" />
<xsd:element name="AdresseBtq" type="xsd:string" nillable="true" />
<xsd:element name="AdresseVoie" type="xsd:string" nillable="true" />
<xsd:element name="AdresseRue" type="xsd:string" nillable="true" />
<xsd:element name="CP" type="xsd:int" nillable="true" />
<xsd:element name="Ville" type="xsd:string" nillable="true" />
<xsd:element name="Pays" type="xsd:string" nillable="true" />
<xsd:element name="Civilite" type="xsd:string" nillable="true" />
<xsd:element name="NbEtab" type="xsd:int" nillable="true" />
<xsd:element name="Tel" type="xsd:string" nillable="true" />
<xsd:element name="Fax" type="xsd:string" nillable="true" />
<xsd:element name="Web" type="xsd:string" nillable="true" />
<xsd:element name="Mail" type="xsd:string" nillable="true" />
<xsd:element name="FJ" type="xsd:int" nillable="true" />
<xsd:element name="FJ_lib" type="xsd:string" nillable="true" />
<xsd:element name="Siren" type="xsd:int" nillable="true" />
<xsd:element name="Nic" type="xsd:int" nillable="true" />
<xsd:element name="NafEnt" type="xsd:string" nillable="true" />
<xsd:element name="NafEntLib" type="xsd:string" nillable="true" />
<xsd:element name="Capital" type="xsd:int" nillable="true" />
<xsd:element name="CapitalDev" type="xsd:string" nillable="true" />
<xsd:element name="CapitalLib" type="xsd:string" nillable="true" />
<xsd:element name="DateCreaEt" type="xsd:int" nillable="true" />
<xsd:element name="DateCreaEn" type="xsd:int" nillable="true" />
<xsd:element name="DateClotEn" type="xsd:int" nillable="true" />
<xsd:element name="EffEnTr" type="xsd:string" nillable="true" />
<xsd:element name="EffEnTrLib" type="xsd:string" nillable="true" />
<xsd:element name="Effectif" type="xsd:string" nillable="true" />
<xsd:element name="Dept" type="xsd:string" nillable="true" />
<xsd:element name="codeCommune" type="xsd:int" nillable="true" />
<xsd:element name="TrancheCA" type="xsd:string" nillable="true" />
<xsd:element name="TrancheCALib" type="xsd:string" nillable="true" />
<xsd:element name="dir1Titre" type="xsd:string" nillable="true" />
<xsd:element name="dir1NomPrenom" type="xsd:string" nillable="true" />
<xsd:element name="dir1DateFct" type="xsd:string" nillable="true" />
<xsd:element name="SituationJuridique" type="xsd:string" nillable="true" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ErrorStruct">
<xsd:sequence>
<xsd:element name="errnum" type="xsd:int" nillable="true" />
<xsd:element name="errmsg" type="xsd:string" nillable="true" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="getIdentiteResponse">
<xsd:sequence>
<xsd:element name="error" type="typens:ErrorStruct" nillable="true" />
<xsd:element name="result" type="typens:EntrepStruct" nillable="true" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="getIdentite">
<xsd:sequence>
<xsd:element name="siret" type="xsd:int" nillable="true" />
<xsd:element name="id" type="xsd:int" nillable="true" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<wsdl:message name="getIdentiteRequest">
<wsdl:part name="parameters" element="typens:getIdentite"/>
</wsdl:message>
<wsdl:message name="getIdentiteResponse">
<wsdl:part name="parameters" element="typens:getIdentiteResponse"/>
</wsdl:message>
<wsdl:portType name="WsEntreprisesPortType">
<wsdl:operation name="getIdentite">
<wsdl:documentation>Retourne une fiche identite entreprise</wsdl:documentation>
<wsdl:input message="wsdlns:getIdentiteRequest" />
<wsdl:output message="wsdlns:getIdentiteResponse" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="WsEntreprisesBinding" type="wsdlns:WsEntreprisesPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getIdentite">
<soap:operation soapAction=""/>
<wsdl:input name="getIdentiteRequest">
<soap:body use="literal" namespace="urn:WsEntreprises" />
</wsdl:input>
<wsdl:output name="getIdentiteResponse">
<soap:body use="literal" namespace="urn:WsEntreprises"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="WsEntreprisesService">
<wsdl:port name="WsEntreprisesPort" binding="wsdlns:WsEntreprisesBinding">
<soap:address location="http://tville.scores-decisions.com/afnic/" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

View File

@ -0,0 +1,136 @@
<?xml version='1.0' encoding="UTF-8"?>
<wsdl:definitions name="entreprises"
targetNamespace="urn:entreprises"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:wsdlns="urn:entreprises"
xmlns:typens="urn:entreprises"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
>
<wsdl:types>
<xsd:schema
elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:entreprises">
<xsd:complexType name="EntrepElement">
<xsd:sequence>
<xsd:element name="id" type="xsd:int" nillable="true" />
<xsd:element name="Siret" type="xsd:string" nillable="true" />
<xsd:element name="SiretSiege" type="xsd:string" nillable="true" />
<xsd:element name="Siege" type="xsd:int" nillable="true" />
<xsd:element name="Actif" type="xsd:int" nillable="true" />
<xsd:element name="AutreId" type="xsd:string" nillable="true" />
<xsd:element name="Nom" type="xsd:string" nillable="true" />
<xsd:element name="Nom2" type="xsd:string" nillable="true" />
<xsd:element name="Sigle" type="xsd:string" nillable="true" />
<xsd:element name="Enseigne" type="xsd:string" nillable="true" />
<xsd:element name="Adresse" type="xsd:string" nillable="true" />
<xsd:element name="Adresse2" type="xsd:string" nillable="true" />
<xsd:element name="AdresseNum" type="xsd:int" nillable="true" />
<xsd:element name="AdresseBtq" type="xsd:string" nillable="true" />
<xsd:element name="AdresseVoie" type="xsd:string" nillable="true" />
<xsd:element name="AdresseRue" type="xsd:string" nillable="true" />
<xsd:element name="CP" type="xsd:int" nillable="true" />
<xsd:element name="Ville" type="xsd:string" nillable="true" />
<xsd:element name="Pays" type="xsd:string" nillable="true" />
<xsd:element name="Civilite" type="xsd:string" nillable="true" />
<xsd:element name="NbEtab" type="xsd:int" nillable="true" />
<xsd:element name="Tel" type="xsd:string" nillable="true" />
<xsd:element name="Fax" type="xsd:string" nillable="true" />
<xsd:element name="Web" type="xsd:string" nillable="true" />
<xsd:element name="Mail" type="xsd:string" nillable="true" />
<xsd:element name="FJ" type="xsd:int" nillable="true" />
<xsd:element name="FJ_lib" type="xsd:string" nillable="true" />
<xsd:element name="Siren" type="xsd:int" nillable="true" />
<xsd:element name="Nic" type="xsd:int" nillable="true" />
<xsd:element name="NafEnt" type="xsd:string" nillable="true" />
<xsd:element name="NafEntLib" type="xsd:string" nillable="true" />
<xsd:element name="Capital" type="xsd:int" nillable="true" />
<xsd:element name="CapitalDev" type="xsd:string" nillable="true" />
<xsd:element name="Capitsequenceib" type="xsd:string" nillable="true" />
<xsd:element name="DateCreaEt" type="xsd:int" nillable="true" />
<xsd:element name="DateCreaEn" type="xsd:int" nillable="true" />
<xsd:element name="DateClotEn" type="xsd:int" nillable="true" />
<xsd:element name="EffEnTr" type="xsd:string" nillable="true" />
<xsd:element name="EffEnTrLib" type="xsd:string" nillable="true" />
<xsd:element name="Effectif" type="xsd:string" nillable="true" />
<xsd:element name="Dept" type="xsd:string" nillable="true" />
<xsd:element name="codeCommune" type="xsd:int" nillable="true" />
<xsd:element name="TrancheCA" type="xsd:string" nillable="true" />
<xsd:element name="TrancheCALib" type="xsd:string" nillable="true" />
<xsd:element name="dir1Titre" type="xsd:string" nillable="true" />
<xsd:element name="dir1NomPrenom" type="xsd:string" nillable="true" />
<xsd:element name="dir1DateFct" type="xsd:string" nillable="true" />
<xsd:element name="SituationJuridique" type="xsd:string" nillable="true" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ErrorElement">
<xsd:sequence>
<xsd:element name="errnum" type="xsd:int" nillable="true" />
<xsd:element name="errmsg" type="xsd:string" nillable="true" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="EntrepResult">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="error" type="typens:ErrorElement" nillable="true" />
<xsd:element name="result" type="typens:EntrepElement" nillable="true" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="IdentiteRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="siret" type="xsd:int" nillable="true" />
<xsd:element name="id" type="xsd:int" nillable="true" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</wsdl:types>
<wsdl:message name="IdentiteRequest">
<wsdl:part name="parameters" element="typens:IdentiteRequest"/>
</wsdl:message>
<wsdl:message name="EntrepResult">
<wsdl:part name="parameters" element="typens:EntrepResult"/>
</wsdl:message>
<wsdl:portType name="entreprisesPortType">
<wsdl:operation name="getIdentite">
<wsdl:documentation>Retourne une fiche identite entreprise</wsdl:documentation>
<wsdl:input message="wsdlns:IdentiteRequest" name="getIdentiteRequest"/>
<wsdl:output message="wsdlns:EntrepResult" name="getIdentiteResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="entreprisesBinding" type="wsdlns:entreprisesPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getIdentite">
<soap:operation soapAction="getIdentite"/>
<wsdl:input name="getIdentiteRequest">
<soap:body use="literal" />
</wsdl:input>
<wsdl:output name="getIdentiteResponse">
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="entreprisesService">
<wsdl:port name="entreprisesPort" binding="wsdlns:entreprisesBinding">
<soap:address location="http://tville.scores-decisions.com/afnic/" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

Some files were not shown because too many files have changed in this diff Show More