<?php
class MTel
{
	public $body = '';
	public $header = '';
	public $codeRetour = 0;

	public $cookie='';
	public $urlBase='http://www.pagespro.com/recherche.php';
	public $url='';
	public $referer='';
	public $enCache=false;
	private $accesDistant=false;

	public $iDb;

	public function __construct($accesDistant=false, $db=null)
	{
		$this->accesDistant=$accesDistant;
		$this->accesDistant=false;	// Accès bloqué par "pagespro"
		if ($this->accesDistant) {
			$this->url=$this->urlBase;
			$page=getUrl($this->url,$this->cookie,'',$this->referer, false, '', '', 3);
			$this->referer=$this->url;
			$this->cookie=$page['header']['Set-Cookie'];
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];
		}
		if ( $db === null ) {
		    $this->iDb=new WDB('jo');
		} else {
            $this->iDb = $db;
		}

	}

	/**
	 * Information contact
	 * @param string $siret
	 * @param string $nic
	 * @param boolean $last
	 * @param int $actif
	 * @return array Retourne une liste de téléphone
	 */
	public function getTel($siret, $nic=0, $last=false, $actif=null)
	{
		$tabRet=array();

		if (strlen($siret)>9) {
			$nic = substr($siret,-5)*1;
			$siren = round($siret/100000)*1;
		} else {
			$siren=$siret*1;
		}

		if ($siren<1000)	return $tabRet;

		/** Si le siren est de taille < à 9, on ajoute des 0 significatifs **/
		if (strlen($siren)<=9) {
		    $siren = str_pad($siren, 9, '0', STR_PAD_LEFT);
		}
		if (strlen($nic)>0) {
		    $nic = str_pad($nic, 5, '0', STR_PAD_LEFT);
		}

		$strNic='';
		if ($nic*1>0)	$strNic="AND (nic=$nic OR nic=0)";
		$strActif='';
		if ($actif==1)		$strActif=" AND actif=1 ";
		elseif($actif==0)	$strActif=" AND actif=0 ";

		$ret=$this->iDb->select(
		    'telephonie',
			'siren,nic,dateProvPartenaire,typeTel,infoTel,LPAD(telephone,10,0) AS telephone,actif,partenaire,idUtilisateur,dateInsert,dateInsert*1 AS dateInsertYmd,dateConfPartenaire,partenaireConf,nbConf,idUpdate,dateUpdate,dateUpdate*1 AS dateUpdateYmd',
			"siren=$siren $strNic $strActif AND dateSuppr=0 ORDER BY typeTel ASC, nbConf DESC", false, MYSQL_ASSOC);

		if (count($ret)>0) {

			$this->enCache=true;
			foreach ($ret as $tabTel)
			{
				if ($tabTel['typeTel']=='an8' && $tabTel['infoTel']*1>0) {
					$an8=$tabTel['infoTel']*1;
					$retTmp=$this->iDb->select('tabAn8', 'libAn8', "codAn8='$an8'", false, MYSQL_ASSOC);
					$infoTel=ucfirst(strtolower($retTmp[0]['libAn8']));
				} else {
					$infoTel=$tabTel['infoTel'];
				}

				if ($tabTel['partenaireConf']>0)	$source=$tabTel['partenaireConf'];
				else								$source=$tabTel['partenaire'];
				if ($tabTel['dateUpdateYmd']>$tabTel['dateInsertYmd'])	$dateMAJ=$tabTel['dateUpdateYmd'];
				else													$dateMAJ=$tabTel['dateInsertYmd'];

				$tabR = array(
				    'siren'=>$siren,
					'nic'=>$tabTel['nic'],
					'typeTel'=>$tabTel['typeTel'],
					'infoTel'=>$infoTel,
					'telephone'=>$tabTel['telephone'],
					'actif'=>$tabTel['actif'],
					'source'=>$source,
					'dateMAJ'=>$dateMAJ,
				);
                $tabRet[]=$tabR;
				if ($last) {
					if ($source==175 && !@isset($tabLast[$tabTel['typeTel']][1]))		@$tabLast[$tabTel['typeTel']][1]=$tabR;
					elseif(($source==118 ||
							$source==250 ||
							$source==253) && !@isset($tabLast[$tabTel['typeTel']][2]))	@$tabLast[$tabTel['typeTel']][2]=$tabR;
					elseif ($source<>2	&& !@isset($tabLast[$tabTel['typeTel']][3]))	@$tabLast[$tabTel['typeTel']][3]=$tabR;
					elseif ($source==2	&& !@isset($tabLast[$tabTel['typeTel']][4]))	@$tabLast[$tabTel['typeTel']][4]=$tabR;
				}
			}

		} elseif ($this->accesDistant) {

            $this->enCache=false;
			$tabPost = array(
			    'p_ACTION'=>'',
				'p_ORDRE'=>'AfficheRes',
				'a_PAGE'=>'1',
				'a_TAG'=>'',
				'a_OccRecherche'=>'',
				'typeRecherche'=>'express',
				'satellite'=>'siret',
				'a_activ'=>'',
				'a_rai_soc'=>'',
				'a_naf'=>'',
				'a_siren'=>$siret,
				'a_tel'=>'',
				'a_geo'=>'',
				'typeTri'=>'',
				'ordreTri'=>'',
				'a_session'=>'',
            );
			//$page=getUrl($this->url,$this->cookie,'',$this->referer, false, '', '', 3);
			$page=getUrl($this->url,$this->cookie,$tabPost,$this->referer,false,'','',3);
			$this->referer=$this->url;
			$this->body=$page['body'];
			$this->codeRetour=$page['code'];

			$nbResults=0;
			if (preg_match('/<b class="total_responses_nr">(.*)réponses<\/b>/Uisu', $this->body, $matches))
				$nbResults=trim(strtr(strip_tags($matches[1]), array('&nbsp;'=>'','&ndash;'=>'')));

			if ($nbResults>0) {
				$tabResultsHtml=explode('<div class="results_part1">', $this->body);
				for ($i=1; isset($tabResultsHtml[$i]);$i++) {
					$res=$tabTel=array();
					$body=$tabResultsHtml[$i];
					$res['nom']=trim(htm2txt(@getTextInHtml($body, '<div class="results_title">', '_title">', '</div>')));
					$res['adresse']=trim(htm2txt(@getTextInHtml($body, '<div class="coordonnees">','<div>','<table id="t_coord_')));

					$res['urlSite']=trim(htm2txt(@getTextInHtml($body, '<b class="siteweb">Site Web :</b>&nbsp;', "javascript:SiteURL('", "','")));
					$res['urlMail']=trim(htm2txt(@getTextInHtml($body, '<b>E-mail :</b>', "&amp;mail=", "', ")));
					$res['urlLogo']=trim(htm2txt(@getTextInHtml($body, '<div class="results_inset_logo">', '" src="', '" border="')));
					$res['tefet']=trim(htm2txt(@getTextInHtml($body, '<b>Effectif établ : </b>','</b>','</div>')));

					$res['tefet']=trim(htm2txt(@getTextInHtml($body, '<b>Effectif établ : </b>','</b>','</div>')));
					$res['siret']=trim(htm2txt(@getTextInHtml($body, '<b>Siret : </b>','</b>','</div>')));
					$res['nafet']=trim(htm2txt(strip_tags(@getTextInHtml($body, '<b>Code NAF : </b>','</b>','</div>'))));

					$res['domaines']=trim(preg_replace('/ +/', ' ', preg_replace('/\r+|\n+|\s+/',' ',htm2txt(strip_tags(@getTextInHtml($body, '<div class="puce_domaine">','<strong>','</div>'))))));

					if ($res['urlSite']<>'') {
						$this->iDb->insert('telephonie', array(
						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'dateProvPartenaire'=>date('Ymd'),
							'typeTel'=>'web',
							'infoTel'=>$res['urlSite'],
							'telephone'=>0,
							'actif'=>1,
							'partenaire'=>253,
                        ));
  						$tabRet[] = array(
  						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'typeTel'=>'web',
							'infoTel'=>$res['urlSite'],
							'telephone'=>0,
						);
					}
					if ($res['urlLogo']<>'') {
						$this->iDb->insert('telephonie', array(
						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'dateProvPartenaire'=>date('Ymd'),
							'typeTel'=>'logo',
							'infoTel'=>$res['urlLogo'],
							'telephone'=>0,
							'actif'=>1,
							'partenaire'=>253,
                        ));
  						$tabRet[] = array(
  						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'typeTel'=>'logo',
							'infoTel'=>$res['urlLogo'],
							'telephone'=>0,
						);
					}
					if ($res['domaines']<>'') {
						$this->iDb->insert('telephonie', array(
						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'dateProvPartenaire'=>date('Ymd'),
							'typeTel'=>'domaines',
							'infoTel'=>$res['domaines'],
							'telephone'=>0,
							'actif'=>1,
							'partenaire'=>253,
                        ));
  						$tabRet[]=array(
  						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'typeTel'=>'domaines',
							'infoTel'=>$res['domaines'],
							'telephone'=>0,
						);
					}
					if ($res['urlMail']<>'') {
						$this->iDb->insert('telephonie', array(
						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'dateProvPartenaire'=>date('Ymd'),
							'typeTel'=>'mail',
							'infoTel'=>$res['urlMail'],
							'telephone'=>0,
							'actif'=>1,
							'partenaire'=>253,
                        ));
						$tabRet[]=array(
						    'siren'=>$siren,
							'nic'=>substr($res['siret'],-5),
							'typeTel'=>'mail',
							'infoTel'=>$res['urlMail'],
							'telephone'=>0,
                        );
					}

					if (preg_match_all('/<tr>(?:.*)<th>(?:.*)<span>(.*)(tél|fax)(?:.*)<\/span>(?:.*)<\/th>(?:.*)<td>(?:.*)<span>(.*)<\/span>(?:.*)<\/td>(?:.*)<\/tr>/Uis', $body, $matches)) {
						foreach ($matches[2] as $j=>$tmp) {
							$lib=$tmp;
							$precis=trim(strtr($matches[1][$j], array('-'=>' ')));
							$num=trim(strtr($matches[3][$j],array('&nbsp;'=>'','<br />'=>'')));
							$tabTel["$lib-$num"]=array('telFax'=>$lib,'type'=>$precis, 'telNum'=>$num);
						}
						$tabTel=array_values($tabTel);


						foreach ($tabTel as $tabT) {
							$tabRet[]=array(
							    'siren'=>$siren,
                                'nic'=>substr($res['siret'],-5),
								'typeTel'=>trimAccent($tabT['telFax']),
								'infoTel'=>$tabT['type'],
								'telephone'=>$tabT['telNum'],
								'actif'=>1,
							);
							$this->iDb->insert('telephonie', array(
							    'siren'=>$siren,
								'nic'=>substr($res['siret'],-5),
								'dateProvPartenaire'=>date('Ymd'),
								'typeTel'=>trimAccent($tabT['telFax']),
								'infoTel'=>$tabT['type'],
								'telephone'=>$tabT['telNum'],
								'actif'=>1,
								'partenaire'=>253,
                            ));
						}
					}
				}
			}
		}

		if ($last) {
			$tabRet=array();
			foreach($tabLast as $typeTel=>$tabPriorite) {
				ksort($tabPriorite);
				$tabRet[]=current($tabPriorite);
			}
		}

		return $tabRet;
	}

}