Subversion Repositories eFlore/Projets.eflore-projets

Compare Revisions

Ignore whitespace Rev 839 → Rev 843

/tags/v0.1-20130829/services/bibliotheque/RequetesAssemblage.php
New file
0,0 → 1,90
<?php
 
/** FONCTIONS D'ASSEMBLAGE DE REQUETE
*
* @package eflore-projets
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org>
* @author Delphine CAUQUIL <delphine@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
* @version 1.0
* @copyright 1999-2011 Tela Botanica (accueil@tela-botanica.org)
*/
 
class RequetesAssemblage {
private $table;
private $total_resultat;
private $Bdd;
private $condition;
public function __construct(BDD $bdd) {
$this->Bdd = $bdd;
}
 
public function getTotal_resultat() {
return $this->total_resultat;
}
public function retournerRequeteJointure($requete_jointure) {
$jointure = '';
if ($requete_jointure !== "") {
foreach ($requete_jointure as $req_j) {
$jointure .= ' '.$req_j['type'].' '.$req_j['table'].' ON '
.implode(' AND', $req_j['on']);
}
}
return $jointure;
}
 
public function assemblerLaRequete(Requete $requete_param) {
$this->table = $requete_param->table;
$requete_jointure = $this->retournerRequeteJointure($requete_param->requete_jointure);
$this->condition = $this->retournerRequeteCondition($requete_param->requete_condition);
$limites = $this->delimiterResultatsRequete($requete_param->limite_besoin, $requete_param->limite_requete);
$requete = ' SELECT '.$requete_param->champs_recherches.' FROM '.$requete_param->table.' '
.$requete_jointure .' '.$this->condition.' '.$limites;
return $requete;
}
 
public function retournerRequeteCondition($requete_condition) {
$condition = '';
if ($requete_condition !== "") {
$condition = ' WHERE '.implode(' AND ', $requete_condition);
}
return $condition;
}
 
public function calculerTotalResultat() {
$requete = 'SELECT count(*) as nombre FROM '.$this->table.' '.$this->condition;
$res = $this->Bdd->recuperer($requete);
if ($res) {
$this->total_resultat = $res['nombre'];
} else {
$this->total_resultat = 0;
$e = 'Données introuvables dans la base';
throw new Exception($e, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
}
}
 
public function delimiterResultatsRequete($limite_besoin, $limite_requete) {
$this->calculerTotalResultat();
$requete_limite = '';
if ($limite_besoin) {
if (($limite_requete['depart'] <= $this->total_resultat) ){
if (($limite_requete['limite'] + $limite_requete['depart'] )
< $this->total_resultat ){
$requete_limite = 'LIMIT '.$limite_requete['depart'].', '
.$limite_requete['limite'];
}
} else {
$e = "Erreur : la valeur pour le paramètre navigation.départ est supérieure".
" au nombre total de résultats.";
throw new Exception($e, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
}
}
return $requete_limite;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/robots/WikipediaBot.php
New file
0,0 → 1,158
<?php
class WikipediaBot {
const HTTP_URL_REQUETE_SEPARATEUR = '&';
private $langue = 'fr';
private $url = '';
private $parametres = array();
private $titre = '';
private $txt = '';
private $userAgent = 'eFloreBot v0.1';
private $reponse_entetes = null;
 
public function __construct($options = array()) {
if (array_key_exists('langue', $options)) {
$this->langue = strtolower($options['langue']);
}
}
 
public function chargerPage($article) {
$this->initialiserRequete();
$this->url = $this->getBaseApiURL();
$this->parametres = array(
'action' => 'query',
'prop' => 'revisions',
'titles' => $article,
'rvprop' => 'content',
'redirects' => 1
);
$this->resultats = $this->consulterAPI();
$sxGetAID = $this->resultats['query']['pages'];
$sxGetAID = array_shift($sxGetAID);
$this->titre = $sxGetAID['title'];
$this->txt = $sxGetAID['revisions'][0]['*'];
}
 
public function getPageTitre() {
return $this->titre;
}
 
public function getPageTxt() {
return $this->txt;
}
 
public function getTaxobox() {
$taxobox = '';
if (preg_match('/([{]{2}Taxobox début.+[{]{2}Taxobox fin[}]{2})/s', $this->txt, $match)) {
$taxobox = $match[1];
}
return $taxobox;
}
 
public function extraireTaxobox() {
$taxobox = $this->getTaxobox();
$this->txt = str_replace($taxobox, '', $this->txt);
return $taxobox;
}
 
public function getSectionParNumero($num) {
$sections = preg_split('/[=]{2}[^=]+[=]{2}/U', $this->txt);
//Debug::printr($sections);
$sectionTxt = isset($sections[$num]) ? $sections[$num] : '';
return $sectionTxt;
}
 
public function getSectionParTitre($titre) {
$section = '';
if (preg_match('/[=]{2} '.$titre.' [=]{2}(.*)\n\n/sU', $this->txt, $match)) {
$section = $match[1];
}
return $section;
}
 
public function rendre($wikitxt) {
$wikitxt .= '<references />';
$this->initialiserRequete();
$this->url = $this->getBaseApiURL();
$this->parametres = array(
'action' => 'parse',
'prop' => 'text',
'text' => $wikitxt
);
$this->resultats = $this->consulterAPI();
$txt = $this->resultats['parse']['text']['*'];
$txt = $this->remplacerUrls($txt);
return $txt;
}
 
private function initialiserRequete() {
$this->url = '';
$this->parametres = array();
$this->resultats = array();
}
 
private function getBaseWpURL() {
$baseURL = "http://{$this->langue}.wikipedia.org";
return $baseURL;
}
 
private function getBaseApiURL() {
$baseURL = $this->getBaseWpURL().'/w/api.php';
return $baseURL;
}
 
private function consulterAPI() {
$this->parametres['format'] = 'php';
$resultat = $this->consulterEnPost();
$resultat = unserialize($resultat);
 
if (isset($resultat['error'])) {
throw new Exception($resultat['error']['info'], $resultat['error']['info']);
}
return $resultat;
}
 
private function consulterEnPost() {
return $this->consulter('POST');
}
 
private function consulter($mode) {
$entetes = array(
'Content-type' => 'application/x-www-form-urlencoded',
'User-Agent' => $this->userAgent);
$contexte = array('http' => array(
'method' => $mode,
'header' => $this->getEnteteChaine($entetes),
'content' => http_build_query($this->parametres, null, self::HTTP_URL_REQUETE_SEPARATEUR)));
$contexteFlux = stream_context_create($contexte);
$flux = fopen($this->url, 'r', false, $contexteFlux);
 
if (!$flux) {
$this->reponse_entetes = $http_response_header;
$e = "L'ouverture de l'url '{$this->url}' par la méthode HTTP '$mode' a échoué!";
throw new Exception($e);
}
// Informations sur les en-têtes et métadonnées du flux
$this->reponse_entetes = stream_get_meta_data($flux);
// Contenu actuel de $url
$contenu = stream_get_contents($flux);
fclose($flux);
return $contenu;
}
 
private function getEnteteChaine(Array $entetes) {
$entetesCleVal = array();
foreach ($entetes as $cle => $valeur) {
$entetesCleVal[] = $cle.': '.$valeur;
}
return implode("\r\n", $entetesCleVal);
}
 
private function remplacerUrls($txt) {
$remplacements = array(
'href="/wiki/' => 'href="'.$this->getBaseWpURL().'/wiki/',
'href="/w/' => 'href="'.$this->getBaseWpURL().'/w/');
$txt = strtr($txt, $remplacements);
return $txt;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/EnteteHttp.php
New file
0,0 → 1,7
<?php
class EnteteHttp {
public $code = RestServeur::HTTP_CODE_OK;
public $encodage = 'utf-8';
public $mime = 'application/json';
}
?>
/tags/v0.1-20130829/services/bibliotheque/ResultatService.php
New file
0,0 → 1,7
<?php
class ResultatService {
public $mime = 'application/json';
public $encodage = 'utf-8';
public $corps = '';
}
?>
/tags/v0.1-20130829/services/bibliotheque/Utilisateurs.php
New file
0,0 → 1,114
<?php
class Utilisateurs {
const TPL_URL_WS_ANNUAIRE = 'http://www.tela-botanica.org/service:annuaire:utilisateur/identite-par-courriel/%s';
 
private $courriels = array();
private $identites = array();
private $clientRest = null;
 
/**
* Prend en paramêtre un tableau de courriels.
*
* @param array $courriels un tableau de courriels pour lesquels il faut rechercher les infos d'identité
*/
public function __construct(Array $courriels = array(), RestClient $clientRest = null) {
$this->courriels = $courriels;
$this->clientRest = is_null($clientRest) ? new RestClient() : $clientRest;
}
 
public function setCourriels($courriels) {
$this->courriels = $courriels;
}
/**
* Lance l'interrogation du service de l'annuaire.
*
* @return null.
*/
public function chargerIdentites() {
$this->identites = $this->getIdentites();
}
 
/**
* Retourne après avoir interrogé un service de l'annuaire, les intitulés correspondant aux
* courriels des utilisateurs.
*
* @return mixed tableau avec en clé le courriel et en valeur l'intitulé de la personne à
* afficher, false en cas d'erreur ou de résultat vide.
*/
public function getIntitules() {
$intitules = false;
$this->chargerIdentites();
if ($this->identites) {
$intitules = array();
foreach ($this->identites as $courriel => $infos) {
$intitules[$courriel] = $infos['intitule'];
}
}
return $intitules;
}
 
/**
* Retourne un intitulé en fonction d'un courriel.
*
* @return String l'intitulé de l'utilisateur ou une chaine vide en cas de problème.
*/
public function getIntitule($courriel) {
$intitule = '';
if ($this->contenirCourriel($courriel)) {
$intitule = $this->identites[$courriel]['intitule'];
}
return $intitule;
}
 
/**
* Retourne l'identifiant de l'utilisateur en fonction d'un courriel.
*
* @return String l'id de l'utilisateur ou une chaine vide en cas de problème.
*/
public function getId($courriel) {
$id = '';
if ($this->contenirCourriel($courriel)) {
$id = $this->identites[$courriel]['id'];
}
return $id;
}
 
private function contenirCourriel($courriel) {
$ok = ($this->identites && isset($this->identites[$courriel])) ? true : false;
return $ok;
}
 
private function getIdentites() {
$utilisateursInfos = $this->consulterServiceAnnuaire();
$identites = $this->extraireIdentites($utilisateursInfos);
return $identites;
}
 
private function consulterServiceAnnuaire() {
$url = sprintf(self::TPL_URL_WS_ANNUAIRE, implode(',', $this->courriels));
$json = $this->clientRest->consulter($url);
$utilisateurs = json_decode($json, true);
return $utilisateurs;
}
 
private function extraireIdentites($utilisateursInfos) {
$identites = array();
foreach ($this->courriels as $courriel) {
$info = array('id' => null, 'intitule' => '');
if (isset($utilisateursInfos[$courriel])) {
$info['intitule'] = $utilisateursInfos[$courriel]['intitule'];
$info['id'] = $utilisateursInfos[$courriel]['id'];
} else {
$info['intitule'] = $this->tronquerCourriel($courriel);
}
$identites[$courriel] = $info;
}
return $identites;
}
 
private function tronquerCourriel($courriel) {
$courriel = str_replace(substr($courriel, strpos($courriel, '@')), '@...', $courriel);
return $courriel;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/Ressources.php
New file
0,0 → 1,108
<?php
class Ressources {
 
private $ressources = array();
 
public function __construct(Array $ressources) {
$this->ressources = $ressources;
}
 
public function getParPosition($position) {
$valeur = '';
if (array_key_exists($position, $this->ressources)) {
$valeur = $this->ressources[$position];
}
return $valeur;
}
 
public function getNombre() {
return count($this->ressources);
}
 
public function getProjetNom() {
return $this->getParPosition(0);
}
 
public function getServiceNom() {
return $this->getParPosition(1);
}
 
public function getDetailsId() {
return (int) $this->getParPosition(2);
}
 
public function etreId($aTester) {
$etreId = is_numeric($aTester) ? true : false;
return $etreId;
}
 
public function etreStats($aTester) {
$etreStats = $aTester == 'stats' ? true : false;
return $etreStats;
}
 
public function etreTypeDeStats($aTester) {
$typesStats = array('annees', 'rangs', 'initiales');
$etreStatsType = in_array($aTester, $typesStats) ? true : false;
return $etreStatsType;
}
 
public function etreRelations($aTester) {
$etreRelations = $aTester == 'relations' ? true : false;
return $etreRelations;
}
 
public function etreTypeDeRelations($aTester) {
$typesRelations = array('synonymie', 'homonymie', 'flores');
$etreRelationsType = in_array($aTester, $typesRelations) ? true : false;
return $etreRelationsType;
}
 
public function getServiceClasse() {
$classeNom = '';
if ($this->getNombre() == 2) {
if ($this->getServiceNom() == 'noms') {
$classeNom = 'NomsListe';
} else if ($this->getServiceNom() == 'taxons') {
$classeNom = 'TaxonsListe';
} else if ($this->getServiceNom() == 'ontologies') {
$classeNom = 'OntologiesListe';
}
 
} else if ($this->getNombre() == 3) {
$position3 = $this->getParPosition(2);
if ($this->etreId($position3)) {
if ($this->getServiceNom() == 'noms') {
$classeNom = 'NomDetails';
} else if ($this->getServiceNom() == 'taxons') {
$classeNom = 'TaxonDetails';
}
}
} else if ($this->getNombre() == 4) {
$position3 = $this->getParPosition(2);
$position4 = $this->getParPosition(3);
if ($this->etreStats($position3)) {
if ($this->etreTypeDeStats($position4)) {
$classeNom = 'NomsStats'.ucfirst($position4);
}
} else if ($this->etreId($position3)) {
if ($this->etreRelations($position4)) {
$classeNom = 'NomRelations';
}
}
} else if ($this->getNombre() == 5) {
$position3 = $this->getParPosition(2);
$position4 = $this->getParPosition(3);
$position5 = $this->getParPosition(4);
if ($this->etreId($position3)) {
if ($this->etreRelations($position4)) {
if ($this->etreTypeDeRelations($position5)) {
$classeNom = 'NomRelations'.ucfirst($position5);
}
}
}
}
return $classeNom;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/interfaces/NomDetails.php
New file
0,0 → 1,6
<?php
interface NomDetails {
public function __construct(NomDetailsGenerique $nomDetails);
public function consulter();
}
?>
/tags/v0.1-20130829/services/bibliotheque/interfaces/OntologiesListe.php
New file
0,0 → 1,6
<?php
interface OntologiesListe {
public function __construct(OntologiesListeGenerique $ontologiesListe);
public function consulter();
}
?>
/tags/v0.1-20130829/services/bibliotheque/interfaces/NomsListe.php
New file
0,0 → 1,6
<?php
interface NomsListe {
public function __construct(NomsListeGenerique $nomsListe);
public function consulter();
}
?>
/tags/v0.1-20130829/services/bibliotheque/VersionVerificateur.php
New file
0,0 → 1,44
<?php
class VersionVerificateur {
 
private $ressources = null;
private $parametres = null;
private $versions = null;
 
public function __construct(Ressources $ressources, Parametres $parametres, Versions $versions) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->versions = $versions;
}
 
public function verifier() {
$this->verifierDispoMultiProjetPourService();
$this->verifierExistance();
}
 
private function verifierDispoMultiProjetPourService() {
$servicesMultiProjet = array('NomDetails');
$classeService = $this->ressources->getServiceClasse();
$versionDemandee = $this->parametres->get('version.projet');
if ($versionDemandee == '*' && in_array($classeService, $servicesMultiProjet) === false) {
$message = "L'affichage de plusieurs versions ne fonctionne que pour les ressources de type /ressources/#id";
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
}
 
private function verifierExistance() {
$versionDemandee = $this->parametres->get('version.projet');
$versionTrouvee = $this->versions->getVersions();
if (is_numeric($versionDemandee)) {
if (count($versionTrouvee) == 0) {
$projet = $this->ressources->getProjetNom();
$message = "La version '$versionDemandee' n'est pas disponible pour le projet '$projet' !";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
}
 
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/generique/NomDetailsGenerique.php
New file
0,0 → 1,30
<?php
class NomDetailsGenerique {
 
private $parametres = null;
private $ressources = null;
private $nomDao = null;
private $nomFormateur = null;
private $nom = array();
 
public function __construct(Ressources $ressources, Parametres $parametres, NomDAO $nomDao, NomFormateur $nomFormateur) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->nomDao = $nomDao;
$this->nomFormateur = $nomFormateur;
}
 
public function consulter() {
$this->nom = $this->nomDao->rechercherInfosNom();
$retour = $this->formaterDetails();
return $retour;
}
 
private function formaterDetails() {
$this->nomFormateur->setNomAFormater($this->nom);
$this->nomFormateur->setChampsRetour($this->parametres->getListe('retour.champs'));
$details = $this->nomFormateur->formaterDetails();
return $details;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/generique/OntologiesListeGenerique.php
New file
0,0 → 1,157
<?php
class OntologiesListeGenerique {
 
private $parametres = null;
private $ressources = null;
private $ontologieDao = null;
private $ontologieFormateur = null;
 
private $listeUrl = null;
private $nbreTotalTermes = 0;
private $termes = array();
 
public function __construct(Ressources $ressources, Parametres $parametres, OntologieDAO $ontologieDao, OntologieFormateur $ontologieFormateur) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->ontologieDao = $ontologieDao;
$this->ontologieFormateur = $ontologieFormateur;
}
 
public function setListeUrl($url) {
$this->listeUrl = $url;
}
 
public function consulter() {
$this->rechercher();
if ($this->avoirResultats()) {
$this->trierResultats();
$retour = $this->construireTableauRetour();
} else {
$message = "Aucun résultat ne correspond a votre requête !";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
return $retour;
}
 
private function rechercher() {
$resultats = array();
$resultats = $this->ontologieDao->rechercher();
$this->termes = $resultats;
$this->nbreTotalTermes = $this->ontologieDao->recupererNombreTermesTotal();
}
 
private function avoirResultats() {
$resultat = ($this->nbreTotalTermes == 0) ? false : true;
return $resultat;
}
 
private function trierResultats() {
$recherche = $this->parametres->get('recherche');
if ($recherche == 'floue') {
$this->termes = $this->ontologieDao->trierResultatsFloue($this->termes);
}
}
 
private function construireTableauRetour() {
$retour = array('entete' => array(), 'resultats' => array());
$retour['resultats'] = $this->construireResultats();
$retour['entete'] = $this->construireEntete();
return $retour;
}
 
private function construireResultats() {
$nomsFormates = array();
foreach ($this->termes as $terme) {
$id = $terme['id_terme'];
$termesFormates[$id] = $this->formaterTerme($terme);
}
return $termesFormates;
}
 
private function formaterTerme($infos) {
$termeAFormater = new OntologieDO($infos);
$this->ontologieFormateur->setTermeAFormater($termeAFormater);
$this->ontologieFormateur->setChampsRetour($this->parametres->getListe('retour.champs'));
$terme = $this->ontologieFormateur->formaterListe();
return $terme;
}
 
private function construireEntete() {
$entete = array('masque' => '', 'depart' => 0, 'limite' => 100, 'total' => 0);
$entete['masque'] = $this->formaterEnteteMasque();
$entete['depart'] = (int) $this->parametres->get('navigation.depart');
$entete['limite'] = (int) $this->parametres->get('navigation.limite');
$entete['total'] = $this->nbreTotalTermes;
if ($hrefPrecedent = $this->formaterEnteteHrefPrecedent()) {
$entete['href.precedent'] = $hrefPrecedent;
}
if ($hrefSuivant = $this->formaterEnteteHrefSuivant()) {
$entete['href.suivant'] = $hrefSuivant;
}
return $entete;
}
 
private function formaterEnteteMasque() {
$masquesStrictes = array('code');
$paramsMasque = array(
'' => 'terme',
'code' => 'id_terme',
'nom' => 'terme',
'description' => 'definition');
$etendre = ($this->parametres->get('recherche') == 'etendue') ? true : false;
 
$masqueComplet = array();
foreach ($paramsMasque as $masqueType => $champ) {
$masqueParam = 'masque'.($masqueType != '' ? '.'.$masqueType : $masqueType);
if ($this->parametres->exister($masqueParam)) {
$masqueValeur = $this->parametres->get($masqueParam);
$masque = "$champ=$masqueValeur";
$masque .= ($etendre && in_array($masqueType, $masquesStrictes) === false) ? '%' : '';
 
$masqueComplet[] = $masque;
}
}
return implode('&', $masqueComplet);
}
 
private function formaterEnteteHrefPrecedent() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departPrecedent = $departActuel - $limite;
$href = null;
if ($departPrecedent >= 0) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departPrecedent, $limite);
}
return $href;
}
 
private function formaterEnteteHrefSuivant() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departSuivant = $departActuel + $limite;
$href = null;
if ($departSuivant < $this->nbreTotalTermes) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departSuivant, $limite);
}
return $href;
}
 
private function construireTplHrefNavigation() {
$requetes = array();
$this->parametres->rewind();
while (is_null($parametre = $this->parametres->key()) === false) {
if (strpos($parametre, 'navigation') === false) {
$valeur = $this->parametres->current();
$requetes[] = "$parametre=$valeur";
}
$this->parametres->next();
}
$requetes[] = "navigation.depart=%s";
$requetes[] = "navigation.limite=%s";
$tpl = $this->listeUrl.'?'.implode('&', $requetes);
return $tpl;
}
}
/tags/v0.1-20130829/services/bibliotheque/generique/NomsListeGenerique.php
New file
0,0 → 1,187
<?php
class NomsListeGenerique {
 
private $parametres = null;
private $ressources = null;
private $nomDao = null;
private $nomFormateur = null;
 
private $listeUrl = null;
private $nbreNomsTotal = 0;
private $noms = array();
 
public function __construct(Ressources $ressources, Parametres $parametres, NomDAO $nomDao, NomFormateur $nomFormateur) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->nomDao = $nomDao;
$this->nomFormateur = $nomFormateur;
}
 
public function setListeUrl($url) {
$this->listeUrl = $url;
}
 
public function consulter() {
$this->rechercher();
if ($this->avoirResultats()) {
$this->trierNoms();
$retour = $this->construireTableauRetour();
} else {
$message = "Aucun résultat ne correspond a votre requête !";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
return $retour;
}
 
private function avoirResultats() {
$resultat = ($this->nbreNomsTotal == 0) ? false : true;
return $resultat;
}
 
 
private function rechercher() {
$resultats = array();
$recherche = $this->parametres->get('recherche');
 
if ($recherche == 'floue') {
$resultats = $this->nomDao->rechercherFloue();
} else {
$resultats = $this->nomDao->rechercher();
}
$this->noms = $resultats;
$this->nbreNomsTotal = $this->nomDao->recupererNombreNomsTotal();
}
 
private function trierNoms() {
$recherche = $this->parametres->get('recherche');
if ($recherche == 'floue') {
$this->trierRechercheFloue();
}
}
 
public function trierRechercheFloue() {
$nomDemande = $this->parametres->get('masque');
$nomDemandeSimple = strtolower(Chaine::supprimerAccents($nomDemande));
 
foreach ($this->noms as $id => $nom) {
$nomFlouSimple = strtolower(Chaine::supprimerAccents($nom['nom_sci']));
// Prime pour la ressemblance globale :
$score = 500 - levenshtein($nomFlouSimple, $nomDemandeSimple);
// On affine
$score += similar_text($nomDemandeSimple, $nomFlouSimple) * 3;
$this->noms[$id]['score'] = $score;
}
$noms = $this->noms;
$this->noms = Tableau::trierMD($noms, array('score' => false));
//print_r($this->noms);
}
 
private function construireTableauRetour() {
$retour = array('entete' => array(), 'resultats' => array());
$retour['resultats'] = $this->construireResultats();
$retour['entete'] = $this->construireEntete();
return $retour;
}
 
private function construireResultats() {
$nomsFormates = array();
foreach ($this->noms as $nom) {
$id = $nom['num_nom'];
$nomsFormates[$id] = $this->formaterNom($nom);
}
return $nomsFormates;
}
 
private function formaterNom($infos) {
$nomAFormater = new NomDO($infos);
$this->nomFormateur->setNomAFormater($nomAFormater);
$this->nomFormateur->setChampsRetour($this->parametres->getListe('retour.champs'));
$nom = $this->nomFormateur->formaterListe();
return $nom;
}
 
private function construireEntete() {
$entete = array('masque' => '', 'depart' => 0, 'limite' => 100, 'total' => 0);
$entete['masque'] = $this->formaterEnteteMasque();
$entete['depart'] = (int) $this->parametres->get('navigation.depart');
$entete['limite'] = (int) $this->parametres->get('navigation.limite');
$entete['total'] = $this->nbreNomsTotal;
if ($hrefPrecedent = $this->formaterEnteteHrefPrecedent()) {
$entete['href.precedent'] = $hrefPrecedent;
}
if ($hrefSuivant = $this->formaterEnteteHrefSuivant()) {
$entete['href.suivant'] = $hrefSuivant;
}
return $entete;
}
 
private function formaterEnteteMasque() {
$masquesStrictes = array('nn', 'rg');
$paramsMasque = array(
'' => 'nom_sci',
'nn' => 'num_nom',
'rg' => 'rang',
'sg' => 'nom_supra_generique',
'gen' => 'genre',
'sp' => 'epithete_sp',
'ssp' => 'epithete_infra_sp',
'au' => 'auteur',
'an' => 'annee');
$etendre = ($this->parametres->get('recherche') == 'etendue') ? true : false;
 
$masqueComplet = array();
foreach ($paramsMasque as $masqueType => $champ) {
$masqueParam = 'masque'.($masqueType != '' ? '.'.$masqueType : $masqueType);
if ($this->parametres->exister($masqueParam)) {
$masqueValeur = $this->parametres->get($masqueParam);
$masque = "$champ=$masqueValeur";
$masque .= ($etendre && in_array($masqueType, $masquesStrictes) === false) ? '%' : '';
 
$masqueComplet[] = $masque;
}
}
return implode('&', $masqueComplet);
}
 
private function formaterEnteteHrefPrecedent() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departPrecedent = $departActuel - $limite;
$href = null;
if ($departPrecedent >= 0) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departPrecedent, $limite);
}
return $href;
}
 
private function formaterEnteteHrefSuivant() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departSuivant = $departActuel + $limite;
$href = null;
if ($departSuivant < $this->nbreNomsTotal) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departSuivant, $limite);
}
return $href;
}
 
private function construireTplHrefNavigation() {
$requetes = array();
$this->parametres->rewind();
while (is_null($parametre = $this->parametres->key()) === false) {
if (strpos($parametre, 'navigation') === false) {
$valeur = $this->parametres->current();
$requetes[] = "$parametre=$valeur";
}
$this->parametres->next();
}
$requetes[] = "navigation.depart=%s";
$requetes[] = "navigation.limite=%s";
$tpl = $this->listeUrl.'?'.implode('&', $requetes);
return $tpl;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/generique/TaxonsListeGenerique.php
New file
0,0 → 1,187
<?php
class TaxonsListeGenerique {
 
private $parametres = null;
private $ressources = null;
private $nomDao = null;
private $nomFormateur = null;
 
private $listeUrl = null;
private $nbreTotalNoms = 0;
private $noms = array();
 
public function __construct(Ressources $ressources, Parametres $parametres, NomDAO $nomDao, NomFormateur $nomFormateur) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->nomDao = $nomDao;
$this->nomFormateur = $nomFormateur;
}
 
public function setListeUrl($url) {
$this->listeUrl = $url;
}
 
public function consulter() {
$this->noms = $this->rechercher();
$this->nbreNomsTotal = $this->nomDao->recupererNombreNomsTotal();
$this->trierNoms();
$retour = $this->construireTableauRetour();
return $retour;
}
 
private function rechercher() {
$resultats = array();
$recherche = $this->parametres->get('recherche');
 
if ($recherche == 'stricte') {
$resultats = $this->nomDao->rechercherStricte();
} else if ($recherche == 'etendue') {
$resultats = $this->nomDao->rechercherEtendue();
} else if ($recherche == 'floue') {
$resultats = $this->nomDao->rechercherFloue();
}
 
return $resultats;
}
 
private function trierNoms() {
$recherche = $this->parametres->get('recherche');
if ($recherche == 'floue') {
$this->trierRechercheFloue();
}
}
 
public function trierRechercheFloue() {
$nomDemande = $this->parametres->get('masque');
$nomDemandeSimple = strtolower(Chaine::supprimerAccents($nomDemande));
 
foreach ($this->noms as $id => $nom) {
$nomFlouSimple = strtolower(Chaine::supprimerAccents($nom['nom_sci']));
// Prime pour la ressemblance globale :
$score = 500 - levenshtein($nomFlouSimple, $nomDemandeSimple);
// On affine
$score += similar_text($nomDemandeSimple, $nomFlouSimple) * 3;
$this->noms[$id]['score'] = $score;
}
$noms = $this->noms;
$this->noms = Tableau::trierMD($noms, array('score' => false));
//print_r($this->noms);
}
 
private function construireTableauRetour() {
$retour = array('entete' => array(), 'resultats' => array());
$retour['resultats'] = $this->construireResultats();
$retour['entete'] = $this->construireEntete();
return $retour;
}
 
private function construireResultats() {
$nomsFormates = array();
foreach ($this->noms as $nom) {
$id = $nom['num_nom'];
$nomsFormates[$id] = $this->formaterNom($nom);
}
return $nomsFormates;
}
 
private function formaterNom($infos) {
$nomAFormater = new NomDO($infos);
$this->nomFormateur->setNomAFormater($nomAFormater);
$this->nomFormateur->setChampsRetour($this->parametres->getListe('retour.champs'));
$nom = $this->nomFormateur->formaterListe();
return $nom;
}
 
private function construireEntete() {
$entete = array('masque' => '', 'depart' => 0, 'limite' => 100, 'total' => 0);
$entete['masque'] = $this->formaterEnteteMasque();
$entete['depart'] = (int) $this->parametres->get('navigation.depart');
$entete['limite'] = (int) $this->parametres->get('navigation.limite');
$entete['total'] = $this->nbreNomsTotal;
if ($hrefPrecedent = $this->formaterEnteteHrefPrecedent()) {
$entete['href.precedent'] = $hrefPrecedent;
}
if ($hrefSuivant = $this->formaterEnteteHrefSuivant()) {
$entete['href.suivant'] = $hrefSuivant;
}
return $entete;
}
 
private function formaterEnteteMasque() {
$masqueComplet = array();
if ($this->parametres->exister('masque')) {
$masque = '';
$masque .= 'nom_sci='.$this->parametres->get('masque');
if ($this->parametres->get('recherche') == 'etendue') {
$masque .= '%';
}
$masqueComplet[] = $masque;
}
if ($this->parametres->exister('masque.sg')) {
$masque = '';
$masque .= 'nom_supra_generique='.$this->parametres->get('masque.sg');
if ($this->parametres->get('recherche') == 'etendue') {
$masque .= '%';
}
$masqueComplet[] = $masque;
}
if ($this->parametres->exister('masque.gen')) {
$masque = '';
$masque .= 'genre='.$this->parametres->get('masque.gen');
if ($this->parametres->get('recherche') == 'etendue') {
$masque .= '%';
}
$masqueComplet[] = $masque;
}
if ($this->parametres->exister('masque.sp')) {
$masque = '';
$masque .= 'epithete_sp='.$this->parametres->get('masque.sp');
if ($this->parametres->get('recherche') == 'etendue') {
$masque .= '%';
}
$masqueComplet[] = $masque;
}
return implode('&', $masqueComplet);
}
 
private function formaterEnteteHrefPrecedent() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departPrecedent = $departActuel - $limite;
$href = null;
if ($departPrecedent >= 0) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departPrecedent, $limite);
}
return $href;
}
 
private function formaterEnteteHrefSuivant() {
$limite = $this->parametres->get('navigation.limite');
$departActuel = $this->parametres->get('navigation.depart');
$departSuivant = $departActuel + $limite;
$href = null;
if ($departSuivant < $this->nbreNomsTotal) {
$squelette = $this->construireTplHrefNavigation();
$href = sprintf($squelette, $departSuivant, $limite);
}
return $href;
}
 
private function construireTplHrefNavigation() {
$requetes = array();
$this->parametres->rewind();
while (is_null($parametre = $this->parametres->key()) === false) {
if (strpos($parametre, 'navigation') === false) {
$valeur = $this->parametres->current();
$requetes[] = "$parametre=$valeur";
}
$this->parametres->next();
}
$requetes[] = "navigation.depart=%s";
$requetes[] = "navigation.limite=%s";
$tpl = $this->listeUrl.'?'.implode('&', $requetes);
return $tpl;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/CacheEflore.php
New file
0,0 → 1,68
<?php
class CacheEflore {
 
private $service;
private $config;
private $dureecache = 0;
private $projetNom;
private $serviceNom;
private $cache;
private $cacheActif;
 
public function __construct($service, $projetNom, $serviceNom, $cacheActif) {
$this->cacheActif = $cacheActif;
$this->service = $service;
$this->chargerDureeCache();
$this->projetNom = $projetNom;
$this->serviceNom = $serviceNom;
$this->cache = new CacheSimple(array(
"mise_en_cache" => true,
"stockage_chemin" => Config::get('chemin_cache').'services'.DS,
"duree_de_vie" => $this->dureecache));
}
 
public function chargerDureeCache() {
if ($this->cacheActif == "1") {
$this->dureecache = Commun::getDureeCache();
}
}
 
public function consulter($ressources, $parametres) {
$id = $this->genererID($ressources, $parametres);
$retour = unserialize($this->cache->charger($id));
if ($retour == false) {
$retour = $this->mettreEnCache($ressources, $parametres);
}
 
return $retour;
}
 
public function mettreEnCache($ressources, $parametres) {
$retour = $this->service->consulter($ressources, $parametres);
$id = $this->genererID($ressources, $parametres);
if ($this->dureecache > 0) {
$this->cache->sauver(serialize($retour), $id);
}
return $retour;
}
 
public function genererID($ressources, $parametres) {
$chaineRessources = "";
$chaineParametres = "";
if (count($ressources) > 0) {
foreach ($ressources as $key => $val) {
$chaineRessources .= "$key:$val;";
}
}
 
if (count($parametres) > 0) {
foreach ($parametres as $key => $val) {
$chaineParametres .= "$key:$val;";
}
}
 
$chaineMD5 = $this->projetNom.'/'.$this->serviceNom.'/'.md5($chaineRessources.$chaineParametres);
return $chaineMD5;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/Conteneur.php
New file
0,0 → 1,201
<?php
class Conteneur {
protected $parametres = array();
protected $partages = array();
 
public function __construct(array $parametres = null) {
$this->parametres = is_null($parametres) ? array() : $parametres;
}
 
public function getParametre($cle) {
$valeur = isset($this->parametres[$cle]) ? $this->parametres[$cle] : Config::get($cle);
return $valeur;
}
 
public function getParametreTableau($cle) {
$tableau = array();
$parametre = $this->getParametre($cle);
if (empty($parametre) === false) {
$tableauPartiel = explode(',', $parametre);
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = trim($champ);
} else {
list($cle, $val) = explode('=', $champ);
$tableau[trim($cle)] = trim($val);
}
}
}
return $tableau;
}
 
public function setParametre($cle, $valeur) {
$this->parametres[$cle] = $valeur;
}
 
public function getParametresUrl() {
if (!isset($this->partages['Parametres'])){
$this->partages['Parametres'] = new Parametres($this->parametres['parametres'], $this->getBdd());
}
return $this->partages['Parametres'];
}
 
public function getParametresUrlVerificateur() {
if (!isset($this->partages['ParametresVerificateur'])){
$parametres = $this->getParametresUrl();
$parametresAPI = $this->getParametreTableau('parametresAPI');
$this->partages['ParametresVerificateur'] = new ParametresVerificateur($parametres, $parametresAPI);
}
return $this->partages['ParametresVerificateur'];
}
 
public function getRessourcesUrl() {
if (!isset($this->partages['Ressources'])){
$this->partages['Ressources'] = new Ressources($this->parametres['ressources']);
}
return $this->partages['Ressources'];
}
 
public function getRessourcesUrlVerificateur() {
if (!isset($this->partages['RessourcesVerificateur'])){
$ressources = $this->getRessourcesUrl();
$projetsDispo = $this->getParametreTableau('projetsDispo');
$servicesDispo = $this->getParametreTableau('servicesDispo');
$this->partages['RessourcesVerificateur'] = new RessourcesVerificateur($ressources, $projetsDispo, $servicesDispo);
}
return $this->partages['RessourcesVerificateur'];
}
public function getUrlFormatage() {
if (!isset($this->partages['UrlFormatage'])){
$Bdd = $this->getBdd();
$this->partages['UrlFormatage'] = new UrlFormatage($Bdd);
}
return $this->partages['UrlFormatage'];
}
public function getRequetesAssemblage() {
if (!isset($this->partages['RequetesAssemblage'])){
$this->partages['RequetesAssemblage'] = new RequetesAssemblage($this->getBdd());
}
return $this->partages['RequetesAssemblage'];
}
 
public function getVersionVerificateur() {
if (!isset($this->partages['VersionVerificateur'])){
$ressources = $this->getRessourcesUrl();
$parametres = $this->getParametresUrl();
$versions = $this->getVersions();
$this->partages['VersionVerificateur'] = new VersionVerificateur($ressources, $parametres, $versions);
}
return $this->partages['VersionVerificateur'];
}
 
public function getBdd() {
if (!isset($this->partages['Bdd'])){
$this->partages['Bdd'] = new Bdd();
}
return $this->partages['Bdd'];
}
 
public function getCacheSimple($options = array()) {
$cache = new CacheSimple($options);
return $cache;
}
 
public function getVersions() {
if (!isset($this->partages['Versions'])){
$parametres = $this->getParametresUrl();
$ressources = $this->getRessourcesUrl();
$bdd = $this->getBdd();
$versions = new Versions($parametres, $bdd);
$this->partages['Versions'] = $versions;
}
return $this->partages['Versions'];
}
 
public function getProjet() {
if (!isset($this->partages['Projet'])){
$ressources = $this->getRessourcesUrl();
$projet = new Projet($ressources);
$projet->setCheminBase($this->getParametre('cheminBase'));
$projet->setCheminConfig($this->getParametre('chemin_configurations'));
$projet->setCheminBiblio($this->getParametre('chemin_bibliotheque'));
$projet->initialiser();
$projet->setParamsVerif($this->getParametresUrlVerificateur());
$projet->setRessourcesVerif($this->getRessourcesUrlVerificateur());
$projet->setVersionVerif($this->getVersionVerificateur());
$projet->setServiceGenerique($this->getServiceGenerique());
$this->partages['Projet'] = $projet;
}
return $this->partages['Projet'];
}
 
public function getNomDao() {
$ressources = $this->getRessourcesUrl();
$parametres = $this->getParametresUrl();
$bdd = $this->getBdd();
$versions = $this->getVersions();
$nomDao = new NomDAO($ressources, $parametres, $bdd, $versions);
return $nomDao;
}
 
public function getOntologiesDao() {
$ressources = $this->getRessourcesUrl();
$parametres = $this->getParametresUrl();
$bdd = $this->getBdd();
$versions = $this->getVersions();
$ontologieDao = new OntologieDAO($ressources, $parametres, $bdd, $versions);
return $ontologieDao;
}
 
public function getNomFormateur() {
$formateur = new NomFormateur();
$formateur->setBdd($this->getBdd());
$formateur->setChampsProjet($this->getParametreTableau('champsProjet'));
$formateur->setDetailsHrefTpl($this->getParametre('detailsHrefTpl'));
$formateur->setOntologieHrefTpl($this->getParametre('ontologieHrefTpl'));
return $formateur;
}
 
public function getOntologiesFormateur() {
$formateur = new OntologieFormateur();
$formateur->setBdd($this->getBdd());
$formateur->setChampsProjet($this->getParametreTableau('champsProjet'));
$formateur->setDetailsHrefTpl($this->getParametre('detailsHrefOntologiesTpl'));
$formateur->setLangueDemandee($this->getParametresUrl()->get('retour.langue'));
return $formateur;
}
 
public function getWikipediaBot($options = array()) {
$wpBot = new WikipediaBot($options);
return $wpBot;
}
 
public function getUrl($url) {
$url = new Url($url);
return $url;
}
 
public function getServiceGenerique() {
$ressources = $this->getRessourcesUrl();
$classe = $ressources->getServiceClasse();
$classeGenerique = $classe.'Generique';
if ($ressources->getServiceNom() == 'noms' || $ressources->getServiceNom() == 'taxons') {
$service = new $classeGenerique($this->getRessourcesUrl(), $this->getParametresUrl(), $this->getNomDao(), $this->getNomFormateur());
if ($classe == 'NomsListe') {
$service->setListeUrl($this->getParametre('listeUrl'));
}
} else if ($ressources->getServiceNom() == 'ontologies') {
$service = new $classeGenerique($this->getRessourcesUrl(), $this->getParametresUrl(), $this->getOntologiesDao(), $this->getOntologiesFormateur());
if ($classe == 'OntologiesListe') {
$service->setListeUrl($this->getParametre('listeUrlOntologies'));
}
}
 
return $service;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomRangDecorateur.php
New file
0,0 → 1,47
<?php
class NomRangDecorateur extends NomDecorateur {
 
private $nomDecorateur = null;
private $rang = null;
private $bdd = null;
private $ontologieHrefTpl = null;
protected $correspondances = array(
'rang' => 'Intitule',
'rang.code' => 'Code',
'rang.href' => 'Href',
'rang.*' => 'Intitule,Code,Href');
 
public function __construct(NomDecorateur $nomDecorateur, Bdd $bdd = null, $ontologieHrefTpl) {
$this->nomDecorateur = $nomDecorateur;
$this->rang = $this->nomDecorateur->nom->getTag('rang');
$this->bdd = is_null($bdd) ? new Bdd() : $bdd;
$this->ontologieHrefTpl = $ontologieHrefTpl;
}
 
public function ajouterCode() {
$squelette = 'bdnt.rangTaxo:%s';
$rangCode = sprintf($squelette, $this->rang);
$this->nomDecorateur->nomFormate['rang.code'] = $rangCode;
}
 
public function ajouterHref() {
$href = sprintf($this->ontologieHrefTpl, $this->rang);
$this->nomDecorateur->nomFormate['rang.href'] = $href;
}
 
public function ajouterIntitule() {
$resultat = $this->rechercherOntologieNomParCode($this->rang);
$this->nomDecorateur->nomFormate['rang'] = $resultat['nom'];
}
 
// TODO : supprimer cette recherche dans la bdd de cette classe
private function rechercherOntologieNomParCode($code) {
$code = $this->bdd->proteger($code);
$requete = 'SELECT nom '.
'FROM bdnt_ontologies_v4_30 '.
"WHERE code = $code ";
$resultats = $this->bdd->recuperer($requete);
return $resultats;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomCompoDecorateur.php
New file
0,0 → 1,84
<?php
class NomCompoDecorateur extends NomDecorateur {
 
private $nomDecorateur;
protected $correspondances = array(
'nom_sci.*' => 'Compo',
'nom_sci.supra_generique', 'SupraGenre',
'nom_sci.genre' => 'Genre',
'nom_sci.infra_generique' => 'InfraGenre',
'nom_sci.sp' => 'Sp',
'nom_sci.type_epithete' => 'TypeInfraSp',
'nom_sci.infra_sp' => 'InfraSp',
'nom_sci.cultivar_groupe' => 'CultivarGroupe',
'nom_sci.cultivar' => 'Cultivar',
'nom_sci.nom_commercial' => 'NomCommercial');
 
public function __construct(NomDecorateur $nomDecorateur) {
$this->nomDecorateur = $nomDecorateur;
}
 
public function ajouterCompo() {
$this->ajouterSupraGenre();
$this->ajouterGenre();
$this->ajouterInfraGenre();
$this->ajouterSp();
$this->ajouterTypeInfraSp();
$this->ajouterInfraSp();
$this->ajouterCultivarGroupe();
$this->ajouterCultivar();
$this->ajouterNomCommercial();
}
 
public function ajouterSupraGenre() {
$this->ajouterPourChampSonFormatage('nom_supra_generique', 'supra_generique');
}
 
public function ajouterGenre() {
$this->ajouterPourChampSonFormatage('genre', 'genre');
}
 
public function ajouterInfraGenre() {
$this->ajouterPourChampSonFormatage('epithete_infra_generique', 'infra_generique');
}
 
public function ajouterSp() {
$this->ajouterPourChampSonFormatage('epithete_sp', 'sp');
}
 
public function ajouterTypeInfraSp() {
$this->ajouterPourChampSonFormatage('type_epithete', 'type_epithete');
}
 
public function ajouterInfraSp() {
$this->ajouterPourChampSonFormatage('epithete_infra_sp', 'infra_sp');
}
 
public function ajouterCultivarGroupe() {
$this->ajouterPourChampSonFormatage('cultivar_groupe', 'cultivar_groupe');
}
 
public function ajouterCultivar() {
$this->ajouterPourChampSonFormatage('cultivar', 'cultivar');
}
 
public function ajouterNomCommercial() {
$this->ajouterPourChampSonFormatage('nom_commercial', 'nom_commercial');
}
 
private function ajouterPourChampSonFormatage($champ, $format) {
$valeur = $this->nomDecorateur->nom->getTag($champ);
if ($this->exister($valeur)) {
$this->nomDecorateur->nomFormate["nom_sci.$format"] = $valeur;
}
}
 
private function exister($valeur) {
$existe = true;
if (is_null($valeur) || $valeur == '') {
$existe = false;
}
return $existe;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomChampsProjetDecorateur.php
New file
0,0 → 1,36
<?php
class NomChampsProjetDecorateur extends NomDecorateur {
 
private $nomDecorateur = null;
private $champs = array();
protected $correspondances = array();
 
public function __construct(NomDecorateur $nomDecorateur, Array $champs) {
$this->nomDecorateur = $nomDecorateur;
$this->champs = $champs;
$this->correspondances = array_flip($this->champs);
}
 
public function traiterChampsRetour(Array $champsRetour) {
foreach ($champsRetour as $champ) {
if (array_key_exists($champ, $this->correspondances)) {
$champBdd = $this->correspondances[$champ];
$champSortie = $champ;
if ($this->nomDecorateur->nom->verifierTag($champBdd)) {
$valeur = $this->nomDecorateur->nom->getTag($champBdd);
$this->nomDecorateur->nomFormate[$champSortie] = $valeur;
}
}
}
}
 
public function ajouterChampsSupplementaires() {
foreach ($this->champs as $champBdd => $champSortie) {
if ($this->nomDecorateur->nom->verifierTag($champBdd)) {
$valeur = $this->nomDecorateur->nom->getTag($champBdd);
$this->nomDecorateur->nomFormate[$champSortie] = $valeur;
}
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomDecorateur.php
New file
0,0 → 1,96
<?php
class NomDecorateur implements NomResponsabilite {
protected $nom = null;
protected $nomFormate = array();
private $detailsHrefTpl = null;
protected $correspondances = array(
'id' => 'Id',
'nom_sci' => 'Intitule',
'href' => 'Href',
'auteur' => 'Auteur',
'annee' => 'Annee',
'biblio_origine' => 'Biblio',
'nom_addendum' => 'Addendum',
'notes' => 'Notes',
'homonyme' => 'Homonyme');
 
public function __construct(NomDO $nomADecorer, $detailsHrefTpl) {
$this->nom = $nomADecorer;
$this->detailsHrefTpl = $detailsHrefTpl;
$this->initialiserNomFormate();
}
 
public function traiterChampsRetour(Array $champsRetour) {
foreach ($champsRetour as $champ) {
if (array_key_exists($champ, $this->correspondances)) {
$methodesAExecuter = explode(',', $this->correspondances[$champ]);
foreach ($methodesAExecuter as $methodeNom) {
$methodeAjouter = 'ajouter'.$methodeNom;
if (method_exists($this, $methodeAjouter)) {
$this->$methodeAjouter();
}
}
}
}
}
 
public function ajouterId() {
$this->nomFormate['id'] = (int) $this->nom->getTag('num_nom');
}
 
public function ajouterIntitule() {
$this->nomFormate['nom_sci'] = $this->nom->getTag('nom_sci');
}
 
public function ajouterHref() {
if ($this->nom->verifierTag('num_nom')) {
$href = sprintf($this->detailsHrefTpl, $this->nom->getTag('num_nom'));
$this->nomFormate['href'] = $href;
}
}
 
public function ajouterAuteur() {
if ($this->nom->verifierTag('auteur')) {
$this->nomFormate['auteur'] = $this->nom->getTag('auteur');
}
}
 
public function ajouterAnnee() {
if ($this->nom->verifierTag('annee')) {
$this->nomFormate['annee'] = $this->nom->getTag('annee');
}
}
 
public function ajouterBiblio() {
if ($this->nom->verifierTag('biblio_origine')) {
$this->nomFormate['biblio_origine'] = $this->nom->getTag('biblio_origine');
}
}
 
public function ajouterAddendum() {
if ($this->nom->verifierTag('nom_addendum')) {
$this->nomFormate['nom_addendum'] = $this->nom->getTag('nom_addendum');
}
}
 
public function ajouterNotes() {
if ($this->nom->verifierTag('notes')) {
$this->nomFormate['notes'] = $this->nom->getTag('notes');
}
}
 
public function ajouterHomonyme() {
if ($this->nom->verifierTag('homonyme') && $this->nom->getTag('homonyme') == 1) {
$this->nomFormate['homonyme'] = true;
}
}
 
public function initialiserNomFormate() {
$this->nomFormate = array();
}
 
public function getNomFormate() {
return $this->nomFormate;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomRetenuDecorateur.php
New file
0,0 → 1,47
<?php
class NomRetenuDecorateur extends NomDecorateur {
 
private $nomDecorateur = null;
private $numNom = null;
private $numNomRetenu = null;
private $nomSciRetenu = null;
private $detailsHrefTpl = null;
protected $correspondances = array(
'retenu' => 'Retenu',
'nom_retenu' => 'Intitule',
'nom_retenu.id' => 'Id',
'nom_retenu.href' => 'Href',
'nom_retenu.*' => 'Intitule,Id,Href');
 
public function __construct(NomDecorateur $nomDecorateur, $detailsHrefTpl) {
$this->nomDecorateur = $nomDecorateur;
$this->numNom = $this->nomDecorateur->nom->getTag('num_nom');
$this->numNomRetenu = $this->nomDecorateur->nom->getTag('num_nom_retenu');
$this->nomSciRetenu = $this->nomDecorateur->nom->getTag('nr_nom_sci');
$this->detailsHrefTpl = $detailsHrefTpl;
}
 
public function ajouterRetenu() {
$nn = (int) $this->numNom;
$nnr = (int) $this->numNomRetenu;
$this->nomDecorateur->nomFormate['retenu'] = ($nn == $nnr) ? true : false;
}
 
public function ajouterId() {
if (empty($this->numNomRetenu) === false) {
$this->nomDecorateur->nomFormate['nom_retenu.id'] = (int) $this->numNomRetenu;
}
}
 
public function ajouterHref() {
if (empty($this->numNomRetenu) === false) {
$href = sprintf($this->detailsHrefTpl, $this->numNomRetenu);
$this->nomDecorateur->nomFormate['nom_retenu.href'] = $href;
}
}
 
public function ajouterIntitule() {
$this->nomDecorateur->nomFormate['nom_retenu'] = $this->nomSciRetenu;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomResponsabilite.php
New file
0,0 → 1,5
<?php
interface NomResponsabilite {
public function traiterChampsRetour(Array $champsRetour);
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/decorateurs/NomBasionymeDecorateur.php
New file
0,0 → 1,44
<?php
class NomBasionymeDecorateur extends NomDecorateur {
 
private $nomDecorateur = null;
private $basionyme = null;
private $basionymeId = null;
private $detailsHrefTpl = null;
protected $correspondances = array(
'basionyme' => 'Intitule',
'basionyme.id' => 'Id',
'basionyme.href' => 'Href',
'basionyme.*' => 'Intitule,Id,Href');
 
public function __construct(NomDecorateur $nomDecorateur, $detailsHrefTpl) {
$this->nomDecorateur = $nomDecorateur;
$this->detailsHrefTpl = $detailsHrefTpl;
if ($this->nomDecorateur->nom->verifierTag('basionyme')) {
$this->basionymeId = $this->nomDecorateur->nom->getTag('basionyme');
}
if ($this->nomDecorateur->nom->verifierTag('nb_nom_sci')) {
$this->basionyme = $this->nomDecorateur->nom->getTag('nb_nom_sci');
}
}
 
public function ajouterId() {
if (is_null($this->basionymeId) === false) {
$this->nomDecorateur->nomFormate['basionyme.id'] = $this->basionymeId;
}
}
 
public function ajouterHref() {
if (is_null($this->basionymeId) === false) {
$href = sprintf($this->detailsHrefTpl, $this->basionymeId);
$this->nomDecorateur->nomFormate['basionyme.href'] = $href;
}
}
 
public function ajouterIntitule() {
if (is_null($this->basionyme) === false) {
$this->nomDecorateur->nomFormate['basionyme'] = $this->basionyme;
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/NomDO.php
New file
0,0 → 1,21
<?php
class NomDO {
private $infos;
 
public function __construct(Array $infos) {
$this->infos = $infos;
}
 
public function getTag($tag) {
return isset($this->infos[$tag]) ? $this->infos[$tag] : null;
}
 
public function verifierTag($tag) {
$existe = true;
if ($this->getTag($tag) == null || $this->getTag($tag) == '') {
$existe = false;
}
return $existe;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/NomDAO.php
New file
0,0 → 1,155
<?php
class NomDAO {
private $bdd = null;
private $versions = null;
private $requeteNbreNomsTotal = null;
 
public function __construct(Ressources $ressources, Parametres $parametres, Bdd $bdd, Versions $versions) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->bdd = $bdd;
$this->versions = $versions;
}
 
public function rechercherInfosNom() {
$table = $this->getTable();
$detailsId = $this->ressources->getDetailsId();
$detailsId = $this->bdd->proteger($detailsId);
$requete =
'SELECT ns.*, '.
' nr.nom_sci AS nr_nom_sci, nb.nom_sci AS nb_nom_sci '.
"FROM $table AS ns ".
" LEFT JOIN $table AS nr ON (ns.num_nom_retenu = nr.num_nom) ".
" LEFT JOIN $table AS nb ON (ns.basionyme = nb.num_nom) ".
"WHERE ns.num_nom = $detailsId ";
$resultats = $this->bdd->recuperer($requete);
$nom = new NomDO($resultats);
return $nom;
}
 
public function rechercher() {
$clause = $this->getClauseSelectSpeciale();
$table = $this->getTable();
$conditions = $this->getConditions();
$where = $this->getWhere($conditions);
$navigation = $this->getNavigation();
 
$requete = "SELECT $clause ns.*, ".
' nr.nom_sci AS nr_nom_sci, nb.nom_sci AS nb_nom_sci '.
"FROM $table AS ns ".
" LEFT JOIN $table AS nr ON (ns.num_nom_retenu = nr.num_nom) ".
" LEFT JOIN $table AS nb ON (ns.basionyme = nb.num_nom) ".
$where.' '.$conditions.' '.
'ORDER BY ns.nom_sci ASC '.
"LIMIT $navigation ";
$this->requeteNbreNomsTotal = $this->transformerRequetePourNbreNomsTotal($requete);
$resultats = $this->bdd->recupererTous($requete);
 
return $resultats;
}
 
public function rechercherFloue() {
$clause = $this->getClauseSelectSpeciale();
$table = $this->getTable();
$masque = $this->parametres->getMasquePourBdd();
$where = $this->getWhere();
$navigation = $this->getNavigation();
 
$requete = "SELECT $clause ns.*, ".
' nr.nom_sci AS nr_nom_sci, nb.nom_sci AS nb_nom_sci '.
"FROM $table AS ns ".
" LEFT JOIN $table AS nr ON (ns.num_nom_retenu = nr.num_nom) ".
" LEFT JOIN $table AS nb ON (ns.basionyme = nb.num_nom) ".
$where .
($masque ? ($where ? ' AND ' : ' WHERE ').
" (SOUNDEX(ns.nom_sci) = SOUNDEX($masque)) ".
" OR (SOUNDEX(REVERSE(ns.nom_sci)) = SOUNDEX(REVERSE($masque))) " : '').
'ORDER BY ns.nom_sci ASC '.
"LIMIT $navigation ";
$this->requeteNbreNomsTotal = $this->transformerRequetePourNbreNomsTotal($requete);
$resultats = $this->bdd->recupererTous($requete);
return $resultats;
}
 
private function getClauseSelectSpeciale() {
$clause = (Config::get('bdd_protocole') == 'mysql') ? 'SQL_CALC_FOUND_ROWS' : '';
return $clause;
}
 
private function getTable() {
$versions = $this->versions->getVersions();
$derniereVersion = end($versions);
$projetNom = strtolower($this->ressources->getProjetNom());
return $projetNom.'_v'.$derniereVersion;
}
 
private function getConditions() {
$masquesStrictes = array('nn', 'rg');
$paramsMasque = array(
'' => 'nom_sci',
'nn' => 'num_nom',
'rg' => 'rang',
'sg' => 'nom_supra_generique',
'gen' => 'genre',
'sp' => 'epithete_sp',
'ssp' => 'epithete_infra_sp',
'au' => 'auteur',
'an' => 'annee');
 
$operateurParDefaut = $this->getOperateurCondition();
$conditionsSql = array();
foreach ($paramsMasque as $typeMasque => $champ) {
$operateur = in_array($typeMasque, $masquesStrictes) ? '=' : $operateurParDefaut;
if ($valeurMasque = $this->parametres->getMasquePourBdd($typeMasque)) {
$conditionsSql[] = "ns.$champ $operateur $valeurMasque";
}
}
return implode(' AND ', $conditionsSql);
}
 
private function getOperateurCondition() {
$operateur = '';
$recherche = $this->parametres->get('recherche');
if ($recherche == 'stricte') {
$operateur = '=';
} else if ($recherche == 'etendue') {
$operateur = 'LIKE';
}
return $operateur;
}
 
private function getWhere($conditions = '') {
$where = '';
if ($this->ressources->getServiceNom() == 'taxons') {
$where = 'WHERE ns.num_nom = ns.num_nom_retenu ';
} else if ($conditions != '') {
$where = 'WHERE ';
}
return $where;
}
 
private function getNavigation() {
$debut = (int) $this->parametres->get('navigation.depart');
$nbre = $this->parametres->get('navigation.limite');
$navigation = "$debut,$nbre";
return $navigation;
}
 
private function transformerRequetePourNbreNomsTotal($requete) {
$requete = preg_replace('/SELECT .* FROM/', 'SELECT COUNT(*) AS nbre FROM', $requete);
$requete = preg_replace('/LIMIT [0-9]+,[0-9]+/', '', $requete);
return $requete;
}
 
public function recupererNombreNomsTotal() {
if (Config::get('bdd_protocole') == 'mysql') {
$requete = 'SELECT FOUND_ROWS() AS nbre';
} else {
$requete = $this->requeteNbreNomsTotal;
}
 
$nombre = $this->bdd->recuperer($requete);
return (int) $nombre['nbre'];
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/nom/NomFormateur.php
New file
0,0 → 1,121
<?php
class NomFormateur {
 
private $nomAFormater = null;
private $decorateurs = array();
private $bdd = null;
private $champsProjet = array();
private $champsRetour = null;
private $detailsHrefTpl = null;
private $ontologieHrefTpl = null;
 
public function setNomAFormater(NomDO $nomDO) {
$this->nomAFormater = $nomDO;
}
 
public function setChampsRetour(Array $champsRetour) {
$this->champsRetour = $champsRetour;
}
 
public function setChampsProjet(Array $champsProjet) {
$this->champsProjet = $champsProjet;
}
 
public function setDetailsHrefTpl($tpl) {
$this->detailsHrefTpl = $tpl;
}
 
public function setBdd($bdd) {
$this->bdd = $bdd;
}
 
public function setOntologieHrefTpl($tpl) {
$this->ontologieHrefTpl = $tpl;
}
 
public function formaterDetails() {
$nomDeco = new NomDecorateur($this->nomAFormater, $this->detailsHrefTpl);
$retenuDeco = new NomRetenuDecorateur($nomDeco, $this->detailsHrefTpl);
$rangDeco = new NomRangDecorateur($nomDeco, $this->bdd, $this->ontologieHrefTpl);
$compoDeco = new NomCompoDecorateur($nomDeco);
$basioDeco = new NomBasionymeDecorateur($nomDeco, $this->detailsHrefTpl);
$projetDeco = new NomChampsProjetDecorateur($nomDeco, $this->champsProjet);
 
if ($this->avoirDemandeChampsRetour()) {
$this->decorateurs[] = $nomDeco;
$this->decorateurs[] = $retenuDeco;
$this->decorateurs[] = $rangDeco;
$this->decorateurs[] = $compoDeco;
$this->decorateurs[] = $basioDeco;
$this->decorateurs[] = $projetDeco;
 
$this->traiterChampsRetour();
} else {
$nomDeco->ajouterId();
$nomDeco->ajouterIntitule();
 
$retenuDeco->ajouterRetenu();
$retenuDeco->ajouterId();
$retenuDeco->ajouterIntitule();
$retenuDeco->ajouterHref();
 
$rangDeco->ajouterCode();
$rangDeco->ajouterIntitule();
$rangDeco->ajouterHref();
 
$compoDeco->ajouterCompo();
 
$nomDeco->ajouterAuteur();
$nomDeco->ajouterAnnee();
$nomDeco->ajouterBiblio();
$nomDeco->ajouterAddendum();
$nomDeco->ajouterNotes();
 
$basioDeco->ajouterId();
$basioDeco->ajouterIntitule();
$basioDeco->ajouterHref();
 
$projetDeco->ajouterChampsSupplementaires();
}
return $nomDeco->getNomFormate();
}
 
public function formaterListe() {
$nomDeco = new NomDecorateur($this->nomAFormater, $this->detailsHrefTpl);
$nomDeco->ajouterIntitule();
 
$retenuDeco = new NomRetenuDecorateur($nomDeco, $this->detailsHrefTpl);
$retenuDeco->ajouterRetenu();
 
$nomDeco->ajouterHref();
 
if ($this->avoirDemandeChampsRetour()) {
$this->decorateurs[] = $nomDeco;
$this->decorateurs[] = $retenuDeco;
 
$this->decorateurs[] = new NomRangDecorateur($nomDeco, $this->bdd, $this->ontologieHrefTpl);
$this->decorateurs[] = new NomCompoDecorateur($nomDeco);
$this->decorateurs[] = new NomBasionymeDecorateur($nomDeco, $this->detailsHrefTpl);
$this->decorateurs[] = new NomChampsProjetDecorateur($nomDeco, $this->champsProjet);
 
$this->traiterChampsRetour();
}
 
return $nomDeco->getNomFormate();
}
 
private function avoirDemandeChampsRetour() {
$demande = true;
if ($this->champsRetour === null || count($this->champsRetour) == 0) {
$demande = false;
}
return $demande;
}
 
private function traiterChampsRetour() {
foreach ($this->decorateurs as $deco) {
$deco->traiterChampsRetour($this->champsRetour);
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/Parametres.php
New file
0,0 → 1,124
<?php
// TODO : il est peut être nécessaire de mieux distinguer les attributs parametres et parametresOrigine
// TODO : déplacer les méthodes getMasquePourBdd et getPourBdd dans les DAO
class Parametres implements Iterator {
 
private $parametres = array();
private $parametresOrigine = array();
private $parametresTypeEntier = array('navigation.limite', 'navigation.depart');
private $bdd = null;
 
public function __construct(Array $parametres, Bdd $bdd) {
$this->parametresOrigine = $parametres;
$this->parametres = $this->parametresOrigine;
$this->bdd = $bdd;
$this->definirValeursParDefaut();
}
 
public function current () {
return current($this->parametresOrigine);
}
 
public function key() {
return key($this->parametresOrigine);
}
 
public function next() {
return next($this->parametresOrigine);
}
 
public function rewind() {
return reset($this->parametresOrigine);
}
 
public function valid() {
return current($this->parametresOrigine) == false ? false : true;
}
 
public function get($parametreCode) {
$valeur = '';
if ($this->exister($parametreCode)) {
$valeur = $this->parametres[$parametreCode];
}
return $this->etreParametreDeTypeEntier($parametreCode) ? (int) $valeur : $valeur;
}
 
private function etreParametreDeTypeEntier($parametreCode) {
$entier = in_array($parametreCode, $this->parametresTypeEntier) ? true : false;
return $entier;
}
 
public function getListe($parametreCode) {
$valeurs = array();
if ($this->exister($parametreCode)) {
$valeurs = explode(',', $this->parametres[$parametreCode]);
$valeurs = array_map('trim', $valeurs);
}
return $valeurs;
}
 
public function exister($parametreCode) {
$existe = false;
if (array_key_exists($parametreCode, $this->parametres) && $this->parametres[$parametreCode] != '') {
$existe = true;
}
return $existe;
}
 
public function getPourBdd($parametreCode) {
$valeur = false;
if ($this->exister($parametreCode)) {
$valeur = $this->get($parametreCode);
$valeur = $this->proteger($valeur);
}
return $valeur;
}
 
private function proteger($valeur) {
$valeur = $this->bdd->proteger($valeur);
return $valeur;
}
 
public function getMasquePourBdd($type = '') {
$masque = false;
$parametreMasque = 'masque'.($type != '' ? '.'.$type : $type);
if ($this->exister($parametreMasque)) {
$masque = $this->get($parametreMasque);
$recherche = $this->get('recherche');
if ($recherche == 'etendue') {
$masque = str_replace(' ', '% ', $masque);
$masque .= '%';
}
$masque = $this->proteger($masque);
}
return $masque;
}
 
private function definirValeursParDefaut() {
if ($this->exister('recherche') == false) {
$this->parametres['recherche'] = 'stricte';
}
if ($this->exister('ns.format') == false) {
$this->parametres['ns.format'] = 'txt';
}
if ($this->exister('retour') == false) {
$this->parametres['retour'] = 'application/json';
}
if ($this->exister('retour.format') == false) {
$this->parametres['retour.format'] = 'max';
}
if ($this->exister('retour.langue') == false) {
$this->parametres['retour.langue'] = 'fr';
}
if ($this->exister('version.projet') == false) {
$this->parametres['version.projet'] = '+';
}
if ($this->exister('navigation.depart') == false) {
$this->parametres['navigation.depart'] = (int) 0;
}
if ($this->exister('navigation.limite') == false) {
$this->parametres['navigation.limite'] = (int) 100;
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/Projet.php
New file
0,0 → 1,135
<?php
class Projet {
private $ressources = null;
private $paramsVerif = null;
private $ressourcesVerif = null;
private $versionVerif = null;
private $cheminBase = '';
private $cheminConfig = '';
private $cheminBiblio = '';
private $serviceGenerique = '';
 
public function __construct(Ressources $ressources) {
$this->ressources = $ressources;
}
 
public function setCheminBase($chemin) {
$this->cheminBase = $chemin;
}
 
public function setCheminConfig($chemin) {
$this->cheminConfig = $chemin;
}
 
public function setCheminBiblio($chemin) {
$this->cheminBiblio = $chemin;
}
 
public function setParamsVerif($paramsVerificateur) {
$this->paramsVerif = $paramsVerificateur;
}
 
public function setVersionVerif($versionVerificateur) {
$this->versionVerif = $versionVerificateur;
}
 
public function setRessourcesVerif($ressourcesVerificateur) {
$this->ressourcesVerif = $ressourcesVerificateur;
}
 
public function setServiceGenerique($generique) {
$this->serviceGenerique = $generique;
}
 
public function initialiser() {
$this->chargerConfig();
// php5.3 : Enregistrement en première position des autoload de la méthode gérant les classes des services
if (phpversion() < 5.3) {
spl_autoload_register(array($this, 'chargerClasseProjet'));
} else {
spl_autoload_register(array($this, 'chargerClasseProjet'), true , true);
}
}
 
private function chargerConfig() {
$projet = $this->getNom();
$chemin = $this->cheminConfig."config_$projet.ini";
Config::charger($chemin);
}
 
public function getNom() {
return $this->ressources->getProjetNom();
}
 
public function getClasse() {
return $this->ressources->getServiceClasse().ucfirst($this->getNom());
}
 
private function chargerClasseProjet($classe) {
if (class_exists($classe)) {
return null;
}
 
$chemins = array();
$chemins[] = $this->cheminBase.$this->getNom().DS;
$chemins[] = $this->cheminBase.'commun'.DS;
$chemins[] = $this->cheminBiblio;
$chemins[] = $this->cheminBiblio.'generique'.DS;
$chemins[] = $this->cheminBiblio.'interfaces'.DS;
$chemins[] = $this->cheminBiblio.'nom'.DS;
$chemins[] = $this->cheminBiblio.'nom'.DS.'decorateurs'.DS;
$chemins[] = $this->cheminBiblio.'ontologie'.DS;
$chemins[] = $this->cheminBiblio.'ontologie'.DS.'decorateurs'.DS;
 
foreach ($chemins as $chemin) {
$chemin = $chemin.$classe.'.php';
if (file_exists($chemin)) {
require_once $chemin;
}
}
}
 
public function verifier() {
$this->paramsVerif->verifier();
$this->ressourcesVerif->verifier();
$this->versionVerif->verifier();
$this->verifierExistanceServiceClasse();
}
 
private function verifierExistanceServiceClasse() {
$classe = $this->getClasse();
$existe = $this->verifierExistanceClasseDuProjet($classe);
 
if ($existe === false) {
$service = $this->ressources->getServiceNom();
$projet = $this->getNom();
$message = "La classe du service demandé '$service' n'existe pas dans le projet '$projet' !";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
}
 
private function verifierExistanceClasseDuProjet($classe) {
$chemins = array();
$chemins[] = $this->cheminBase.$this->getNom().DS.$classe.'.php';
$chemins[] = $this->cheminBase.'commun'.DS.$classe.'.php';
 
$existe = false;
foreach ($chemins as $chemin) {
if (file_exists($chemin)) {
$existe = true;
break;
}
}
return $existe;
}
 
public function consulter() {
$serviceNom = $this->getClasse();
$service = new $serviceNom($this->serviceGenerique);
$retour = $service->consulter();
return $retour;
}
 
}
?>
/tags/v0.1-20130829/services/bibliotheque/RessourcesVerificateur.php
New file
0,0 → 1,51
<?php
class RessourcesVerificateur {
 
private $ressources = null;
private $projetsDispo = array();
private $servicesDispo = array();
 
public function __construct(Ressources $ressources, Array $projetsDispo, Array $servicesDispo) {
$this->ressources = $ressources;
$this->projetsDispo = $projetsDispo;
$this->servicesDispo = $servicesDispo;
}
 
public function verifier() {
$this->verifierPresenceRessources();
$this->verifierPresenceProjet();
$this->verifierPresenceService();
}
 
private function verifierPresenceRessources() {
if ($this->ressources->getNombre() == 0) {
$message = "Aucune ressource n'a été indiquée.\n".
"Veuillez indiquer au moins un code de projet et un type de service.";
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
}
 
private function verifierPresenceProjet() {
$projet = $this->ressources->getProjetNom();
if (in_array($projet, $this->projetsDispo) === false) {
$message = "La ressource '$projet' n'indique pas un projet existant.\n".
"Les projets existant sont :\n".implode(', ', $this->projetsDispo);
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
}
 
private function verifierPresenceService() {
$service = $this->ressources->getServiceNom();
if (in_array($service, $this->servicesDispo) === false) {
$message = "La service demandé '$service' n'est pas disponible pour le projet '{$this->ressources->getProjetNom()}' !\n".
"Les services disponibles sont : ".implode(', ', $this->servicesDispo);
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
}
 
 
}
?>
/tags/v0.1-20130829/services/bibliotheque/Versions.php
New file
0,0 → 1,65
<?php
class Versions {
private $parametres = null;
private $ressources = null;
private $bdd = null;
private $projetNom = null;
private $versionsDispo = array();
private $versionCourrante = array();
 
public function __construct(Parametres $parametres, Ressources $ressources, Bdd $bdd) {
$this->parametres = $parametres;
$this->ressources = $ressources;
$this->bdd = $bdd;
$this->projetNom = $this->ressources->getProjetNom();
$this->versionsDispo = $this->chargerVersionsDisponibles();
}
 
private function chargerVersionsDisponibles() {
$tableMeta = $this->projetNom.'_meta';
$requete = "SELECT version FROM $tableMeta";
$resultat = $this->bdd->recupererTous($requete);
if ($resultat == '') {
//cas ou la requete comporte des erreurs
$message = "La requête SQL de versionnage formée comporte une erreur : $requete";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
} elseif ($resultat === false) {
$message = "Versions introuvables dans la table des méta-données";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
} else {
foreach ($resultat as $version) {
$versionsDispo[] = $version['version'];
}
}
 
return $versionsDispo;
}
 
public function getVersions() {
$versions = array();
$versionDemandee = $this->parametres->get('version.projet');
if ($versionDemandee == '+') {
$versions[] = end($this->versionsDispo);
} else if (is_numeric($versionDemandee)) {
if (in_array($versionDemandee, $this->versionsDispo)) {
$versions[] = $versionDemandee;
}
} else if ($versionDemandee == '*') {
$versions = $this->versionsDispo;
}
$versions = $this->remplacerPointParUnderscore($versions);
return $versions;
}
 
private function remplacerPointParUnderscore($versions) {
if (count($versions) > 0) {
foreach ($versions as $cle => $valeur) {
$versions[$cle] = str_replace('.', '_', $valeur);
}
}
return $versions;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/OntologieDO.php
New file
0,0 → 1,21
<?php
class OntologieDO {
private $infos;
 
public function __construct(Array $infos) {
$this->infos = $infos;
}
 
public function getTag($tag) {
return isset($this->infos[$tag]) ? $this->infos[$tag] : null;
}
 
public function verifierTag($tag) {
$existe = true;
if ($this->getTag($tag) == null || $this->getTag($tag) == '') {
$existe = false;
}
return $existe;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/OntologieDAO.php
New file
0,0 → 1,202
<?php
class OntologieDAO {
private $bdd = null;
private $versions = null;
private $requeteNbreTermesTotal = null;
private $masquesStrictes = array();
private $paramsMasque = array();
 
public function __construct(Ressources $ressources, Parametres $parametres, Bdd $bdd, Versions $versions) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->bdd = $bdd;
$this->versions = $versions;
$this->masquesStrictes = array('code');
$this->paramsMasque = array(
'' => 'nom',
'code' => 'id_terme',
'nom' => $this->getChampPourLangue('nom'),
'description' => $this->getChampPourLangue('description'));
}
 
public function getDetails() {
$table = $this->getTableTerme();
$tableType = $this->getTableType();
$detailsId = $this->ressources->getDetailsId();
$detailsId = $this->bdd->proteger($detailsId);
$requete =
'SELECT o.*, type '.
"FROM $table AS o ".
" LEFT JOIN $tableType ON (ce_type = id_type) ".
"WHERE id_terme = $detailsId ";
$resultats = $this->bdd->recuperer($requete);
$terme = new OntologieDO($resultats);
return $terme;
}
 
public function rechercher() {
$clause = $this->getClauseSelectSpeciale();
$table = $this->getTableTerme();
$tableType = $this->getTableType();
$tablePublication = $this->getTablePublication();
$tableAuteur = $this->getTableAuteur();
$tableImage = $this->getTableImage();
$conditions = $this->getConditions();
$where = $this->getWhere($conditions);
$ordre = $this->getOrdre();
$navigation = $this->getNavigation();
 
$requete = "SELECT $clause o.*, t.type, p.*, a.*, i.* ".
"FROM $table AS o ".
" LEFT JOIN $tableType AS t ON (ce_type = id_type) ".
" LEFT JOIN $tablePublication AS p ON (ce_publication = id_publication) ".
" LEFT JOIN $tableAuteur AS a ON (ce_auteur = id_auteur) ".
" LEFT JOIN $tableImage AS i ON (ce_image = id_image) ".
$where.' '.$conditions.' '.$ordre.' '.
"LIMIT $navigation ";
//die($requete);
$this->requeteNbreNomsTotal = $this->transformerRequetePourNbreTermesTotal($requete);
$resultats = $this->bdd->recupererTous($requete);
 
return $resultats;
}
 
private function getClauseSelectSpeciale() {
$clause = (Config::get('bdd_protocole') == 'mysql') ? 'SQL_CALC_FOUND_ROWS' : '';
return $clause;
}
 
private function getTableTerme() {
return sprintf($this->getNomTableTpl(), 'terme');
}
 
private function getTableType() {
return sprintf($this->getNomTableTpl(), 'type');
}
 
private function getTablePublication() {
return sprintf($this->getNomTableTpl(), 'publication');
}
 
private function getTableAuteur() {
return sprintf($this->getNomTableTpl(), 'auteur');
}
 
private function getTableImage() {
return sprintf($this->getNomTableTpl(), 'image');
}
 
private function getTableHierarchie() {
return sprintf($this->getNomTableTpl(), 'hierarchie');
}
 
private function getNomTableTpl() {
$versions = $this->versions->getVersions();
$derniereVersion = end($versions);
$projetNom = strtolower($this->ressources->getProjetNom());
return $projetNom.'_ontologies_%s_v'.$derniereVersion;
}
 
private function getConditions() {
$operateurParDefaut = $this->getOperateurCondition();
$conditionsSql = array();
foreach ($this->paramsMasque as $typeMasque => $champ) {
$operateur = in_array($typeMasque, $this->masquesStrictes) ? '=' : $operateurParDefaut;
if ($valeurMasque = $this->parametres->getMasquePourBdd($typeMasque)) {
if ($operateur == 'SOUNDEX') {
$tpl = '(SOUNDEX(%s) = SOUNDEX(%s)) OR (SOUNDEX(REVERSE(%s)) = SOUNDEX(REVERSE(%s))) ';
$conditionsSql[] = sprintf($tpl, $champ, $valeurMasque, $champ, $valeurMasque);
} else {
$conditionsSql[] = "$champ $operateur $valeurMasque";
}
}
}
return implode(' AND ', $conditionsSql);
}
 
private function getOperateurCondition() {
$operateur = '';
$recherche = $this->parametres->get('recherche');
if ($recherche == 'stricte') {
$operateur = '=';
} else if ($recherche == 'etendue') {
$operateur = 'LIKE';
} else if ($recherche == 'floue') {
$operateur = 'SOUNDEX';
}
return $operateur;
}
 
private function getWhere($conditions = '') {
$where = '';
if ($conditions != '') {
$where = 'WHERE ';
}
return $where;
}
 
private function getOrdre() {
$champNom = $this->getChampPourLangue('nom');
$ordre = "ORDER BY $champNom ASC ";
return $ordre;
}
 
private function getChampPourLangue($champ) {
$lg = $this->parametres->get('retour.langue');
if ($lg == 'en') {
$champ .= '_en';
}
return $champ;
}
 
private function getNavigation() {
$debut = (int) $this->parametres->get('navigation.depart');
$nbre = $this->parametres->get('navigation.limite');
$navigation = "$debut,$nbre";
return $navigation;
}
 
private function transformerRequetePourNbreTermesTotal($requete) {
$requete = preg_replace('/SELECT .* FROM/', 'SELECT COUNT(*) AS nbre FROM', $requete);
$requete = preg_replace('/LIMIT [0-9]+,[0-9]+/', '', $requete);
return $requete;
}
 
public function trierResultatsFloue($termes) {
foreach ($this->paramsMasque as $typeMasque => $champ) {
if ($termeDemande = $this->parametres->getMasquePourBdd($typeMasque)) {
$termeDemandeSimple = strtolower(Chaine::supprimerAccents($termeDemande));
 
foreach ($termes as $id => $terme) {
$termeFlouSimple = strtolower(Chaine::supprimerAccents($terme[$this->getChampPourLangue('nom')]));
// Prime pour la ressemblance globale :
$leven = levenshtein($termeFlouSimple, $termeDemandeSimple);
// On affine
$similar = similar_text($termeDemandeSimple, $termeFlouSimple) * 3;
// Prime Soundex
$soundex = (soundex($termeDemandeSimple) == soundex($termeFlouSimple)) ? 1000 : 0;
// Calcul du score
$score = 500 - $leven + $similar + $soundex;
 
$termes[$id]['score'] = $score;
$termes[$id]['score_calcul'] = "$termeDemandeSimple / $termeFlouSimple : 500 - $leven + $similar + $soundex = $score";
}
$termes = Tableau::trierMD($termes, array('score' => SORT_DESC));
}
}
//echo 'ici<pre>'.print_r($termes, true).'</pre>';die();
return $termes;
}
 
public function recupererNombreTermesTotal() {
if (Config::get('bdd_protocole') == 'mysql') {
$requete = 'SELECT FOUND_ROWS() AS nbre';
} else {
$requete = $this->requeteNbreNomsTotal;
}
 
$nombre = $this->bdd->recuperer($requete);
return (int) $nombre['nbre'];
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/OntologieFormateur.php
New file
0,0 → 1,89
<?php
class OntologieFormateur {
 
private $termeAFormater = null;
private $decorateurs = array();
private $bdd = null;
private $champsProjet = array();
private $champsRetour = null;
private $detailsHrefTpl = null;
private $langueDemandee = null;
 
public function setTermeAFormater(OntologieDO $ontologieDO) {
$this->termeAFormater = $ontologieDO;
}
 
public function setChampsRetour(Array $champsRetour) {
$this->champsRetour = $champsRetour;
}
 
public function setChampsProjet(Array $champsProjet) {
$this->champsProjet = $champsProjet;
}
 
public function setDetailsHrefTpl($tpl) {
$this->detailsHrefTpl = $tpl;
}
 
public function setLangueDemandee($langue) {
$this->langueDemandee = $langue;
}
 
public function setBdd($bdd) {
$this->bdd = $bdd;
}
 
public function formaterDetails() {
$termeDeco = new OntologieDecorateur($this->termeAFormater, $this->detailsHrefTpl, $this->langueDemandee);
$projetDeco = new OntologieChampsProjetDecorateur($termeDeco, $this->champsProjet);
 
if ($this->avoirDemandeChampsRetour()) {
$this->decorateurs[] = $termeDeco;
$this->decorateurs[] = $projetDeco;
 
$this->traiterChampsRetour();
} else {
$termeDeco->ajouterId();
$termeDeco->ajouterIntitule();
$termeDeco->ajouterDescription();
$termeDeco->ajouterClasseId();
$termeDeco->ajouterClasse();
$termeDeco->ajouterClasseHref();
 
$projetDeco->ajouterChampsSupplementaires();
}
 
return $termeDeco->getTermeFormate();
}
 
public function formaterListe() {
$termeDeco = new OntologieDecorateur($this->termeAFormater, $this->detailsHrefTpl, $this->langueDemandee);
$termeDeco->ajouterId();
$termeDeco->ajouterIntitule();
$termeDeco->ajouterHref();
 
if ($this->avoirDemandeChampsRetour()) {
$this->decorateurs[] = $termeDeco;
$this->decorateurs[] = new OntologieChampsProjetDecorateur($termeDeco, $this->champsProjet);
 
$this->traiterChampsRetour();
}
 
return $termeDeco->getTermeFormate();
}
 
private function avoirDemandeChampsRetour() {
$demande = true;
if ($this->champsRetour === null || count($this->champsRetour) == 0) {
$demande = false;
}
return $demande;
}
 
private function traiterChampsRetour() {
foreach ($this->decorateurs as $deco) {
$deco->traiterChampsRetour($this->champsRetour);
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/decorateurs/OntologieChampsProjetDecorateur.php
New file
0,0 → 1,38
<?php
class OntologieChampsProjetDecorateur extends OntologieDecorateur {
 
private $ontologieDecorateur = null;
private $champs = array();
protected $correspondances = array();
 
public function __construct(OntologieDecorateur $ontologieDecorateur, Array $champs) {
$this->ontologieDecorateur = $ontologieDecorateur;
$this->champs = $champs;
$this->correspondances = array_flip($this->champs);
}
 
public function traiterChampsRetour(Array $champsRetour) {
//die(print_r($this->correspondances,true));
foreach ($champsRetour as $champ) {
if (array_key_exists($champ, $this->correspondances)) {
$champBdd = $this->correspondances[$champ];
$champSortie = $champ;
//die(print_r($this->ontologieDecorateur->terme,true));
if ($this->ontologieDecorateur->terme->verifierTag($champBdd)) {
$valeur = $this->ontologieDecorateur->terme->getTag($champBdd);
$this->ontologieDecorateur->termeFormate[$champSortie] = $valeur;
}
}
}
}
 
public function ajouterChampsSupplementaires() {
foreach ($this->champs as $champBdd => $champSortie) {
if ($this->ontologieDecorateur->terme->verifierTag($champBdd)) {
$valeur = $this->ontologieDecorateur->terme->getTag($champBdd);
$this->ontologieDecorateur->termeFormate[$champSortie] = $valeur;
}
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/decorateurs/OntologieDecorateur.php
New file
0,0 → 1,92
<?php
class OntologieDecorateur implements OntologieResponsabilite {
protected $terme = null;
protected $termeFormate = array();
private $detailsHrefTpl = null;
private $langueDemandee = null;
protected $correspondances = array(
'id' => 'Id',
'nom' => 'Intitule',
'description' => 'Description',
'href' => 'Href',
'classe' => 'Classe',
'classe.id' => 'ClasseId',
'classe.href' => 'ClasseHref',
'classe.*' => 'ClasseId,Classe,ClasseHref');
 
public function __construct(OntologieDO $termeADecorer, $detailsHrefTpl, $langueDemandee) {
$this->terme = $termeADecorer;
$this->detailsHrefTpl = $detailsHrefTpl;
$this->langueDemandee = $langueDemandee;
$this->initialiserTermeFormate();
}
 
public function traiterChampsRetour(Array $champsRetour) {
foreach ($champsRetour as $champ) {
if (array_key_exists($champ, $this->correspondances)) {
$methodesAExecuter = explode(',', $this->correspondances[$champ]);
foreach ($methodesAExecuter as $methodeNom) {
$methodeAjouter = 'ajouter'.$methodeNom;
if (method_exists($this, $methodeAjouter)) {
$this->$methodeAjouter();
}
}
}
}
}
 
public function ajouterId() {
$this->termeFormate['id'] = (int) $this->terme->getTag('id_terme');
}
 
public function ajouterIntitule() {
if ($this->langueDemandee == 'en') {
$this->termeFormate['nom'] = $this->terme->getTag('nom_en');
} else {
$this->termeFormate['nom'] = $this->terme->getTag('nom');
}
}
 
public function ajouterDescription() {
if ($this->langueDemandee == 'en') {
if ($this->terme->verifierTag('description_en')) {
$this->termeFormate['description'] = $this->terme->getTag('description_en');
}
} else {
if ($this->terme->verifierTag('description')) {
$this->termeFormate['description'] = $this->terme->getTag('description');
}
}
}
 
public function ajouterHref() {
if ($this->terme->verifierTag('id_terme')) {
$href = sprintf($this->detailsHrefTpl, $this->terme->getTag('id_terme'));
$this->termeFormate['href'] = $href;
}
}
 
public function ajouterClasseId() {
$this->termeFormate['classe.id'] = (int) $this->terme->getTag('ce_type');
}
 
public function ajouterClasse() {
$this->termeFormate['classe'] = (string) $this->terme->getTag('type');
}
 
public function ajouterClasseHref() {
if ($this->terme->verifierTag('ce_type')) {
$href = sprintf($this->detailsHrefTpl, $this->terme->getTag('ce_type'));
$this->termeFormate['classe.href'] = $href;
}
}
 
public function initialiserTermeFormate() {
$this->termeFormate = array();
}
 
public function getTermeFormate() {
return $this->termeFormate;
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/ontologie/decorateurs/OntologieResponsabilite.php
New file
0,0 → 1,5
<?php
interface OntologieResponsabilite {
public function traiterChampsRetour(Array $champsRetour);
}
?>
/tags/v0.1-20130829/services/bibliotheque/JSON.php
New file
0,0 → 1,806
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
 
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id$
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
 
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
 
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
 
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
 
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
 
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
 
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
 
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
 
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
 
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
 
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
 
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
 
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
 
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
 
// ignoring UTF-32 for now, sorry
return '';
}
 
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
 
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
 
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
 
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
 
// ignoring UTF-32 for now, sorry
return '';
}
 
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
 
case 'NULL':
return 'null';
 
case 'integer':
return (int) $var;
 
case 'double':
case 'float':
return (float) $var;
 
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
 
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
 
$ord_var_c = ord($var{$c});
 
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
 
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
 
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
 
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
 
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
 
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
 
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
 
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
 
return '"'.$ascii.'"';
 
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
 
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
 
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
 
return '{' . join(',', $properties) . '}';
}
 
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
 
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
 
return '[' . join(',', $elements) . ']';
 
case 'object':
$vars = get_object_vars($var);
 
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
 
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
 
return '{' . join(',', $properties) . '}';
 
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
 
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
 
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
 
return $this->encode(strval($name)) . ':' . $encoded_value;
}
 
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
 
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
 
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
 
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
 
), '', $str);
 
// eliminate extraneous space
return trim($str);
}
 
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
 
switch (strtolower($str)) {
case 'true':
return true;
 
case 'false':
return false;
 
case 'null':
return null;
 
default:
$m = array();
 
if (is_numeric($str)) {
// Lookie-loo, it's a number
 
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
 
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
 
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
 
for ($c = 0; $c < $strlen_chrs; ++$c) {
 
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
 
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
 
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
 
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
 
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
 
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
 
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
 
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
 
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
 
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
 
}
 
}
 
return $utf8;
 
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
 
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
 
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
 
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
 
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
 
} else {
return $obj;
 
}
}
 
//print("\nparsing {$chrs}\n");
 
$strlen_chrs = strlen($chrs);
 
for ($c = 0; $c <= $strlen_chrs; ++$c) {
 
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
 
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
 
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
 
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
 
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
 
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
 
}
 
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
 
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
 
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
 
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
 
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
 
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
 
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
 
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
 
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
 
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
 
}
 
}
 
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
 
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
 
}
 
}
}
}
 
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
 
return false;
}
}
 
if (class_exists('PEAR_Error')) {
 
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
 
} else {
 
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
 
}
}
 
}
?>
/tags/v0.1-20130829/services/bibliotheque/Requete.php
New file
0,0 → 1,12
<?php
 
class Requete {
 
public $champs_recherches = " * ";
public $table = "";
public $requete_condition = "";
public $requete_jointure = "";
public $limite_requete = array('depart' => 0, 'limite' => 100);
public $limite_besoin = false;
}
?>
/tags/v0.1-20130829/services/bibliotheque/ReponseHttp.php
New file
0,0 → 1,85
<?php
class ReponseHttp {
 
private $resultatService = null;
private $erreurs = array();
 
public function __construct() {
$this->resultatService = new ResultatService();
if (function_exists('json_decode') == false){
require_once (dirname(__FILE__).'/JSON.php');
function json_decode($content, $assoc = false){
if ($assoc) {
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
} else {
$json = new Services_JSON;
}
return $json->decode($content);
}
}
 
if ( !function_exists('json_encode') ){
function json_encode($content){
$json = new Services_JSON;
return $json->encode($content);
}
}
}
 
public function setResultatService($resultat) {
if (!($resultat instanceof ResultatService)) {
$this->resultatService->corps = $resultat;
} else {
$this->resultatService = $resultat;
}
}
 
public function getCorps() {
if ($this->etreEnErreur()) {
$this->resultatService->corps = $this->erreurs[0]['message'];
} else {
$this->transformerReponseCorpsSuivantMime();
}
return $this->resultatService->corps;
}
 
public function ajouterErreur(Exception $e) {
$this->erreurs[] = array('entete' => $e->getCode(), 'message' => $e->getMessage());
}
 
public function emettreLesEntetes() {
$enteteHttp = new EnteteHttp();
if ($this->etreEnErreur()) {
$enteteHttp->code = $this->erreurs[0]['entete'];
$enteteHttp->mime = 'text/html';
} else {
$enteteHttp->encodage = $this->resultatService->encodage;
$enteteHttp->mime = $this->resultatService->mime;
}
header("Content-Type: $enteteHttp->mime; charset=$enteteHttp->encodage");
RestServeur::envoyerEnteteStatutHttp($enteteHttp->code);
}
 
private function etreEnErreur() {
$enErreur = false;
if (count($this->erreurs) > 0) {
$enErreur = true;
}
return $enErreur;
}
 
private function transformerReponseCorpsSuivantMime() {
switch ($this->resultatService->mime) {
case 'application/json' :
if (isset($_GET['callback'])) {
$contenu = $_GET['callback'].'('.json_encode($this->resultatService->corps).');';
} else {
$contenu = json_encode($this->resultatService->corps);
}
$this->resultatService->corps = $contenu;
break;
}
}
 
}
?>
/tags/v0.1-20130829/services/bibliotheque/ParametresVerificateur.php
New file
0,0 → 1,99
<?php
class ParametresVerificateur {
private $parametres = null;
private $parametresApi = array();
private $erreursParametres = array();
private $typesVerif = array(
'recherche' => 'Simple',
'ns.format' => 'Simple',
'retour' => 'Simple',
'retour.format' => 'Simple',
'retour.langue' => 'RegExp',
'ns.structure' => 'Multiple',
'version.projet' => 'RegExp'
);
private $valeursPermises = array(
'recherche' => 'stricte|floue|etendue',
'ns.format' => 'htm|txt',
'retour' => 'application/json|image/jpeg',
'retour.format' => 'min|max|oss|perso',
'retour.langue' => '/^(?:[*]|orig|[a-z]{2})$/',
'ns.structure' => '|an|au|bib|ad',
'version.projet' => '/^(?:[0-9]+[.][0-9]+|[*+])$/'
);
 
public function __construct(Parametres $parametres, Array $parametresApi) {
$this->parametres = $parametres;
$this->parametresApi = $parametresApi;
}
 
public function verifier() {
$this->verifierConformiteApi();
$this->verifierValeurs();
}
 
public function verifierConformiteApi() {
$this->parametres->rewind();
while (is_null($parametre = $this->parametres->key()) === false) {
if (in_array($parametre, $this->parametresApi) === false) {
$message = "Le paramètre '$parametre' n'est pas pris en compte par cette version de l'API.";
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
$this->parametres->next();
}
}
 
public function verifierValeurs() {
foreach ($this->typesVerif as $parametre => $type) {
$methode = "verifierValeur$type";
$this->$methode($parametre);
}
 
if (count($this->erreursParametres) > 0) {
array_unshift($this->erreursParametres, 'Erreur dans le paramètrage de votre URL :');
$message = implode('<br/>', $this->erreursParametres);
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
}
 
private function verifierValeurSimple($parametre) {
$valeur = $this->parametres->get($parametre);
$valeursPermises = $this->valeursPermises[$parametre];
$permissionOk = $this->verifierValeursPermises($valeur, $valeursPermises);
if ($permissionOk == false) {
$this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $valeursPermises";
}
}
 
private function verifierValeursPermises($valeur, $valeursPermises) {
$permise = false;
if (in_array($valeur, explode('|', $valeursPermises))) {
$permise = true;
}
return $permise;
}
 
private function verifierValeurRegExp($parametre) {
$valeur = $this->parametres->get($parametre);
$regexp = $this->valeursPermises[$parametre];
$permissionOk = preg_match($regexp, $valeur) ? true : false;
if ($permissionOk == false) {
$this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $regexp";
}
}
 
private function verifierValeurMultiple($parametre) {
$valeursConcatenees = $this->parametres->get($parametre);
$valeursPermises = $this->valeursPermises[$parametre];
$valeurs = explode(',', $valeursConcatenees);
foreach ($valeurs as $valeur) {
$permissionOk = $this->verifierValeursPermises($valeur, $valeursPermises);
if ($permissionOk == false) {
$this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $valeursPermises";
}
}
}
}
?>
/tags/v0.1-20130829/services/bibliotheque/Outils.php
New file
0,0 → 1,21
<?php
class Outils {
 
public static function recupererTableauConfig($parametres) {
$tableau = array();
$tableauPartiel = explode(',', Config::get($parametres));
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = $champ;
} else {
list($cle, $val) = explode('=', $champ);
$clePropre = trim($cle);
$valeurPropre = trim($val);
$tableau[$clePropre] = $valeurPropre;
}
}
return $tableau;
}
}
?>