<?php

define('BDF_HOST','http://protectel.scrypto.fr');
define('BDF_PAGE','/iBDF/RequeteLanceur.php');
define('BDF_FILETIME', 8);

require_once 'common/curl.php';

// --------------------------------------------------------------------------- //
// enleveLiens
// --------------------------------------------------------------------------- //
function enleveLiens($contenu, $discriminant)
{
    $pos1 = 0;
    while (($pos1 = strpos($contenu, '<a ', $pos1)) != false) {
        $pos2 = strpos($contenu, '</a>', $pos1);
        if ($pos2 == false) {
            break;
        }
        $pos2 += 4;
        if (substr_count($contenu, $discriminant, $pos1, $pos2 - $pos1) > 0) {
            $pos3 = strpos($contenu, '>', $pos1) + 1;
            if ($pos3 == $pos2 - 1) {
                $pos1  = $pos2;
                continue;
            }
            $rep = strip_tags(substr($contenu, $pos3, $pos2 - $pos3 - 4));
            $contenu = substr_replace($contenu, $rep, $pos1, $pos2 - $pos1);
            $pos1 += strlen($rep);
        } else {
            $pos1 = $pos2;
        }
    }

    return $contenu;
}

function bdf_loadpage($url)
{
	global $firephp;
	$firephp->log($url, 'url');
	$page = getUrl($url, '', '', '', false, '', '',15);
	//Fichier non disponible
	if($page['code']==408 || $page['code']==400){
		$output = false;
	//Ecriture du fichier sur le serveur en local
	}else{
		$body = $page['body'];
		$output = $body;
	}

	$output = utf8_encode($output);

	$output = bdf_removeblock($output);
	$output = removeTag('html', $output, true, false);
	$output = removeTag('head', $output, true, false);
	$output = removeTag('body', $output, true, false);
	$output = removeTag('meta', $output, false, false);
	$output = removeTag('title', $output, true, true);
	$output = removeTag('script', $output, true, true);

	$output = changeLinkToLowerCase($output);
	$output = bdf_lien_siren($output);
	$output = stripslashes($output);

	$firephp->log($output, 'content');

	return $output;
}

function bdf_removeblock($content)
{
    $output = $content;

    $output = enleveLiens($output, '#nullepart');

    $output = enleveLiens($output, 'window.print');

    $output = str_replace('\'/FIBEN/',
                          '\'/fiben/', $output);
    return $output;
}

function removeTag($balise, $content, $endOfTag = true, $removeContent = true)
{
	if( $endOfTag )
	{
		if( $removeContent)
			$output = preg_replace(
				'@<'.$balise.'[^>]*?>.*?</'.$balise.'>@si',
				'',
				$content
			);
		else
			$output = preg_replace(
				array('@<'.$balise.'[^>]*?>@', '@</'.$balise.'>@'),
				'',
				$content
			);
	}
	else
	{
		$output = preg_replace(
				'@<'.$balise.'[^>]*?>@',
				'',
				$content
			);
	}
	return $output;
}

function changeLinkToLowerCase($content)
{
	global $firephp;
	//$pattern = "/\< *[img][^\>]*[href] *= *[\"\']{0,1}([^\"\'\ >]*)/i";
	$pattern = '/(\<img[^>].*?>)/ie';
	$replace = "strtolower('\\1')";
	$content = preg_replace($pattern,$replace,$content);

	$pattern = '/(\<script[^>].*?>)/ie';
	$replace = "strtolower('\\1')";
	$content = preg_replace($pattern,$replace,$content);

	$pattern = '/(\<link[^>].*?>)/ie';
	$replace = "strtolower('\\1')";
	$content = preg_replace($pattern,$replace,$content);

	$pattern = '/(\<link[^>].*?>)/ie';
	$replace = "strtolower('\\1')";
	$content = preg_replace($pattern,$replace,$content);

	$pattern = '/(\<table[^>].*?>)/ie';
	$replace = "strtolower('\\1')";
	$content = preg_replace($pattern,$replace,$content);

	$content = stripslashes($content);
	//$firephp->log($content, 'content');

	return $content;
}

function bdf_lien_module($id, $service = 'fiben', $req = '', $rech = array() )
{
	global $firephp;
	$firephp->log($req,'req');

	$func_module = 'bdf_modules_'.$service;
	$modules = $func_module();
	$params = array();
	$firephp->log($rech, 'rech');
	if(is_array($rech) && count($rech)>0){
		foreach($rech as $key => $val)
		{
			${$key} = $val;
		}
	}

	//Paramètres URL
	foreach($modules[$id]['params'] as $mparams => $fparams)
	{
		$addParams = array();
		//Paramètres de chaque fonction
		$func_params = array();
		if(is_array($fparams)){
			foreach($fparams as $fparam)
			{
				$firephp->log(${$fparam},$fparam);
				$func_params[] = ${$fparam};
			}
		}

		//$firephp->log($mparams, 'mparams');
		//$firephp->log($func_params, 'func_params');

		$addParams = call_user_func_array('bdf_param_'.$mparams, $func_params);
		//Rassemblement de tout les paramètres
		$params = array_merge($params, $addParams);
	}
	//Paramètres sous format URL
	$output = '';
	foreach($params as $key => $value)
	{
		if(!empty($output)) $output.= '&';
		$output.= $key.'='.$value;
	}
	$firephp->log($output, 'output');
	return BDF_HOST.BDF_PAGE.'?'.$output;
}

function bdf_lien_siren($c)
{
    $p = '/(width="160" class="clFond".*)([0-9]{3} [0-9]{3} [0-9]{3} [0-9]{5})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

    $p = '/(class="clGrasFond".*)([0-9]{3} [0-9]{3} [0-9]{3})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

    $p = '/(width="130" class="clFond".*)([0-9]{3} [0-9]{3} [0-9]{3})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

    $p = '/(class="clFond" width="80".*)([0-9]{3} [0-9]{3} [0-9]{3})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

    $p = '/(class="clTexte" width="184".*)([0-9]{3} [0-9]{3} [0-9]{3})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

    $p = '/(class="clFond" width="255".*)([0-9]{3} [0-9]{3} [0-9]{3})/';
    $r = '$1<a href="./?page=identite&siret=$2">$2</a>';
    $c = preg_replace($p, $r, $c);

	$c = stripslashes($c);
    return $c;
}

function bdf_lien_clebdf()
{
	//Détection des clebdf

	//Remplacement du lien
}

function bdf_lien_plusinfos()
{



}

function bdf_param_banque()
{
	return array(
		'Etablissement' => '12345',
		'Guichet'		=> '00001',
	);
}

function bdf_param_utilisateur()
{
	return array(
		'Utilisateur' 	=> 'Dupont', //$_SESSION['tabInfo']['login']
		'MDP'			=> '', //$_SESSION['tabInfo']['password']
	);
}

function bdf_param_profil()
{
	return array(
		'Profil' => 'Agence',
	);
}

function bdf_param_service($service = 'FIBEN')
{
	return array(
		'Service' => strtoupper($service),
	);
}

function bdf_param_req($req)
{
	global $firephp;
	$firephp->log($req, 'req');
	return array(
		'Req' => $req,
	);
}

function bdf_param_typeop($id)
{
	return array(
		'TypeOp' => $id,
	);
}

function bdf_param_denom($denom)
{
	return array(
		'Denom' => $denom,
	);
}

function bdf_param_type($type)
{
	return array(
		'Type' => $type,
	);
}

function bdf_param_code($code)
{
	return array(
		'Code' => $code,
	);
}

function bdf_param_rechet($rechet)
{
	if(empty($rechet)) $output = 'N';
	else $output = 'O';

	return array(
		'RechEt' => $output,
	);
}

function bdf_param_ape($ape)
{
	return array(
		'APE' => $ape,
	);
}

function bdf_modules_fiben()
{
	return array(
		'27' => array(
			'titre' => '27. Panorama',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'28'=> array(
			'titre' => '28. Concours Bancaires',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'29'=> array(
			'titre' => '29. Impayés',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'30'=> array(
			'titre' => '30. Concours Bancaires gpe',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'37'=> array(
			'titre' => '37. Cotation',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'38'=> array(
			'titre' => '38. Score',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'40'=> array(
			'titre' => '40. Relations Bancaires',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'41'=> array(
			'titre' => '41. Etablissement secondaires',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'45'=> array(
			'titre' => '45. Jugements',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'51'=> array(
			'titre' => '51. Dirigeants',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'52'=> array(
			'titre' => '52. Capital',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req') ,
				'typeop'		=> array('id')
			),
		),
		'54'=> array(
			'titre' => '54. Participation',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'56'=> array(
			'titre' => '56. Fonction De Direction',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'57'=> array(
			'titre' => '57. Orga liens financiers',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'58'=> array(
			'titre' => '58. Orga liens de direction',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'60'=> array(
			'titre' => '60. Bilan Synthètique',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'62'=> array(
			'titre' => '62. SIG',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'63'=> array(
			'titre' => '63. Tableaux des flux',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'64'=> array(
			'titre' => '64. Ratios',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'66'=> array(
			'titre' => '66. Chiffres Consolidés',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'67'=> array(
			'titre' => '67. Comptes Consolidés',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'68'=> array(
			'titre' => '68. Dossier Comptable',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'69'=> array(
			'titre' => '69. Liasse Fiscale',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'70'=> array(
			'titre' => '70. Eléments de risque',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'72'=> array(
			'titre' => '72. Diagnostic Synthètique',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'DE'=> array(
			'titre' => 'DE. Dossier Découverte',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'07'=> array(
			'titre' => '07. Recherche',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array(),
				'typeop'		=> array('id'),
				'denom'			=> array('denom'),
				'type'			=> array('type'),
				'code'			=> array('code'),
				'rechet'		=> array('rechet'),
				'ape'			=> array('ape'),
			),
			'liste' => false,
		),

	);
}


function bdf_modules_fcc()
{
	return array(
		'G'=> array(
			'titre' => 'FCC Simplifié',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array('service'),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
		'D'=> array(
			'titre' => 'FCC Détaillé',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array('service'),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
	);

}

function bdf_modules_ficp()
{
	return array(
		'G'=> array(
			'titre' => 'FICP',
			'params' => array(
				'banque'		=> array(),
				'utilisateur'	=> array(),
				'profil'		=> array(),
				'service'		=> array('service'),
				'req' 			=> array('req'),
				'typeop'		=> array('id')
			),
		),
	);
}

function bdf_filetimeover($fichier)
{
	$timeover = false;
	$dateFile = filemtime($fichier);
	$now = mktime(date('G'), date('i'), date('s'), date('m') , date('d'), date('Y'));
	$maxTime = mktime(date('G',$dateFile)+BDF_FILETIME, date('i',$dateFile), date('s',$dateFile), date("m",$dateFile), date("d",$dateFile), date("Y",$dateFile));
	if($now>$maxTime) $timeover = true;
	return $timeover;
}