<?php
/*
 * SDmotor
 * Cette classe gere tous les cas possibles de recherche avec le moteur sphinx.
 * Tous les types de recherches entreprise.
 *
 * Par : Damien Lasserre, Le 13/11/2011 a 12h12.
 * CC  : dlasserre@scores-decisions.com
 * CR  : CopyRight Scores et Decisions.
 */
Class SDmotor
{
    protected $formR;
    protected $index;
    protected $debug = true;
    
    /** Critères pour sphinx **/
    protected $Crtiteres = array('raisonSociale'    => '',
                                 'Voie'             => '@addresse',
                                 'cpVille'          => '@ville',
                                 'telFax'           => '@(tel, fax)',
                                 'naf'              => '@ape_etab'
    );

    /** Séquance d'échappement. **/
    protected $form2crit = array('siren'            => 'I',
                                 'raisonSociale'    => 'S',
                                 'departement'      => 'D',
                                 'localite'         => 'L',
                                 'cpVille'          => 'D',
                                 'numeroVoie'       => 'N',
                                 'Voie'             => 'R',
                                 'Ville'            => 'V',
                                 'SPH_MATCH'        => EOF
    );
    
    protected $mode;  // Le MatchingMode de sphinx
    protected $deb;   // La Page de début.
    protected $nbRep; // Le Nombre de reponse par page
    protected $max;	  // Le Nombre maximum de résultats.
    protected $total_time; // Le temps d'éxecution de la recherche.

    /** Parametres de la partie debug (Interface de test)**/
    protected $quorum;
    protected $sequances;
    protected $proximites;
    protected $poids;
    protected $actif;
    /** **/

    protected $maxSizeWord; // Taille Minimum des mots pour la raisonSociale
    protected $Quorumsize;  // Inutilisé pour le moment.
    protected $ProximiteSize; // Taille de la proximite.
    
    protected $page; // La page courante.
    public    $html; // HTML propre au debug (interface de test)
    protected $pertinance; // La pertinence dans la recherche. (sirenage)
    
    protected $acronyme;

    /**
     * @param <type> $deb Page courante.
     * @param <type> $nbRep Nombre de reponse / pages
     * @param <type> $max Nombre Maximum de reponses.
     *
     * Fonction de recherche entreprise, ici nous allons crée tous les cas de recherche possible
     * De la recherche par exact match ou Phonetique en passant par le gestionnaire de condition de Sphinx
     * A savoir nous retirerons des critéres celon les resultats de sphinx.
     */
    public function __construct()
    {
            $this->total_time  = 0;

            $this->quorum       = false;
            $this->sequances   = false;
            $this->proximites   = false;
            $this->poids           = false;
            $this->actif            = false;
            
            $this->nbRep         = 10;
            $this->max             = 1000;
            
            $this->debug = true;
    }
    
    public function _initForm($formR)
    {
        $formulaire = array();
        $ok = false;
            foreach($formR as $name => $form) {
                if($name != 'controller' and $name != 'action' and $name != 'module' and $name != 'Envoyer') {
                    if($this->index == 'dir' and ($name == 'nom' or $name == 'prenom' and !$ok)) {
                        $formulaire['raisonSociale'] = $formR['nom'].' '.$formR['prenom'];
                        $ok = true;
                    }
                    $formulaire[$name] = (empty($form))?'':$form;
                }
        }
        $this->formR = $formulaire;
    }
    
    public function databaseJO()
	{
		$db = new mysqli('192.168.78.230', 'sphinx', 'indexer', 'jo');
		if (mysqli_connect_error()) {
			$this->println('Erreur : Ne peut pas se connecter a la base.');
			return;
		}
		$db->query("SET NAMES 'utf8';");
		return $db;
	}
    
    /**
     *
     * Fonction d'entrée dans la classe
     * Elle s'occupe de setter les parametres de sphinx et d'éxecuter le bon type de recherche.
     *
     * @todo voir pour la verification du mode de sortie de sphinx.
     * Prévoir un input de selection avec les différents modes de sortie.
     * $this->sphinx->SetSortMode(SPH_SORT_EXTENDED, "@adr_num desc");
     *
     */
    public function search()
    {
        $pass                 = 0;
        $quorumActif    = false;
        $quorum           = array();
        $array              = array();

        if(!empty($this->formR['raisonSociale']))
            $this->formR['raisonSociale'] = $this->formatRaisonSociale($this->formR['raisonSociale']);
        foreach($this->formR as $name => $form) {
            if(array_key_exists($name, $this->form2crit) and !empty($this->formR[$name]))
                $array[$name] = $form;
        }
        $this->formR = $array;
        if(!$this->sphinx and $this->debug)
            return (array('Nombre de Réponses :' => 0,
                          'Nombre de Réponses Totales :' => 0,
                          'Durée exécution :' => $total_time,
                          'Erreure :' => 'Le formulaire est Vide !')
        );
        /*$this->filtreCaracteresSpeciaux();*/
        $this->sphinx->SetSortMode($this->setSortMode(SPH_MATCH_EXTENDED2), "@weight rang");
        $this->sphinx->SetLimits(intval($this->deb), intval($this->nbRep), intval($this->max));
        $this->maxSizeWord = 0;
        switch($this->formR['SPH_MATCH']) {
            case 'SPH_MATCH_ALL':
                $this->sphinx->SetMatchMode(SPH_MATCH_ALL);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_ALL');
                $this->printStatus($resSphinx);
                break;
            case 'SPH_MATCH_ANY':
                $this->sphinx->SetMatchMode(SPH_MATCH_ANY);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_ANY');
                $this->printStatus($resSphinx);
                break;
            case 'SPH_MATCH_PHRASE':
                $this->sphinx->SetMatchMode(SPH_MATCH_PHRASE);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_PHRASE');
                $this->printStatus($resSphinx);
                break;
            case 'SPH_MATCH_BOOLEAN':
                $this->sphinx->SetMatchMode(SPH_MATCH_BOOLEAN);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_BOOLEAN');
                $this->printStatus($resSphinx);
                break;
            case 'SPH_MATCH_EXTENDED':
                $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_EXTENDED');
                $this->printStatus($resSphinx);
                break;
            default:
                $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
                if(!empty($this->formR['raisonSociale']) and $this->index == 'ent')
                        $this->formR['raisonSociale'] = $this->removeSmallWord($this->formR['raisonSociale']);
                if(!empty($this->formR['Voie']))
                        $this->formR['Voie'] = $this->formatAdress ($this->formR['Voie']);
                $resSphinx = $this->SPH_MATCH_('SPH_MATCH_EXTENDED2');
                $this->printStatus($resSphinx);
                break;
            case 'SPH_MATCH_FULLSCAN':
                return;
        }
        if($resSphinx['matches'] > 0) {
            $this->setTime($resSphinx['time']);
            /*$this->getResultSphinx($resSphinx);*/
        }
        return ($this->getResponse($resSphinx));
    }
/***************************************************************************************************************/
/** Partie Requette **/

    /**
     * Grosse fonction de traitement des sequences ainsi que les différent sequencing de sphinx
     * Comme la gestion du quorum d'écrémenté sur la raisonSociale et l'Adresse
     * + La gestion des doublons et des espaces.
     *
     * @param $type vaut le type de recherche SPH_MATCH_?
     * @return les résultats dans le cas ou il y a des résultats.
     *
     */
    public function SPH_MATCH_($type)
    {
        global $link, $sequence, $wordformRS, $adrRef;    	
    	require_once realpath(dirname(__FILE__)) . '/sequence.php';

        if($this->debug) $html = '';
        $ref = array('acrony', 'normal', 'points', 'split', 'space', 'double', 'quorum');
        $i = 0;
        if($this->detectedSequance() == 'S.S')
            $valeur = 'S';
        else {
            $valeur = explode(':', $this->detectedSequance());
            $valeur = trim($valeur[0]);
        }
        print_r($this->formR);
        foreach($link[$valeur]['id'] as $seqId)  {
            if($this->debug) $html .= '<br /><b>Séquence :</b> '.$sequence[$link[$valeur]['id'][$i]].'<br />';
            $tab = explode('.', $sequence[$link[$valeur]['id'][$i]]);
            if(in_array('S', $tab)) {
                    $nb = 1;
                    if($this->debug) $html .= '<table>';
                    for ($quorum = $this->countQorum(); $quorum > 0; $quorum--) {
                        foreach($ref as $seq) {
                            if($this->index != 'ent' and ($seq == 'acrony' or $seq == 'split'))
                                continue;
                            if($link[$valeur][$seq]) {
                                if(isset($passe) and $passe == $sequence[$link[$valeur]['id'][$i]])
                                        $seq = 'quorum';
                                if(in_array('R', explode('.', $sequence[$link[$valeur]['id'][$i]])))
                                {
                                    for($quorumR = $this->countQorumR(); $quorumR > 0; $quorumR--) {
                                            $request = $this->constructQuerySequance($sequence[$link[$valeur]['id'][$i]], $type, array($quorum, $quorumR), $seq);
                                            $result = $this->sphinx->Query($request, $this->index);
                                            if($this->debug) {
                                                $html .='<tr style="background-color:'.(($result['total'] == 0)?'#FFE8E8':'#E8FFE8').'">';
                                                $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;">'.$nb++.'</td>';
                                                $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;width:400px;">'.$request.'</td>';
                                                $html .= '<td style="border:1px solid silver;padding:3px;color:'.(($result['total']==0)?'red':'green').'">'.$result['total'].'/'.$result['total_found']. '</td>';
                                                if($seq != 'quorum')
                                                    $html .= '<td style="border:1px solid silver;padding:3px;"><i>'.$seq.'</i></td>';
                                                else
                                                    $html .= '<td style="border:1px solid silver;padding:3px;"><i style="font-size:10px;"> quorum R:'.$quorum.'</i></td>';
                                                $html .= '</tr>';
                                            }
                                            if($result['total'] > 0)
                                                break;
                                    }
                                    if($result['total'] > 0 or $passe == $sequence[$link[$valeur]['id'][$i]])
                                        break;
                                } else {
                                    $request = $this->constructQuerySequance($sequence[$link[$valeur]['id'][$i]], $type, array($quorum, false), $seq);
                                    $result = $this->sphinx->Query($request, $this->index);
                                    if($this->debug) {
                                        $html .='<tr style="background-color:'.(($result['total'] == 0)?'#FFE8E8':'#E8FFE8').'">';
                                        $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;">'.$nb++.'</td>';
                                        $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;width:400px;">'.$request.'</td>';
                                        $html .= '<td style="border:1px solid silver;padding:3px;color:'.(($result['total']==0)?'red':'green').'">'.$result['total'].'/'.$result['total_found']. '</td>';
                                        if($seq != 'quorum')
                                            $html .= '<td style="border:1px solid silver;padding:3px;"><i>'.$seq.'</i></td>';
                                        else
                                            $html .= '<td style="border:1px solid silver;padding:3px;"><i style="font-size:10px;"> quorum:'.$quorum.'</i></td>';
                                        $html .= '</tr>';
                                    }
                                    if($result['total'] > 0 or $passe == $sequence[$link[$valeur]['id'][$i]])
                                        break;
                                }
                            }
                            if($result['total'] > 0)
                                break;
                        }
                        if($result['total'] > 0)
                            break;
                        $passe = $sequence[$link[$valeur]['id'][$i]];
                    }
                    if($this->debug) $html .='</table>';
            } elseif(in_array('R', $tab)) {
                if($this->debug) $html .= '<table>';
                $nb = 1;
                for($qv=count(explode(' ', trim($this->formR['Voie']))); $qv > 0; $qv--) {
                    $request = $this->constructQuerySequance($sequence[$link[$valeur]['id'][$i]], $type, array(false, $qv), $seq);
                    $result  = $this->sphinx->Query($request, $this->index);
                    if($this->debug) {
                        $html .='<tr style="background-color:'.(($result['total'] == 0)?'#FFE8E8':'#E8FFE8').'">';
                        $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;">'.$nb++.'</td>';
                        $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;width:400px;">'.$request.'</td>';
                        $html .= '<td style="border:1px solid silver;padding:3px;color:'.(($result['total']==0)?'red':'green').'">'.$result['total'].'/'.$result['total_found']. '</td>';
                        if($seq != 'quorum')
                            $html .= '<td style="border:1px solid silver;padding:3px;"><i>'.$seq.'</i></td>';
                        else
                            $html .= '<td style="border:1px solid silver;padding:3px;"><i style="font-size:10px;"> quorum:'.$quorum.'</i></td>';
                        $html .= '</tr>';
                    }
                    if($result['total'] > 0) {
                        break;
                    }
                }
                if($this->debug) $html .= '</table>';
            } else {
                if($this->debug) $html .= '<table>';
                $request = $this->constructQuerySequance($sequence[$link[$valeur]['id'][$i]], $type, array(false, false), $seq);
                $result  = $this->sphinx->Query(($request != " ")?$request:'', $this->index);
                if($this->debug) {
                    $html .='<tr style="background-color:'.(($result['total'] == 0)?'#FFE8E8':'#E8FFE8').'">';
                    $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;">'.$nb++.'</td>';
                    $html .= '<td style="border:1px solid silver;padding:3px;font-size:11px;width:400px;">'.$request.'</td>';
                    $html .= '<td style="border:1px solid silver;padding:3px;color:'.(($result['total']==0)?'red':'green').'">'.$result['total'].'/'.$result['total_found']. '</td>';
                    if($seq != 'quorum')
                        $html .= '<td style="border:1px solid silver;padding:3px;"><i>'.$seq.'</i></td>';
                    else
                        $html .= '<td style="border:1px solid silver;padding:3px;"><i style="font-size:10px;"> quorum:'.$quorum.'</i></td>';
                    $html .= '</tr>';
                    $html .= '</table>';
                }
            }
            if($result['total'] > 0) {
                    break;
            }
            $i++;
        }
        $this->pertinance = $this->levenshteinCrit($sequence[$link[$valeur]['id'][$i]]);
        if($this->debug) $this->printInformations($html);
        return ($result);
    }

    /**
     * Cette fonction permet une recherche simple avec les annonce juste un filtre + un champs de recherche
     * J'ai preferer ne pas la mettre dans le moteur car trop leger pour suporter les requette du moteur se serai une surcharge pour rien...
     * 
     * getResponse implemente la requete SQL, pour respecter la hierarchie de code !
     * @return type 
     */
    public function HistoSearch()
    {
         if(!empty($this->formR['annee1']))
            $this->sphinx->setFilter('annee1', array($this->formR['annee1']));
         $resSphinx = $this->sphinx->Query($this->formR['recherche'], $this->index);
        return  ($this->getResponse($resSphinx));
    }
    
    /**
     * Gestion de la raison sociale Formatage
     * avec des preg_replace etc...
     **/
    public function formatRaisonSociale($rs, $double = false)
    {
        global $link, $sequence, $wordformRS, $adrRef;    	
    	require_once realpath(dirname(__FILE__)) . '/sequence.php';

        if(!empty($this->formR['raisonSociale'])) {
            $request = '';
            $array = explode(' ', $rs);
            foreach($array as $item) {
                $item = str_replace('\'', ' ', $item);
                if((strlen($item) > $this->maxSizeWord and !in_array(strtoupper($item), $wordformRS) and $this->index == 'ent') or strlen($item) > $this->maxSizeWord and count($array) == 1) {
                    if($double)
                        $request .= preg_replace('/(?:([^*])\1)\1*/', '$1', $item).' ';
                    else
                        $request .= $item.' ';
                } else {
                     $request .= $item.' ';
                }
            }
            return ($request);
        }
    }
    
    /**
     * Fonction qui permet de gerer les CP et le Ville
     * @param type $cp
     * @return type 
     */
    public function formatCP($cp) 
    {
        $matches = '';
        $arrayChamp = explode(' ', trim($cp));
        $str        = false;
        
        for($i=0; $i < count($arrayChamp); $i++) 
        {
            if(preg_match('/^[0-9]{1,}$/', $cp, $matches)) 
            {
                if (strlen($matches[0]) == 1 and $matches[0] < 10) {
                    $matches[0] = '0'.$matches[0];
                }
                $size = strlen($matches[0]);
                if($size >= 2 and $this->index == 'ent' or $this->index == 'dir') {
                        if(substr($matches[0], 0, 2) > 95 ) {
                            // DOM-TOM outre mers
                            $this->sphinx->setFilter('adr_dep', array((int)substr($matches[0], 0, 3)));      
                        } else if (substr($matches[0], 0, 2) == 20) {
                            // Teritoire de la corse 2A et 2B @todo Attention a la compilation transformer 2A et 2B en 200
                            $this->sphinx->setFilter('adr_dep', array(200));
                        } else {
                            // Classique Metropole
                            $this->sphinx->setFilter('adr_dep', array((int)(substr($cp, 0, 2))));
                        }
                        if($size == 5) {
                            $this->sphinx->setFilter('adr_cp', array(intval($matches[0])));
                        }
                }
            }
            else
                $str .= $arrayChamp[$i];
        }
        return ($str);
    }
    
    public function FiltreDateDeNaissance()
    {
        if(!empty($this->formR['dirDateNaissMM'])) {
            if($this->formR['dirDateNaissMM'] > 0 and $this->formR['dirDateNaissMM'] < 12) {
                if(($this->formR['dirDateNaissMM'] % 2) != 0 )
                {
                    if($this->formR['dirDateNaissJJ'] > 0 and $this->formR['dirDateNaissJJ'] < 31) {
                       $this->sphinx->setFilter('naiss_jour', array($this->formR[dirDateNaissJJ]));
                    } 
                } else {
                    if($this->formR['dirDateNaissJJ'] > 0 and $this->formR['dirDateNaissJJ'] < 29) {
                       $this->sphinx->setFilter('naiss_jour', array($this->formR[dirDateNaissJJ]));
                    }
                }
            }
        } else {
            if(!empty($this->formR['dirDateNaissJJ'])) {
                $this->sphinx->setFilter('naiss_jour', array($this->formR[dirDateNaissJJ]));
            }
        }
        if($this->formR['dirDateNaissAAAA'] > 0 and $this->formR['dirDateNaissAAAA']  < date('Y')) {
                $this->sphinx->setFilter('naiss_annee', array($this->formR[dirDateNaissAAAA]));
            }
    }
    
    /**
     * Retire les petits mots de la raisonSociale.
     * @param $rs => raisonSociale
     * @return raisonSociale modifié.
     */
    public function removeSmallWord($rs)
    {
        global $link, $sequence, $wordformRS, $adrRef;    	
    	require_once realpath(dirname(__FILE__)) . '/sequence.php';
        
        $array = explode(' ', $rs);
        if(count($array) > 2) {
            foreach($array as $item) {
                if(strlen($item) > 1 and !in_array(strtoupper($item), $wordformRS)) {
                    $request .= $item.' ';
                } else if (strlen($item) == 1) {
                    $this->acronyme .= $item;
                }
            }
        }
        return ((empty($request))?$rs:$request);
    }

    /**
     * Elle format l'adresse.
     * @param $adress
     * @return adresse modifié.
     */
    public function formatAdress($adress)
    {
        require_once 'sequence.php';

        $adr = explode(' ', $adress);
        foreach($adr as $item) {
            if(!in_array($item, $adrRef)) {
                    $request .= $item.' ';
            }
        }
        return ($request);
    }

/***************************************************************************************************************/
/** Partie Sequance **/

    /**
     * Calcule le quorum selon le nombre de mots présents dans la RS.
     * @return Nombre.
     */
    public function countQorum()
    {
        $i=0;
        $val = explode(' ', $this->formR['raisonSociale']);
        foreach($val as $item) {
            if(empty($item))
                    unset($val[$i]);
            $i++;
        }
        return (count($val));
    }

    public function countQorumR()
    {
        $i=0;
        $val = explode(' ', $this->formR['Voie']);
        foreach($val as $item) {
            if(empty($item))
                    unset($val[$i]);
            $i++;
        }
        return (count($val));
    }

/***************************************************************************************************************/
/** Partie Sequance **/

    /**
     * Permet de determiner la sequence celon les parametres entré dans les formulaire.
     * @return sequence formater sous ce type "S.D.R : RaisonSociale Departement Voie"
     */
    public function detectedSequance()
    {
            $sequance = "";
            foreach($this->formR as $name => $form) {
                if($name != 'SPH_MATCH' and !empty($this->formR[$name])) {
                    $sequance .= '.'.$this->form2crit[$name];
                    $values .= $name.', ';
                }
            }
            return (substr($sequance,1).' : '.$values);
    }

    /**
     * Elle construit la requette pour sphinx celon certain parametre et un certain formatage.
     *
     * @param $sequances de format "S.D.V"
     * @param $type type de recherche sphinx SPH_MATCH_?
     * @param $qorum pour la raisons sociale
     * @param $seq type de sequence "espace, normal, double"
     * @return $request bien formater pour sphinx.
     */
    protected function constructQuerySequance($sequances, $type, $quorum, $seq)
    {
        $this->sphinx->ResetFilters();
        $adresse = '@adresse "';
        $ville = '@ville "';
        $request = '';
            foreach($this->form2crit as $name => $crit) {
                $diff = explode('.', $sequances);
                if(in_array($crit, $diff)) {
                    if ($name == 'raisonSociale') {
                        $request = $request .= (($type=='SPH_MATCH_EXTENDED' or $type=='SPH_MATCH_EXTENDED2')?'@nom ':'').'';      
                        switch($seq) {
                                case 'radica':
                                        //$request = substr(trim($this->formR['raisonSociale']), 0, 3);
                                        break;
                                case 'quorum':
                                        $request .= ' "'.$this->formR[$name].'"'.(($quorum[0] >= 1)?'/'.$quorum[0]:'');
                                        break;
                                case 'space':
                                        $request .= '"'.str_replace(' ', '', $this->formatRaisonSociale($this->formR[$name])).'" | ';
                                        $request .= '"'.str_replace(' ', '', $this->formatRaisonSociale($this->formR[$name], true)).'"';
                                        break;
                                case 'double':
                                        $request .= '"'.$this->formatRaisonSociale($this->formR[$name], true).'" | ';
                                        $request .= '"'.$this->formatRaisonSociale($this->formR[$name], true).'" '.(($quorum[0] >= 1)?'/'.$quorum[0]:'').' ';
                                        break;
                                case 'points':
                                        $request .= '"'.str_replace('.', '', $this->formR[$name]).'"';
                                        break;
                                case 'acrony':
                                        if(!empty($this->acronyme) and strlen($this->acronyme) > 2) {
                                            $request .= '"'.$this->acronyme.' '.$this->formatRaisonSociale($this->formR[$name]).'"/'.$quorum[0];
                                        }
                                        break;
                                case 'split':
                                        for($count=0;$count < 2; $count++) {
                                            $rs = (($i == 0)?trim($this->formR[$name]):str_replace('.', '', trim($this->formR[$name])));
                                            $precedent = '';
                                            $request .= '(';
                                            if(count(explode(' ', $rs)) == 1)
                                            {
                                                    for($i=0; $i < strlen($rs); $i++) {
                                                            $precedent .= $rs[$i];
                                                            $request .= ' "'.$precedent.' '.substr($rs, $i+1).'"'.(($i+1 != strlen($rs))?'  ':'');
                                                            if($i+1 < strlen($rs))
                                                                $request .= ' | ';

                                                    }
                                            }
                                            $request .=($count == 0)?') |':')';
                                        }
                                    break;
                                default:
                                    if($this->index == 'act')
                                        $request .= '"'.$this->formR[$name].'" /'.(count(explode(' ', $this->formR['raisonSociale']))-1).' | ';
                                    else
                                        $request .= '"'.$this->formR[$name].'" | ';
                                   $request .= '@nom "'.$this->formatRaisonSociale($this->formR[$name], true).'"';
                        }
                    }                                  
                    else if($name == 'cpVille') { 
                        $str = $this->formatCP($this->formR[$name]);
                        if($str != false) {
                            $adresse .= $str;
                        }
                    }
                    else if($name == 'Ville') {
                        $ville .= $this->formR[$name].' ';
                    }
                    else if($name == 'naf') {
                        $this->sphinx->setFilter('naf', array($this->formR[$name]));
                    }
                    else if($name == 'Voie') {
                        $adresse .= $this->formR[$name].' ';
                    }
                    else if ($name == 'siret') {
                        if(strlen($this->formR[$name]) == 14) {
                                $this->sphinx->setFilter('siren', array(substr($this->formR[$name], 0, 9)));
                                $this->sphinx->setfilter('nic', array(substr($this->formR[$name], 9)));
                        } else if (strlen($this->fomrR[$name]) == 9) {
                                $this->sphinx->setFilter('siren', array($this->formR[$name]));
                        }
                    }
                    else if($name == 'numeroVoie') {
                        $this->sphinx->setFilter('adr_num', array($this->formR[$name]));
                    }
                    else if($name == 'actMin' or $name == 'actMax') {
                        if(!empty($this->formR['actMin']) and !empty($this->formR['actMax']))
                            $this->sphinx->SetFilterRange('PminNum', $this->formR['actMin'], $this->formR['actMax']);
                    }
                   else if ($name == 'dirDateNaissJJ' or $name == 'dirDateNaissMM' or $name = 'dirDateNaissAAAA') {
                        $this->FiltreDateDeNaissance();
                    }
                    else if ($this->actif) {
                        $this->sphinx->setFilter('actif', array(1));
                    }else {
                        $request .= $this->formR[$name].' ';
                    }
                }
            }
        if($adresse != '@adresse "') {
            $request = $request .' '.$adresse.'"'. (($quorum[1]!=false)?'/'.$quorum[1]:'');
        }
        if($ville != '@ville "')
            $request = $request .' '.$ville.'"';
        echo $request.'<br />';
        return ($request);
    }

/***************************************************************************************************************/
/** Partie Pertinence **/
/* La pertinence doit être calculé a partir des critères recherche ( la séquence utilisé ) moins la séquence avec la quelle
* ont a trouvé les résultat ainsi que la distance des mots de la RS ou des l'adresse.
* exemple :
* S = scores et decisions
* D = 78
* V = Rambouillet(s)
*
* SDV = 20; resultat de base
*   -> 0 resultats
* SD = 15;
*	 -> 1 resultat
* V = levenshtein : ~1 alors 5-1 (étant le poid de V) = 4 donc 15+4 = 19 pourquoi -1, La proximité est proche plus le nombre est grand plus l'éloignement l'est.
* total pertinence = 19
*
* @param <type> $formR
* @param <type> $mySql
*/

    protected function levenshteinCrit($crit)
    {
        $pertinance = 0;
        $weight = array('I' => 10, 'S' => 9, 'D' => 6, 'L' => 4, 'V' => 5, 'N' => 2, 'R' => 3);
        $crit = explode('.', $crit);
        for($i=0; $i < count($crit); $i++) {
            $pertinance += $weight[$crit[$i]];
        }
        return ($pertinance);
    }

    protected function checkParamsRS($rs) 
    {
        if(strlen($rs) > 3)
            return (false);
        else
            return (true);
    }
    
    protected function getPertinence($formR, $mySql)
    {
        $formR = strtoupper($formR);
        $mySql = strtoupper($mySql);

        $array = explode(' ', $mySql);
        $array2 = explode(' ', $formR);

        for($i = 0;$i < count($array2); $i++) {
            if(in_array($array2[$i], $array)) {
                    $size += levenshtein($formR, $mySql);
            }
        }
        return (($size)?$size:100);
    }

/***************************************************************************************************************/
/** Partie Reponse **/

    public function getResponse($resSphinx)
    {
        $i= 0;
        $response = array();
        switch($this->index) {
                 case 'ent':
                     $sql = 'SELECT raisonSociale, CONCAT(siren, nic) AS siret, siren, nic, siege, raisonSociale, 
                                                sigle, enseigne,  adr_num, adr_typeVoie, adr_libVoie, adr_comp, adr_cp, 
                                                adr_ville, tel, fax, cj, actif, ape_etab, ape_entrep FROM etablissements WHERE id IN (';
                    foreach($resSphinx['matches'] as $elements) {
                        /*$sql .= 'id='.$elements['id'];*/
                        $sql .= $elements['id'];
                        if($i+1 < count($resSphinx['matches']))
                                $sql .= ', ';
                        $i++;
                    }
                    $sql .= ") ORDER BY rang DESC";
                break;
                case 'dir':
                    $sql = 'SELECT e.id, e.raisonSociale, CONCAT(e.siren, e.nic) AS siret, e.siren, e.nic, e.siege, e.raisonSociale, 
                                e.sigle, e.enseigne,  e.adr_num, e.adr_typeVoie, e.adr_libVoie, e.adr_comp, e.adr_cp, e.adr_ville, e.tel, 
                                e.fax, e.cj, e.actif, e.ape_etab, ape_entrep, d.nom, d.prenom, l.libelle AS fonction_lib  from rncs_dirigeants = d, etablissements e, bodacc_fonctions l WHERE d.id IN (';
                    foreach($resSphinx['matches'] as $elements)  {
                        $sql .= $elements['id'];
                        if($i+1 < count($resSphinx['matches']))
                                $sql .= ', ';
                        $i++;
                    }       
                   $sql  .= ' ) AND d.siren=e.siren and d.fonction_code=l.codeFct AND e.siege=1 GROUP BY d.siren, d.id ORDER BY e.rang DESC, e.actif DESC, e.siege DESC, e.id ASC';
                break;
                case 'act':
                    $sql    = 'SELECT DISTINCT e.siren, l.id AS lienId, l.actif AS lienActif, l.source, l.Pmin, l.PpPm, l.id2, '.
                                'l.Siren2, l.RaisonSociale, l.Pays, '.
                                'IF(l.dateUpdate>IF(l.dateInsert>l.dateLien,l.dateInsert,l.dateLien),l.dateUpdate,IF(l.dateInsert>l.dateLien,l.dateInsert,l.dateLien)) AS dateLien, '.
                                'e.id, CONCAT(siren,nic) AS siret, siren, nic, siege, e.raisonSociale, sigle, '.
                                'enseigne, adr_num, adr_typeVoie, adr_libVoie, adr_comp, adr_cp, adr_ville, '.
                                'tel, fax, cj, e.actif, ape_etab, ape_entrep, e.rang '.
                                'FROM liens l, etablissements e '.
                                'WHERE l.id IN (';
                    foreach($resSphinx['matches'] as $elements)  {
                        $sql .= $elements['id'];
                        if($i+1 < count($resSphinx['matches']))
                                $sql .= ', ';
                        $i++;
                    }
                    $sql .= ") AND l.Siren1=e.siren AND siege=1 AND e.actif=1 ORDER BY e.rang DESC";
                break;
                case 'Histo' :
                    $sql = 'SELECT Histo as Loc, id, nomFichier, annee1, bod, texte FROM bodacc_cor WHERE id IN ( ';
                    foreach($resSphinx['matches'] as $elements)  {
                        $sql .= $elements['id'];
                        if($i+1 < count($resSphinx['matches']))
                                $sql .= ', ';
                        $i++;
                    }
                    $sql .= ')';
                break;
        }
        $i = 0;
        $db = $this->databaseJO();
        $result = $db->query($sql);
         while($row = mysqli_fetch_assoc($result)) {
             if($this->index != 'Histo') {
                $response['reponses'][$i]['Siret'] = $row['siret'];
                $response['reponses'][$i]['Siren'] = $row['siren'];
                $response['reponses'][$i]['Nic'] = $row['nic'];
                $response['reponses'][$i]['Siege'] = $row['siege'];
                $response['reponses'][$i]['Nom'] = $row['raisonSociale'];
                $response['reponses'][$i]['Nom2'] = '';
                $response['reponses'][$i]['Sigle'] = $row['sigle'];
                $response['reponses'][$i]['Enseigne']   = $row['enseigne'];
                $response['reponses'][$i]['Adresse'] = $row['adr_num'].' '.$row['adr_typeVoie'].' '.$row['adr_libVoie'];
                $response['reponses'][$i]['Adresse2'] = $row['adr_comp'];
                $response['reponses'][$i]['CP'] = $row['adr_cp'];
                $response['reponses'][$i]['Ville'] = $row['adr_ville'];
                $response['reponses'][$i]['Tel'] = $row['tel'];
                $response['reponses'][$i]['Fax'] = $row['fax'];
                $response['reponses'][$i]['FJ'] = $row['cj'];
                $response['reponses'][$i]['Actif'] = $row['actif'];
                $response['reponses'][$i]['NafEtab'] = $row['ape_etab'];
                $response['reponses'][$i]['NafEnt'] = $row['ape_entrep'];
             }
             switch($this->index) {
                 case  'ent':
                    $pertinence = $this->getPertinence($this->formR['raisonSociale'], $row['raisonSociale']);
                    $response['reponses'][$i]['Pertinence'] = $pertinence;
                 break;
                 case  'act':
                    $response['reponses'][$i]['ActNomRs'] = $row['raisonSociale'];
                    $response['reponses'][$i]['ActPays'] = $row['Pays'];
                    $response['reponses'][$i]['ActDateLien'] = $row['dateLien'];
                    $response['reponses'][$i]['ActActif'] = $row['actif'];
                    $response['reponses'][$i]['ActPmin'] = $row['Pmin'];
                 break;
                 case  'dir':
                    $response['reponses'][$i]['DirRs']  = '';
                    $response['reponses'][$i]['DirNom']  = $row['nom'];
                    $response['reponses'][$i]['DirPrenom']  = $row['prenom'];
                    $response['reponses'][$i]['DirNomUsage']  = '';
                    $response['reponses'][$i]['DirDateEffet']  = '';
                    $response['reponses'][$i]['DirFonction']  = $row['fonction_lib'];
                    $response['reponses'][$i]['DirDepart']  = '';
                 break;
                 case 'Histo':
                    $response['reponses'][$i]['Localisation'] = $row['Loc'];
                    $response['reponses'][$i]['Fichier'] = $row['nomFichier'];
                    $response['reponses'][$i]['Annee'] = $row['annee'];
                    $response['reponses'][$i]['Code'] = $row['bod'];
                    $response['reponses'][$i]['Texte'] = $row['texte'];
                    
                    $response['reponses'][$i]['id'] = $row['id'];
                    $response['reponses'][$i]['Pertinence'] = $resSphinx[$row['id']]['weight'];
                 break;
             }
             $i++;
         }
        return ($response);
    }

/***************************************************************************************************************/
/** Partie debug **/

    protected function cmp($a, $b)
    {
        return (($a < $b)?-1:1);
    }

    public function getResultSphinx($resSphinx)
    {
        $response = $this->getResponse($resSphinx);
        /** Sortir les resultats par pertinence **/
        //usort($response, array($this, 'cmp'));
        $html .= '<ol>';
        if($this->index == 'ent') {
            for($i= 0; $i < count($response['reponses']); $i++) {
                $html .= '<li>['.$response['reponses'][$i]['Pertinence'].'] [ '.$response['reponses'][$i]['Siren'].' ] <b>'.$response['reponses'][$i]['Nom'].'</b> '.$response['reponses'][$i]['CP'].' '.$response['reponses'][$i]['Adresse'].' '.$response['reponses'][$i]['Ville'].'</li>';
            }
        } else if ($this->index == 'act') {
            for($i= 0; $i < count($response['reponses']); $i++) {
               $html .= '<li><b>'.$response['reponses'][$i]['ActNomRs'].'</b> '.$response['reponses'][$i]['ActPays'].' '.$response['reponses'][$i]['ActDateLien'].' '.$response['reponses'][$i]['ActPmin'].'</li>';
            }
        } else if ($this->index == 'dir') {
             for($i= 0; $i < count($response['reponses']); $i++) {
               $html .= '<li><b>'.$response['reponses'][$i]['DirNom'].'</b> '.$response['reponses'][$i]['DirPrenom'].' '.$response['reponses'][$i]['Nom'].'</li>';
             }
        }
        $html .= '</ol>';
        $this->printInformations($html);
        $critere = explode(':', $this->detectedSequance());
        $html = '<b>Critères detectés : </b>'.$critere[0].'<br />';
        
        $this->printInformations($html);
    }

    protected function printStatus($response)
    {
        if(!$response) {
            return ($this->printError('Erreur : '.$this->sphinx->GetLastError()));
        }
        if ($this->sphinx->GetLastWarning()) {
            return ($this->printError('Erreur : '.$this->sphinx->GetLastWarning()));
        }
        $html = '<b>Résultats trouvés : <span style="color:'.(($response['total']>0)?'green':'red').'">'.$response['total'].'</span> sur <span style="color:'.(($response['total_found']>0)?'green':'red').'">'.$response['total_found'].'</span> trouvé en '.$response['time'].' secondes !<br /></b>';
        $html .= '<br>Statistiques de recherches :<br />';
        $html .= '<ol>';
        if(isset($response['words'])) {
            foreach($response['words'] as $words => $info) {
                    $html .= '<li><b>'.$words.'</b> a été trouvé <span style="color:'.(($info['hits']>0)?'green':'red').'">'.$info['hits'].'</span> fois</li>';
            }
        }
        $html .= '</ol>';
        $this->printInformations($html);
    }

    protected function printError($error)
    {
        $this->html .= '<div style="color:black;background-color:#FFBFBF;border:1px dashed white;">';
                $this->html .= $error;
        $this->html .= '</div>';
    }

    protected function printInformations($informations)
    {
        if($this->debug) {
            $this->html .= '<div style="text-align:left;margin:5px;background-image: url(/themes/default/images/information.png);font-size:13px;font-family:Verdana;margin-top:10px;padding:5px;color:black;background-color:black;border:1px dashed white;">';
                    $this->html .= $informations;
            $this->html .= '</div>';
        }
    }
/***************************************************************************************************************/
/** Partie Setters **/

    public function setSortMode($mode) {
        switch($mode) {
            case 'SPH_SORT_RELEVANCE':
                    return (SPH_SORT_RELEVANCE);
            case 'SPH_SORT_ATTR_DESC':
                    return (SPH_SORT_ATTR_DESC);
            case 'SPH_SORT_ATTR_ASC':
                    return (SPH_SORT_ATTR_ASC);
            case 'SPH_SORT_TIME_SEGMENTS':
                    return (SPH_SORT_TIME_SEGMENTS);
            case 'SPH_SORT_EXTENDED':
                    return (SPH_SORT_EXTENDED);
            case 'SPH_SORT_EXPR':
                    return (SPH_SORT_EXPR);
            default:
                    return (SPH_SORT_RELEVANCE);
        }
    }

    public function setForm($form) {
        $this->formR = $form;
    }

    public function setSphinx($sphinx) {
        $this->sphinx = $sphinx;     
    }

    public function execute() {
        return $this->search();   
    }

    public function setTime($time) {
        $this->total_time += $time;
    }

    public function setMaxSizeWord($size) {
        $this->maxSizeWord = $size;
    }

    public function setSequance($bool = true) {
        $this->sequances = $bool;
    }

    public function setQuorums($bool = true) {
        $this->quorum = $bool;
    }

    public function setProximotes($bool = true) {
        $this->proximites = $bool;
    }

    public function setPoids($bool = true) {
        $this->poids = $bool;
    }

    public function setActif($bool = true) {
        $this->actif = $bool;
    }

    public function setQuorumsize($size) {
        $this->Quorumsize = $size;
    }

    public function setProximiteSize($size) {
        $this->ProximiteSize = $size;
    }

    public function setNbRep($max) {
        $this->nbRep = $max;
    }

    public function setDebug($bool = true) {
        $this->debug = $bool;
    }

    public function setPage($page) {
        $this->page = $page;
    }
    
    public function setDeb($deb) {
        $this->deb = $deb;
    }
    
    public function setMax($max) {
        $this->max = $max;
    }
    
    public function setIndex($index) {
        $this->index = $index;
    }
/***************************************************************************************************************/
}

?>