<?php

require_once 'framework/common/curl.php';

class Metier_Partenaires_MCoface {

	public $body = '';
	public $header = '';
	public $codeRetour = 0;

	public $nscrl = 0;	// Numéro interne SCRL
	public $rcsVille='';
	public $rcsType='';

	public $rSocAdrCPVille='';	// RaisonSocialeAdresseVille (utile pour le débug)
	public $raisonSociale='';	// Raison Sociale
	public $adresse='';			// Adresse complète (avec CP et Cille)

	public $sigle='';
	public $enseigne='';
	public $nbEtab='';

	public $adrNumVoie;
	public $adrIndRep;
	public $adrTypeVoie;
	public $adrLibVoie;
	public $adrCP;
	public $adrVille;

	public $tel='';
	public $fax='';
	public $web='';
	public $mail='';
	public $activite='';	// Activité Déclarée au bodacc
	public $naf='';			// NAF
	public $nafLib='';

	public $bourseIsin='';
	public $bourseMarche='';
	public $bourseVille='';

	public $tabInfos=array();
	public $tabBilans=array();

	public $infoEco=false;
	public $capitalType='';
	public $capitalMontant='';
	public $capitalDevise ='';
	public $steInactive = '';
	public $dateCreation='';		// Notion INSEE
	public $dateImmatriculation='';	// Notion Greffe et RNCS uniquement
	public $fj='';
	public $nationalite='';
	public $enBourse='';
	public $effectif='';
	public $tabDirigeants=array();
	public $strLiensFi='';
	public $strElemsFi='';

	public $derExerciceAnnee='';
	public $derExerciceDuree='';
	public $derExerciceDClot='';
	public $derExerciceCA='';
	public $derExerciceResultat='';
	public $derExerciceDevise='';

	public $dateFermeture='';
	public $score_pouey='';
	public $score_conan='';
	public $score_afdcc='';
	public $vigilance='';
	public $tabJug=array();
	public $tabAct=array();
	public $tabFil=array();
	public $tabEtab=array();

	function __construct($siren)
	{
		$referer='';
		$url='http://www.cofacerating.fr/portail/entreprise_identite/identite.asp?ip=pagespro&lg=fr&nsiren='.$siren;
		$page=getUrl($url, '', '', $referer, false, 'www.cofacerating.fr', '', 10);
		$this->body=$page['body'];
		$this->codeRetour=$page['code'];
		$this->header=$page['header'];
		$this->nscrl=@getTextInHtml($this->body, '&nscrl=', '=','&');
		$this->rSocAdrCPVille=trim(str_replace(chr(160), ' ', html_entity_decode(utf8_encode(@getTextInHtml($this->body, '<td WIDTH="40%" bgcolor="#F3E5CC" class="tabligne"> <b> Raison sociale<br>', '<td WIDTH="60%" bgcolor="#FFF3DE" class="tabval"><b>','</tr>')))));
		$tmp=explode('<br>', $this->rSocAdrCPVille);
		$this->raisonSociale=trim($tmp[0]);
		unset($tmp[0]);
		$this->adresse=trim(strip_tags(implode(',', $tmp)));
		$this->tel=trim(@getTextInHtml($this->body, '<td bgcolor="#F3E5CC" class="tabligne"><b>Téléphone<br>', '<td bgcolor="#FFF3DE" class="tabval" valign="top">', '<br>'));
		$this->fax=trim(@getTextInHtml($this->body, 'Télécopie</b></td>', '<br>', '</td>'));
		$this->web=trim(@getTextInHtml($this->body, '<td bgcolor="#F3E5CC" class="tabligne"><b>Adresse internet <br>', ' class="tabval"><a class="tabval" HREF="', '" target="_new">'));
		$this->mail=trim(@getTextInHtml($this->body, '<a class="tabval" href="mailto:', ':', '">'));

		$bourse=trim(@getTextInHtml($this->body, 'Ville Bourse</b></td>', 'class="tabval">', '</td>'));
		$tmp=explode('<br>', $bourse);
		$this->bourseIsin=trim($tmp[0]);
		$this->bourseMarche=trim($tmp[1]);
		$this->bourseVille=trim($tmp[2]);

		$infosDispo=trim(@getTextInHtml($this->body, '<b>Liste Produits</b><br></td>', '<br></td><td class="menu3"><img src="../images/vide.gif" border="0"><br></td><td colspan="2" class="menu3">', 'Un secteur ou une région en France</a><br></td>'));
		$tabTmp=explode('<a href="', $infosDispo);
		foreach ($tabTmp as $k=>$lien) {
			preg_match('/^(.*)">(.*)<\/a>/i', $lien, $matches);
			if ($matches[2]<>'')							$this->tabInfos[$matches[2]]=$matches[1];
			if (substr($matches[2], 0, 12)=='rapport éco.')	$this->infoEco='http://www.cofacerating.fr/portail/entreprise_identite/'.$matches[1];//ip=pagespro&
			elseif (substr($matches[2], 0, 6)=='bilan ')	$this->tabBilans[]=substr($matches[2], 6,strlen($matches[2])-6);
		}
		$this->activite=trim(str_replace(chr(160), ' ', html_entity_decode(utf8_encode(@getTextInHtml($this->body, '<td WIDTH="40%" bgcolor="#F3E5CC" class="tabligne" valign="top"><b>Libellé code activité </b></td>', '<td WIDTH="60%" bgcolor="#FFF3DE" class="tabval">', '</td>')))));
		$this->naf=trim(@getTextInHtml($this->body, '<a href="../chaineeco_dynaeco/DynaEco.asp?cnaf=', 'cnaf=', '&'));

		/**
		 ** Recherche du NIC sur Société .com
		 **/

		/*
		$refererS='http://www.societe.com/';
		$urlS='http://www.societe.com/cgi-bin/recherche?rncs='.$siren.'&vu=1';
		$page=getUrl($urlS, '', '', $refererS, false, 'www.societe.com');
		$ste=$page['body'];
		$this->nic=trim(@getTextInHtml($ste, 'SIRET</div><div class="ficheAltCol2 size11">', $siren, '</div>'));

		$strTmp=trim(@getTextInHtml($ste, '<b><span class="size10">RCS', 'RCS ', ' '.substr($siren,0,3)));
		$tabTmp=explode(' ', $strTmp);
		$this->rcsVille=$tabTmp[0];//<td class="txtBlanc" align="left"><b><span class="size10">RCS Paris B 552 144 503<br></span></b></td>
		$this->rcsType=$tabTmp[1];

		$strTmp=trim(@getTextInHtml($ste, '<div class="ficheAltCol1 size11">Code activité</div>', '<div class="ficheAltCol2 size11">', '</div>'));
		$tabTmp=explode(' - ', $strTmp);
		$this->naf=$tabTmp[0];
		$this->nafLib=$tabTmp[1];

		// <div class="ficheAltCol1 size11">Siège social</div><div class="ficheAltCol2 size11">75 Avenue la Grande Armee - 75116 PARIS 16</div>

		$strTmp=trim(@getTextInHtml($ste, '<div class="ficheAltCol1 size11">Capital social', '<div class="ficheAltCol2 size11">', '</div>'));
		$this->capitalType='social';
		$tabTmp=explode(' ', $strTmp);
		$this->capitalMontant=str_replace(',', '.', str_replace('.', '', $tabTmp[0]));
		$this->capitalDevise =$tabTmp[1];

		$this->fj=trim(@getTextInHtml($ste, '<div class="ficheAltCol1 size11">Forme juridique', '<div class="ficheAltCol2 size11">', '</div>'));
		$this->nationalite=trim(@getTextInHtml($ste, '<div class="ficheAltCol1 size11">Nationalit&eacute;</div>', '<div class="ficheAltCol2 size11">', '</div>'));

		$strTmp=trim(@getTextInHtml($ste, '&nbsp;DIRIGEANT(S)&nbsp;</span></span></div>', '<div class="ficheCadre" style="min-height:85px;">', '<div class="spacer"></div>'));
		$tabTmp=explode('<div class="h1bleu2"></div>', $strTmp);
		foreach ($tabTmp as $k=>$dir) {
			if (trim($dir)=='') break;
			$tabTmp1=explode('</div><div class="ficheAltCol2 size11">', $dir);
			$tabTmp2=explode('représenté par', $tabTmp1[1]);
			if (isset($tabTmp2[1]) && $tabTmp2[1]<>'')	{
				$soc=trim($tabTmp2[0]);
				$diri=trim($tabTmp2[1]);
			} else {
				$soc='';
				$diri=trim($tabTmp1[1]);
			}
			preg_match("/^(Mme|M\.|Mlle|Mle|M) ([A-Z\s]*) ([A-Z][a-z\s]*)/", $diri, $matches);
			//print_r($matches);
			$this->tabDirigeants[]=array('FONCTION'=>trim(strip_tags($tabTmp1[0])), 'SOCIETE'=>$soc, 'GENRE'=>$matches[1], 'PRENOM'=>trim($matches[3]), 'NOM'=>trim($matches[2]));
		}

		$this->dateImmatriculation=trim(@getTextInHtml($ste, '<div class="ficheAltCol1 size11"> Immatriculation', '<div class="ficheAltCol2 size11">', '</div>'));
		//06-03-2007</div>
/*	Date Creation = ""
	En bourse = ""
	Effectif societe = ""
	Dirigeants :
**/
		$urlRacine='http://infobilan.decideur.com/';
		$tabPost=array(	'choix'=>'1',
						'pagePrecedente'=>'recherche_entreprise.html',
						'nomsocRech'=>'',
						'cpRech'=>'',
						'villeRech'=>'',
						'nomdirRech'=>'',
						'predirRech'=>'',
						'sirenRech'=>$siren,
						'telRech'=>'',);
					//	'Rechercher'=>'',
		$url=$urlRacine.'liste_result.html';
		$referer=$urlRacine.'recherche_entreprise.html';
		$page=getUrl($url,'', $tabPost, $referer, false, 'infobilan.decideur.com');
		$this->body=$page['body'];
		$strCookie=$page['header']['Set-Cookie'];
		$refererInfoD=$url;

		if(preg_match_all('/<a href="choix_pdt\.html\?(.*)" class="tt1">(.*)<\/a><\/span><br>/i', $page['body'], $matches))
			$urlInfoD=$urlRacine.'choix_pdt.html?'.$matches[1][0];
		else
			$urlInfoD='';

		$page=getUrl($this->infoEco, '', '', $url, false, 'www.cofacerating.fr');
		if (strpos($page['body'], '<b>Choix du mode de paiement</b>')===false) {	// Le rapport éco. est cadeau !!!
			$this->infoEco=true;
			$eco=$page['body'];
			//die ($eco);
			$strTmp=strip_tags(@getTextInHtml($eco, ' class="tabligne" > Capital &nbsp (', '(', '</tr><tr>'));
			$tabTmp=explode(')', $strTmp);
			$this->capitalType=$tabTmp[0];
			$tabTmp=explode('&nbsp', $tabTmp[1]);
			$this->capitalMontant=trim(str_replace(chr(160), '', $tabTmp[0]));
			$this->capitalDevise =trim(str_replace(chr(160), '', $tabTmp[1]));

			$this->steInactive=trim(@getTextInHtml($eco, ' class="tabligne" > Société inactive</td>', 'class="tabval" >', '</td>'));

			$this->dateCreation=trim(@getTextInHtml($eco, ' class="tabligne" > Date de création</td>', 'class="tabval" >', '</td>'));
			$this->fj=trim(@getTextInHtml($eco, ' class="tabligne" > Forme juridique</td>', 'class="tabval" >', '</td>'));
			$this->effectif=trim(@getTextInHtml($eco, ' class="tabligne" > Effectif', 'class="tabval" >', '</td>'));

			if (count($this->tabDirigeants)==0) { // Si il y a déjà des dirigeants on garde ceux de Société.com !!!
				$strTmp=trim(@getTextInHtml($eco, ' class="tabligne" > Cotation en bourse</td>', '<td bgcolor="#F3E5CC" class="tabligne" >', '<td bgcolor="#F3E5CC" class="tabligne" > Effectif'));
				$tabTmp=explode('<td bgcolor="#F3E5CC" class="tabligne" >', $strTmp);
				foreach ($tabTmp as $k=>$dir) {
					$tabTmp1=explode('<td bgcolor="#FFF3DE" class="tabval" >', $dir);
					$tabTmp2=explode('&nbsp', trim(strip_tags($tabTmp1[1])));
					$this->tabDirigeants[]=array('FONCTION'=>trim(strip_tags($tabTmp1[0])), 'GENRE'=>trim($tabTmp2[0]), 'PRENOM'=>trim($tabTmp2[1]), 'NOM'=>trim($tabTmp2[2]));
				}
			}

			$this->strLiensFi=trim(strip_tags(@getTextInHtml($eco, '<td class="tabtot">LIENS FINANCIERS</td>', '<tr>', '</td></tr>')));
			$this->strElemsFi=trim(strip_tags(@getTextInHtml($eco, '<td class="tabtot">ELEMENTS FINANCIERS</td>', '<tr>', '</td></tr>')));
		}

		$refererP='http://www.score3.fr/';
		$urlP='http://www.score3.fr/entreprise.shtml?siren='.$siren;
		$page=getUrl($urlP, '', '', $refererP, false, 'www.score3.fr');
		$pou=$page['body'];
		$fp=fopen('./pouet.html', 'w');
		fwrite($fp, $pou);
		fclose($fp);

		if ($urlInfoD<>'') {
			$page=getUrl($urlInfoD,$strCookie,'', $refererInfoD, false, 'infobilan.decideur.com');
			$referer=$urlInfoD;
			if ($this->nscrl==0)	$this->nscrl=@getTextInHtml($url, 'nscrlP=', '=','&');

			$url=$urlRacine.'fiche_ident.html';
			$page=getUrl($url,$strCookie,'', $referer, false, 'infobilan.decideur.com');
			$this->body=$page['body'];

			if ($this->raisonSociale=='')
				$this->raisonSociale=trim(@getTextInHtml($this->body, '<span class="libelle2">Soci&eacute;t&eacute;', ' :', '</span>'));

			if ($this->adresse=='')
				$this->adresse=trim(@getTextInHtml($this->body, '<span class="libelle2">Adresse</span> <strong>:', '</strong>', '</td>'));

			if ($this->tel=='')
				$this->tel=trim(@getTextInHtml($this->body, '<td valign="top"><span class="libelle2">T&eacute;l', '</span>', '<br>'));
			if ($this->fax=='')
				$this->fax=trim(@getTextInHtml($this->body, '<span class="libelle2">Fax</span>', ' :', '<br>'));
			if ($this->web=='')
				$this->web=trim(@getTextInHtml($this->body, '<span class="libelle2">Site Web</span>', '<a href="', '" target="_blank">'));
			if ($this->mail=='')
				$this->mail=trim(@getTextInHtml($this->body, '<span class="libelle2">E-mail</span>', '<a href="mailto:', '">'));
			if ($this->naf=='')
				$this->naf=trim(@getTextInHtml($this->body, '<span class="libelle2">Code NAF</span>', ' :', '</td>'));

			if(preg_match('/<td valign="top"><span class="libelle2">Capital social<\/span> : (\d*)(.*)<br>/isU', $this->body, $matches)
				&& ($this->capitalMontant=='' || $this->capitalDevise=='')) {
					$this->capitalMontant=trim($matches[1]);
					$this->capitalDevise=trim($matches[2]);
			}

			if ($this->fj=='')
				$this->fj=trim(@getTextInHtml($this->body, '<span class="libelle2">Forme juridique</span>', ' :', '<br>'));
			if ($this->nationalite=='')
				$this->nationalite=trim(@getTextInHtml($this->body, '<span class="libelle2">Nationalit&eacute;</span>', ' :', '</td>'));
			if ($this->effectif=='')
				$this->effectif=trim(@getTextInHtml($this->body, '<td valign="top"><span class="libelle2">Effectif</span>', ' :', '<br>'));
			if ($this->activite=='')
				$this->activite=trim(@getTextInHtml($this->body, '<span class="libelle2">Activit&eacute;</span>', ' :', '<br>'));

			/** Actionnaires **/
			$strTmp=trim(@getTextInHtml($this->body, 'ACTIONNAIRES<br>', '</div></h1>', '<h1>'));
			if(preg_match_all('/<p><span class="libelle2">(.*)<\/span> - <span class="libelle2">Participation<\/span> : (.*) %<br>(.*)<\/p>/isU', $strTmp, $matches)) {
				foreach ($matches[1] as $i=>$nom) {
					$this->tabAct[$i]['nom']=trim($nom);
					$this->tabAct[$i]['pct']=trim($matches[2][$i]);
					$this->tabAct[$i]['rcs']=trim(str_replace('RCS : ','',strip_tags($matches[3][$i])));
				}
			}

			/** Filiales **/
			$strTmp=trim(@getTextInHtml($this->body, 'FILIALES<br>', '</div></h1>', '<h1>'));
			if(preg_match_all('/<p><span class="libelle2">(.*)<\/span> - <span class="libelle2">Participation<\/span> :(.*)%<br>(.*)<\/p>/isU', $strTmp, $matches)) {
				foreach ($matches[1] as $i=>$nom) {
					$this->tabFil[$i]['nom']=trim($nom);
					$this->tabFil[$i]['pct']=trim($matches[2][$i]);
					$this->tabFil[$i]['rcs']=trim(str_replace('RCS :','',strip_tags($matches[3][$i])));
				}
			}

			/** CA et Résultat **/
			$strTmp=trim(@getTextInHtml($this->body, '<h1>PRINCIPAUX ELEMENTS FINANCIERS<br>', '</div></h1>', '</p>'));
			if(preg_match('/<p><span class="libelle2">CA (.*)<\/span>(.*)<br>/isU', $strTmp, $matches)) {
				$this->derExerciceAnnee=trim($matches[1]);
				$this->derExerciceCA=trim(str_replace(':',' ', $matches[2]));
			}
			if(preg_match('/<span class="libelle2">R&eacute;sultat(.*)<\/span>(.*)$/isU', $strTmp, $matches)) {
				$this->derExerciceResultat=trim(str_replace(':',' ', $matches[2]));
			}

			$infoBilan=print_r($page, true);
			$fp=fopen('./infobilan.html', 'w');
			fwrite($fp, $infoBilan);
			fclose($fp);
		}

		if ($this->nbEtab=='' || $this->nbEtab=='0') {
			$this->nbEtab=trim(strip_tags(str_replace('afficher la liste...', '', @getTextInHtml($pou, '<tr><td class="ligne1_2">Etablissements </td>', '<td class="ligne2_2">', '</td></tr>'))));
			$urlPEtab='http://www.score3.fr/etablissements.shtml?page=1&siren='.$siren;
			$refererPEtab=$urlP;
			$page=getUrl($urlPEtab, '', '', $refererPEtab, false, 'www.score3.fr');
			$pou2=$page['body'];
			if(preg_match_all('/<tr bgcolor="(?:\S*)"><td class="ligne1b" align="center" width="10%">(\d*)<\/td><td class="ligne2" height="50"><table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td class="infos">(.*)<\/td><\/tr><\/table>/isU', $pou2, $matches)) {
				foreach ($matches[1] as $i=>$nic) {
					$strEtab=$matches[2][$i];
					$this->tabEtab[$i]['siren']=$siren;
					$this->tabEtab[$i]['nic']=$nic;
					$this->tabEtab[$i]['siret']=$siren.$nic;

					$this->tabEtab[$i]['enseigne']=trim(str_replace(chr(160),' ',utf8_decode(strip_tags(@getTextInHtml($strEtab, '<span class="titre3">', '">', '</span>')))));
					$this->tabEtab[$i]['adresse']=trim(str_replace(chr(160),' ',utf8_decode(strip_tags(@getTextInHtml($strEtab, '<span class="infos">', '">', '<br>')))));
					$strTmp=trim(str_replace(chr(160),' ',utf8_decode(strip_tags(@getTextInHtml($strEtab, '<span class="infos">', '<br>', '</span>')))));
					$tabTmp=explode(' ', $strTmp);
					$this->tabEtab[$i]['cp']=$tabTmp[0];
					unset($tabTmp[0]);
					$this->tabEtab[$i]['ville']=implode(' ',$tabTmp);
					$strTmp=trim(strip_tags(@getTextInHtml($strEtab, '<td class="infos" align="right" valign="top">', '">', ')')));
					$tabTmp=explode('(', $strTmp);
					$this->tabEtab[$i]['naf_code']=$tabTmp[1];
					$this->tabEtab[$i]['naf_lib']=trim(str_replace(chr(160),' ',utf8_decode($tabTmp[0])));
					if (preg_match('/<br>T.l\.(.*)$/i',$strEtab,$matches2))
						 $this->tabEtab[$i]['tel']=trim(str_replace(chr(160),' ',utf8_decode($matches2[1])));
					else $this->tabEtab[$i]['tel']='';
				}
			}
			$this->nbEtab=count($this->tabEtab);
			$fp=fopen('./pouet_etab.html', 'w');
			fwrite($fp, $pou2);
			fclose($fp);
		}

		if ($this->effectif=='' || $this->effectif=='0' || $this->effectif=='NC')
			$this->effectif=trim(@getTextInHtml($pou, '<tr><td class="ligne1_2">Effectifs</td>', '<td class="ligne2_2">', '</td></tr>'));

		if ($this->dateImmatriculation=='' || $this->dateImmatriculation=='0')
			$this->dateImmatriculation=trim(@getTextInHtml($pou, '<tr><td class="ligne1_2">Date d\'immatriculation</td>', '<td class="ligne2_2">', '</td></tr>'));
		if ($this->dateFermeture=='' || $this->dateFermeture=='0')
			$this->dateFermeture=trim(@getTextInHtml($pou, '<tr><td class="ligne1_2">Date de fin d\'exploitation</td>', '<td class="ligne2_2">', '</td></tr>'));

		if ($this->tel=='' || $this->tel=='0')
			$this->tel=trim(@getTextInHtml($pou, '<tr><td class="ligne1_2">Téléphone</td>', '<td class="ligne2_2">', '</td></tr>'));

		if ($this->fax=='' || $this->fax=='0')
			$this->fax=trim(@getTextInHtml($pou, '<tr><td class="ligne1_2">Fax</td>', '<td class="ligne2_2">', '</td></tr>'));

		$strTmp=trim(@getTextInHtml($pou, 'Procédures collectives</td></tr>', '</table></td>', '</td><td background'));
		if(preg_match_all('/<tr><td class="ligne1_2">(.*)<\/td><td class="ligne2_2">(.*)<\/td><\/tr>/isU', $strTmp, $matches)) {
			foreach ($matches[1] as $i=>$jug) {
				$this->tabJug[$i]['date']=$matches[1][$i];
				$this->tabJug[$i]['juge']=$matches[2][$i];
			}
		}

		$this->score_pouey=trim(@getTextInHtml($pou, '<param name="movie" value="cadran.swf?rotation=', '&amp;type=pouey&amp;valeur=', '">'));
		$this->score_conan=trim(@getTextInHtml($pou, '<param name="movie" value="cadran.swf?rotation=', '&amp;type=ch&amp;valeur=', '">'));
		$this->score_afdcc=trim(@getTextInHtml($pou, '<param name="movie" value="cadran.swf?rotation=', '&amp;type=afdcc&amp;valeur=', '">'));
		$this->vigilance  =trim(@getTextInHtml($pou, '<param name="movie" value="vigilance.swf', 'degre=', '">'));

		if(preg_match('/Date de l\'exercice<\/td><td class="ligne2_2">(.*) sur (\d*) mois<\/td><\/tr>/isU', $pou, $matches)) {
			$this->derExerciceDClot=trim($matches[1]);
			$this->derExerciceDuree=trim($matches[2]);
		}

		/* Siret SIEGE
		2   Fonction, Nom Prénoù ET Date NAissance du PP
		5	Liste des actes
		*/
		if ($this->codeRetour==200)
			return true;

		return false;
	}

}

?>