diff --git a/docs/README.txt b/docs/README.txt index 3092d023..cdce1fb3 100644 --- a/docs/README.txt +++ b/docs/README.txt @@ -100,10 +100,6 @@ apt-get install php-apc apt-get install php5-curl apt-get install php5-xmlrpc -Paquet PEAR -- Mail -- Mail_Mime - WKHTMLTOPDF =========== apt-get install libXrender1 diff --git a/library/Metier/insee/classMInsee.php b/library/Metier/insee/classMInsee.php index 9ccc8da1..47fad194 100644 --- a/library/Metier/insee/classMInsee.php +++ b/library/Metier/insee/classMInsee.php @@ -2262,7 +2262,7 @@ class MInsee if ($nic<>0) $where=" siren=$siren AND nic=$nic "; else $where=" siren=$siren AND siege=1 "; - $insee = $this->iDb->select('insee.bascule', 'siren, nic, apen5, apen4, apet5, apet4', $where, true, MYSQL_ASSOC); + $insee = $this->iDb->select('insee.bascule', 'siren, nic, apen5, apen4, apet5, apet4', $where, false, MYSQL_ASSOC); if ( count($insee)==0 ) { return false; } @@ -2992,7 +2992,7 @@ class MInsee $tabProcol = $this->getAnnoncesLegales($siren, 0, 'P', false); if ( count($tabProcol) > 0 ) { $tabDates = array(); - foreach ($tabProcol as $iProcol=>$procol) { + foreach ($tabProcol as $iProcol => $procol) { $tabDates[] = $procol['dateJugement']; } rsort($tabDates); @@ -3621,7 +3621,7 @@ class MInsee // Eléments Financiers en provenance du dernier Bilan $rep = $this->iDb->select('jo.bilans', 'siren, dateExercice, dureeExercice, monnaie, typeBilan, unite, postes, dateProvPartenaire, dateInsert', - "siren=$siren AND typeBilan IN ('N','S') ORDER BY dateExercice DESC LIMIT 0,1", true, MYSQL_ASSOC); + "siren=$siren AND typeBilan IN ('N','S') ORDER BY dateExercice DESC LIMIT 0,1", false, MYSQL_ASSOC); if ( count($rep)>0 ) { $entrep = $rep[0]; $tabRet['bilanAnnee'] = substr($entrep['dateExercice'],0,4); @@ -4067,6 +4067,14 @@ class MInsee return $tabRet; } + /** + * Retourne le nombre d'annonces + * @param string $siren + * @param number $idAnnonce + * @param string $rubrique + * @param string $deleted + * @return int + */ public function getAnnoncesLegalesCount($siren, $idAnnonce = 0, $rubrique = '', $deleted = false) { // --- Where Bodacc @@ -4112,9 +4120,10 @@ class MInsee } /** - * + * Where SQL * @param string $type bodacc, histo * @param mixed $rubrique + * @return boolean|string */ public function getAnnoncesLegalesRubrique($type, $rubrique = '') { @@ -4232,22 +4241,34 @@ class MInsee // --- Type annonce if ($type == 'annonce') { - if ($rubrique=='P' || - $rubrique=='PH') { // Procédure collective + // Procédure collective + if ($rubrique=='P' || $rubrique=='PH') { $where = " AND a.typeEven BETWEEN 1000 AND 1999 AND a.typeEven NOT IN(1005, 1010, 1050, 1055, 1550) "; - } elseif ($rubrique=='D') { // Dissolution de la société + } + // Dissolution de la société + elseif ($rubrique=='D') { $where = " AND a.typeEven IN (2202, 2203, 2204, 2210, 2211, 2212) "; - } elseif ($rubrique=='A') { // Absorption + } + // Absorption + elseif ($rubrique=='A') { $where = " AND a.typeEven IN (2720, 2721) "; - } elseif ($rubrique=='C' || $rubrique=='BODC') { // Dépôt des comptes + } + // Dépôt des comptes + elseif ($rubrique=='C' || $rubrique=='BODC') { $where = " AND a.typeEven BETWEEN 3000 AND 3999 "; } elseif ($rubrique=='R') { $where = " AND a.typeEven IN (2202, 2203, 2204, 2210, 2211, 2212) "; - } elseif ($rubrique=='L') { // Location gérance Locataire + } + // Location gérance Locataire + elseif ($rubrique=='L') { $where = " AND a.typeEven IN (2800, 2875, 2880, 2881, 2885, 2840) "; - } elseif ($rubrique=='G') { // Location gérance Propriétaire + } + // Location gérance Propriétaire + elseif ($rubrique=='G') { $where = " AND a.typeEven IN (2850, 2851, 2860, 2870) "; - } elseif ($rubrique=='V') { // Ventes/Cessions + } + // Ventes/Cessions + elseif ($rubrique=='V') { $where = " AND a.typeEven IN (5500, 5501, 5502, 5503, 5510, 5600, 5650) "; } elseif (is_array($rubrique) && count($rubrique)>0) { $where = " AND (a.typeEven IN (".implode(',',$rubrique).') OR '; @@ -4265,6 +4286,420 @@ class MInsee return $where; } + /** + * Parse les annonces légales pour déterminer leur rubrique + * plus rapide d'executer sur la liste des annonces légales que d'executer les requetes SQL + * @param array $annonces Annonces au format BDD + * @param mixed $rubrique + * @return array + * Retourne une liste filtrer suivant la/les rubriques + */ + public function annoncesInRubrique($annonces, $rubrique) + { + $annonceFilter = array(); + + foreach ($annonces as $ann) { + + // --- Formatage bodacc + if ($ann['SourceTable'] == 'bodacc') { + $typeEven = explode(' ', $ann['typeEven']); + // Procédure collective + if ($rubrique=='P' || $rubrique=='PH') { + $evenOk = true; + foreach($typeEven as $even) { + if (in_array($even, array('1005','1010','1050','1055','1550'))) { + $evenOk = false; + break; + } + } + if ($ann['Rubrique'] == 'procol' && $evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Dissolution de la société + elseif ($rubrique=='D') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2202','2203','2204','2210','2211','2212'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Absorption + elseif ($rubrique=='A') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2720','2721'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // BODACC A + elseif ($rubrique=='BODA') { + if (in_array($ann['Rubrique'], array('creations', 'procol', 'ventes'))) { + $annonceFilter[] = $ann; + } + } + // BODACC B + elseif ($rubrique=='BODB') { + if (in_array($ann['Rubrique'], array('mmd', 'radiations'))) { + $annonceFilter[] = $ann; + } + } + // Dépôt des comptes, BODACC C + elseif ($rubrique=='C' || $rubrique=='BODC') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('3100','3200','3300','3999'))) { + $evenOk = true; + break; + } + } + if ($ann['Rubrique'] == 'comptes' || $evenOk === true) { + $annonceFilter[] = $ann; + } + } elseif ($rubrique=='R') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2202','2203','2204','2210','2211','2212'))) { + $evenOk = true; + break; + } + } + if ($ann['Rubrique'] == 'radiations' || $evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Location gérance Locataire + elseif ($rubrique=='L') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2800','2875','2880','2881','2885','2840','4355'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Location gérance Propriétaire + elseif ($rubrique=='G') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2850','2851','2860','2870'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Ventes/Cessions + elseif ($rubrique=='V') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('5500','5501','5502','5503','5510','5600','5650'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } elseif (is_array($rubrique) && count($rubrique) > 0) { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, $rubrique)) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + } + + // --- Formattage Histo + elseif ($ann['SourceTable'] == 'histo') { + if ($rubrique=='P') { + if ($ann['E1GSIR'] != 340460104 && $ann['CODEVE'] >= 50 && $ann['CODEVE'] <= 79 ) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='PH') { + if ($ann['CODEVE'] >= 50 && $ann['CODEVE'] <= 79 ) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='R') { + if ($ann['CODEVE'] >= 40 && $ann['CODEVE'] <= 42 ) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='L') { + if (in_array($ann['CODEVE'], array(37,42))) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='G') { + if ($ann['CODEVE'] == 38) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='BODA') { + if ($ann['JAL'] == 1) { + $annonceFilter[] = $ann; + } + } + elseif ($rubrique=='BODB') { + if ($ann['JAL'] == 200) { + $annonceFilter[] = $ann; + } + } + elseif (is_array($rubrique)) { + $tabCodEve = $tabCodRol = array(); + foreach ($rubrique as $codeEvenTmp) { + $codRet=array_search($codeEvenTmp, $this->HistoRoleConvert); // Ne gère pas les ; de tabtmp2 + if ($codRet) { + $tabCodRol[] = $codRet; + } else { + $tabCodEve[] = array_search($codeEvenTmp, $this->HistoEvenConvert)*1; + } + } + $where =''; + $tabCodEve = array_unique($tabCodEve); + $tabCodRol = array_unique($tabCodRol); + if (in_array($ann['CODEVE'], $tabCodEve) || in_array($ann['ROLE'], $tabCodRol)) { + $annonceFilter[] = $ann; + } + } + } + + // --- Formattage Annonce + elseif ($ann['SourceTable'] == 'annonce') { + // Procédure collective + if ($rubrique=='P' || $rubrique=='PH') { + if ($ann['typeEven'] >= 1000 && $ann['typeEven'] <= 1999 && !in_array($ann['typeEven'], array('1005','1010','1050','1055','1550'))) { + $annonceFilter[] = $ann; + } + } + // Dissolution de la société + elseif ($rubrique=='D') { + if (in_array($ann['typeEven'], array('2202','2203','2204','2210','2211','2212'))) { + $annonceFilter[] = $ann; + } + } + // Absorption + elseif ($rubrique=='A') { + if (in_array($ann['typeEven'], array('2720','2721'))) { + $annonceFilter[] = $ann; + } + } + // Dépôt des comptes + elseif ($rubrique=='C' || $rubrique=='BODC') { + if ($ann['typeEven'] >= 3000 && $ann['typeEven'] <= 3999) { + $annonceFilter[] = $ann; + } + } elseif ($rubrique=='R') { + if (in_array($ann['typeEven'], array('2202','2203','2204','2210','2211','2212'))) { + $annonceFilter[] = $ann; + } + } + // Location gérance Locataire + elseif ($rubrique=='L') { + if (in_array($ann['typeEven'], array('2800','2875','2880','2881','2885','2840'))) { + $annonceFilter[] = $ann; + } + } + // Location gérance Propriétaire + elseif ($rubrique=='G') { + if (in_array($ann['typeEven'], array('2850','2851','2860','2870'))) { + $annonceFilter[] = $ann; + } + } + // Ventes/Cessions + elseif ($rubrique=='V') { + if (in_array($ann['typeEven'], array('5500','5501','5502','5503','5510','5600','5650'))) { + $annonceFilter[] = $ann; + } + } elseif (is_array($rubrique) && count($rubrique)>0) { + foreach($typeEven as $even) { + if (in_array($even, $rubrique)) { + $annonceFilter[] = $ann; + } + } + } + } + + } + + return $annonceFilter; + } + + /** + * Tri les annonces de la fonction getAnnoncesLegales + * @param array $annonces + * @param mixed $rubrique + * @return array + */ + public function annoncesFilter($annonces, $rubrique) + { + $annonceFilter = array(); + + foreach ($annonces as $ann) { + + $typeEven = array(); + foreach ($ann['evenements'] as $item) { + $typeEven[] = $item['CodeEven']; + } + + // Procédure collective + if ($rubrique=='P' || $rubrique=='PH') { + $evenOk = true; + foreach($typeEven as $even) { + if (in_array($even, array('1005','1010','1050','1055','1550'))) { + $evenOk = false; + break; + } + } + if ($ann['Rubrique'] == 'procol' && $evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Dissolution de la société + elseif ($rubrique=='D') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2202','2203','2204','2210','2211','2212'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Absorption + elseif ($rubrique=='A') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2720','2721'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // BODACC A + elseif ($rubrique=='BODA') { + if (in_array($ann['Rubrique'], array('creations', 'procol', 'ventes'))) { + $annonceFilter[] = $ann; + } + } + // BODACC B + elseif ($rubrique=='BODB') { + if (in_array($ann['Rubrique'], array('mmd', 'radiations'))) { + $annonceFilter[] = $ann; + } + } + // Dépôt des comptes, BODACC C + elseif ($rubrique=='C' || $rubrique=='BODC') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('3100','3200','3300','3999'))) { + $evenOk = true; + break; + } + } + if ($ann['Rubrique'] == 'comptes' || $evenOk === true) { + $annonceFilter[] = $ann; + } + } elseif ($rubrique=='R') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2202','2203','2204','2210','2211','2212'))) { + $evenOk = true; + break; + } + } + if ($ann['Rubrique'] == 'radiations' || $evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Location gérance Locataire + elseif ($rubrique=='L') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2800','2875','2880','2881','2885','2840','4355'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Location gérance Propriétaire + elseif ($rubrique=='G') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('2850','2851','2860','2870'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + // Ventes/Cessions + elseif ($rubrique=='V') { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, array('5500','5501','5502','5503','5510','5600','5650'))) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } elseif (is_array($rubrique) && count($rubrique) > 0) { + $evenOk = false; + foreach($typeEven as $even) { + if (in_array($even, $rubrique)) { + $evenOk = true; + break; + } + } + if ($evenOk === true) { + $annonceFilter[] = $ann; + } + } + } + + return $annonceFilter; + } + + /** + * Analyse les annonces légales pour déterminer si en plan + * @param string $type Type d'annonce bodacc|histo|annonces + * @param int $fj Code catégorie juridique + * @param array $annonce Une annonce + */ public function getAnnoncesLegalesPlan($type, $fj, $annonce) { $classWDate = new WDate(); @@ -4827,7 +5262,7 @@ class MInsee } } - if ($ann['Rubrique']=='procol') $procol=true; + if ($ann['Rubrique']=='procol') $procol = true; $dateCes=str_replace('-','', $ann['dateCessationActivite'])*1; $dateDeb=str_replace('-','', $ann['dateDebutActivite'])*1; @@ -5192,123 +5627,115 @@ class MInsee // --- Vérification if ($visualisation === false) { - /** - * On vérifie si la société n'est pas in bonis pour les raisons suivantes : - * 1502 : Clôture de la procédure pour extinction du passif - */ - if ($rubrique=='P') { - $tabJugements=array(); - foreach ($tabRet as $i=>$ann) { - $tabJugements[$ann['dateJugement']]=$ann['evenements'][0]['CodeEven']; + // --- Si il y a des annonces + if (count($tabRet) > 0) { + $tabJugements = array(); + // --- Liste des jugements principaux - élimination des secondaires + foreach ($tabRet as $i => $ann) { + $tabJugements[$ann['dateJugement']] = $ann['evenements'][0]['CodeEven']; } - // Si plan recherche des annonces suivantes - if ($this->dureePlan>0) { - ksort($tabJugements); - // Tableau chronologique des dates de jugement ==> code jugement - reset($tabJugements); - foreach ($tabJugements as $dateJuge=>$codeJuge) { - if ($dateJuge>$this->debutPlan & ( - ($codeJuge>=1100 && $codeJuge<=1101)|| // Sauvegarde - ($codeJuge>=1200 && $codeJuge<=1202)||$codeJuge==1211|| // RJ - ($codeJuge>=1300 && $codeJuge<=1313)|| // LJ - ($codeJuge>=1500 && $codeJuge<=1504) ) ) // Cloture + // --- Gestions des conditions pour l'affichage de l'indicateur procédure collectives + if ($rubrique=='P') { + // Si plan recherche des annonces suivantes + if ($this->dureePlan > 0) { + ksort($tabJugements); + // Tableau chronologique des dates de jugement => code jugement + foreach ($tabJugements as $dateJuge => $codeJuge) { // Si plan suivi de SV, RJ, LJ ou clôture alors pas de plan - $this->dureePlan=0; - } - } - - // Tableau ante-chronologique des dates de jugement ==> code jugement - krsort($tabJugements); - reset($tabJugements); - - $tabNoProcol=array(); - $tmp=$this->iDb->select('jo.tabEvenements', 'codEven,affProcol', 'affProcol>0', false, MYSQL_ASSOC); - foreach ($tmp as $tmp2) - $tabNoProcol[$tmp2['codEven']]=$tmp2['affProcol']; - - if (@array_key_exists(current($tabJugements), $tabNoProcol)) { - // Ce code jugement Procol n'appel pas forcément l'indicateur : SituationJuridique=P - switch($tabNoProcol[current($tabJugements)]) { - case 1: // PAS DE MENTION DE LA PROCOL - $tabRet=array(); - break; - case 2: // Ne pas mentionner la procol si CJ=1xxx - //$tabId=$this->getIdentiteLight($siren); - if (substr($tabId['FJ'],0,1)*1==1) { - $tabRet=array(); - } elseif ($tabId['Actif']*1>0 && substr($tabId['FJ'],0,1)*1<>9 ) { - $derProcol =str_replace('-','',key($tabJugements))*1; - $maxLatence=date('Ymd',mktime(0,0,0,(substr($derProcol,4,2)*1)+1,substr($derProcol,6,2),substr($derProcol,0,4))); - if (date('Ymd')>$maxLatence) { - $tabRet=array(); + if ($dateJuge>$this->debutPlan & ( + ($codeJuge>=1100 && $codeJuge<=1101)|| // Sauvegarde + ($codeJuge>=1200 && $codeJuge<=1202)|| $codeJuge==1211|| // RJ + ($codeJuge>=1300 && $codeJuge<=1313)|| // LJ + ($codeJuge>=1500 && $codeJuge<=1504) ) ) { // Cloture + $this->dureePlan = 0; } - } - break; - case 3: // Pas Procol si actif RCS - //$tabId=$this->getIdentiteLight($siren); - if ($tabId['Actif']*1>0) { - $tabRet=array(); - } - break; - case 4: // Le dernier jugement est un appel => Procol Suspendu - $this->appelJugement=true; - break; - } - } - - if (count($tabRet)>0) { - $derProcol=str_replace('-','',key($tabJugements))*1; - $dateTropAncienne=(date('Ymd')*1)-120000; - if ($derProcol<$dateTropAncienne) { - //$tabId=$this->getIdentiteLight($siren); - if ($tabId['Actif']*1>0) { - /** Procédure trop ancienne **/ - $derPr=$classWDate->dateT('Ymd','d/m/Y',$derProcol); - $tabRet=array(); } - } elseif ((current($tabJugements)>=1300 && current($tabJugements)<=1313 && current($tabJugements)!=1310) || - (current($tabJugements)>=1500 && current($tabJugements)<=1504)) { - /** En Procol mais présence d'une annonce de cloture ou LJ - avec Bilan publié ultérieurement - **/ - $mBil=new MBilans($siren, $this->iDb); - $tabBilans=$mBil->listeBilans($accesDist); - $derExercice=0; + } - foreach ($tabBilans as $idx=>$bilan) - if ($bilan['dateExercice']>$derExercice) $derExercice=$bilan['dateExercice']; + // Tableau ante-chronologique des dates de jugement ==> code jugement + krsort($tabJugements); + $evenFirst = current($tabJugements); + $derProcol = str_replace('-','', key($tabJugements))*1; + //@todo : Mettre en cache + $tabNoProcol = array(); + $tmp = $this->iDb->select('jo.tabEvenements', 'codEven, affProcol', 'affProcol>0', false, MYSQL_ASSOC); + foreach ($tmp as $tmp2) { + $tabNoProcol[$tmp2['codEven']] = $tmp2['affProcol']; + } + + // --- Evenements effaçant l'indicateur P dans Situation Juridique + if (array_key_exists($evenFirst, $tabNoProcol)) { + switch ($tabNoProcol[$evenFirst]) { + // PAS DE MENTION DE LA PROCOL + case 1: + $tabRet = array(); + break; + // Ne pas mentionner la procol si CJ=1xxx + case 2: + if (substr($tabId['FJ'],0,1)*1==1) { + $tabRet = array(); + } elseif ($tabId['Actif']*1 > 0 && substr($tabId['FJ'],0,1)*1 != 9) { + $maxLatence = date('Ymd',mktime(0,0,0,(substr($derProcol,4,2)*1)+1,substr($derProcol,6,2),substr($derProcol,0,4))); + if (date('Ymd') > $maxLatence) { + $tabRet = array(); + } + } + break; + // Pas Procol si actif RCS + case 3: + if ($tabId['Actif']*1>0) { + $tabRet = array(); + } + break; + // Le dernier jugement est un appel => Procol Suspendu + case 4: + $this->appelJugement = true; + break; + } + } + + // --- Procédure trop ancienne plus de 12 ans et actif + $dateTropAncienne = (date('Ymd')*1)-120000; + if ($derProcol < $dateTropAncienne && $tabId['Actif']*1 > 0) { + $derPr = $classWDate->dateT('Ymd','d/m/Y', $derProcol); + $tabRet = array(); + } + // --- En Procol mais présence d'une annonce de cloture ou LJ avec Bilan publié ultérieurement + elseif ( ($evenFirst>=1300 && $evenFirst<=1313 && $evenFirst!=1310) || ($evenFirst>=1500 && $evenFirst<=1504)) { + $mBil = new MBilans($siren, $this->iDb); + $tabBilans = $mBil->listeBilans($accesDist); + $derExercice = 0; + foreach ($tabBilans as $idx => $bilan) { + if ($bilan['dateExercice'] > $derExercice) { + $derExercice = $bilan['dateExercice']; + } + } if ($derExercice>$derProcol) { - $derEx=$classWDate->dateT('Ymd','d/m/Y',$derExercice); - $derPr=$classWDate->dateT('Ymd','d/m/Y',$derProcol); - $tabRet=array(); + $derEx = $classWDate->dateT('Ymd', 'd/m/Y', $derExercice); + $derPr = $classWDate->dateT('Ymd', 'd/m/Y', $derProcol); + $tabRet = array(); } } } - } - - elseif ($rubrique=='D' && count($tabRet)>0) { - $tabJugements=array(); - foreach ($tabRet as $i=>$ann) { - $tabJugements[$ann['DateParution']]=$ann['evenements'][0]['CodeEven']; - } - // Tableau ante-chronologique des dates de jugement ==> code jugement - krsort($tabJugements); - reset($tabJugements); - - $mBil = new MBilans($siren, $this->iDb); - $tabBilans = $mBil->listeBilans($accesDist); - $derExercice = 0; - $derProcol = str_replace('-','',key($tabJugements))*1; - foreach ($tabBilans as $idx=>$bilan){ - if ($bilan['dateExercice']>$derExercice) { - $derExercice = $bilan['dateExercice']; + // --- Dissolution mais bilan après événements + elseif ($rubrique == 'D') { + // Tableau ante-chronologique des dates de jugement ==> code jugement + krsort($tabJugements); + $mBil = new MBilans($siren, $this->iDb); + $tabBilans = $mBil->listeBilans(false, 3); + $derExercice = 0; + $derProcol = str_replace('-','',key($tabJugements))*1; + foreach ($tabBilans as $idx => $bilan){ + if ($bilan['dateExercice'] > $derExercice) { + $derExercice = $bilan['dateExercice']; + } + } + if ($derExercice > $derProcol) { + $derEx = $classWDate->dateT('Ymd','d/m/Y',$derExercice); + $derPr = $classWDate->dateT('Ymd','d/m/Y',$derProcol); + $tabRet = array(); } - } - if ($derExercice > $derProcol) { - $derEx=$classWDate->dateT('Ymd','d/m/Y',$derExercice); - $derPr=$classWDate->dateT('Ymd','d/m/Y',$derProcol); - $tabRet = array(); } } } @@ -5327,28 +5754,23 @@ class MInsee */ public function getAnnoncesBalo($siren, $idAnnonce=0, $offset=0, $lignes=100) { - $siren=$siren*1; - $siren = str_pad($siren, 9, '0', STR_PAD_LEFT); $strIdAnn=''; $tabRet=array(); if ($idAnnonce>0) { - //$idBalo=//.$tabBalo['Num_Affaire'].','.$tabBalo['Num_Parution']; $tmp=explode('.', $idAnnonce); - //if (strlen($tmp[0])==9 && is_numeric($tmp[0])) $rcs=$tmp[0]; - if (is_numeric($tmp[0])) $num=$tmp[0]; - if (is_numeric($tmp[1])) $par=$tmp[1]; - //$idBaloPdf=basename($tabBalo['Url_Annonce_Pdf']); + if (is_numeric($tmp[0])) $num=$tmp[0]; + if (is_numeric($tmp[1])) $par=$tmp[1]; $strIdAnn=" AND Num_Affaire='$num' AND Num_Parution='$par' "; - //$idAnnonce } $mBalo = new MBalo(); - $bodacc = $this->iDb->select('jo.balo', - "Societe_Rcs, Categorie, Num_Affaire, Date_Parution, Num_Parution, Url_Annonce_Html, Url_Annonce_Pdf, Annonce_Html, dateInsert", "Societe_Rcs='$siren' AND Date_Parution>='2004-01-01' $strIdAnn ORDER BY Date_Parution DESC, Num_Affaire LIMIT $offset, $lignes", + $bodacc = $this->iDb->select('jo.balo', "Societe_Rcs, Categorie, Num_Affaire, Date_Parution, Num_Parution, + Url_Annonce_Html, Url_Annonce_Pdf, Annonce_Html, dateInsert", + "Societe_Rcs='$siren' $strIdAnn ORDER BY Date_Parution DESC, Num_Affaire LIMIT $offset, $lignes", false, MYSQL_ASSOC); $k=0; @@ -5361,28 +5783,26 @@ class MInsee ); $tabRet[$k]=array( - 'id'=>$ann['Num_Affaire'].'.'.$ann['Num_Parution'], - 'BodaccCode'=>'BALO', - 'BodaccNum'=>$ann['Num_Parution'], - 'NumAnnonce'=>$ann['Num_Affaire'], - 'DateParution'=>$ann['Date_Parution'], - //'Departement'=>'',$ann['Tribunal_Dept'], - //'Tribunal'=>$ann['triNom'], - //'TribunalSiret'=>$ann['triSiret'], - //'Rubrique'=>$ann['Rubrique'], - 'typeAnnonce'=>'Insertion', - 'dateInsertionSD'=>$ann['dateInsert'], - 'evenements'=>$tabRetEven, - 'Lien_Annonce_Pdf'=>basename($ann['Url_Annonce_Pdf']), + 'id' => $ann['Num_Affaire'].'.'.$ann['Num_Parution'], + 'BodaccCode' => 'BALO', + 'BodaccNum' => $ann['Num_Parution'], + 'NumAnnonce' => $ann['Num_Affaire'], + 'DateParution' => $ann['Date_Parution'], + 'typeAnnonce' => 'Insertion', + 'dateInsertionSD' => $ann['dateInsert'], + 'evenements' => $tabRetEven, + 'Lien_Annonce_Pdf' => basename($ann['Url_Annonce_Pdf']), ); - if ($idAnnonce<>0) - $tabRet[$k]['texteAnnonce'] = strtr( - preg_replace('//Uis', '', - preg_replace('/( class=".*")/ie', ' ', $ann['Annonce_Html'])), - array(' '=>' ', ''=>'', ''=>'') - ); + if ($idAnnonce<>0) { + $tabRet[$k]['texteAnnonce'] = strtr( + preg_replace('//Uis', '', + preg_replace('/( class=".*")/ie', ' ', $ann['Annonce_Html'])), + array(' '=>' ', ''=>'', ''=>'') + ); + } } } + return $tabRet; } @@ -5394,7 +5814,7 @@ class MInsee public function getAnnoncesBaloCount($siren) { $bodacc = $this->iDb->select('jo.balo', "count(*) AS nb", - "Societe_Rcs='$siren' AND Date_Parution>='2004-01-01' ORDER BY Date_Parution DESC, Num_Affaire", false, MYSQL_ASSOC); + "Societe_Rcs='$siren' ORDER BY Date_Parution DESC, Num_Affaire", false, MYSQL_ASSOC); $nb = 0; if (count($bodacc)>0) { $nb = $bodacc[0]['nb']; @@ -6276,13 +6696,12 @@ class MInsee if ($nic=='' || $nic*1==0 || $nic>99999) $strNic=" AND nic=nicSiege"; else $strNic=" AND nic=$nic"; - $tabTmp=$this->iDb->select('insee.insee_avis', 'raiSoc, dateMaj, siren, nic, etatEt, dateEtatEt, typeEtab, adresseEt0, adresseEt1, adresseEt2, adresseEt3, fj, fjLib, nafEt, nafEtLib, effEtPeriode, effEtTr, erreurs, adresseEn0, adresseEn1, adresseEn2, adresseEn3, nafEn, nafEnLib, effEnPeriode, effEnTr, fjEn, fjEnLib, employes, etatEn, dateEtatEn, nicSiege, nbEtabActifs, dateInsert, dateUpdate, DATE(IF(dateUpdate>dateInsert, dateUpdate, dateInsert))*1 AS dateMajSD', - "siren=$siren $strNic", - false, MYSQL_ASSOC); + $tabTmp=$this->iDb->select('insee.insee_avis', + 'raiSoc, dateMaj, siren, nic, etatEt, dateEtatEt, typeEtab, adresseEt0, adresseEt1, adresseEt2, adresseEt3, fj, fjLib, nafEt, nafEtLib, effEtPeriode, effEtTr, erreurs, adresseEn0, adresseEn1, adresseEn2, adresseEn3, nafEn, nafEnLib, effEnPeriode, effEnTr, fjEn, fjEnLib, employes, etatEn, dateEtatEn, nicSiege, nbEtabActifs, dateInsert, dateUpdate, DATE(IF(dateUpdate>dateInsert, dateUpdate, dateInsert))*1 AS dateMajSD', + "siren=$siren $strNic", false, MYSQL_ASSOC); $tabInfos=@$tabTmp[0]; if ($tabInfos['dateMajSD']==date('Ymd')) { $tabInfos['enCache']=true; -// sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "classMInsee::getAvisInsee... en cache sur $siren", print_r($tabInfos, true)); return $tabInfos; } @@ -6292,22 +6711,16 @@ class MInsee $page = getUrl($url, $cookie, '', $referer, false, 'avis-situation-sirene.insee.fr', '', 5); //Code en 4xx ou 5xx signifie une erreur du serveur $codeN = floor($page['code']/100); - if($codeN==4 || $codeN==5) - { + if($codeN==4 || $codeN==5) { return false; } - else - { + else { $tabInfos=array(); $referer = $url; $body = $page['body']; $serviceDispo = true; - if (preg_match("/
Fiche établissement<\/h3>/Uis", $body, $matches))//
  • établissement
  • $tabInfos['fiche']='etab'; @@ -6387,17 +6797,6 @@ class MInsee $tabInfos['effEtTr']=trim($matches[2]); } - /* $strCsv=$siren.';'.$nic.';'.$tabInfos['fiche'].';'.$tabInfos['dateMaj'].';'. - $tabInfos['siren'].';'.$tabInfos['nic'].';'.$tabInfos['raiSoc'].';'. - $tabInfos['etat'].';'.$tabInfos['dateEtat'].';'.$tabInfos['fjCod'].';'.$tabInfos['fjLib'].';'. - $tabInfos['nafCod'].';'.$tabInfos['nafLib'].';'.$tabInfos['effPeriode'].';'. - $tabInfos['effTranche'].';'. - $tabInfos['typeEtab'].';'.@implode(';',@$tabAdresse). - ";\n"; - $fp=@fopen(PATH_LOGS."avis.csv", "a"); - @fwrite($fp, $strCsv); - @fclose($fp); - */ // $body contient l'avis de situation au format html $tabErreurs=array(); if (preg_match('/name="erreurs" value="(.*)" class="erreurText" readonly/Ui', $body, $matches1) || @@ -6471,10 +6870,8 @@ class MInsee 'dateInsert'=>date('YmdHis'))); } $tabInfos['enCache']=false; -// sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "classMInsee::getAvisInsee... en ACCES HTTP sur $siren", print_r($tabInfos, true).mysql_error()); } - else - { + else { return false; } return $tabInfos; diff --git a/library/Metier/partenaires/classMTel.php b/library/Metier/partenaires/classMTel.php index c0e9a90a..57206671 100644 --- a/library/Metier/partenaires/classMTel.php +++ b/library/Metier/partenaires/classMTel.php @@ -280,12 +280,13 @@ class MTel } } - if ($last) - { - $tabRet=array(); - foreach($tabLast as $typeTel=>$tabPriorite) { - ksort($tabPriorite); - $tabRet[]=current($tabPriorite); + if ($last) { + $tabRet = array(); + if ($tabLast != null && count($tabLast) > 0 ) { + foreach($tabLast as $typeTel=>$tabPriorite) { + ksort($tabPriorite); + $tabRet[]=current($tabPriorite); + } } } diff --git a/library/Metier/partenaires/classMTva.php b/library/Metier/partenaires/classMTva.php index 867858a5..159ff1d8 100644 --- a/library/Metier/partenaires/classMTva.php +++ b/library/Metier/partenaires/classMTva.php @@ -42,7 +42,6 @@ class MTva $info = $this->iDb->select('sdv1.siren_tva', "LPAD(cle,2,0) AS cle, DATE_FORMAT(dateMod,'%Y%m%d') as DateMAJ", "siren=$siren", false, MYSQL_ASSOC); $tab=$info[0]; if (count($tab)>0) { - //sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "classMTva sur $siren en cache", print_r($tab, true)); if ( $tab['cle']<>NULL || ( $tab['cle']==NULL && $tab['DateMAJ']>=date('Ymd',mktime(0,0,0,date('m')-6,date('d'),date('Y'))) )) { $cle=$tab['cle']; if ($cle==NULL) { $attribue=false; $cle=$cleAlgo; } @@ -51,7 +50,6 @@ class MTva $this->vatDefined=$attribue; return true; } - //sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "classMTva sur $siren REVALIDATION", print_r($tab, true)); } $cle=$cleAlgo; $nbIndispo=0; @@ -98,8 +96,7 @@ class MTva $this->vatDefined=true; return true; //return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'result'=>array('siren'=>$siren, 'vatNumber'=>"FR$cle$siren", 'vatDefined'=>true)); - } elseif (strpos($body, 'Service non disponible')>0 || - strpos($body, 'ponse trop long.')>0) { + } elseif (strpos($body, 'Service non disponible')>0 || strpos($body, 'ponse trop long.')>0) { $nbIndispo++; if ($nbIndispo<3) { //echo date ('Y/m/d - H:i:s') .' - '.$eol; diff --git a/library/Metier/scores/classMScores.php b/library/Metier/scores/classMScores.php index 94d564e1..fa129cb8 100644 --- a/library/Metier/scores/classMScores.php +++ b/library/Metier/scores/classMScores.php @@ -30,7 +30,7 @@ function getIndiscoreHisto($siren) $ret = $iDb->query($query); $tabRet = array(); while( $ret = $iDb->fetch(MYSQL_ASSOC) ) { - $tabRet[]=array( + $tabRet[] = array( 'siren' => $ret['siren'], 'actif' => $ret['actif'], 'procol' => $ret['procol'], @@ -619,7 +619,7 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail //Définition du nom des variables require_once realpath(dirname(__FILE__)).'/globalCommentaires.php'; - $NIVEAU=$cycleClient; // 1, 2, 3 ou 5 Niveau de version des commentaires + $NIVEAU = $cycleClient; // 1, 2, 3 ou 5 Niveau de version des commentaires if ( $db === null ) { $iDb = new WDB(); @@ -628,12 +628,11 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail } $iRncs = new MRncs($iDb); $iInsee = new MInsee($iDb); - $iInsee->AnnoncesInMemory = true; /** * Récupération des informations identitaire */ - $tabIdentite=$iInsee->getIdentiteEntreprise($siren, $nic, 0, false, $accesDist); + $tabIdentite = $iInsee->getIdentiteEntreprise($siren, $nic, 0, false, false); $timer['identite']=microtime(true); if (empty($tabIdentite)) { @@ -1119,7 +1118,6 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail // On renverse les tableaux 2008, 2007, 2006... en 2006, 2007, 2008 $tabRegX = array_reverse($tabRegX); - global $Y, $Yaff; // Tableau des années en paramètres + $nbAnnees Projetées global $PROJECTAUX; // Taux de projection de n à n+$nbAnnees global $PROJECCOEF; @@ -1321,43 +1319,48 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail } /** Divers éléments calculés **/ + $iInsee->AnnoncesLegalesVisu = true; + $CompanyAnnonces = $iInsee->getAnnoncesLegales($siren); + $iInsee->AnnoncesLegalesVisu = false; // Annonces de dépôt des comptes - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, 'C', false, true); - $nbDepotCpt=count($tabDepotCpt); - $nbMoisMax=0; - $ANNONCEBODCMANQDATE=false; - $ANNONCEBODCREGUL=true; - $BILANDERANNEE=0; - $tabAnnBodc=array(); - if($nbDepotCpt>0) { - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, 'C'); + $nbDepotCpt = count($tabDepotCpt); + $nbMoisMax = 0; + $ANNONCEBODCMANQDATE = false; + $ANNONCEBODCREGUL = true; + $BILANDERANNEE = 0; + $tabAnnBodc = array(); + if($nbDepotCpt > 0) { + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep == 0) { // On prend la dernière Annonce de dépot de comptes - $ANNONCEPUB=true; + $ANNONCEPUB = true; - $tabTmp=array(); - foreach ($depot['evenements'] as $even) - $tabTmp[]=$even['LibEven']; - // Libellé code Even de la plus récente annonce publiée peu importe la source - $ANNONCEDER=implode(', ', $tabTmp); - $ANNONCEDERDATE=$depot['DateParution']; - switch(substr($depot['BodaccCode'],0,1)) { - case 'B': $ANNONCEDERSOURCE='BODACC'; break;// INPI, Publication Régionale - case 'P': $ANNONCEDERSOURCE='RNCS'; break; - case 'G': $ANNONCEDERSOURCE='GREFFE DU TRIBUNAL'; break; - default: $ANNONCEDERSOURCE='JOURNAL REGIONAL'; break; + $tabTmp = array(); + foreach ($depot['evenements'] as $even) { + $tabTmp[] = $even['LibEven']; } - $ANNONCEDERTEXTE=$depot['texteAnnonce'];// INPI, Publication Régionale + // Libellé code Even de la plus récente annonce publiée peu importe la source + $ANNONCEDER = implode(', ', $tabTmp); + $ANNONCEDERDATE = $depot['DateParution']; + switch(substr($depot['BodaccCode'],0,1)) { + case 'B': $ANNONCEDERSOURCE = 'BODACC'; break; // INPI, Publication Régionale + case 'P': $ANNONCEDERSOURCE = 'RNCS'; break; + case 'G': $ANNONCEDERSOURCE = 'GREFFE DU TRIBUNAL'; break; + default: $ANNONCEDERSOURCE = 'JOURNAL REGIONAL'; break; + } + $ANNONCEDERTEXTE = $depot['texteAnnonce']; // INPI, Publication Régionale // Date de l'annonce - $ANNONCEDATE=$depot['DateParution']; - $ANNONCEBODCDATE=$depot['DateParution']; - $BILANDERANNEE=date('Y', mktime(0, 0, 0, $classWdate->dateT('Y-m-d', 'm', $depot['dateEffet']), $classWdate->dateT('Y-m-d', 'd', $depot['dateEffet']), $classWdate->dateT('Y-m-d', 'Y', $depot['dateEffet'])+1)); - $ANNONCEBODDATE=$depot['DateParution'];//dateEffet - if ($nbDepotCpt==1 && // 1 seul dépôt des comptes - abs($classWdate->nbMoisEntre(date('Y-m-d'), $dateCrea))<60) // Entreprise de moins de 5 ans (60 mois) - $nbMoisMax=abs($classWdate->nbMoisEntre($dateCrea,$depot['dateEffet'])); + $ANNONCEDATE = $depot['DateParution']; + $ANNONCEBODCDATE = $depot['DateParution']; + $BILANDERANNEE = date('Y', mktime(0, 0, 0, $classWdate->dateT('Y-m-d', 'm', $depot['dateEffet']), $classWdate->dateT('Y-m-d', 'd', $depot['dateEffet']), $classWdate->dateT('Y-m-d', 'Y', $depot['dateEffet'])+1)); + $ANNONCEBODDATE = $depot['DateParution']; //dateEffet + if ($nbDepotCpt==1 && // 1 seul dépôt des comptes + abs($classWdate->nbMoisEntre(date('Y-m-d'), $dateCrea))<60) {// Entreprise de moins de 5 ans (60 mois) + $nbMoisMax=abs($classWdate->nbMoisEntre($dateCrea,$depot['dateEffet'])); + } } else { if (abs($classWdate->nbMoisEntre($lastDepot, $depot['dateEffet']))>$nbMoisMax) { $nbMoisMax=abs($classWdate->nbMoisEntre($lastDepot, $depot['dateEffet'])); @@ -1389,48 +1392,55 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail // Publications régulieres et 12 mois identiques if ( ($nbMoisBilDate+1) == $nbMoisBilCumul || $nbMoisBilDate == $nbMoisBilCumul - || ($nbMoisBilDate-1)==$nbMoisBilCumul ) { - $ANNONCEBODCREGUL=1; + || ($nbMoisBilDate-1) == $nbMoisBilCumul ) { + $ANNONCEBODCREGUL = 1; // Annonces BODACC de changement de date d'exercice - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2303), false); - if (count($tabDepotCpt)>0) $ANNONCEBODCREGUL=2; + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2303)); + if (count($tabDepotCpt)>0) $ANNONCEBODCREGUL = 2; - } else { - // Pas de publication régulière des comptes - $ANNONCEBODCREGUL=0; + } + // Pas de publication régulière des comptes + else { + $ANNONCEBODCREGUL = 0; } - if ($BILANDERANNEE==0 && date('m')*1>6) // Pas de Dernière année de bilan et on est en juillet passé + // Pas de Dernière année de bilan et on est en juillet passé + if ($BILANDERANNEE==0 && date('m')*1>6) { $BILANDERANNEE=date('Y', mktime(0, 0, 0, date('m'), date('d'), date('Y')-1)); - elseif ($BILANDERANNEE==0 && date('m')*1<=6) // Pas de Dernière année de bilan et on est au premier semestre + } + // Pas de Dernière année de bilan et on est au premier semestre + elseif ($BILANDERANNEE==0 && date('m')*1<=6) { $BILANDERANNEE=date('Y', mktime(0, 0, 0, date('m'), date('d'), date('Y')-2)); + } // Annonces BODACC A - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, 'BODA', false, true); - $nbDepotA=count($tabDepotCpt); - if ($nbDepotA>0) { - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, 'BODA'); + $nbDepotA = count($tabDepotCpt); + if ($nbDepotA > 0) { + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep == 0) { $ANNONCEBODADATE=$depot['DateParution']; - if ($classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODADATE)>$classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODDATE)) { - $ANNONCEBODDATE=$depot['DateParution']; - $tabTmp=array(); - foreach ($depot['evenements'] as $even) - $tabTmp[]=$even['LibEven']; + if ($classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODADATE) > $classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODDATE)) { + $ANNONCEBODDATE = $depot['DateParution']; + $tabTmp = array(); + foreach ($depot['evenements'] as $even) { + $tabTmp[] = $even['LibEven']; + } // Libellé code Even de la plus récente annonce publiée peu importe la source - $ANNONCEDER=implode(', ', $tabTmp); + $ANNONCEDER = implode(', ', $tabTmp); $ANNONCEDERDATE=$depot['DateParution']; switch(substr($depot['BodaccCode'],0,1)) { - case 'B': $ANNONCEDERSOURCE='BODACC'; break;// INPI, Publication Régionale - case 'P': $ANNONCEDERSOURCE='RNCS'; break; - case 'G': $ANNONCEDERSOURCE='GREFFE DU TRIBUNAL'; break; - default: $ANNONCEDERSOURCE='JOURNAL REGIONAL'; break; + case 'B': $ANNONCEDERSOURCE = 'BODACC'; break; // INPI, Publication Régionale + case 'P': $ANNONCEDERSOURCE = 'RNCS'; break; + case 'G': $ANNONCEDERSOURCE = 'GREFFE DU TRIBUNAL'; break; + default: $ANNONCEDERSOURCE = 'JOURNAL REGIONAL'; break; } - $ANNONCEDERTEXTE=$depot['texteAnnonce'];// INPI, Publication Régionale + $ANNONCEDERTEXTE = $depot['texteAnnonce'];// INPI, Publication Régionale } - } elseif ( ($iDep+1)==$nbDepotA ) { - // La première annonce de Bodacc A étant cencée être celle de création - $TRIBUNAL_CREATION=strtr($depot['Tribunal'],array('TC '=>'Tribunal de Commerce de ')); + } + // La première annonce de Bodacc A étant cencée être celle de création + elseif ( ($iDep+1)==$nbDepotA ) { + $TRIBUNAL_CREATION = strtr($depot['Tribunal'], array('TC '=>'Tribunal de Commerce de ')); } $ANNONCEBOD++; $ANNONCEBODA++; @@ -1438,26 +1448,27 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail } // Annonces BODACC B - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, 'BODB', false, true); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { - $ANNONCEBODBDATE=$depot['DateParution']; - if ($classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODBDATE)>$classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODDATE)) { + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, 'BODB'); + if (is_array($tabDepotCpt) && count($tabDepotCpt) > 0){ + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep == 0) { + $ANNONCEBODBDATE = $depot['DateParution']; + if ($classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODBDATE) > $classWdate->dateT('Y-m-d', 'Ymd',$ANNONCEBODDATE)) { $ANNONCEBODDATE=$depot['DateParution']; - $tabTmp=array(); - foreach ($depot['evenements'] as $even) - $tabTmp[]=$even['LibEven']; + $tabTmp = array(); + foreach ($depot['evenements'] as $even) { + $tabTmp[] = $even['LibEven']; + } // Libellé code Even de la plus récente annonce publiée peu importe la source - $ANNONCEDER=implode(', ', $tabTmp); - $ANNONCEDERDATE=$depot['DateParution']; + $ANNONCEDER = implode(', ', $tabTmp); + $ANNONCEDERDATE = $depot['DateParution']; switch(substr($depot['BodaccCode'],0,1)) { case 'B': $ANNONCEDERSOURCE='BODACC'; break;// INPI, Publication Régionale case 'P': $ANNONCEDERSOURCE='RNCS'; break; case 'G': $ANNONCEDERSOURCE='GREFFE DU TRIBUNAL'; break; default: $ANNONCEDERSOURCE='JOURNAL REGIONAL'; break; } - $ANNONCEDERTEXTE=$depot['texteAnnonce'];// INPI, Publication Régionale + $ANNONCEDERTEXTE = $depot['texteAnnonce'];// INPI, Publication Régionale } } $ANNONCEBOD++; @@ -1466,198 +1477,225 @@ function calculIndiScore($siren, $nic=0, $accesDist=false, $cycleClient=2, $mail } // Annonces BODACC Changement d'adresse - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2300,2301,2901,2902,2903,2904), false); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0){ $ANNONCEADRDATE = $depot['DateParution']; } + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2300,2301,2901,2902,2903,2904)); + if (is_array($tabDepotCpt) && count($tabDepotCpt) > 0){ + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep == 0) { + $ANNONCEADRDATE = $depot['DateParution']; + } $ANNONCEADR++; } } // Annonces BODACC Changement de dirigeant - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2315), false, true); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { $ANNONCEDIRDATE = $depot['DateParution']; } + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2315)); + if (is_array($tabDepotCpt) && count($tabDepotCpt) > 0){ + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep==0) { + $ANNONCEDIRDATE = $depot['DateParution']; + } $ANNONCEDIR++; - if (preg_match('/Commissaire/i', $depot['texteAnnonce'])) { + if (preg_match('/Commissaire/iu', $depot['texteAnnonce'])) { $ANNONCECAC++; - /** @todo $ANNONCECAC2 dans les 24 derniers mois - ** et $ANNONCECAC3 dans les 36 derniers mois - **/ - if ($ANNONCECAC==1) - $ANNONCECACDATE=$depot['DateParution']; + if ($ANNONCECAC == 1) { + $ANNONCECACDATE = $depot['DateParution']; + } } } } // Annonces BODACC Changement de FJur - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2307), false); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { $ANNONCEFJURDATE = $depot['DateParution']; } - // @todo A revoir + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2307)); + if (is_array($tabDepotCpt) && count($tabDepotCpt) > 0){ + foreach ($tabDepotCpt as $iDep => $depot) { + if ($iDep==0) { + $ANNONCEFJURDATE = $depot['DateParution']; + } $FJUR_PRE=''; - //if ($iDep==1 && trim($depot['libFJ'])<>'') $FJUR_PRE=$depot['libFJ']; $ANNONCEFJUR++; } } // Annonces BODACC Fusion/Absorptions - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2700,2701,2702,2703,2710,2720,2721,2725,2726,2730,2740), false); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ + /** + * 2700 Fusion/Absorption (entitée absorbante) + * 2701 Fusion/Absorption (Entitée absorbante. Entité absorbée inconnue) + * 2702 Fusion/Absorption (Entitée absorbante. Entité absorbée mal SIRENEE) + * 2703 Fusion/Absorption (Entitée absorbante. Entité absorbée non SIRENEE) + * 2720 Fusion/Absorption (entitée absorbée) + * 2721 Fusion/Absorption (entitée absorbée non identifiée) + * 2725 Fusion/Absorption + */ + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2700,2701,2702,2703,2710,2720,2721,2725,2726,2730,2740)); + if (is_array($tabDepotCpt) && count($tabDepotCpt) > 0){ foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) { $ANNONCEFUSDATE=$depot['DateParution']; } + if ($iDep == 0) { + $ANNONCEFUSDATE = $depot['DateParution']; + } $ANNONCEFUS++; foreach ($depot['evenements'] as $even) { switch ($even['CodeEven']*1) { case 2710: // Projet de fusion (entitée absorbante) case 2726: // Projet de Fusion/Absorption case 2730: // Projet de fusion (entitée absorbée) - $FUSIONPROJET_DATE=$depot['dateJugement']; // Date du projet de fusion - $FUSIONPROJET=$depot['complement']; // Présence d'un projet de fusion, libellé du projet - $FUSIONPROJET_SIREN=''; + $FUSIONPROJET_DATE = $depot['dateJugement']; // Date du projet de fusion + $FUSIONPROJET = $depot['complement']; // Présence d'un projet de fusion, libellé du projet + $FUSIONPROJET_SIREN = ''; if (preg_match_all("/((?:[0-9]{9,9})|(?:[0-9]{3,3} [0-9]{3,3} [0-9]{3,3})|(?:[0-9]{3,3}\.[0-9]{3,3}\.[0-9]{3,3})|(?:[0-9]{3,3}-[0-9]{3,3}-[0-9]{3,3}))/", $FUSIONPROJET, $matches)) { foreach ($matches[1] as $FUSIONPROJET_SIREN) { - $FUSIONPROJET_SIREN=strtr($FUSIONPROJET_SIREN, array('.'=>'','-'=>'', ' '=>'')); - if (!$iInsee->valideSiren($FUSIONPROJET_SIREN)) $FUSIONPROJET_SIREN=0; - else break; + $FUSIONPROJET_SIREN = strtr($FUSIONPROJET_SIREN, array('.'=>'','-'=>'', ' '=>'')); + if (!$iInsee->valideSiren($FUSIONPROJET_SIREN)) { + $FUSIONPROJET_SIREN=0; + } else { + break; + } } } - if ($FUSIONPROJET_SIREN*1<100) $FUSIONPROJET_SIREN=''; + if ($FUSIONPROJET_SIREN*1<100) $FUSIONPROJET_SIREN = ''; break; } } - /* - 2700 Fusion/Absorption (entitée absorbante) - 2701 Fusion/Absorption (Entitée absorbante. Entité absorbée inconnue) - 2702 Fusion/Absorption (Entitée absorbante. Entité absorbée mal SIRENEE) - 2703 Fusion/Absorption (Entitée absorbante. Entité absorbée non SIRENEE) - 2720 Fusion/Absorption (entitée absorbée) - 2721 Fusion/Absorption (entitée absorbée non identifiée) - 2725 Fusion/Absorption - */ } } // Annonces BODACC Changement de capital - $annCapPre=0; - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2100,2101,2102), false); - if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ - foreach ($tabDepotCpt as $iDep=>$depot) { - if ($iDep==0) - // Date de la plus récente Annonce changement de capital - $ANNONCECAPDATE=$depot['DateParution']; - if ($iDep==1) { - if ($depot['capitalDev']=='EUR') $CAPITAL_PRE=$depot['capital']; - elseif ($depot['capitalDev']=='FRF') $CAPITAL_PRE=round($depot['capital']/6.55957); + $annCapPre = 0; + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2100,2101,2102)); + $tabDepotCpt = array_reverse($tabDepotCpt); + $CAPITAL_PRE = 0; + if (is_array($tabDepotCpt) && count($tabDepotCpt)>0) { + foreach ($tabDepotCpt as $iDep => $depot) { + // Date de la plus récente Annonce changement de capital + $ANNONCECAPDATE = $depot['DateParution']; + if (count($tabDepotCpt)>1 && $iDep == count($tabDepotCpt)-2) { + if ($depot['capitalDev']=='FRF') { + $CAPITAL_PRE = round($depot['capital']/6.55957); + } else { + $CAPITAL_PRE = $depot['capital']; + } } - + // Boucle sur les evenements foreach ($depot['evenements'] as $even) { + // Evenement 2101 : Modificaition de capital + if ($even['CodeEven'] == 2101) { + if ($iDep > 0 && $CAPITAL_PRE > 0) { + if ($depot['capitalDev']=='FRF') { + $annonceCapital = round($depot['capital']/6.55957); + } else { + $annonceCapital = $depot['capital']; + } + // Augmentation + if ($annonceCapital > $CAPITAL_PRE) { + $even['CodeEven'] = 2102; + } + // Diminution + elseif ($annonceCapital < $CAPITAL_PRE) { + $even['CodeEven'] = 2100; + } + } + } switch ($even['CodeEven']*1) { - case 2100:// Diminution de capital + // Diminution de capital + case 2100: $ANNONCECAPDIM++; - if ($ANNONCECAPDIM==1) { - // Date de la plus récente Annonce de diminution de capital - $ANNONCECAPDIMDATE=$depot['DateParution']; - // Année de la plus récente Annonce diminution de capital - $ANNONCECAPDIM_AAF=substr($depot['DateParution'],0,4); - } else - // Année de la plus ancienne Annonce diminution de capital - $ANNONCECAPDIM_AAD=substr($depot['DateParution'],0,4); - if ($annCapPre==2102) - $ANNONCECAPAUGDIM++; // Augmentation suivie de diminution de capital - $annCapPre=2100; + if ($ANNONCECAPDIM == 1) { + // Année de la plus ancienne Annonce diminution de capital + $ANNONCECAPDIM_AAD = substr($depot['DateParution'],0,4); + } else { + // Date de la plus récente Annonce de diminution de capital + $ANNONCECAPDIMDATE = $depot['DateParution']; + // Année de la plus récente Annonce diminution de capital + $ANNONCECAPDIM_AAF = substr($depot['DateParution'],0,4); + } + // Augmentation suivie de diminution de capital + if ($annCapPre == 2102) { + $ANNONCECAPAUGDIM++; + } + $annCapPre = 2100; break; - case 2102:// Augmentation de capital + // Augmentation de capital + case 2102: $ANNONCECAPAUG++; - if ($ANNONCECAPAUG==1) { - // Date de la plus récente Annonce Augmentation de capital - $ANNONCECAPAUGDATE=$depot['DateParution']; - // Année de la plus récente Annonce Augmentation de capital - $ANNONCECAPAUG_AAF=substr($depot['DateParution'],0,4); - } else - // Année de la plus ancienne Annonce Augmentation de capital - $ANNONCECAPAUG_AAD=substr($depot['DateParution'],0,4); - if ($annCapPre==2100) - $ANNONCECAPDIMAUG++; // Diminution suivie de Augmentation de capital - $annCapPre=2102; + if ($ANNONCECAPAUG == 1) { + // Année de la plus ancienne Annonce Augmentation de capital + $ANNONCECAPAUG_AAD = substr($depot['DateParution'],0,4); + } else { + // Date de la plus récente Annonce Augmentation de capital + $ANNONCECAPAUGDATE = $depot['DateParution']; + // Année de la plus récente Annonce Augmentation de capital + $ANNONCECAPAUG_AAF = substr($depot['DateParution'],0,4); + } + // Diminution suivie de Augmentation de capital + if ($annCapPre == 2100){ + $ANNONCECAPDIMAUG++; + } + $annCapPre = 2102; break; } } $ANNONCECAP++; - - /** @todo : Récupérer le montant du changement et alimenter ou non cette variable - **/ $ANNONCECAPSIG++; - - if ($CAPITAL_PRE==0) { - // Rechercher le capital à la création ou dans une annonce précédente ! - $CAPITAL_PRE=0; - } } } // Annonces BODACC Cessation d'activité avec dissolution - $tabDepotCpt=$iInsee->getAnnoncesLegales($siren, 0, array(2202,2203,2204,2210,2212), false); + $tabDepotCpt = $iInsee->annoncesFilter($CompanyAnnonces, array(2202,2203,2204,2210,2212)); if (is_array($tabDepotCpt) && count($tabDepotCpt)>0){ foreach ($tabDepotCpt as $iDep=>$depot) { - //sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Indiscore sur $siren : Annonce de Dissolution avec Bilan A", "Dernier Bilan = $BILANDATE et Annonce de dissolution = ".$depot['DateParution']); if ($BILANDATEupdate('jo.scores_surveillance', $tabUpdate2, "siren=$siren", false, 0, true)) { debugLog('W', 'Erreur lors de la MAJ du score en surveillance pour '. $tabIdentite['Nom'], __LINE__, __FILE__, __FUNCTION__, __CLASS__); } } diff --git a/library/Metier/sphinx/rechercheFonc.php b/library/Metier/sphinx/rechercheFonc.php index 279c19e4..d3c0c92c 100644 --- a/library/Metier/sphinx/rechercheFonc.php +++ b/library/Metier/sphinx/rechercheFonc.php @@ -655,7 +655,7 @@ function clientSphinx(&$formR) require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; break; case 2: - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; break; } diff --git a/library/Scores/Ws/Server.php b/library/Scores/Ws/Server.php index f359cbd1..acfb32bf 100644 --- a/library/Scores/Ws/Server.php +++ b/library/Scores/Ws/Server.php @@ -339,6 +339,7 @@ class Scores_Ws_Server * @var unknown_type */ public $listError = array( + '0000' => "Erreur indeterminé", '0900' => "Identifiant ou mot de passe incorrect", '0901' => "Accès WS non authorisé pour cet utilisateur", '0902' => "Méthode non authorisée dans votre profil", @@ -684,8 +685,14 @@ class Scores_Ws_Server else { $sql->where('u.login=?', $login); } - $resultId = $userM->fetchAll($sql); - + try { + $resultId = $userM->fetchAll($sql); + } catch (Zend_Db_Exception $e) { + $c = Zend_Registry::get('config'); + file_put_contents($c->profil->path->data.'/log/application.log', + date('Y-m-d H:i:s').'- AUTH : '.$e->getMessage()."\n", FILE_APPEND); + return '0000'; + } /** * No user, deleted or disable */ @@ -1122,6 +1129,7 @@ class Scores_Ws_Server 'login' => $login, 'authenticate' => $authenticate, 'ip' => $ip, + 'dateInsert' => date('YmdHis'), ); try { $authLogM = new Application_Model_Sdv1UtilisateursAuthLog(); diff --git a/library/SdMetier/Search/Engine.php b/library/SdMetier/Search/Engine.php index 52628d4a..5f0a3e87 100644 --- a/library/SdMetier/Search/Engine.php +++ b/library/SdMetier/Search/Engine.php @@ -16,7 +16,7 @@ class SdMetier_Search_Engine if ($version == 1){ require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; } elseif ($version == 2){ - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; } } diff --git a/library/Vendors/sphinxapi/sphinxapi-2.2.9.php b/library/Vendors/sphinxapi/sphinxapi-2.2.9.php new file mode 100644 index 00000000..c6c1978b --- /dev/null +++ b/library/Vendors/sphinxapi/sphinxapi-2.2.9.php @@ -0,0 +1,1832 @@ +=8 ) + { + $v = (int)$v; + return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); + } + + // x32, int + if ( is_int($v) ) + return pack ( "NN", $v < 0 ? -1 : 0, $v ); + + // x32, bcmath + if ( function_exists("bcmul") ) + { + if ( bccomp ( $v, 0 ) == -1 ) + $v = bcadd ( "18446744073709551616", $v ); + $h = bcdiv ( $v, "4294967296", 0 ); + $l = bcmod ( $v, "4294967296" ); + return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit + } + + // x32, no-bcmath + $p = max(0, strlen($v) - 13); + $lo = abs((float)substr($v, $p)); + $hi = abs((float)substr($v, 0, $p)); + + $m = $lo + $hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912 + $q = floor($m/4294967296.0); + $l = $m - ($q*4294967296.0); + $h = $hi*2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328 + + if ( $v<0 ) + { + if ( $l==0 ) + $h = 4294967296.0 - $h; + else + { + $h = 4294967295.0 - $h; + $l = 4294967296.0 - $l; + } + } + return pack ( "NN", $h, $l ); +} + +/// pack 64-bit unsigned +function sphPackU64 ( $v ) +{ + assert ( is_numeric($v) ); + + // x64 + if ( PHP_INT_SIZE>=8 ) + { + assert ( $v>=0 ); + + // x64, int + if ( is_int($v) ) + return pack ( "NN", $v>>32, $v&0xFFFFFFFF ); + + // x64, bcmath + if ( function_exists("bcmul") ) + { + $h = bcdiv ( $v, 4294967296, 0 ); + $l = bcmod ( $v, 4294967296 ); + return pack ( "NN", $h, $l ); + } + + // x64, no-bcmath + $p = max ( 0, strlen($v) - 13 ); + $lo = (int)substr ( $v, $p ); + $hi = (int)substr ( $v, 0, $p ); + + $m = $lo + $hi*1316134912; + $l = $m % 4294967296; + $h = $hi*2328 + (int)($m/4294967296); + + return pack ( "NN", $h, $l ); + } + + // x32, int + if ( is_int($v) ) + return pack ( "NN", 0, $v ); + + // x32, bcmath + if ( function_exists("bcmul") ) + { + $h = bcdiv ( $v, "4294967296", 0 ); + $l = bcmod ( $v, "4294967296" ); + return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit + } + + // x32, no-bcmath + $p = max(0, strlen($v) - 13); + $lo = (float)substr($v, $p); + $hi = (float)substr($v, 0, $p); + + $m = $lo + $hi*1316134912.0; + $q = floor($m / 4294967296.0); + $l = $m - ($q * 4294967296.0); + $h = $hi*2328.0 + $q; + + return pack ( "NN", $h, $l ); +} + +// unpack 64-bit unsigned +function sphUnpackU64 ( $v ) +{ + list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); + + if ( PHP_INT_SIZE>=8 ) + { + if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again + if ( $lo<0 ) $lo += (1<<32); + + // x64, int + if ( $hi<=2147483647 ) + return ($hi<<32) + $lo; + + // x64, bcmath + if ( function_exists("bcmul") ) + return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); + + // x64, no-bcmath + $C = 100000; + $h = ((int)($hi / $C) << 32) + (int)($lo / $C); + $l = (($hi % $C) << 32) + ($lo % $C); + if ( $l>$C ) + { + $h += (int)($l / $C); + $l = $l % $C; + } + + if ( $h==0 ) + return $l; + return sprintf ( "%d%05d", $h, $l ); + } + + // x32, int + if ( $hi==0 ) + { + if ( $lo>0 ) + return $lo; + return sprintf ( "%u", $lo ); + } + + $hi = sprintf ( "%u", $hi ); + $lo = sprintf ( "%u", $lo ); + + // x32, bcmath + if ( function_exists("bcmul") ) + return bcadd ( $lo, bcmul ( $hi, "4294967296" ) ); + + // x32, no-bcmath + $hi = (float)$hi; + $lo = (float)$lo; + + $q = floor($hi/10000000.0); + $r = $hi - $q*10000000.0; + $m = $lo + $r*4967296.0; + $mq = floor($m/10000000.0); + $l = $m - $mq*10000000.0; + $h = $q*4294967296.0 + $r*429.0 + $mq; + + $h = sprintf ( "%.0f", $h ); + $l = sprintf ( "%07.0f", $l ); + if ( $h=="0" ) + return sprintf( "%.0f", (float)$l ); + return $h . $l; +} + +// unpack 64-bit signed +function sphUnpackI64 ( $v ) +{ + list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) ); + + // x64 + if ( PHP_INT_SIZE>=8 ) + { + if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again + if ( $lo<0 ) $lo += (1<<32); + + return ($hi<<32) + $lo; + } + + // x32, int + if ( $hi==0 ) + { + if ( $lo>0 ) + return $lo; + return sprintf ( "%u", $lo ); + } + // x32, int + elseif ( $hi==-1 ) + { + if ( $lo<0 ) + return $lo; + return sprintf ( "%.0f", $lo - 4294967296.0 ); + } + + $neg = ""; + $c = 0; + if ( $hi<0 ) + { + $hi = ~$hi; + $lo = ~$lo; + $c = 1; + $neg = "-"; + } + + $hi = sprintf ( "%u", $hi ); + $lo = sprintf ( "%u", $lo ); + + // x32, bcmath + if ( function_exists("bcmul") ) + return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c ); + + // x32, no-bcmath + $hi = (float)$hi; + $lo = (float)$lo; + + $q = floor($hi/10000000.0); + $r = $hi - $q*10000000.0; + $m = $lo + $r*4967296.0; + $mq = floor($m/10000000.0); + $l = $m - $mq*10000000.0 + $c; + $h = $q*4294967296.0 + $r*429.0 + $mq; + if ( $l==10000000 ) + { + $l = 0; + $h += 1; + } + + $h = sprintf ( "%.0f", $h ); + $l = sprintf ( "%07.0f", $l ); + if ( $h=="0" ) + return $neg . sprintf( "%.0f", (float)$l ); + return $neg . $h . $l; +} + + +function sphFixUint ( $value ) +{ + if ( PHP_INT_SIZE>=8 ) + { + // x64 route, workaround broken unpack() in 5.2.2+ + if ( $value<0 ) $value += (1<<32); + return $value; + } + else + { + // x32 route, workaround php signed/unsigned braindamage + return sprintf ( "%u", $value ); + } +} + +function sphSetBit ( $flag, $bit, $on ) +{ + if ( $on ) + { + $flag += ( 1<<$bit ); + } else + { + $reset = 255 ^ ( 1<<$bit ); + $flag = $flag & $reset; + } + return $flag; +} + + +/// sphinx searchd client class +class SphinxClient +{ + var $_host; ///< searchd host (default is "localhost") + var $_port; ///< searchd port (default is 9312) + var $_offset; ///< how many records to seek from result-set start (default is 0) + var $_limit; ///< how many records to return from result-set starting at offset (default is 20) + var $_mode; ///< query matching mode (default is SPH_MATCH_EXTENDED2) + var $_weights; ///< per-field weights (default is 1 for all fields) + var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE) + var $_sortby; ///< attribute to sort by (defualt is "") + var $_min_id; ///< min ID to match (default is 0, which means no limit) + var $_max_id; ///< max ID to match (default is 0, which means no limit) + var $_filters; ///< search filters + var $_groupby; ///< group-by attribute name + var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with) + var $_groupsort; ///< group-by sorting clause (to sort groups in result set with) + var $_groupdistinct;///< group-by count-distinct attribute + var $_maxmatches; ///< max matches to retrieve + var $_cutoff; ///< cutoff to stop searching at (default is 0) + var $_retrycount; ///< distributed retries count + var $_retrydelay; ///< distributed retries delay + var $_anchor; ///< geographical anchor point + var $_indexweights; ///< per-index weights + var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25) + var $_rankexpr; ///< ranking mode expression (for SPH_RANK_EXPR) + var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit) + var $_fieldweights; ///< per-field-name weights + var $_overrides; ///< per-query attribute values overrides + var $_select; ///< select-list (attributes or expressions, with optional aliases) + var $_query_flags; ///< per-query various flags + var $_predictedtime; ///< per-query max_predicted_time + var $_outerorderby; ///< outer match sort by + var $_outeroffset; ///< outer offset + var $_outerlimit; ///< outer limit + var $_hasouter; + + var $_error; ///< last error message + var $_warning; ///< last warning message + var $_connerror; ///< connection error vs remote error flag + + var $_reqs; ///< requests array for multi-query + var $_mbenc; ///< stored mbstring encoding + var $_arrayresult; ///< whether $result["matches"] should be a hash or an array + var $_timeout; ///< connect timeout + + ///////////////////////////////////////////////////////////////////////////// + // common stuff + ///////////////////////////////////////////////////////////////////////////// + + /// create a new client object and fill defaults + function SphinxClient () + { + // per-client-object settings + $this->_host = "localhost"; + $this->_port = 9312; + $this->_path = false; + $this->_socket = false; + + // per-query settings + $this->_offset = 0; + $this->_limit = 20; + $this->_mode = SPH_MATCH_EXTENDED2; + $this->_weights = array (); + $this->_sort = SPH_SORT_RELEVANCE; + $this->_sortby = ""; + $this->_min_id = 0; + $this->_max_id = 0; + $this->_filters = array (); + $this->_groupby = ""; + $this->_groupfunc = SPH_GROUPBY_DAY; + $this->_groupsort = "@group desc"; + $this->_groupdistinct= ""; + $this->_maxmatches = 1000; + $this->_cutoff = 0; + $this->_retrycount = 0; + $this->_retrydelay = 0; + $this->_anchor = array (); + $this->_indexweights= array (); + $this->_ranker = SPH_RANK_PROXIMITY_BM25; + $this->_rankexpr = ""; + $this->_maxquerytime= 0; + $this->_fieldweights= array(); + $this->_overrides = array(); + $this->_select = "*"; + $this->_query_flags = sphSetBit ( 0, 6, true ); // default idf=tfidf_normalized + $this->_predictedtime = 0; + $this->_outerorderby = ""; + $this->_outeroffset = 0; + $this->_outerlimit = 0; + $this->_hasouter = false; + + $this->_error = ""; // per-reply fields (for single-query case) + $this->_warning = ""; + $this->_connerror = false; + + $this->_reqs = array (); // requests storage (for multi-query case) + $this->_mbenc = ""; + $this->_arrayresult = false; + $this->_timeout = 0; + } + + function __destruct() + { + if ( $this->_socket !== false ) + fclose ( $this->_socket ); + } + + /// get last error message (string) + function GetLastError () + { + return $this->_error; + } + + /// get last warning message (string) + function GetLastWarning () + { + return $this->_warning; + } + + /// get last error flag (to tell network connection errors from searchd errors or broken responses) + function IsConnectError() + { + return $this->_connerror; + } + + /// set searchd host name (string) and port (integer) + function SetServer ( $host, $port = 0 ) + { + assert ( is_string($host) ); + if ( $host[0] == '/') + { + $this->_path = 'unix://' . $host; + return; + } + if ( substr ( $host, 0, 7 )=="unix://" ) + { + $this->_path = $host; + return; + } + + $this->_host = $host; + $port = intval($port); + assert ( 0<=$port && $port<65536 ); + $this->_port = ( $port==0 ) ? 9312 : $port; + $this->_path = ''; + } + + /// set server connection timeout (0 to remove) + function SetConnectTimeout ( $timeout ) + { + assert ( is_numeric($timeout) ); + $this->_timeout = $timeout; + } + + + function _Send ( $handle, $data, $length ) + { + if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length ) + { + $this->_error = 'connection unexpectedly closed (timed out?)'; + $this->_connerror = true; + return false; + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////// + + /// enter mbstring workaround mode + function _MBPush () + { + $this->_mbenc = ""; + if ( ini_get ( "mbstring.func_overload" ) & 2 ) + { + $this->_mbenc = mb_internal_encoding(); + mb_internal_encoding ( "latin1" ); + } + } + + /// leave mbstring workaround mode + function _MBPop () + { + if ( $this->_mbenc ) + mb_internal_encoding ( $this->_mbenc ); + } + + /// connect to searchd server + function _Connect () + { + if ( $this->_socket!==false ) + { + // we are in persistent connection mode, so we have a socket + // however, need to check whether it's still alive + if ( !@feof ( $this->_socket ) ) + return $this->_socket; + + // force reopen + $this->_socket = false; + } + + $errno = 0; + $errstr = ""; + $this->_connerror = false; + + if ( $this->_path ) + { + $host = $this->_path; + $port = 0; + } + else + { + $host = $this->_host; + $port = $this->_port; + } + + if ( $this->_timeout<=0 ) + $fp = @fsockopen ( $host, $port, $errno, $errstr ); + else + $fp = @fsockopen ( $host, $port, $errno, $errstr, $this->_timeout ); + + if ( !$fp ) + { + if ( $this->_path ) + $location = $this->_path; + else + $location = "{$this->_host}:{$this->_port}"; + + $errstr = trim ( $errstr ); + $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)"; + $this->_connerror = true; + return false; + } + + // send my version + // this is a subtle part. we must do it before (!) reading back from searchd. + // because otherwise under some conditions (reported on FreeBSD for instance) + // TCP stack could throttle write-write-read pattern because of Nagle. + if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) ) + { + fclose ( $fp ); + $this->_error = "failed to send client protocol version"; + return false; + } + + // check version + list(,$v) = unpack ( "N*", fread ( $fp, 4 ) ); + $v = (int)$v; + if ( $v<1 ) + { + fclose ( $fp ); + $this->_error = "expected searchd protocol version 1+, got version '$v'"; + return false; + } + + return $fp; + } + + /// get and check response packet from searchd server + function _GetResponse ( $fp, $client_ver ) + { + $response = ""; + $len = 0; + + $header = fread ( $fp, 8 ); + if ( strlen($header)==8 ) + { + list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) ); + $left = $len; + while ( $left>0 && !feof($fp) ) + { + $chunk = fread ( $fp, min ( 8192, $left ) ); + if ( $chunk ) + { + $response .= $chunk; + $left -= strlen($chunk); + } + } + } + if ( $this->_socket === false ) + fclose ( $fp ); + + // check response + $read = strlen ( $response ); + if ( !$response || $read!=$len ) + { + $this->_error = $len + ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)" + : "received zero-sized searchd response"; + return false; + } + + // check status + if ( $status==SEARCHD_WARNING ) + { + list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) ); + $this->_warning = substr ( $response, 4, $wlen ); + return substr ( $response, 4+$wlen ); + } + if ( $status==SEARCHD_ERROR ) + { + $this->_error = "searchd error: " . substr ( $response, 4 ); + return false; + } + if ( $status==SEARCHD_RETRY ) + { + $this->_error = "temporary searchd error: " . substr ( $response, 4 ); + return false; + } + if ( $status!=SEARCHD_OK ) + { + $this->_error = "unknown status code '$status'"; + return false; + } + + // check version + if ( $ver<$client_ver ) + { + $this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work", + $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff ); + } + + return $response; + } + + ///////////////////////////////////////////////////////////////////////////// + // searching + ///////////////////////////////////////////////////////////////////////////// + + /// set offset and count into result set, + /// and optionally set max-matches and cutoff limits + function SetLimits ( $offset, $limit, $max=0, $cutoff=0 ) + { + assert ( is_int($offset) ); + assert ( is_int($limit) ); + assert ( $offset>=0 ); + assert ( $limit>0 ); + assert ( $max>=0 ); + $this->_offset = $offset; + $this->_limit = $limit; + if ( $max>0 ) + $this->_maxmatches = $max; + if ( $cutoff>0 ) + $this->_cutoff = $cutoff; + } + + /// set maximum query time, in milliseconds, per-index + /// integer, 0 means "do not limit" + function SetMaxQueryTime ( $max ) + { + assert ( is_int($max) ); + assert ( $max>=0 ); + $this->_maxquerytime = $max; + } + + /// set matching mode + function SetMatchMode ( $mode ) + { + trigger_error ( 'DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API', E_USER_DEPRECATED ); + assert ( $mode==SPH_MATCH_ALL + || $mode==SPH_MATCH_ANY + || $mode==SPH_MATCH_PHRASE + || $mode==SPH_MATCH_BOOLEAN + || $mode==SPH_MATCH_EXTENDED + || $mode==SPH_MATCH_FULLSCAN + || $mode==SPH_MATCH_EXTENDED2 ); + $this->_mode = $mode; + } + + /// set ranking mode + function SetRankingMode ( $ranker, $rankexpr="" ) + { + assert ( $ranker===0 || $ranker>=1 && $ranker_ranker = $ranker; + $this->_rankexpr = $rankexpr; + } + + /// set matches sorting mode + function SetSortMode ( $mode, $sortby="" ) + { + assert ( + $mode==SPH_SORT_RELEVANCE || + $mode==SPH_SORT_ATTR_DESC || + $mode==SPH_SORT_ATTR_ASC || + $mode==SPH_SORT_TIME_SEGMENTS || + $mode==SPH_SORT_EXTENDED || + $mode==SPH_SORT_EXPR ); + assert ( is_string($sortby) ); + assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 ); + + $this->_sort = $mode; + $this->_sortby = $sortby; + } + + /// bind per-field weights by order + /// DEPRECATED; use SetFieldWeights() instead + function SetWeights ( $weights ) + { + die("This method is now deprecated; please use SetFieldWeights instead"); + } + + /// bind per-field weights by name + function SetFieldWeights ( $weights ) + { + assert ( is_array($weights) ); + foreach ( $weights as $name=>$weight ) + { + assert ( is_string($name) ); + assert ( is_int($weight) ); + } + $this->_fieldweights = $weights; + } + + /// bind per-index weights by name + function SetIndexWeights ( $weights ) + { + assert ( is_array($weights) ); + foreach ( $weights as $index=>$weight ) + { + assert ( is_string($index) ); + assert ( is_int($weight) ); + } + $this->_indexweights = $weights; + } + + /// set IDs range to match + /// only match records if document ID is beetwen $min and $max (inclusive) + function SetIDRange ( $min, $max ) + { + assert ( is_numeric($min) ); + assert ( is_numeric($max) ); + assert ( $min<=$max ); + $this->_min_id = $min; + $this->_max_id = $max; + } + + /// set values set filter + /// only match records where $attribute value is in given set + function SetFilter ( $attribute, $values, $exclude=false ) + { + assert ( is_string($attribute) ); + assert ( is_array($values) ); + assert ( count($values) ); + + if ( is_array($values) && count($values) ) + { + foreach ( $values as $value ) + assert ( is_numeric($value) ); + + $this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values ); + } + } + + /// set string filter + /// only match records where $attribute value is equal + function SetFilterString ( $attribute, $value, $exclude=false ) + { + assert ( is_string($attribute) ); + assert ( is_string($value) ); + $this->_filters[] = array ( "type"=>SPH_FILTER_STRING, "attr"=>$attribute, "exclude"=>$exclude, "value"=>$value ); + } + + /// set range filter + /// only match records if $attribute value is beetwen $min and $max (inclusive) + function SetFilterRange ( $attribute, $min, $max, $exclude=false ) + { + assert ( is_string($attribute) ); + assert ( is_numeric($min) ); + assert ( is_numeric($max) ); + assert ( $min<=$max ); + + $this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); + } + + /// set float range filter + /// only match records if $attribute value is beetwen $min and $max (inclusive) + function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false ) + { + assert ( is_string($attribute) ); + assert ( is_float($min) ); + assert ( is_float($max) ); + assert ( $min<=$max ); + + $this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max ); + } + + /// setup anchor point for geosphere distance calculations + /// required to use @geodist in filters and sorting + /// latitude and longitude must be in radians + function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long ) + { + assert ( is_string($attrlat) ); + assert ( is_string($attrlong) ); + assert ( is_float($lat) ); + assert ( is_float($long) ); + + $this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long ); + } + + /// set grouping attribute and function + function SetGroupBy ( $attribute, $func, $groupsort="@group desc" ) + { + assert ( is_string($attribute) ); + assert ( is_string($groupsort) ); + assert ( $func==SPH_GROUPBY_DAY + || $func==SPH_GROUPBY_WEEK + || $func==SPH_GROUPBY_MONTH + || $func==SPH_GROUPBY_YEAR + || $func==SPH_GROUPBY_ATTR + || $func==SPH_GROUPBY_ATTRPAIR ); + + $this->_groupby = $attribute; + $this->_groupfunc = $func; + $this->_groupsort = $groupsort; + } + + /// set count-distinct attribute for group-by queries + function SetGroupDistinct ( $attribute ) + { + assert ( is_string($attribute) ); + $this->_groupdistinct = $attribute; + } + + /// set distributed retries count and delay + function SetRetries ( $count, $delay=0 ) + { + assert ( is_int($count) && $count>=0 ); + assert ( is_int($delay) && $delay>=0 ); + $this->_retrycount = $count; + $this->_retrydelay = $delay; + } + + /// set result set format (hash or array; hash by default) + /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs + function SetArrayResult ( $arrayresult ) + { + assert ( is_bool($arrayresult) ); + $this->_arrayresult = $arrayresult; + } + + /// set attribute values override + /// there can be only one override per attribute + /// $values must be a hash that maps document IDs to attribute values + function SetOverride ( $attrname, $attrtype, $values ) + { + trigger_error('DEPRECATED: Do not call this method. Use SphinxQL REMAP() function instead.', E_USER_DEPRECATED); + assert ( is_string ( $attrname ) ); + assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) ); + assert ( is_array ( $values ) ); + + $this->_overrides[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values ); + } + + /// set select-list (attributes or expressions), SQL-like syntax + function SetSelect ( $select ) + { + assert ( is_string ( $select ) ); + $this->_select = $select; + } + + function SetQueryFlag ( $flag_name, $flag_value ) + { + $known_names = array ( "reverse_scan", "sort_method", "max_predicted_time", "boolean_simplify", "idf", "global_idf" ); + $flags = array ( + "reverse_scan" => array ( 0, 1 ), + "sort_method" => array ( "pq", "kbuffer" ), + "max_predicted_time" => array ( 0 ), + "boolean_simplify" => array ( true, false ), + "idf" => array ("normalized", "plain", "tfidf_normalized", "tfidf_unnormalized" ), + "global_idf" => array ( true, false ), + ); + + assert ( isset ( $flag_name, $known_names ) ); + assert ( in_array( $flag_value, $flags[$flag_name], true ) || ( $flag_name=="max_predicted_time" && is_int ( $flag_value ) && $flag_value>=0 ) ); + + if ( $flag_name=="reverse_scan" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 0, $flag_value==1 ); + if ( $flag_name=="sort_method" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 1, $flag_value=="kbuffer" ); + if ( $flag_name=="max_predicted_time" ) + { + $this->_query_flags = sphSetBit ( $this->_query_flags, 2, $flag_value>0 ); + $this->_predictedtime = (int)$flag_value; + } + if ( $flag_name=="boolean_simplify" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 3, $flag_value ); + if ( $flag_name=="idf" && ( $flag_value=="normalized" || $flag_value=="plain" ) ) $this->_query_flags = sphSetBit ( $this->_query_flags, 4, $flag_value=="plain" ); + if ( $flag_name=="global_idf" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 5, $flag_value ); + if ( $flag_name=="idf" && ( $flag_value=="tfidf_normalized" || $flag_value=="tfidf_unnormalized" ) ) $this->_query_flags = sphSetBit ( $this->_query_flags, 6, $flag_value=="tfidf_normalized" ); + } + + /// set outer order by parameters + function SetOuterSelect ( $orderby, $offset, $limit ) + { + assert ( is_string($orderby) ); + assert ( is_int($offset) ); + assert ( is_int($limit) ); + assert ( $offset>=0 ); + assert ( $limit>0 ); + + $this->_outerorderby = $orderby; + $this->_outeroffset = $offset; + $this->_outerlimit = $limit; + $this->_hasouter = true; + } + + + ////////////////////////////////////////////////////////////////////////////// + + /// clear all filters (for multi-queries) + function ResetFilters () + { + $this->_filters = array(); + $this->_anchor = array(); + } + + /// clear groupby settings (for multi-queries) + function ResetGroupBy () + { + $this->_groupby = ""; + $this->_groupfunc = SPH_GROUPBY_DAY; + $this->_groupsort = "@group desc"; + $this->_groupdistinct= ""; + } + + /// clear all attribute value overrides (for multi-queries) + function ResetOverrides () + { + $this->_overrides = array (); + } + + function ResetQueryFlag () + { + $this->_query_flags = sphSetBit ( 0, 6, true ); // default idf=tfidf_normalized + $this->_predictedtime = 0; + } + + function ResetOuterSelect () + { + $this->_outerorderby = ''; + $this->_outeroffset = 0; + $this->_outerlimit = 0; + $this->_hasouter = false; + } + + ////////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, run given search query through given indexes, + /// and return the search results + function Query ( $query, $index="*", $comment="" ) + { + assert ( empty($this->_reqs) ); + + $this->AddQuery ( $query, $index, $comment ); + $results = $this->RunQueries (); + $this->_reqs = array (); // just in case it failed too early + + if ( !is_array($results) ) + return false; // probably network error; error message should be already filled + + $this->_error = $results[0]["error"]; + $this->_warning = $results[0]["warning"]; + if ( $results[0]["status"]==SEARCHD_ERROR ) + return false; + else + return $results[0]; + } + + /// helper to pack floats in network byte order + function _PackFloat ( $f ) + { + $t1 = pack ( "f", $f ); // machine order + list(,$t2) = unpack ( "L*", $t1 ); // int in machine order + return pack ( "N", $t2 ); + } + + /// add query to multi-query batch + /// returns index into results array from RunQueries() call + function AddQuery ( $query, $index="*", $comment="" ) + { + // mbstring workaround + $this->_MBPush (); + + // build request + $req = pack ( "NNNNN", $this->_query_flags, $this->_offset, $this->_limit, $this->_mode, $this->_ranker ); + if ( $this->_ranker==SPH_RANK_EXPR ) + $req .= pack ( "N", strlen($this->_rankexpr) ) . $this->_rankexpr; + $req .= pack ( "N", $this->_sort ); // (deprecated) sort mode + $req .= pack ( "N", strlen($this->_sortby) ) . $this->_sortby; + $req .= pack ( "N", strlen($query) ) . $query; // query itself + $req .= pack ( "N", count($this->_weights) ); // weights + foreach ( $this->_weights as $weight ) + $req .= pack ( "N", (int)$weight ); + $req .= pack ( "N", strlen($index) ) . $index; // indexes + $req .= pack ( "N", 1 ); // id64 range marker + $req .= sphPackU64 ( $this->_min_id ) . sphPackU64 ( $this->_max_id ); // id64 range + + // filters + $req .= pack ( "N", count($this->_filters) ); + foreach ( $this->_filters as $filter ) + { + $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"]; + $req .= pack ( "N", $filter["type"] ); + switch ( $filter["type"] ) + { + case SPH_FILTER_VALUES: + $req .= pack ( "N", count($filter["values"]) ); + foreach ( $filter["values"] as $value ) + $req .= sphPackI64 ( $value ); + break; + + case SPH_FILTER_RANGE: + $req .= sphPackI64 ( $filter["min"] ) . sphPackI64 ( $filter["max"] ); + break; + + case SPH_FILTER_FLOATRANGE: + $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] ); + break; + + case SPH_FILTER_STRING: + $req .= pack ( "N", strlen($filter["value"]) ) . $filter["value"]; + break; + + default: + assert ( 0 && "internal error: unhandled filter type" ); + } + $req .= pack ( "N", $filter["exclude"] ); + } + + // group-by clause, max-matches count, group-sort clause, cutoff count + $req .= pack ( "NN", $this->_groupfunc, strlen($this->_groupby) ) . $this->_groupby; + $req .= pack ( "N", $this->_maxmatches ); + $req .= pack ( "N", strlen($this->_groupsort) ) . $this->_groupsort; + $req .= pack ( "NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay ); + $req .= pack ( "N", strlen($this->_groupdistinct) ) . $this->_groupdistinct; + + // anchor point + if ( empty($this->_anchor) ) + { + $req .= pack ( "N", 0 ); + } else + { + $a =& $this->_anchor; + $req .= pack ( "N", 1 ); + $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"]; + $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"]; + $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] ); + } + + // per-index weights + $req .= pack ( "N", count($this->_indexweights) ); + foreach ( $this->_indexweights as $idx=>$weight ) + $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight ); + + // max query time + $req .= pack ( "N", $this->_maxquerytime ); + + // per-field weights + $req .= pack ( "N", count($this->_fieldweights) ); + foreach ( $this->_fieldweights as $field=>$weight ) + $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight ); + + // comment + $req .= pack ( "N", strlen($comment) ) . $comment; + + // attribute overrides + $req .= pack ( "N", count($this->_overrides) ); + foreach ( $this->_overrides as $key => $entry ) + { + $req .= pack ( "N", strlen($entry["attr"]) ) . $entry["attr"]; + $req .= pack ( "NN", $entry["type"], count($entry["values"]) ); + foreach ( $entry["values"] as $id=>$val ) + { + assert ( is_numeric($id) ); + assert ( is_numeric($val) ); + + $req .= sphPackU64 ( $id ); + switch ( $entry["type"] ) + { + case SPH_ATTR_FLOAT: $req .= $this->_PackFloat ( $val ); break; + case SPH_ATTR_BIGINT: $req .= sphPackI64 ( $val ); break; + default: $req .= pack ( "N", $val ); break; + } + } + } + + // select-list + $req .= pack ( "N", strlen($this->_select) ) . $this->_select; + + // max_predicted_time + if ( $this->_predictedtime>0 ) + $req .= pack ( "N", (int)$this->_predictedtime ); + + $req .= pack ( "N", strlen($this->_outerorderby) ) . $this->_outerorderby; + $req .= pack ( "NN", $this->_outeroffset, $this->_outerlimit ); + if ( $this->_hasouter ) + $req .= pack ( "N", 1 ); + else + $req .= pack ( "N", 0 ); + + // mbstring workaround + $this->_MBPop (); + + // store request to requests array + $this->_reqs[] = $req; + return count($this->_reqs)-1; + } + + /// connect to searchd, run queries batch, and return an array of result sets + function RunQueries () + { + if ( empty($this->_reqs) ) + { + $this->_error = "no queries defined, issue AddQuery() first"; + return false; + } + + // mbstring workaround + $this->_MBPush (); + + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop (); + return false; + } + + // send query, get response + $nreqs = count($this->_reqs); + $req = join ( "", $this->_reqs ); + $len = 8+strlen($req); + $req = pack ( "nnNNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, 0, $nreqs ) . $req; // add header + + if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || + !( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH ) ) ) + { + $this->_MBPop (); + return false; + } + + // query sent ok; we can reset reqs now + $this->_reqs = array (); + + // parse and return response + return $this->_ParseSearchResponse ( $response, $nreqs ); + } + + /// parse and return search query (or queries) response + function _ParseSearchResponse ( $response, $nreqs ) + { + $p = 0; // current position + $max = strlen($response); // max position for checks, to protect against broken responses + + $results = array (); + for ( $ires=0; $ires<$nreqs && $p<$max; $ires++ ) + { + $results[] = array(); + $result =& $results[$ires]; + + $result["error"] = ""; + $result["warning"] = ""; + + // extract status + list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $result["status"] = $status; + if ( $status!=SEARCHD_OK ) + { + list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $message = substr ( $response, $p, $len ); $p += $len; + + if ( $status==SEARCHD_WARNING ) + { + $result["warning"] = $message; + } else + { + $result["error"] = $message; + continue; + } + } + + // read schema + $fields = array (); + $attrs = array (); + + list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + while ( $nfields-->0 && $p<$max ) + { + list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $fields[] = substr ( $response, $p, $len ); $p += $len; + } + $result["fields"] = $fields; + + list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + while ( $nattrs-->0 && $p<$max ) + { + list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $attr = substr ( $response, $p, $len ); $p += $len; + list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $attrs[$attr] = $type; + } + $result["attrs"] = $attrs; + + // read match count + list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + + // read matches + $idx = -1; + while ( $count-->0 && $p<$max ) + { + // index into result array + $idx++; + + // parse document id and weight + if ( $id64 ) + { + $doc = sphUnpackU64 ( substr ( $response, $p, 8 ) ); $p += 8; + list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + } + else + { + list ( $doc, $weight ) = array_values ( unpack ( "N*N*", + substr ( $response, $p, 8 ) ) ); + $p += 8; + $doc = sphFixUint($doc); + } + $weight = sprintf ( "%u", $weight ); + + // create match entry + if ( $this->_arrayresult ) + $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight ); + else + $result["matches"][$doc]["weight"] = $weight; + + // parse and create attributes + $attrvals = array (); + foreach ( $attrs as $attr=>$type ) + { + // handle 64bit ints + if ( $type==SPH_ATTR_BIGINT ) + { + $attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8; + continue; + } + + // handle floats + if ( $type==SPH_ATTR_FLOAT ) + { + list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + list(,$fval) = unpack ( "f*", pack ( "L", $uval ) ); + $attrvals[$attr] = $fval; + continue; + } + + // handle everything else as unsigned ints + list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + if ( $type==SPH_ATTR_MULTI ) + { + $attrvals[$attr] = array (); + $nvalues = $val; + while ( $nvalues-->0 && $p<$max ) + { + list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $attrvals[$attr][] = sphFixUint($val); + } + } else if ( $type==SPH_ATTR_MULTI64 ) + { + $attrvals[$attr] = array (); + $nvalues = $val; + while ( $nvalues>0 && $p<$max ) + { + $attrvals[$attr][] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8; + $nvalues -= 2; + } + } else if ( $type==SPH_ATTR_STRING ) + { + $attrvals[$attr] = substr ( $response, $p, $val ); + $p += $val; + } else if ( $type==SPH_ATTR_FACTORS ) + { + $attrvals[$attr] = substr ( $response, $p, $val-4 ); + $p += $val-4; + } else + { + $attrvals[$attr] = sphFixUint($val); + } + } + + if ( $this->_arrayresult ) + $result["matches"][$idx]["attrs"] = $attrvals; + else + $result["matches"][$doc]["attrs"] = $attrvals; + } + + list ( $total, $total_found, $msecs, $words ) = + array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) ); + $result["total"] = sprintf ( "%u", $total ); + $result["total_found"] = sprintf ( "%u", $total_found ); + $result["time"] = sprintf ( "%.3f", $msecs/1000 ); + $p += 16; + + while ( $words-->0 && $p<$max ) + { + list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $word = substr ( $response, $p, $len ); $p += $len; + list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; + $result["words"][$word] = array ( + "docs"=>sprintf ( "%u", $docs ), + "hits"=>sprintf ( "%u", $hits ) ); + } + } + + $this->_MBPop (); + return $results; + } + + ///////////////////////////////////////////////////////////////////////////// + // excerpts generation + ///////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, and generate exceprts (snippets) + /// of given documents for given query. returns false on failure, + /// an array of snippets on success + function BuildExcerpts ( $docs, $index, $words, $opts=array() ) + { + assert ( is_array($docs) ); + assert ( is_string($index) ); + assert ( is_string($words) ); + assert ( is_array($opts) ); + + $this->_MBPush (); + + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop(); + return false; + } + + ///////////////// + // fixup options + ///////////////// + + if ( !isset($opts["before_match"]) ) $opts["before_match"] = ""; + if ( !isset($opts["after_match"]) ) $opts["after_match"] = ""; + if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... "; + if ( !isset($opts["limit"]) ) $opts["limit"] = 256; + if ( !isset($opts["limit_passages"]) ) $opts["limit_passages"] = 0; + if ( !isset($opts["limit_words"]) ) $opts["limit_words"] = 0; + if ( !isset($opts["around"]) ) $opts["around"] = 5; + if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false; + if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false; + if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false; + if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false; + if ( !isset($opts["query_mode"]) ) $opts["query_mode"] = false; + if ( !isset($opts["force_all_words"]) ) $opts["force_all_words"] = false; + if ( !isset($opts["start_passage_id"]) ) $opts["start_passage_id"] = 1; + if ( !isset($opts["load_files"]) ) $opts["load_files"] = false; + if ( !isset($opts["html_strip_mode"]) ) $opts["html_strip_mode"] = "index"; + if ( !isset($opts["allow_empty"]) ) $opts["allow_empty"] = false; + if ( !isset($opts["passage_boundary"]) ) $opts["passage_boundary"] = "none"; + if ( !isset($opts["emit_zones"]) ) $opts["emit_zones"] = false; + if ( !isset($opts["load_files_scattered"]) ) $opts["load_files_scattered"] = false; + + + ///////////////// + // build request + ///////////////// + + // v.1.2 req + $flags = 1; // remove spaces + if ( $opts["exact_phrase"] ) $flags |= 2; + if ( $opts["single_passage"] ) $flags |= 4; + if ( $opts["use_boundaries"] ) $flags |= 8; + if ( $opts["weight_order"] ) $flags |= 16; + if ( $opts["query_mode"] ) $flags |= 32; + if ( $opts["force_all_words"] ) $flags |= 64; + if ( $opts["load_files"] ) $flags |= 128; + if ( $opts["allow_empty"] ) $flags |= 256; + if ( $opts["emit_zones"] ) $flags |= 512; + if ( $opts["load_files_scattered"] ) $flags |= 1024; + $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags + $req .= pack ( "N", strlen($index) ) . $index; // req index + $req .= pack ( "N", strlen($words) ) . $words; // req words + + // options + $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"]; + $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"]; + $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"]; + $req .= pack ( "NN", (int)$opts["limit"], (int)$opts["around"] ); + $req .= pack ( "NNN", (int)$opts["limit_passages"], (int)$opts["limit_words"], (int)$opts["start_passage_id"] ); // v.1.2 + $req .= pack ( "N", strlen($opts["html_strip_mode"]) ) . $opts["html_strip_mode"]; + $req .= pack ( "N", strlen($opts["passage_boundary"]) ) . $opts["passage_boundary"]; + + // documents + $req .= pack ( "N", count($docs) ); + foreach ( $docs as $doc ) + { + assert ( is_string($doc) ); + $req .= pack ( "N", strlen($doc) ) . $doc; + } + + //////////////////////////// + // send query, get response + //////////////////////////// + + $len = strlen($req); + $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len ) . $req; // add header + if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || + !( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT ) ) ) + { + $this->_MBPop (); + return false; + } + + ////////////////// + // parse response + ////////////////// + + $pos = 0; + $res = array (); + $rlen = strlen($response); + for ( $i=0; $i $rlen ) + { + $this->_error = "incomplete reply"; + $this->_MBPop (); + return false; + } + $res[] = $len ? substr ( $response, $pos, $len ) : ""; + $pos += $len; + } + + $this->_MBPop (); + return $res; + } + + + ///////////////////////////////////////////////////////////////////////////// + // keyword generation + ///////////////////////////////////////////////////////////////////////////// + + /// connect to searchd server, and generate keyword list for a given query + /// returns false on failure, + /// an array of words on success + function BuildKeywords ( $query, $index, $hits ) + { + assert ( is_string($query) ); + assert ( is_string($index) ); + assert ( is_bool($hits) ); + + $this->_MBPush (); + + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop(); + return false; + } + + ///////////////// + // build request + ///////////////// + + // v.1.0 req + $req = pack ( "N", strlen($query) ) . $query; // req query + $req .= pack ( "N", strlen($index) ) . $index; // req index + $req .= pack ( "N", (int)$hits ); + + //////////////////////////// + // send query, get response + //////////////////////////// + + $len = strlen($req); + $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len ) . $req; // add header + if ( !( $this->_Send ( $fp, $req, $len+8 ) ) || + !( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS ) ) ) + { + $this->_MBPop (); + return false; + } + + ////////////////// + // parse response + ////////////////// + + $pos = 0; + $res = array (); + $rlen = strlen($response); + list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) ); + $pos += 4; + for ( $i=0; $i<$nwords; $i++ ) + { + list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; + $tokenized = $len ? substr ( $response, $pos, $len ) : ""; + $pos += $len; + + list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4; + $normalized = $len ? substr ( $response, $pos, $len ) : ""; + $pos += $len; + + $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized ); + + if ( $hits ) + { + list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) ); + $pos += 8; + $res [$i]["docs"] = $ndocs; + $res [$i]["hits"] = $nhits; + } + + if ( $pos > $rlen ) + { + $this->_error = "incomplete reply"; + $this->_MBPop (); + return false; + } + } + + $this->_MBPop (); + return $res; + } + + function EscapeString ( $string ) + { + $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', '<' ); + $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=', '\<' ); + + return str_replace ( $from, $to, $string ); + } + + ///////////////////////////////////////////////////////////////////////////// + // attribute updates + ///////////////////////////////////////////////////////////////////////////// + + /// batch update given attributes in given rows in given indexes + /// returns amount of updated documents (0 or more) on success, or -1 on failure + function UpdateAttributes ( $index, $attrs, $values, $mva=false, $ignorenonexistent=false ) + { + // verify everything + assert ( is_string($index) ); + assert ( is_bool($mva) ); + assert ( is_bool($ignorenonexistent) ); + + assert ( is_array($attrs) ); + foreach ( $attrs as $attr ) + assert ( is_string($attr) ); + + assert ( is_array($values) ); + foreach ( $values as $id=>$entry ) + { + assert ( is_numeric($id) ); + assert ( is_array($entry) ); + assert ( count($entry)==count($attrs) ); + foreach ( $entry as $v ) + { + if ( $mva ) + { + assert ( is_array($v) ); + foreach ( $v as $vv ) + assert ( is_int($vv) ); + } else + assert ( is_int($v) ); + } + } + + // build request + $this->_MBPush (); + $req = pack ( "N", strlen($index) ) . $index; + + $req .= pack ( "N", count($attrs) ); + $req .= pack ( "N", $ignorenonexistent ? 1 : 0 ); + foreach ( $attrs as $attr ) + { + $req .= pack ( "N", strlen($attr) ) . $attr; + $req .= pack ( "N", $mva ? 1 : 0 ); + } + + $req .= pack ( "N", count($values) ); + foreach ( $values as $id=>$entry ) + { + $req .= sphPackU64 ( $id ); + foreach ( $entry as $v ) + { + $req .= pack ( "N", $mva ? count($v) : $v ); + if ( $mva ) + foreach ( $v as $vv ) + $req .= pack ( "N", $vv ); + } + } + + // connect, send query, get response + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop (); + return -1; + } + + $len = strlen($req); + $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header + if ( !$this->_Send ( $fp, $req, $len+8 ) ) + { + $this->_MBPop (); + return -1; + } + + if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) )) + { + $this->_MBPop (); + return -1; + } + + // parse response + list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) ); + $this->_MBPop (); + return $updated; + } + + ///////////////////////////////////////////////////////////////////////////// + // persistent connections + ///////////////////////////////////////////////////////////////////////////// + + function Open() + { + if ( $this->_socket !== false ) + { + $this->_error = 'already connected'; + return false; + } + if ( !$fp = $this->_Connect() ) + return false; + + // command, command version = 0, body length = 4, body = 1 + $req = pack ( "nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1 ); + if ( !$this->_Send ( $fp, $req, 12 ) ) + return false; + + $this->_socket = $fp; + return true; + } + + function Close() + { + if ( $this->_socket === false ) + { + $this->_error = 'not connected'; + return false; + } + + fclose ( $this->_socket ); + $this->_socket = false; + + return true; + } + + ////////////////////////////////////////////////////////////////////////// + // status + ////////////////////////////////////////////////////////////////////////// + + function Status ($session=false) + { + assert ( is_bool($session) ); + + $this->_MBPush (); + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop(); + return false; + } + + $req = pack ( "nnNN", SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, $session?0:1 ); // len=4, body=1 + if ( !( $this->_Send ( $fp, $req, 12 ) ) || + !( $response = $this->_GetResponse ( $fp, VER_COMMAND_STATUS ) ) ) + { + $this->_MBPop (); + return false; + } + + $res = substr ( $response, 4 ); // just ignore length, error handling, etc + $p = 0; + list ( $rows, $cols ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8; + + $res = array(); + for ( $i=0; $i<$rows; $i++ ) + for ( $j=0; $j<$cols; $j++ ) + { + list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4; + $res[$i][] = substr ( $response, $p, $len ); $p += $len; + } + + $this->_MBPop (); + return $res; + } + + ////////////////////////////////////////////////////////////////////////// + // flush + ////////////////////////////////////////////////////////////////////////// + + function FlushAttributes () + { + $this->_MBPush (); + if (!( $fp = $this->_Connect() )) + { + $this->_MBPop(); + return -1; + } + + $req = pack ( "nnN", SEARCHD_COMMAND_FLUSHATTRS, VER_COMMAND_FLUSHATTRS, 0 ); // len=0 + if ( !( $this->_Send ( $fp, $req, 8 ) ) || + !( $response = $this->_GetResponse ( $fp, VER_COMMAND_FLUSHATTRS ) ) ) + { + $this->_MBPop (); + return -1; + } + + $tag = -1; + if ( strlen($response)==4 ) + list(,$tag) = unpack ( "N*", $response ); + else + $this->_error = "unexpected response length"; + + $this->_MBPop (); + return $tag; + } +} + +// +// $Id: sphinxapi.php 4885 2015-01-20 07:02:07Z deogar $ +// diff --git a/library/WsScore/Entreprise/v0.8/Service.php b/library/WsScore/Entreprise/v0.8/Service.php index bebaf76a..4b42557d 100644 --- a/library/WsScore/Entreprise/v0.8/Service.php +++ b/library/WsScore/Entreprise/v0.8/Service.php @@ -196,6 +196,7 @@ class Entreprise extends Scores_Ws_Server $identite->dir2LieuNaiss = prepareString($entrep['dir2LieuNaiss']); // Ajouté le 4 08 2009 $identite->Rivoli = $entrep['Rivoli']; + $identite->InfosIris = new stdClass(); $identite->InfosIris->codIris = $entrep['InfosIris']['codIris']; $identite->InfosIris->codComIris = $entrep['InfosIris']['codComIris']; $identite->InfosIris->libIris = prepareString($entrep['InfosIris']['libIris']); @@ -203,6 +204,7 @@ class Entreprise extends Scores_Ws_Server $identite->InfosIris->evoIris = $entrep['InfosIris']['evoIris']; $identite->InfosIris->trIris = $entrep['InfosIris']['trIris']; $identite->InfosIris->grdQuartier = $entrep['InfosIris']['grdQuartier']; + $identite->NatureActivite = $entrep['NatureActivite']; // Nature de l'activité $identite->OrigineCreation = $entrep['OrigineCreation']; // Origine de la création $identite->TypeExploitation = $entrep['TypeExploitation']; @@ -210,6 +212,8 @@ class Entreprise extends Scores_Ws_Server $identite->Saisonnalite = $entrep['Saisonnalite']; // P=Activité permanente / S=Activité saisonnière $identite->SurfaceMagasin = $entrep['ACTISURF']*1; // 0=N/D, 1=inf. à 300m2,2=300 à 400m2, 3=400 à 2500m2, 4=sup. à 2500m2 $identite->SituationJuridique = $entrep['SituationJuridique']; + + $identite->Bilan = new stdClass(); $identite->Bilan->Millesime = $entrep['bilanAnnee']; $identite->Bilan->Cloture = $entrep['bilanDate']; //@todo : date $identite->Bilan->Duree = $entrep['bilanMois']; @@ -3491,7 +3495,8 @@ class Entreprise extends Scores_Ws_Server if (strlen($siret) == 14) $nic = substr($siret,9,5); elseif (strlen($siret) == 9) $nic = ''; - $iInsee = new MInsee(); + $iDb = new WDB(); + $iInsee = new MInsee($iDb); $rep = $iInsee->getEtablissements($siren, $nic, $deb, $nbRep, $maxRep, $dep, $actif, $siege); if ( count($rep['reponses'])==0 && $dep>0 ) { @@ -3571,7 +3576,6 @@ class Entreprise extends Scores_Ws_Server } else { - $iDb = new WDB(); $iDb->insert('jo.siren_inexistants', array( 'siren' => $siren, 'nic' => $nic, diff --git a/library/WsScore/Entreprise/v0.9/Service.php b/library/WsScore/Entreprise/v0.9/Service.php index 1533486e..5e6d6ed1 100644 --- a/library/WsScore/Entreprise/v0.9/Service.php +++ b/library/WsScore/Entreprise/v0.9/Service.php @@ -205,6 +205,7 @@ class Entreprise extends Scores_Ws_Server $identite->dir2LieuNaiss = prepareString($entrep['dir2LieuNaiss']); $identite->Rivoli = $entrep['Rivoli']; + $identite->InfosIris = new stdClass(); $identite->InfosIris->codIris = $entrep['InfosIris']['codIris']; $identite->InfosIris->codComIris = $entrep['InfosIris']['codComIris']; $identite->InfosIris->libIris = prepareString($entrep['InfosIris']['libIris']); @@ -212,6 +213,7 @@ class Entreprise extends Scores_Ws_Server $identite->InfosIris->evoIris = $entrep['InfosIris']['evoIris']; $identite->InfosIris->trIris = $entrep['InfosIris']['trIris']; $identite->InfosIris->grdQuartier = $entrep['InfosIris']['grdQuartier']; + $identite->NatureActivite = $entrep['NatureActivite']; // Nature de l'activité $identite->OrigineCreation = $entrep['OrigineCreation']; // Origine de la création $identite->TypeExploitation = $entrep['TypeExploitation']; @@ -219,6 +221,8 @@ class Entreprise extends Scores_Ws_Server $identite->Saisonnalite = $entrep['Saisonnalite']; // P=Activité permanente / S=Activité saisonnière $identite->SurfaceMagasin = $entrep['ACTISURF']*1; // 0=N/D, 1=inf. à 300m2,2=300 à 400m2, 3=400 à 2500m2, 4=sup. à 2500m2 $identite->SituationJuridique = $entrep['SituationJuridique']; + + $identite->Bilan = new stdClass(); $identite->Bilan->Millesime = $entrep['bilanAnnee']; $identite->Bilan->Cloture = $entrep['bilanDate']; //@todo : date $identite->Bilan->Duree = $entrep['bilanMois']; @@ -246,7 +250,7 @@ class Entreprise extends Scores_Ws_Server $autreSiren->type = $entrep['AutreSiren']['listeSiren']['type']; $tabAutreSiren[] = $autreSiren; } - $identite->AutreSiren = $tabAutreSiren; + $identite->AutreSiren = $tabAutreSiren; $tabAutreSiret = array(); if (count($entrep['AutreSiret'])) { @@ -274,7 +278,7 @@ class Entreprise extends Scores_Ws_Server $tabAutreSiret[] = $autreSiret; } } - $identite->AutreSiret = $tabAutreSiret; + $identite->AutreSiret = $tabAutreSiret; $identite->DateMajINSEE = $entrep['DateMajINSEE']; //@todo : date $identite->DateMajRCS = $entrep['DateMajRCS']; //@todo : date diff --git a/library/WsScore/Gestion/v0.4/Service.php b/library/WsScore/Gestion/v0.4/Service.php index 0cd120f0..62dd5ae9 100644 --- a/library/WsScore/Gestion/v0.4/Service.php +++ b/library/WsScore/Gestion/v0.4/Service.php @@ -40,6 +40,7 @@ class Gestion extends Scores_Ws_Server 'login' => $login, 'authenticate' => 'OK', 'ip' => $ip, + 'dateInsert' => date('YmdHis'), )); } catch (Zend_Db_Exception $e) {} @@ -328,6 +329,7 @@ class Gestion extends Scores_Ws_Server $sql = $serviceM->select() ->from($serviceM, array('id', 'Code', 'Label', 'Editable', 'Active')) ->where('Deleted=?', 0) + ->where('Active=?', 1) ->where('IdClient=?', $id); $result = $serviceM->fetchAll($sql); $services = array(); @@ -545,7 +547,7 @@ class Gestion extends Scores_Ws_Server } if ( count($dataToUpdate) > 0 ) { - $dataToUpdate['DateUpdate'] = date('Y-m-d H:i:s'); + $dataToUpdate['DateUpdate'] = date('YmdHis'); try { $serviceM->update($dataToUpdate, 'id='.$id); return true; diff --git a/library/WsScore/Interne/v0.3/Service.php b/library/WsScore/Interne/v0.3/Service.php index a2ba9bf0..125136b6 100644 --- a/library/WsScore/Interne/v0.3/Service.php +++ b/library/WsScore/Interne/v0.3/Service.php @@ -2370,7 +2370,7 @@ class Interne extends Scores_Ws_Server if (SPHINX_HISTO_VERSION == 1){ require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; } elseif (SPHINX_HISTO_VERSION == 2){ - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; } $cl = new SphinxClient(); diff --git a/library/WsScore/Interne/v0.4/Service.php b/library/WsScore/Interne/v0.4/Service.php index 2c7dd60b..d536b490 100644 --- a/library/WsScore/Interne/v0.4/Service.php +++ b/library/WsScore/Interne/v0.4/Service.php @@ -2328,7 +2328,7 @@ class Interne extends Scores_Ws_Server if (SPHINX_HISTO_VERSION == 1){ require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; } elseif (SPHINX_HISTO_VERSION == 2){ - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; } $cl = new SphinxClient(); diff --git a/library/WsScore/Interne/v0.5/Service.php b/library/WsScore/Interne/v0.5/Service.php index 4df93840..f4c23212 100644 --- a/library/WsScore/Interne/v0.5/Service.php +++ b/library/WsScore/Interne/v0.5/Service.php @@ -1252,7 +1252,7 @@ class Interne extends Scores_Ws_Server if (SPHINX_HISTO_VERSION == 1){ require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; } elseif (SPHINX_HISTO_VERSION == 2){ - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; } $cl = new SphinxClient(); diff --git a/library/WsScore/Interne/v0.6/Service.php b/library/WsScore/Interne/v0.6/Service.php index e0330314..b6f6336d 100644 --- a/library/WsScore/Interne/v0.6/Service.php +++ b/library/WsScore/Interne/v0.6/Service.php @@ -1190,7 +1190,7 @@ class Interne extends Scores_Ws_Server if (SPHINX_HISTO_VERSION == 1){ require_once 'Vendors/sphinxapi/sphinxapi-0.9.9.php'; } elseif (SPHINX_HISTO_VERSION == 2){ - require_once 'Vendors/sphinxapi/sphinxapi-2.1.5.php'; + require_once 'Vendors/sphinxapi/sphinxapi-2.2.9.php'; } $cl = new SphinxClient(); @@ -1480,144 +1480,100 @@ class Interne extends Scores_Ws_Server $this->authenticate(); $c = Zend_Registry::get('config'); $path = "/mnt/clients/oldcrm"; + if (empty($ref)) $ref = '*'; if (empty($nomFic)) $nomFic = ''; $error = new ErrorType(); - $tabFichier=$tabDates=array(); - $numAbo=substr($ref, 0,5); + $tabFichier = $tabDates = array(); + $numAbo = substr($ref, 0,5); if (strtolower($login)=='vwbank') { $ficClient='surveillanceBodacc_SURBODPRDCFTVWBANK'; - $numAbo=$ref='19300'; + $numAbo = $ref = '19300'; } elseif (substr($login,0,6)=='apicil') { $ficClient='surveillanceBodacc_SURBODPRDCFTAPICIL'; - $numAbo=$ref=''; + $numAbo = $ref = ''; } elseif (strtolower($login)=='omni04') { $ficClient='surveillanceBodacc_SURBODPRDFTSOMNIREP'; - $numAbo=$ref=''; - } elseif (strtolower($login)=='bodacca3m') { + $numAbo = $ref = ''; + } elseif (strtolower($login)=='bodacca3m' /*|| strtolower($login)=='mricois'*/) { $ficClient='surveillanceBodacc_SURBODPRDFTSMEDERIC'; - $numAbo=$ref=''; + $numAbo = $ref = ''; } elseif (strtolower($login)=='bodaccomni') { $ficClient='surveillanceBodacc_SURBODPRDFTSOMNIREP'; - $numAbo=$ref=''; + $numAbo = $ref = ''; } elseif (strtolower($login)=='bodacccrr') { $ficClient='surveillanceBodacc_SURBODPRDFTSCRR'; - $numAbo=$ref=''; - } elseif (strtolower($login)=='cpcambr13' || strtolower($login)=='cpcambr14') { + $numAbo = $ref = ''; + } elseif (strtolower($login)=='cpcambr13' || strtolower($login)=='cpcambr14' /*|| strtolower($login)=='mricois'*/) { $ficClient='diffusionBodacc_DIFBODPRDMAICPCAM13'; - $numAbo=$ref=''; + $numAbo = $ref = ''; } elseif (strtolower($login)=='frbsurveillance'){ $ficClient='surveillanceBodacc_SURBODPRDFTPFBOISSON'; + $numAbo = $ref = ''; } else { $ficClient='surveillanceBodacc_SURBODTSTFTSCNASEA'; + $numAbo = $ref = ''; } - // --- Lecture du repertoire - $dh = opendir($path."/"); - if (!$dh) { - $error->errnum = 1; - $error->errmsg = "Impossible d'ouvrir le dossier client"; + // --- Livraison fichier + if ($nomFic!='') { + $directory = $c->profil->path->files; + $ficLength = strlen($ficClient . $numAbo); + if (file_exists($path.'/'.$nomFic) && substr($nomFic, 0, $ficLength) == $ficClient . $numAbo) { + if (!file_exists($directory."/$nomFic.bz2") || filesize($directory."/$nomFic.bz2") <= 14) { + $string = file_get_contents($path."/$nomFic"); + $bz = bzopen($directory."/$nomFic.bz2",'w'); + if ($bz) { + bzwrite($bz, $string, strlen($string)); + bzclose($bz); + } + } + $tabFichier[] = $nomFic; + } else { + $error->errnum = 1; + $error->errmsg = "Impossible d'ouvrir le fichier client"; + } } else { - while (false !== ($filename = readdir($dh))) { - if($filename=='.' && $filename=='..') - continue; - if (substr($filename, -4)=='.csv' && substr($filename,0,42)==$ficClient.$numAbo) { - $tabFichier[] = $filename; - $tabDates[]=substr($filename,43,8); - $tabClients[]=substr($filename,0,42); - } - elseif ($ref=='*' && substr($filename, -4)=='.csv' && substr($filename,0,37)==$ficClient && substr($filename,37,1)<>'_') { - $tabFichier[] = $filename; - $tabDates[]=substr($filename,43,8); - $tabClients[]=substr($filename,0,42); - } - elseif (substr($filename, -4)=='.csv' && substr($filename,0,37)==$ficClient && substr($filename,37,1)=='_') { - $tabFichier[] = $filename; - $tabDates[]=substr($filename,38,8); - $tabClients[]=substr($filename,0,37); - } - elseif (substr($filename, -4)=='.csv' && substr($filename,0,38)==$ficClient && substr($filename,38,1)=='_') { - $tabFichier[] = $filename; - $tabDates[]=substr($filename,39,8); - $tabClients[]=substr($filename,0,38); - } - } - /** Tableau des noms de fichier **/ - sort($tabFichier); - /** Tableau des dates de livraisons **/ - $tabDates=array_unique($tabDates); - sort($tabDates); - /** Tableau des Clients **/ - $tabClients=array_unique($tabClients); - sort($tabClients); + // --- Lecture du repertoire + $dh = opendir($path."/"); + if ($dh) { + while (false !== ($filename = readdir($dh))) { + if ($filename == '.' && $filename =='..') continue; + if (substr($filename, -4) != '.csv') continue; + $ficLength = strlen($ficClient . $numAbo); + if (substr($filename, 0, $ficLength) == $ficClient . $numAbo) { + $tabFichier[] = $filename; + $tabDates[] = substr($filename, $ficLength + 1, 8); + $tabClients[] = substr($filename, 0, $ficLength); + } + } - if ($ref=='*') { - $tabFichier = array(); - // Boucle sur les dates de livraison - foreach ($tabDates as $dateFic) { - if (strlen($dateFic)<>8) continue; - if (!file_exists($path."/$ficClient".'_'."$dateFic.csv") - || filesize($path."/$ficClient".'_'."$dateFic.csv")==0) { + // Tableau des noms de fichier + sort($tabFichier); + // Tableau des dates de livraisons + $tabDates = array_unique($tabDates); + sort($tabDates); + // Tableau des Clients + $tabClients = array_unique($tabClients); + sort($tabClients); + rsort($tabFichier); + } else { + $error->errnum = 1; + $error->errmsg = "Impossible d'ouvrir le dossier client"; + } + } - $fpW=fopen($path."/$ficClient".'_'."$dateFic.csv",'w'); - $entete=true; - // Boucle afin de vérifier si on est sur le bon client - foreach ($tabClients as $nomClient) { - $dh = opendir($path."/"); - while (false !== ($filename = readdir($dh))) { - if (substr($filename,0,51)==$nomClient.'_'.$dateFic && substr($filename,-4)=='.csv') { - $fichier=$filename; - //break; - } - } - $fpR=fopen($path."/".$fichier,'r'); - //return array('error'=>array('errnum'=>0, 'errmsg'=>''), 'results'=>array(($fichier)));//die; - if ($fpR) { - while (!feof($fpR)) { - $ligne=trim(fgets($fpR)); - if (substr($ligne,0,5)=='Siren' && $entete==true) { - fwrite($fpW, 'SITE;'.$ligne.EOL); - $entete=false; - } - elseif (substr($ligne,0,5)<>'Siren' && trim($ligne)<>'') { - fwrite($fpW, strtr($nomClient, array( - 'surveillanceBodacc_SURBODTSTFTS'=>'', - 'surveillanceBodacc_SURBODPRDCFT'=>'')).';'.$ligne.EOL); - } - } - fclose($fpR); - } - } - fclose($fpW); - } - if (strlen($dateFic)==8) - $tabFichier[]=$ficClient.'_'.$dateFic.'.csv'; - } - } - rsort($tabFichier); - - if ($nomFic!='') { - $directory = $c->profil->path->files; - if (!file_exists($directory."/$nomFic.bz2") || filesize($directory."/$nomFic.bz2")<=14) { - $string = file_get_contents($path."/$nomFic"); - $bz = bzopen($directory."/$nomFic.bz2",'w'); - if ($bz) { - bzwrite($bz, $string, strlen($string)); - bzclose($bz); - } - } - } - debugLog('I',"getListeFichierSurv pour $login, $ref, $nomFic : nb fichiers=".count($tabFichier),__LINE__,__FILE__, __FUNCTION__, __CLASS__); - $hostname = 'http://'.$_SERVER['SERVER_NAME']; - if ($_SERVER['SERVER_PORT']!='80'){ - $hostname.= ':'.$_SERVER['SERVER_PORT']; - } - $result = array(); - foreach($tabFichier as $fichier){ - $retFichier = new ListeFichierSurv(); - $retFichier->UrlFichier = $hostname.'/fichier/crm/'.$fichier; - $result[] = $retFichier; - } + $result = array(); + if (count($tabFichier) > 0) { + $hostname = 'http://'.$_SERVER['SERVER_NAME']; + if ($_SERVER['SERVER_PORT'] != '80'){ + $hostname.= ':'.$_SERVER['SERVER_PORT']; + } + foreach($tabFichier as $fichier) { + $retFichier = new ListeFichierSurv(); + $retFichier->UrlFichier = $hostname.'/fichier/crm/'.$fichier; + $result[] = $retFichier; + } } $output = new ListeFichierSurvReturn(); $output->error = $error; diff --git a/library/WsScore/Monitoring/v0.1/Service.php b/library/WsScore/Monitoring/v0.1/Service.php index abe66997..9c38b942 100644 --- a/library/WsScore/Monitoring/v0.1/Service.php +++ b/library/WsScore/Monitoring/v0.1/Service.php @@ -4,7 +4,17 @@ require_once __DIR__ . '/Types.php'; class Monitoring extends Scores_Ws_Server { - protected function getSurveillances($source){} + protected function getSurveillanceList($source = null) + { + /** + * Afficher les surveillances en groupant par siren + * Identite : SIREN, Nom, Adresse + * Clic pour liste des éléments + * Ligne 1 + * Ligne 2 + * + */ + } protected function getSurveillance(){} protected function getSurveillanceById(){} diff --git a/library/WsScore/Source/v0.1/Service.php b/library/WsScore/Source/v0.1/Service.php index 8a65eae5..2ebda564 100644 --- a/library/WsScore/Source/v0.1/Service.php +++ b/library/WsScore/Source/v0.1/Service.php @@ -195,5 +195,6 @@ class Source extends Scores_Ws_Server return $id; } + protected function setContact(){} } \ No newline at end of file diff --git a/library/framework/common/mysql.php b/library/framework/common/mysql.php index 13936126..6e3f50c8 100644 --- a/library/framework/common/mysql.php +++ b/library/framework/common/mysql.php @@ -43,7 +43,7 @@ class WDB $values = str_replace("'NULL'", 'NULL', $values); if ($low_priority) { - $query = 'INSERT DELAYED INTO '.$table.' ('.$fields.') VALUES ('.$values.');'; + $query = 'INSERT INTO '.$table.' ('.$fields.') VALUES ('.$values.');'; } else { $query = 'INSERT INTO '.$table.' ('.$fields.') VALUES ('.$values.');'; } @@ -83,7 +83,7 @@ class WDB $this->errorMsg = ''; if ($low_priority) { - $query='UPDATE LOW_PRIORITY '.$table.' SET '; + $query='UPDATE '.$table.' SET '; } else { $query='UPDATE '.$table.' SET '; } @@ -133,7 +133,7 @@ class WDB $this->errorMsg = ''; if ($low_priority) - $query='DELETE LOW_PRIORITY QUICK FROM '.$table.' WHERE '.$where.';'; + $query='DELETE QUICK FROM '.$table.' WHERE '.$where.';'; else $query='DELETE FROM '.$table.' WHERE '.$where.';'; diff --git a/scripts/jobs/getGreffe.php b/scripts/jobs/getGreffe.php index b15a2f5d..2ebdc9f4 100644 --- a/scripts/jobs/getGreffe.php +++ b/scripts/jobs/getGreffe.php @@ -103,7 +103,7 @@ function sendMail($commande, $type){ switch ( $type ) { case 'BI': $dateBilan = substr($commande->bilanCloture,8,2).'/'.substr($commande->bilanCloture,5,2).'/'.substr($commande->bilanCloture,0,4); - $message.= "Bilan cloturé le "; + $message.= "Bilan cloturé le ".$dateBilan; break; case 'AC': $dateActe = substr($commande->acteDate,8,2).'/'.substr($commande->acteDate,5,2).'/'.substr($commande->acteDate,0,4);