Ajout du framework SD
This commit is contained in:
parent
543c1aa258
commit
e8304e4275
763
library/framework/common/chiffres.php
Normal file
763
library/framework/common/chiffres.php
Normal file
@ -0,0 +1,763 @@
|
||||
<?
|
||||
|
||||
class WChiffes {
|
||||
|
||||
private static $tabChiffresEnLEttres = array( 0=>'zéro',
|
||||
1=>'un',
|
||||
2=>'deux',
|
||||
3=>'trois',
|
||||
4=>'quatre',
|
||||
5=>'cinq',
|
||||
6=>'six',
|
||||
7=>'sept',
|
||||
8=>'huit',
|
||||
9=>'neuf',
|
||||
10=>'dix',
|
||||
11=>'onze',
|
||||
12=>'douze',
|
||||
13=>'treize',
|
||||
14=>'quatorze',
|
||||
15=>'quinze',
|
||||
16=>'seize',
|
||||
17=>'dix sept',
|
||||
18=>'dix huit',
|
||||
19=>'dix neuf',
|
||||
20=>'vingt',
|
||||
21=>'vingt et un',
|
||||
22=>'vingt deux',
|
||||
23=>'vingt trois',
|
||||
24=>'vingt quatre',
|
||||
25=>'vingt cinq',
|
||||
26=>'vingt six',
|
||||
27=>'vingt sept',
|
||||
28=>'vingt huit',
|
||||
29=>'vingt neuf',
|
||||
30=>'trente',
|
||||
40=>'quarante',
|
||||
50=>'cinquante',
|
||||
60=>'soixante',
|
||||
70=>'soixante dix',
|
||||
80=>'quatre vingt',
|
||||
90=>'quatre vingt dix');
|
||||
|
||||
public function ChiffresEnLettres($chiffre) {
|
||||
return array_search($chiffre, self::$tabChiffresEnLEttres);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
define('NEL_SEPTANTE', 0x0001);
|
||||
define('NEL_HUITANTE', 0x0002);
|
||||
define('NEL_OCTANTE', 0x0004);
|
||||
define('NEL_NONANTE', 0x0008);
|
||||
define('NEL_BELGIQUE', NEL_SEPTANTE|NEL_NONANTE);
|
||||
define('NEL_VVF', NEL_SEPTANTE|NEL_HUITANTE|NEL_NONANTE);
|
||||
define('NEL_ARCHAIQUE', NEL_SEPTANTE|NEL_OCTANTE|NEL_NONANTE);
|
||||
define('NEL_SANS_MILLIARD', 0x0010);
|
||||
define('NEL_AVEC_ZILLIARD', 0x0020);
|
||||
define('NEL_TOUS_ZILLIONS', 0x0040);
|
||||
define('NEL_RECTIF_1990', 0x0100);
|
||||
define('NEL_ORDINAL', 0x0200);
|
||||
define('NEL_NIEME', 0x0400);
|
||||
|
||||
|
||||
# Le tableau associatif $NEL contient toutes les variables utilisées
|
||||
# de façon globale dans ce module. ATTENTION : ce nom est assez court,
|
||||
# et cela pourrait poser des problèmes de collision avec une autre
|
||||
# variable si plusieurs modules sont inclus dans le même programme.
|
||||
|
||||
$NEL = array(
|
||||
'1-99' => array(
|
||||
# 0-19
|
||||
'', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept',
|
||||
'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze',
|
||||
'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf',
|
||||
# 20-29
|
||||
'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois',
|
||||
'vingt-quatre', 'vingt-cinq', 'vingt-six',
|
||||
'vingt-sept', 'vingt-huit', 'vingt-neuf',
|
||||
# 30-39
|
||||
'trente', 'trente et un', 'trente-deux', 'trente-trois',
|
||||
'trente-quatre', 'trente-cinq', 'trente-six',
|
||||
'trente-sept', 'trente-huit', 'trente-neuf',
|
||||
# 40-49
|
||||
'quarante', 'quarante et un', 'quarante-deux', 'quarante-trois',
|
||||
'quarante-quatre', 'quarante-cinq', 'quarante-six',
|
||||
'quarante-sept', 'quarante-huit', 'quarante-neuf',
|
||||
# 50-59
|
||||
'cinquante', 'cinquante et un', 'cinquante-deux', 'cinquante-trois',
|
||||
'cinquante-quatre', 'cinquante-cinq', 'cinquante-six',
|
||||
'cinquante-sept', 'cinquante-huit', 'cinquante-neuf',
|
||||
# 60-69
|
||||
'soixante', 'soixante et un', 'soixante-deux', 'soixante-trois',
|
||||
'soixante-quatre', 'soixante-cinq', 'soixante-six',
|
||||
'soixante-sept', 'soixante-huit', 'soixante-neuf',
|
||||
# 70-79
|
||||
'septante', 'septante et un', 'septante-deux', 'septante-trois',
|
||||
'septante-quatre', 'septante-cinq', 'septante-six',
|
||||
'septante-sept', 'septante-huit', 'septante-neuf',
|
||||
# 80-89
|
||||
'huitante', 'huitante et un', 'huitante-deux', 'huitante-trois',
|
||||
'huitante-quatre', 'huitante-cinq', 'huitante-six',
|
||||
'huitante-sept', 'huitante-huit', 'huitante-neuf',
|
||||
# 90-99
|
||||
'nonante', 'nonante et un', 'nonante-deux', 'nonante-trois',
|
||||
'nonante-quatre', 'nonante-cinq', 'nonante-six',
|
||||
'nonante-sept', 'nonante-huit', 'nonante-neuf'
|
||||
),
|
||||
|
||||
'illi' => array('', 'm', 'b', 'tr', 'quatr', 'quint', 'sext'),
|
||||
'maxilli' => 0, # voir plus loin
|
||||
'de_maxillions' => '', # voir plus loin
|
||||
|
||||
'septante' => false, # valeurs possibles : (false|true)
|
||||
'huitante' => false, # valeurs possibles : (false|true|'octante')
|
||||
'nonante' => false, # valeurs possibles : (false|true)
|
||||
'zillions' => false, # valeurs possibles : (false|true)
|
||||
'zilliard' => 1, # valeurs possibles : (0|1|2)
|
||||
'rectif' => false, # valeurs possibles : (false|true)
|
||||
'ordinal' => false, # valeurs possibles : (false|true|'nieme')
|
||||
|
||||
'separateur' => ' '
|
||||
);
|
||||
|
||||
# Si le tableau $NEL['illi'] s'arrête à 'sext', alors les deux valeurs
|
||||
# suivantes sont respectivement '6' et ' de sextillions'.
|
||||
$NEL['maxilli'] = count($NEL['illi']) - 1;
|
||||
$NEL['de_maxillions'] = " de {$NEL['illi'][$NEL['maxilli']]}illions";
|
||||
|
||||
function enlettres_options($options, $separateur=NULL)
|
||||
{
|
||||
global $NEL;
|
||||
|
||||
if ($options !== NULL) {
|
||||
$NEL['septante'] = ($options & NEL_SEPTANTE) ? true : false;
|
||||
$NEL['huitante'] =
|
||||
($options & NEL_OCTANTE) ? 'octante' :
|
||||
(($options & NEL_HUITANTE) ? true : false);
|
||||
$NEL['nonante'] = ($options & NEL_NONANTE) ? true : false;
|
||||
$NEL['zillions'] = ($options & NEL_TOUS_ZILLIONS) ? true : false;
|
||||
$NEL['zilliard'] =
|
||||
($options & NEL_AVEC_ZILLIARD) ? 2 :
|
||||
(($options & NEL_SANS_MILLIARD) ? 0 : 1);
|
||||
$NEL['rectif'] = ($options & NEL_RECTIF_1990) ? true : false;
|
||||
$NEL['ordinal'] =
|
||||
($options & NEL_NIEME) ? 'nieme' :
|
||||
(($options & NEL_ORDINAL) ? true : false);
|
||||
}
|
||||
|
||||
if ($separateur !== NULL) {
|
||||
$NEL['separateur'] = $separateur;
|
||||
}
|
||||
}
|
||||
|
||||
function enlettres_par3($par3)
|
||||
{
|
||||
global $NEL;
|
||||
|
||||
if ($par3 == 0) return '';
|
||||
|
||||
$centaine = floor($par3 / 100);
|
||||
$par2 = $par3 % 100;
|
||||
$dizaine = floor($par2 / 10);
|
||||
|
||||
# On traite à part les particularités du français de référence
|
||||
# 'soixante-dix', 'quatre-vingts' et 'quatre-vingt-dix'.
|
||||
$nom_par2 = NULL;
|
||||
switch ($dizaine) {
|
||||
case 7:
|
||||
if ($NEL['septante'] === false) {
|
||||
if ($par2 == 71) $nom_par2 = 'soixante et onze';
|
||||
else $nom_par2 = 'soixante-' . $NEL['1-99'][$par2 - 60];
|
||||
}
|
||||
break;
|
||||
case 8:
|
||||
if ($NEL['huitante'] === false) {
|
||||
if ($par2 == 80) $nom_par2 = 'quatre-vingts';
|
||||
else $nom_par2 = 'quatre-vingt-' . $NEL['1-99'][$par2 - 80];
|
||||
}
|
||||
break;
|
||||
case 9:
|
||||
if ($NEL['nonante'] === false) {
|
||||
$nom_par2 = 'quatre-vingt-' . $NEL['1-99'][$par2 - 80];
|
||||
}
|
||||
break;
|
||||
}
|
||||
if ($nom_par2 === NULL) {
|
||||
$nom_par2 = $NEL['1-99'][$par2];
|
||||
if (($dizaine == 8) and ($NEL['huitante'] === 'octante')) {
|
||||
$nom_par2 = str_replace('huitante', 'octante', $nom_par2);
|
||||
}
|
||||
}
|
||||
|
||||
# Après les dizaines et les unités, il reste à voir les centaines
|
||||
switch ($centaine) {
|
||||
case 0: return $nom_par2;
|
||||
case 1: return rtrim("cent {$nom_par2}");
|
||||
}
|
||||
|
||||
# Assertion : $centaine = 2 .. 9
|
||||
$nom_centaine = $NEL['1-99'][$centaine];
|
||||
if ($par2 == 0) return "{$nom_centaine} cents";
|
||||
return "{$nom_centaine} cent {$nom_par2}";
|
||||
}
|
||||
|
||||
function enlettres_zilli($idx)
|
||||
{
|
||||
# Noms des 0ème à 9ème zillions
|
||||
static $petit = array(
|
||||
'n', 'm', 'b', 'tr', 'quatr', 'quint', 'sext', 'sept', 'oct', 'non'
|
||||
);
|
||||
# Composantes des 10ème à 999ème zillions
|
||||
static $unite = array(
|
||||
'<', 'un<', 'duo<', 'tre<sé',
|
||||
'quattuor<', 'quin<', 'se<xsé',
|
||||
'septe<mné', 'octo<', 'nove<mné'
|
||||
);
|
||||
static $dizaine = array(
|
||||
'', 'né>déci<', 'ms>viginti<', 'ns>triginta<',
|
||||
'ns>quadraginta<', 'ns>quinquaginta<', 'né>sexaginta<',
|
||||
'né>septuaginta<', 'mxs>octoginta<', 'é>nonaginta<'
|
||||
);
|
||||
static $centaine = array(
|
||||
'>', 'nxs>cent', 'né>ducent', 'ns>trécent',
|
||||
'ns>quadringent', 'ns>quingent', 'né>sescent',
|
||||
'né>septingent', 'mxs>octingent', 'é>nongent'
|
||||
);
|
||||
|
||||
# Règles d'assimilation aux préfixes latins, modifiées pour accentuer
|
||||
# un éventuel 'é' de fin de préfixe.
|
||||
# (1) Si on trouve une lettre deux fois entre < > on la garde.
|
||||
# S'il y a plusieurs lettres dans ce cas, on garde la première.
|
||||
# (2) Sinon on efface tout ce qui est entre < >.
|
||||
# (3) On remplace "treé" par "tré", "seé" par "sé", "septeé" par "septé"
|
||||
# et "noveé" par "nové".
|
||||
# (4) En cas de dizaine sans centaine, on supprime la voyelle en trop.
|
||||
# Par exemple "déciilli" devient "décilli" et "trigintailli" devient
|
||||
# "trigintilli".
|
||||
#
|
||||
# Il est à noter que ces règles PERL (en particulier la première qui
|
||||
# est la plus complexe) sont *très* fortement inspirées du programme
|
||||
# de Nicolas Graner. On pourrait même parler de plagiat s'il n'avait
|
||||
# pas été au courant que je reprenais son code.
|
||||
# Voir <http://www.graner.net/nicolas/nombres/nom.php>
|
||||
# et <http://www.graner.net/nicolas/nombres/nom-exp.php>
|
||||
#
|
||||
static $recherche = array(
|
||||
'/<[a-zé]*?([a-zé])[a-zé]*\1[a-zé]*>/', # (1)
|
||||
'/<[a-zé]*>/', # (2)
|
||||
'/eé/', # (3)
|
||||
'/[ai]illi/' # (4)
|
||||
);
|
||||
static $remplace = array(
|
||||
'\\1', # (1)
|
||||
'', # (2)
|
||||
'é', # (3)
|
||||
'illi' # (4)
|
||||
);
|
||||
|
||||
$nom = '';
|
||||
while ($idx > 0) {
|
||||
$p = $idx % 1000;
|
||||
$idx = floor($idx/1000);
|
||||
|
||||
if ($p < 10) {
|
||||
$nom = $petit[$p] . 'illi' . $nom;
|
||||
} else {
|
||||
$nom = $unite[$p % 10] . $dizaine[floor($p/10) % 10]
|
||||
. $centaine[floor($p/100)] . 'illi' . $nom;
|
||||
}
|
||||
}
|
||||
return preg_replace($recherche, $remplace, $nom);
|
||||
}
|
||||
|
||||
function enlettres_illions($idx)
|
||||
{
|
||||
global $NEL;
|
||||
|
||||
if ($idx == 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($NEL['zillions']) {
|
||||
return enlettres_zilli($idx) . 'ons';
|
||||
}
|
||||
|
||||
$suffixe = '';
|
||||
while ($idx > $NEL['maxilli']) {
|
||||
$idx -= $NEL['maxilli'];
|
||||
$suffixe .= $NEL['de_maxillions'];
|
||||
}
|
||||
return "{$NEL['illi'][$idx]}illions{$suffixe}";
|
||||
}
|
||||
|
||||
function enlettres_avec_illiards($idx)
|
||||
{
|
||||
global $NEL;
|
||||
|
||||
if ($idx == 0) return false;
|
||||
switch ($NEL['zilliard']) {
|
||||
case 0: return false;
|
||||
case 2: return true;
|
||||
}
|
||||
return ($idx == 1);
|
||||
}
|
||||
|
||||
function enlettres($nombre, $options=NULL, $separateur=NULL)
|
||||
{
|
||||
global $NEL;
|
||||
|
||||
if ($options !== NULL or $separateur !== NULL) {
|
||||
$NELsave = $NEL;
|
||||
enlettres_options($options, $separateur);
|
||||
$nom = enlettres($nombre);
|
||||
$NEL = $NELsave;
|
||||
return $nom;
|
||||
}
|
||||
|
||||
# On ne garde que les chiffres, puis on supprime les 0 du début
|
||||
$nombre = preg_replace('/[^0-9]/', '', $nombre);
|
||||
$nombre = ltrim($nombre, '0');
|
||||
|
||||
if ($nombre == '') {
|
||||
if ($NEL['ordinal'] === 'nieme') return 'zéroïème';
|
||||
else return 'zéro';
|
||||
}
|
||||
|
||||
$table_noms = array();
|
||||
for ($idx = 0; $nombre != ''; $idx++) {
|
||||
$par6 = (int)((strlen($nombre) < 6) ? $nombre : substr($nombre, -6));
|
||||
$nombre = substr($nombre, 0, -6);
|
||||
|
||||
if ($par6 == 0) continue;
|
||||
|
||||
$nom_par3_sup = enlettres_par3(floor($par6 / 1000));
|
||||
$nom_par3_inf = enlettres_par3($par6 % 1000);
|
||||
|
||||
$illions = enlettres_illions($idx);
|
||||
if (enlettres_avec_illiards($idx)) {
|
||||
if ($nom_par3_inf != '') {
|
||||
$table_noms[$illions] = $nom_par3_inf;
|
||||
}
|
||||
if ($nom_par3_sup != '') {
|
||||
$illiards = preg_replace('/illion/', 'illiard', $illions, 1);
|
||||
$table_noms[$illiards] = $nom_par3_sup;
|
||||
}
|
||||
} else {
|
||||
switch($nom_par3_sup) {
|
||||
case '':
|
||||
$nom_par6 = $nom_par3_inf;
|
||||
break;
|
||||
case 'un':
|
||||
$nom_par6 = rtrim("mille {$nom_par3_inf}");
|
||||
break;
|
||||
default:
|
||||
$nom_par3_sup = preg_replace('/(vingt|cent)s/', '\\1', $nom_par3_sup);
|
||||
$nom_par6 = rtrim("{$nom_par3_sup} mille {$nom_par3_inf}");
|
||||
break;
|
||||
}
|
||||
$table_noms[$illions] = $nom_par6;
|
||||
}
|
||||
}
|
||||
|
||||
$nom_enlettres = '';
|
||||
foreach ($table_noms as $nom => $nombre) {
|
||||
##
|
||||
# $nombre est compris entre 'un' et
|
||||
# 'neuf cent nonante-neuf mille neuf cent nonante-neuf'
|
||||
# (ou variante avec 'quatre-vingt-dix-neuf')
|
||||
##
|
||||
# $nom peut valoir '', 'millions', 'milliards', 'billions', ...
|
||||
# 'sextillions', 'sextilliards', 'millions de sextillions',
|
||||
# 'millions de sextilliards', etc.
|
||||
##
|
||||
|
||||
# Rectifications orthographiques de 1990
|
||||
if ($NEL['rectif']) {
|
||||
$nombre = str_replace(' ', '-', $nombre);
|
||||
}
|
||||
|
||||
# Nom (éventuel) et accord (éventuel) des substantifs
|
||||
$nom = rtrim("{$nombre} {$nom}");
|
||||
if ($nombre == 'un') {
|
||||
# Un seul million, milliard, etc., donc au singulier
|
||||
# noter la limite de 1 remplacement, pour ne supprimer que le premier 's'
|
||||
# dans 'billions de sextillions de sextillions'
|
||||
$nom = preg_replace('/(illion|illiard)s/', '\\1', $nom, 1);
|
||||
}
|
||||
|
||||
# Ajout d'un séparateur entre chaque partie
|
||||
if ($nom_enlettres == '') {
|
||||
$nom_enlettres = $nom;
|
||||
} else {
|
||||
$nom_enlettres = $nom . $NEL['separateur'] . $nom_enlettres;
|
||||
}
|
||||
}
|
||||
|
||||
if ($NEL['ordinal'] === false) {
|
||||
# Nombre cardinal : le traitement est fini
|
||||
return $nom_enlettres;
|
||||
}
|
||||
|
||||
# Aucun pluriel dans les ordinaux
|
||||
$nom_enlettres =
|
||||
preg_replace('/(cent|vingt|illion|illiard)s/', '\\1', $nom_enlettres);
|
||||
|
||||
if ($NEL['ordinal'] !== 'nieme') {
|
||||
# Nombre ordinal simple (sans '-ième')
|
||||
return $nom_enlettres;
|
||||
}
|
||||
|
||||
if ($nom_enlettres === 'un') {
|
||||
# Le féminin n'est pas traité ici. On fait la supposition
|
||||
# qu'il est plus facile de traiter ce cas à part plutôt
|
||||
# que de rajouter une option rien que pour ça.
|
||||
return 'premier';
|
||||
}
|
||||
|
||||
switch (substr($nom_enlettres, -1)) {
|
||||
case 'e':
|
||||
# quatre, onze à seize, trente à nonante, mille
|
||||
# exemple : quatre -> quatrième
|
||||
return substr($nom_enlettres, 0, -1) . 'ième';
|
||||
case 'f':
|
||||
# neuf -> neuvième
|
||||
return substr($nom_enlettres, 0, -1) . 'vième';
|
||||
case 'q':
|
||||
# cinq -> cinquième
|
||||
return $nom_enlettres . 'uième';
|
||||
}
|
||||
|
||||
# Tous les autres cas.
|
||||
# Exemples: deuxième, troisième, vingtième, trente et unième,
|
||||
# neuf centième, un millionième, quatre-vingt milliardième.
|
||||
return $nom_enlettres . 'ième';
|
||||
}
|
||||
|
||||
function enchiffres_petit($mot)
|
||||
{
|
||||
static $petit = array(
|
||||
# 1-16
|
||||
'un' => 1,
|
||||
'deux' => 2,
|
||||
'trois' => 3,
|
||||
'quatre' => 4,
|
||||
'cinq' => 5,
|
||||
'six' => 6,
|
||||
'sept' => 7,
|
||||
'huit' => 8,
|
||||
'neuf' => 9,
|
||||
'dix' => 10,
|
||||
'onze' => 11,
|
||||
'douze' => 12,
|
||||
'treize' => 13,
|
||||
'quatorze' => 14,
|
||||
'quinze' => 15,
|
||||
'seize' => 16,
|
||||
# 20-90
|
||||
'vingt' => 20,
|
||||
'vingts' => 20,
|
||||
'trente' => 30,
|
||||
'quarante' => 40,
|
||||
'cinquante' => 50,
|
||||
'soixante' => 60,
|
||||
'septante' => 70,
|
||||
'huitante' => 80,
|
||||
'octante' => 80,
|
||||
'nonante' => 90,
|
||||
# 100, 1000
|
||||
'cent' => 100,
|
||||
'cents' => 100,
|
||||
'mil' => 1000,
|
||||
'mille' => 1000
|
||||
);
|
||||
|
||||
if (! isset($petit[$mot]))
|
||||
return false;
|
||||
|
||||
return $petit[$mot];
|
||||
}
|
||||
|
||||
function enchiffres_zilli($mot)
|
||||
{
|
||||
# Noms des 0ème à 9ème zillions
|
||||
static $petits = array(
|
||||
'n', 'm', 'b', 'tr', 'quadr', 'quint', 'sext', 'sept', 'oct', 'non'
|
||||
);
|
||||
# Composantes des 10ème à 999ème zillions
|
||||
static $unites = array(
|
||||
'', 'un', 'duo', 'tre', 'quattuor', 'quin', 'se', 'septe', 'octo', 'nove'
|
||||
);
|
||||
static $dizaines = array(
|
||||
'', 'dec', 'vigint', 'trigint', 'quadragint',
|
||||
'quinquagint', 'sexagint', 'septuagint', 'octogint', 'nonagint'
|
||||
);
|
||||
static $centaines = array(
|
||||
'', 'cent', 'ducent', 'trecent', 'quadringent',
|
||||
'quingent', 'sescent', 'septingent', 'octingent', 'nongent'
|
||||
);
|
||||
# Expressions rationnelles pour extraire les composantes
|
||||
static $um =
|
||||
'(|un|duo|tre(?!c)|quattuor|quin|se(?!p)(?!sc)|septe|octo|nove)[mnsx]?';
|
||||
static $dm =
|
||||
'(|dec|(?:v|tr|quadr|quinqu|sex|septu|oct|non)[aio]gint)[ai]?';
|
||||
static $cm =
|
||||
'(|(?:|du|tre|ses)cent|(?:quadri|qui|septi|octi|no)ngent)';
|
||||
|
||||
$u = array_search($mot, $petits);
|
||||
if ($u !== false) {
|
||||
return '00' . $u;
|
||||
}
|
||||
|
||||
if (preg_match('/^'.$um.$dm.$cm.'$/', $mot, $resultat) < 1) {
|
||||
return false;
|
||||
}
|
||||
$u = array_search($resultat[1], $unites);
|
||||
$d = array_search($resultat[2], $dizaines);
|
||||
$c = array_search($resultat[3], $centaines);
|
||||
if ($u === false or $d === false or $c === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $c.$d.$u;
|
||||
}
|
||||
|
||||
function enchiffres_grand($mot)
|
||||
{
|
||||
# Quelques remplacements initiaux pour simplifier (les 'é' ont déjà
|
||||
# été tous transformés en 'e').
|
||||
# (1) Je supprime le 's' final de '-illions' ou '-illiards' pour ne
|
||||
# tester que '-illion' ou '-illiard'.
|
||||
# (2) Les deux orthographes étant possibles pour quadrillion ou
|
||||
# quatrillion, je teste les deux. Noter que j'aurais pu changer
|
||||
# 'quadr' en 'quatr' au lieu de l'inverse, mais alors cela aurait
|
||||
# aussi changé 'quadragintillion' en 'quatragintillion', ce qui
|
||||
# n'est pas franchement le but recherché.
|
||||
# (3) En latin, on trouve parfois 'quatuor' au lieu de 'quattuor'. De même,
|
||||
# avec google on trouve quelques 'quatuordecillions' au milieu des
|
||||
# 'quattuordecillions' (environ 1 sur 10).
|
||||
# (4) La règle de John Conway et Allan Wechsler préconisait le préfixe
|
||||
# 'quinqua' au lieu de 'quin' que j'ai choisi. Pour accepter les deux,
|
||||
# je remplace 'quinqua' par 'quin', sauf dans 'quinquaginta' (50)
|
||||
# et dans 'quinquadraginta' (45).
|
||||
static $recherche = array(
|
||||
'/s$/', # (1)
|
||||
'/quatr/', # (2)
|
||||
'/quatuor/', # (3)
|
||||
'/quinqua(?!(dra)?gint)/' # (4)
|
||||
);
|
||||
static $remplace = array(
|
||||
'', # (1)
|
||||
'quadr', # (2)
|
||||
'quattuor', # (3)
|
||||
'quin' # (4)
|
||||
);
|
||||
|
||||
$mot = preg_replace($recherche, $remplace, $mot);
|
||||
if ($mot == 'millier') return 1;
|
||||
if ($mot == 'millinillion') return 2000;
|
||||
|
||||
$prefixes = explode('illi', $mot);
|
||||
if (count($prefixes) < 2) {
|
||||
# Il faut au moins un 'illi' dans le nom
|
||||
return false;
|
||||
}
|
||||
switch (array_pop($prefixes)) {
|
||||
case 'on':
|
||||
# zillion : nombre pair de milliers
|
||||
$ard = 0;
|
||||
break;
|
||||
case 'ard':
|
||||
# zilliard : nombre impair de milliers
|
||||
$ard = 1;
|
||||
break;
|
||||
default:
|
||||
# Ce n'est ni un zillion, ni un zilliard
|
||||
return false;
|
||||
}
|
||||
|
||||
$nombre = '';
|
||||
foreach ($prefixes as $prefixe) {
|
||||
$par3 = enchiffres_zilli($prefixe);
|
||||
if ($par3 === false) return false;
|
||||
$nombre .= $par3;
|
||||
}
|
||||
if (strlen($nombre) > 3) {
|
||||
# On n'accepte que les nombres inférieurs au millinillion
|
||||
# pour limiter le temps de calcul
|
||||
return 0;
|
||||
}
|
||||
return 2*$nombre + $ard;
|
||||
}
|
||||
|
||||
class enchiffres_struct
|
||||
{
|
||||
var $valeur;
|
||||
var $discr;
|
||||
|
||||
function enchiffres_struct($mul, $val)
|
||||
{
|
||||
$this->valeur = $this->discr = $val;
|
||||
if ($mul != 0) {
|
||||
$this->valeur *= $mul;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function enchiffres_ajouter_petit(&$table_petits, $petit)
|
||||
{
|
||||
$somme = 0;
|
||||
while (($elem = array_pop($table_petits)) !== NULL) {
|
||||
if ($elem->discr > $petit) {
|
||||
array_push($table_petits, $elem);
|
||||
break;
|
||||
}
|
||||
$somme += $elem->valeur;
|
||||
}
|
||||
$elem = new enchiffres_struct($somme, $petit);
|
||||
array_push($table_petits, $elem);
|
||||
}
|
||||
|
||||
function enchiffres_somme_petits($table_petits)
|
||||
{
|
||||
$somme = 0;
|
||||
foreach ($table_petits as $elem) {
|
||||
$somme += $elem->valeur;
|
||||
}
|
||||
return $somme;
|
||||
}
|
||||
|
||||
function enchiffres_ajouter_grand(&$table_grands, $mantisse, $exposant)
|
||||
{
|
||||
while ($mantisse > 0) {
|
||||
if (isset($table_grands[$exposant])) {
|
||||
$mantisse += $table_grands[$exposant];
|
||||
}
|
||||
$table_grands[$exposant] = $mantisse % 1000;
|
||||
$mantisse = floor($mantisse / 1000);
|
||||
$exposant++;
|
||||
}
|
||||
}
|
||||
|
||||
function enchiffres($nom)
|
||||
{
|
||||
$nom = preg_replace('/[éèÉÈ]/', 'e', $nom);
|
||||
$nom = strtolower($nom);
|
||||
$table_mots = preg_split('/[^a-z]+/', $nom);
|
||||
|
||||
$table_petits = array();
|
||||
$mantisse = $exposant = 0;
|
||||
$table_grands = array();
|
||||
|
||||
foreach ($table_mots as $mot) {
|
||||
$petit = enchiffres_petit($mot);
|
||||
if ($petit !== false) {
|
||||
if ($mantisse != 0) {
|
||||
enchiffres_ajouter_grand($table_grands, $mantisse, $exposant);
|
||||
$mantisse = $exposant = 0;
|
||||
}
|
||||
enchiffres_ajouter_petit($table_petits, $petit);
|
||||
continue;
|
||||
}
|
||||
|
||||
$grand = enchiffres_grand($mot);
|
||||
if ($grand === false) {
|
||||
# Ce n'est pas un nombre
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($grand == 0) {
|
||||
# Ce nombre était trop grand (millinillion et plus) : on annule le
|
||||
# tout pour limiter le temps de calcul.
|
||||
$mantisse = 0;
|
||||
$exposant = 0;
|
||||
$table_petits = array();
|
||||
} else {
|
||||
if (count($table_petits) > 0) {
|
||||
$mantisse = enchiffres_somme_petits($table_petits);
|
||||
$exposant = 0;
|
||||
$table_petits = array();
|
||||
}
|
||||
if ($mantisse != 0) {
|
||||
$exposant += $grand;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($table_petits) > 0) {
|
||||
$mantisse = enchiffres_somme_petits($table_petits);
|
||||
$exposant = 0;
|
||||
}
|
||||
if ($mantisse != 0) {
|
||||
enchiffres_ajouter_grand($table_grands, $mantisse, $exposant);
|
||||
}
|
||||
|
||||
$nombre = "";
|
||||
for ($exposant = 0; count($table_grands) > 0; $exposant++) {
|
||||
if (isset($table_grands[$exposant])) {
|
||||
$par3 = $table_grands[$exposant];
|
||||
unset($table_grands[$exposant]);
|
||||
} else {
|
||||
$par3 = 0;
|
||||
}
|
||||
$nombre = sprintf("%03d", $par3) . $nombre;
|
||||
}
|
||||
$nombre = ltrim($nombre, '0');
|
||||
if ($nombre === '') $nombre = '0';
|
||||
return $nombre;
|
||||
}
|
||||
|
||||
function enchiffres_aerer($nombre, $blanc=' ', $virgule=',', $tranche=3)
|
||||
{
|
||||
# Si c'est un nombre à virgule, on traite séparément les deux parties
|
||||
if ($virgule !== NULL) {
|
||||
$ent_dec = preg_split("/$virgule/", $nombre);
|
||||
if (count($ent_dec) >= 2) {
|
||||
$ent = enchiffres_aerer($ent_dec[0], $blanc, NULL, $tranche);
|
||||
$dec = enchiffres_aerer($ent_dec[1], $blanc, NULL, -$tranche);
|
||||
return $ent . $virgule . $dec;
|
||||
}
|
||||
}
|
||||
|
||||
# On ne garde que les chiffres
|
||||
$nombre = preg_replace('/[^0-9]/', '', $nombre);
|
||||
|
||||
# Il est plus logique d'avoir un nombre positif pour les entiers,
|
||||
# donc négatif pour la partie décimale, mais plus pratique de
|
||||
# faire le contraire pour les substr().
|
||||
$tranche = - (int)$tranche;
|
||||
|
||||
if ($tranche == 0) {
|
||||
# on voulait juste supprimer les caractères en trop, pas en rajouter
|
||||
return $nombre;
|
||||
}
|
||||
|
||||
$nombre_aere = '';
|
||||
if ($tranche < 0) {
|
||||
# entier, ou partie entière d'un nombre décimal
|
||||
while ($nombre != '') {
|
||||
$par3 = substr($nombre, $tranche);
|
||||
$nombre = substr($nombre, 0, $tranche);
|
||||
if ($nombre_aere == '') {
|
||||
$nombre_aere = $par3;
|
||||
} else {
|
||||
$nombre_aere = $par3 . $blanc . $nombre_aere;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
# partie décimale
|
||||
while ($nombre != '') {
|
||||
$par3 = substr($nombre, 0, $tranche);
|
||||
$nombre = substr($nombre, $tranche);
|
||||
if ($nombre_aere == '') {
|
||||
$nombre_aere = $par3;
|
||||
} else {
|
||||
$nombre_aere .= $blanc . $par3;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $nombre_aere;
|
||||
}
|
||||
|
||||
*/
|
||||
?>
|
271
library/framework/common/curl.php
Normal file
271
library/framework/common/curl.php
Normal file
@ -0,0 +1,271 @@
|
||||
<?
|
||||
|
||||
//include_once('/var/www/default/_includes/timer.php');
|
||||
|
||||
/** Parse une page Html et retourne son contenu dans un tableau :
|
||||
** "code" => Code réponse Serveur
|
||||
** "header" => Headers du serveur
|
||||
** "body" => Page HTML
|
||||
**/
|
||||
function parse_response($this_response) {
|
||||
|
||||
|
||||
// Split response into header and body sections
|
||||
list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
|
||||
$response_header_lines = explode("\r\n", $response_headers);
|
||||
|
||||
// First line of headers is the HTTP response code
|
||||
$http_response_line = array_shift($response_header_lines);
|
||||
if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }
|
||||
|
||||
// put the rest of the headers in an array
|
||||
$response_header_array = array();
|
||||
$nbRMID=0;
|
||||
foreach($response_header_lines as $header_line)
|
||||
{
|
||||
list($header,$value) = explode(': ', $header_line, 2);
|
||||
|
||||
if ($header=='Set-cookie' && substr($value,0,5)=='RMID=' && $nbRMID<5)//{
|
||||
$nbRMID++;
|
||||
// echo ("Je gicle le RMID n°$nbRMID\r\n");}
|
||||
else
|
||||
@$response_header_array[$header] .= $value."\n";
|
||||
}
|
||||
return array('code' => $response_code, 'header' => $response_header_array, 'body' => $response_body);
|
||||
}
|
||||
|
||||
/** Récupère une page HTML en fonction des paramètres :
|
||||
** $url Url distante de la page à récupérer
|
||||
** $strCookies Chaine de caractère contenant les cookies
|
||||
** $postData Tableau des données à passer en POST uniquement
|
||||
** $referer Referer à indiquer lors de l'appel de la page
|
||||
** $debug Activer le débogage (True/False)
|
||||
**
|
||||
** ... et retourne son contenu dans un tableau :
|
||||
** "code" => Code réponse Serveur
|
||||
** "header" => Headers du serveur
|
||||
** "body" => Page HTML
|
||||
**/
|
||||
function getUrl($url, $strCookies='', $postData='', $referer='', $debug=false, $host='', $proxy='', $timeout=0) {
|
||||
|
||||
$ch = curl_init();
|
||||
|
||||
if ($host=='')
|
||||
$this_header = array('Host: '. parse_url($url, PHP_URL_HOST));
|
||||
else
|
||||
$this_header = array('Host: '. $host);
|
||||
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_HEADER, 1);
|
||||
if ($proxy<>'') curl_setopt($ch, CURLOPT_PROXY, $proxy);
|
||||
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'username:password'); // Pas nécessaire en authentification NT
|
||||
|
||||
if (((int)$timeout)<>0) {
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int)$timeout);
|
||||
}
|
||||
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
|
||||
//curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
|
||||
|
||||
$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';
|
||||
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
|
||||
curl_setopt($ch, CURLOPT_REFERER, $referer);
|
||||
|
||||
// Add each cookie that has been returned in the response
|
||||
// If cookies need to be added/deleted or value changed, then add code here
|
||||
if ($strCookies!='') {
|
||||
//die('"'.$strCookies.'"');
|
||||
//echo $strCookies."\r\n";
|
||||
$cookies = explode("\n", $strCookies);
|
||||
// Create the basic header
|
||||
foreach($cookies as $this_cookie) {
|
||||
if (trim($this_cookie)<>'')
|
||||
array_push($this_header, 'Cookie: '.$this_cookie);
|
||||
}
|
||||
}
|
||||
|
||||
if ($postData!='') {
|
||||
if (is_array($postData))
|
||||
$post_data=$postData;
|
||||
|
||||
$o="";
|
||||
foreach ($post_data as $k=>$v)
|
||||
{
|
||||
$o.= "$k=".utf8_encode($v)."&";
|
||||
}
|
||||
$post_data=substr($o,0,-1);
|
||||
|
||||
curl_setopt($ch, CURLOPT_POST, 1);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
|
||||
//if in_array('',$this_header
|
||||
/*array_push($this_header, "Content-type: application/x-www-form-urlencoded");
|
||||
array_push($this_header, "Content-Length: 44");*/
|
||||
}
|
||||
|
||||
/* curl_setopt($ch, CURLOPT_STDERR, '/var/www/log/curlerror.log');
|
||||
curl_setopt($ch, CURLOPT_VERBOSE, true);
|
||||
*/
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
|
||||
//print_r($this_header);
|
||||
|
||||
$page=curl_exec($ch);
|
||||
if($page === false) {
|
||||
if (curl_errno($ch) == 28) //TIMEOUT
|
||||
$response=array('code' =>408, 'header' =>array(), 'body' =>'Connexion impossible au site du partenaire');
|
||||
else
|
||||
$response=array('code' =>400, 'header' =>array(), 'body' =>'Erreur Curl : ' . curl_error($ch));
|
||||
|
||||
} else
|
||||
$response = parse_response($page);
|
||||
|
||||
if ($debug){
|
||||
$url2=str_replace('http://', '', $url);
|
||||
$url2=str_replace('/', '_', $url2);
|
||||
$url2=str_replace('?', '(param)', $url2);
|
||||
$url2=str_replace('&', '(et)', $url2);
|
||||
|
||||
|
||||
$fp=fopen('insee/'. date('Ymd-His') .'-'. microtime_float(true) .'-'. $url2 . '.html', 'a');
|
||||
fwrite($fp, $url."\r\n");
|
||||
fwrite($fp, $page);
|
||||
fclose($fp);
|
||||
//echo strip_tags(html_entity_decode($response['body']), '<td>');
|
||||
}
|
||||
//print_r(curl_getinfo($ch));
|
||||
curl_close($ch);
|
||||
return $response;
|
||||
}
|
||||
|
||||
/** Recherche un texte dans une page HTML
|
||||
**
|
||||
**/
|
||||
function getTextInHtml($pageHtml, $strToFind, $strDeb, $strEnd, $include_strDeb=false, $include_strEnd=false, $ltrim=true, $rtrim=true, &$fin, $nbOcc=1) {
|
||||
$tabRet=array();
|
||||
$deb=$nbOccTrouve=0;
|
||||
while( is_int(($deb=strpos($pageHtml,$strToFind,$fin))) ) {
|
||||
$deb++;
|
||||
$deb2 = strpos($pageHtml,$strDeb, $deb);
|
||||
$fin = strpos($pageHtml,$strEnd, $deb2);
|
||||
if (!$include_strDeb)
|
||||
$deb2+=strlen($strDeb);
|
||||
$s_temp = substr($pageHtml, $deb2, ($fin-$deb2));
|
||||
|
||||
if ($ltrim) $s_temp=ltrim($s_temp);
|
||||
if ($rtrim) $s_temp=rtrim($s_temp);
|
||||
|
||||
if ($nbOcc==1) return $s_temp;
|
||||
//echo $s_temp."\r\n";
|
||||
//$a_temp = explode('" class="basic">', $s_temp);
|
||||
$tabUrl[$nbOccTrouve]=$s_temp;
|
||||
$nbOccTrouve++;
|
||||
|
||||
if ($nbOcc==$nbOccTrouve) {
|
||||
// echo "j'ai trouvé le nb demandé, je sort\r\n";
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
return $tabUrl;
|
||||
/*<span class="mongrasvert">
|
||||
<li>Le type de voie a été modifié<br>
|
||||
<li>L'orthographe du mot directeur a été modifiée<br>
|
||||
<li>Le code postal a été forcé à partir du département et de la localité<br> </span>
|
||||
*/
|
||||
}
|
||||
|
||||
function getPdfInfo($f){
|
||||
$tabInfo=array( 'file'=>$f,
|
||||
'fileName'=>basename($f));
|
||||
$handle = @fopen($f, 'r');
|
||||
if ($handle) {
|
||||
//echo '1'.EOL;
|
||||
$i=$nbPages=$buffer=0;
|
||||
while (!feof($handle)) {
|
||||
$prev_buffer=$buffer;
|
||||
$buffer = fgets($handle, 4096);
|
||||
if ($i==0 && preg_match("/^\%PDF\-(.*)\s/U", $buffer, $matches))
|
||||
$tabInfo['version']=$matches[1];
|
||||
elseif (preg_match("/Type\s*\/Page[^s]/", $buffer) )
|
||||
++$nbPages;
|
||||
$i++;
|
||||
}
|
||||
//echo '2'.EOL;
|
||||
if (preg_match("/\%\%EOF$/", $prev_buffer) || preg_match("/\%\%EOF/", $prev_buffer) || preg_match("/\%\%EOF/", $buffer)) {
|
||||
//echo '3'.EOL;
|
||||
$tabInfo['pdfEOF']=true;
|
||||
} else {
|
||||
/*echo '4 prev:'.$prev_buffer.EOL;
|
||||
echo '4 last:'.$buffer.EOL;*/
|
||||
$tabInfo['debugBuffer']=$prev_buffer;
|
||||
return false;
|
||||
}
|
||||
fclose($handle);
|
||||
} else {
|
||||
//echo '5'.EOL;
|
||||
return false;
|
||||
}
|
||||
|
||||
$tabInfo['pdfSize']=filesize($f);
|
||||
$tabInfo['nbPages']=0+$nbPages;
|
||||
//$tabInfo['debugBuffer']=$prev_buffer;
|
||||
return $tabInfo;
|
||||
}
|
||||
|
||||
|
||||
function simpleWhois($domain, $tdl, $debug=false) {
|
||||
// Fonction de traitement
|
||||
// -----------------------------------------------
|
||||
// 0 => Info, le nom est pris
|
||||
// 1 => Info, le nom est libre
|
||||
// 2 => Info, le nom est en pending
|
||||
// 3 => Avertissement, trop de requêtes
|
||||
// 4 => Erreur, il faut spécifier une chaine à rechercher (regexp)
|
||||
// 5 => Erreur, la requête retournée était vide
|
||||
// -----------------------------------------------
|
||||
|
||||
// Informations spécifiques aux extensions
|
||||
$info = array(
|
||||
'fr' => array(
|
||||
'host' => 'whois.nic.fr',
|
||||
'regexp' => 'No[s]*entries[s]*found',
|
||||
'pending' => 'status[s]*:[s]*REDEMPTION'
|
||||
),
|
||||
'com' => array(
|
||||
'host' => 'whois.crsnic.net',
|
||||
'regexp' => 'No[s]*match[s]*for'
|
||||
),
|
||||
'net' => array(
|
||||
'host' => 'whois.crsnic.net',
|
||||
'regexp' => 'No[s]*match[s]*for'
|
||||
),
|
||||
);
|
||||
|
||||
// Initialisation de la sortie
|
||||
$output = '';
|
||||
// Initialisation de la requête
|
||||
$req = fsockopen($info[$tdl]['host'], 43, $errno, $errstr, 5); // le 5 permet de stopper la requete si aucune réponse au bout de 5 secondes
|
||||
// Récupération de la requête
|
||||
if($req){
|
||||
fputs($req, $domain.'.'.$tdl."rn");
|
||||
while(!feof($req)) $output .= fgets($req, 4096);
|
||||
fclose($req);
|
||||
}else unset($req);
|
||||
// mode debug
|
||||
if($debug) return $output;
|
||||
// Sortie vide
|
||||
if(empty($output)) return 5;
|
||||
// Trop de requêtes
|
||||
if(preg_match("/(Too[s]+many[s]+requests|Your[s]+connection[s]+limit[s]+exceeded|daily[s]+whois[s]+limit[s]+exceeded|Maximum[s]+queries|WHOIS[s]+LIMIT[s]+EXCEEDED|referral[s]+host[s]+not[s]+responding|Excessive[s]+querying)/i", $output)) return 3;
|
||||
// Pending
|
||||
if(isset($info[$tdl]['pending']) && !empty($info[$tdl]['pending']) && preg_match("/".$info[$tdl]['pending']."/i", $output)) return 2;
|
||||
// Info de recheche manquant
|
||||
if(!isset($info[$tdl]['regexp']) || empty($info[$tdl]['regexp'])) return 4;
|
||||
// Libre
|
||||
if(preg_match("/".$info[$tdl]['regexp']."/i", $output)) return 1;
|
||||
// Pris
|
||||
return 0;
|
||||
}
|
||||
|
||||
?>
|
204
library/framework/common/dates.php
Normal file
204
library/framework/common/dates.php
Normal file
@ -0,0 +1,204 @@
|
||||
<?
|
||||
|
||||
include_once('chiffres.php');
|
||||
|
||||
|
||||
/**
|
||||
* Classe de gestion des méthodes relatives à la date et à l'heure
|
||||
*
|
||||
* <p>détail de la classe</p>
|
||||
*
|
||||
* @name nom de la classe
|
||||
* @author Nom de l'auteur <adresse@Email.dom>
|
||||
* @link
|
||||
* @copyright Prénom Nom Année
|
||||
* @version 1.0.0
|
||||
* @package Nom du package
|
||||
*/
|
||||
|
||||
class WDate {
|
||||
|
||||
private static $tabMoisEnLettres = array( 1=>'Janvier',
|
||||
2=>'Février',
|
||||
3=>'Mars',
|
||||
4=>'Avril',
|
||||
5=>'Mai',
|
||||
6=>'Juin',
|
||||
7=>'Juillet',
|
||||
8=>'Août',
|
||||
9=>'Septembre',
|
||||
10=>'Octobre',
|
||||
11=>'Novembre',
|
||||
12=>'Décembre');
|
||||
|
||||
/** Retourne le numéro du mois donné au format texte (janvier, mars, etc...)
|
||||
* @param string Mois en toute lettres (janvier, mars, etc...)
|
||||
* @return string Mois en Chiffe (1, 3, 12) / false en cas d'erreur
|
||||
*/
|
||||
public function getNumMois($moisEnLettres) {
|
||||
foreach (self::$tabMoisEnLettres as $num=>$mois)
|
||||
$tabMoisSansAccents[$num]=strtr($mois, 'ééû','eeu');
|
||||
return array_search(ucfirst(strtolower(strtr($moisEnLettres, 'ééû','eeu'))), $tabMoisSansAccents);
|
||||
}
|
||||
|
||||
/** Retourne le libellé nu numéro du mois passé en paramètre
|
||||
* @param int $moisEnChiffre
|
||||
* @return string Libellé du mois / false si le mois passé en paramètre est invalide
|
||||
*/
|
||||
public function getLibelleMois($moisEnChiffre) {
|
||||
if ($moisEnChiffre>0 && $moisEnChiffre<13)
|
||||
return self::$tabMoisEnLettres[$moisEnChiffre];
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Retourne le nombre de mois entre 2 dates au format Ymd
|
||||
**
|
||||
** @param int $dateDeb Date de début au format Ymd
|
||||
** @param int $dateFin Date de fin (ultérieur à la date de début) au format Ymd
|
||||
** @return int Nombre de mois
|
||||
**/
|
||||
function nbMoisEntre($dateDeb, $dateFin=TODAY) {
|
||||
$dDeb=explode('-', Wdate::dateT('Ymd','Y-m-d', $dateDeb));
|
||||
$dFin=explode('-', Wdate::dateT('Ymd','Y-m-d', $dateFin));
|
||||
return ($dFin[0]*12+$dFin[1])-($dDeb[0]*12+$dDeb[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Conversion de formats de dates selon les formats de dates définits en php
|
||||
* @param string Format de la date d'entrée
|
||||
* @param string Format de la date de sortie
|
||||
* @param string Date d'entrée
|
||||
* @return string Date formatée
|
||||
*/
|
||||
public function dateT($formatIN, $formatOUT, $date) {
|
||||
$M='';
|
||||
switch ($formatIN) {
|
||||
case 'd M Y': $tmp=explode(' ', $date); $d=str_replace('1er', '1', $tmp[0]); $m=self::getNumMois($tmp[1]); $Y=$tmp[2]; break;
|
||||
case 'dMY': $Y=substr($date,-4);
|
||||
if (substr($date,0,3)=='1er') { $d=1; $posM=3; }
|
||||
elseif (is_numeric(substr($date,1,1))) { $d=substr($date,0,2); $posM=2; }
|
||||
else { $d=substr($date,0,1); $posM=1; }
|
||||
$M=trim(substr($date, $posM, strlen($date)-4-$posM));
|
||||
//echo "$date:$posM:$M".EOL;
|
||||
$m=self::getNumMois($M);
|
||||
break;
|
||||
case 'Ymd': $d=substr($date,6,2); $m=substr($date,4,2); $Y=substr($date,0,4); break;
|
||||
case 'ymd': $d=substr($date,4,2); $m=substr($date,2,2); $Y=substr($date,0,2);
|
||||
if ($Y<50) $Y='20'.$Y; else $Y='19'.$Y; break;
|
||||
case 'Y-m-d': $d=substr($date,8,2); $m=substr($date,5,2); $Y=substr($date,0,4); break;
|
||||
case 'Y-m': $d=1; $m=substr($date,5,2); $Y=substr($date,0,4); break;
|
||||
case 'd/m/Y': $tmp=explode('/', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
|
||||
case 'd.m.Y': $tmp=explode('.', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
|
||||
case 'd/m/y': $tmp=explode('/', $date); $d=$tmp[0]; $m=$tmp[1];
|
||||
if ($tmp[2]<date('y')) $Y='20'.$tmp[2]; else $Y='19'.$tmp[2]; break;
|
||||
case 'd-m-Y': $tmp=explode('-', $date); $d=$tmp[0]; $m=$tmp[1]; $Y=$tmp[2]; break;
|
||||
case 'm/d/Y': $tmp=explode('/', $date); $d=$tmp[1]; $m=$tmp[0]; $Y=$tmp[2]; break;
|
||||
case 'dmY': $d=substr($date,0,2); $m=substr($date,2,2); $Y=substr($date,4,4); break;
|
||||
case 'dmy': $d=substr($date,0,2); $m=substr($date,2,2); $Y=substr($date,4,2);
|
||||
if ($Y<50) $Y='20'.$Y; else $Y='19'.$Y; break;
|
||||
default: return $date;
|
||||
}
|
||||
|
||||
if ($m*1>0 && $m*1<10) $m='0'.($m*1); if ($d*1>0 && $d*1<10) $d='0'.($d*1);
|
||||
|
||||
switch ($formatOUT) {
|
||||
case 'd/m/Y': return $d.'/'.$m.'/'.$Y; break;
|
||||
case 'm/Y': return $m.'/'.$Y; break;
|
||||
case 'd M Y': return $d.' '.self::$tabMoisEnLettres[$m*1].' '.$Y; break;
|
||||
case 'M Y': return self::$tabMoisEnLettres[$m*1].' '.$Y; break;
|
||||
case 'Y': return $Y; break;
|
||||
case 'm': return $m; break;
|
||||
case 'd': return $d; break;
|
||||
case 'Ym': return $Y.$m; break;
|
||||
case 'Ymd': return $Y.$m.$d; break;
|
||||
case 'Y-m-d': return $Y.'-'.$m.'-'.$d; break;
|
||||
case 'Y/m/d': return $Y.'/'.$m.'/'.$d; break;
|
||||
default: return $date;
|
||||
}
|
||||
}
|
||||
|
||||
/** Calcul de la date après application de la période textuelle (deux ans, six mois, quinze jours, etc...)
|
||||
* @todo Fonction ne fonctionnant qu'avec un chiffre en un seul mot du genre dix mais pas quatre vingt dix !!!
|
||||
* @param date $dateIN au format Ymd
|
||||
* @param string $period (ex : cinq mois, six ans, un jour, 3 mois)
|
||||
* @return date
|
||||
*/
|
||||
function period2Days($dateIN, $period) {
|
||||
$dateV=self::dateT('Ymd', 'Ymd', $dateIN);
|
||||
if ($dateV<>$dateIN) return NULL;
|
||||
$d=substr($dateIN,6,2);
|
||||
$m=substr($dateIN,4,2);
|
||||
$Y=substr($dateIN,0,4);
|
||||
$period=strtolower(trim(strtr($period, "-.,", ' ')));
|
||||
if ($period=='') return NULL;
|
||||
$tabP=explode(' ', $period);
|
||||
if ($tabP[0]*1>0) $chiffre=$tabP[0]*1*1;
|
||||
else $chiffre=WChiffes::ChiffresEnLettres($tabP[0]);
|
||||
switch (end($tabP)) {
|
||||
case 'mois': $dateOUT=date('Ymd', mktime(0, 0, 0, $m+$chiffre, $d, $Y)); break;
|
||||
case 'an':
|
||||
case 'ans': $dateOUT=date('Ymd', mktime(0, 0, 0, $m, $d, $Y+$chiffre)); break;
|
||||
case 'jour':
|
||||
case 'jours': $dateOUT=date('Ymd', mktime(0, 0, 0, $m, $d+$chiffre, $Y)); break;
|
||||
default: $dateOUT=NULL;
|
||||
}
|
||||
return $dateOUT;
|
||||
}
|
||||
|
||||
|
||||
/** le jour est il ferié
|
||||
* @param date $date Date au format SSAA-MM-JJ ou SSAAMMJJ
|
||||
* @param bool $weekend Considérer les WeekEnd comme feriés ? 1=Oui
|
||||
* @return bool
|
||||
**/
|
||||
function jourFerie($date, $weekend=false) {
|
||||
$date =str_replace('-','',strtr($date, '/.:','---'));
|
||||
$jour =self::dateT('Ymd', 'd', $date);
|
||||
$mois =self::dateT('Ymd', 'm', $date);
|
||||
$annee=self::dateT('Ymd', 'Y', $date);
|
||||
$ferie=false;
|
||||
|
||||
// Jours feriées fixes
|
||||
if($jour == 1 && $mois == 1) $ferie = true; // 1er janvier
|
||||
if($jour == 1 && $mois == 5) $ferie = true; // 1er mai
|
||||
if($jour == 8 && $mois == 5) $ferie = true; // 8 mai
|
||||
if($jour == 14 && $mois == 7) $ferie = true; // 14 juillet
|
||||
if($jour == 15 && $mois == 8) $ferie = true; // 15 aout
|
||||
if($jour == 1 && $mois == 11) $ferie = true; // 1 novembre
|
||||
if($jour == 11 && $mois == 11) $ferie = true; // 11 novembre
|
||||
if($jour == 25 && $mois == 12) $ferie = true; // 25 décembre
|
||||
|
||||
// fêtes religieuses mobiles
|
||||
$pak = @easter_date($annee);
|
||||
$jp = date("d", $pak);
|
||||
$mp = date("m", $pak);
|
||||
if($jp == $jour && $mp == $mois){ $ferie = true;} // Pâques
|
||||
$lpk = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) +1, date("Y", $pak) );
|
||||
$jp = date("d", $lpk);
|
||||
$mp = date("m", $lpk);
|
||||
if($jp == $jour && $mp == $mois){ $ferie = true; }// Lundi de Pâques
|
||||
$asc = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 39, date("Y", $pak) );
|
||||
$jp = date("d", $asc);
|
||||
$mp = date("m", $asc);
|
||||
if($jp == $jour && $mp == $mois){ $ferie = true;}//ascension
|
||||
$pe = mktime(date("H", $pak), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 49, date("Y", $pak) );
|
||||
$jp = date("d", $pe);
|
||||
$mp = date("m", $pe);
|
||||
if($jp == $jour && $mp == $mois) {$ferie = true;}// Pentecôte
|
||||
$lp = mktime(date("H", $asc), date("i", $pak), date("s", $pak), date("m", $pak), date("d", $pak) + 50, date("Y", $pak) );
|
||||
$jp = date("d", $lp);
|
||||
$mp = date("m", $lp);
|
||||
if($jp == $jour && $mp == $mois) {$ferie = true;}// lundi Pentecôte
|
||||
|
||||
// Samedis et Dimanches
|
||||
if ($weekend) {
|
||||
$jour_sem = date('N',mktime(0,0,0, $mois, $jour, $annee));
|
||||
if($jour_sem>5) $ferie = true;
|
||||
}
|
||||
|
||||
return $ferie;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
58
library/framework/common/ftp.php
Normal file
58
library/framework/common/ftp.php
Normal file
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
function ftp_mget($ftp_url, $ftp_user, $ftp_pass, $ftp_dir, $local_dir, $debug=null) {
|
||||
$conn_id = @ftp_connect($ftp_url);
|
||||
if (!$conn_id) {
|
||||
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de se connecter au serveur FTP ($ftp_url) !".EOL;
|
||||
return false;
|
||||
}
|
||||
|
||||
$login_result = @ftp_login($conn_id, $ftp_user, $ftp_pass);
|
||||
if (!$login_result) {
|
||||
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de s'authentifier sur le serveur FTP (user=$ftp_user)!".EOL;
|
||||
return false;
|
||||
}
|
||||
// Récupération du contenu d'un dossier
|
||||
$contents = ftp_nlist($conn_id, $ftp_dir);
|
||||
// print_r($contents);
|
||||
// print_r(ftp_rawlist($conn_id, $ftp_dir));
|
||||
$nbFic=0; // Nombre de fichiers récupérés
|
||||
if (is_array($contents))
|
||||
foreach($contents as $k => $server_file) {
|
||||
$tailleDist = ftp_size($conn_id, $server_file);
|
||||
$dateDist = ftp_mdtm($conn_id, $server_file);
|
||||
$tailleLoc=0;
|
||||
if ($dateDist != -1) {
|
||||
$tabFichiers[$server_file]['dateDispo']=date('Y-m-d H:i:s', $dateDist);
|
||||
// echo date ('Y/m/d - H:i:s') ." - Le fichier distant $server_file a été modifié le ".date("d/m/Y à H:i:s.",$dateDist)."\n";
|
||||
} else {
|
||||
$tabFichiers[$server_file]['dateDispo']=NULL;
|
||||
// echo date ('Y/m/d - H:i:s')." - ERREUR : Impossible de récupérer l'heure de modification du fichier distant $server_file !\n";
|
||||
}
|
||||
$tabFichiers[$server_file]['taille']=$tailleDist;
|
||||
if ($tailleDist != -1) {
|
||||
//echo date ('Y/m/d - H:i:s') ." - Taille du fichier distant $server_file est de $tailleDist octets\n";
|
||||
}
|
||||
if (file_exists($local_dir . $server_file)) {
|
||||
$dateLoc=filemtime($local_dir . $server_file);
|
||||
$tabFichiers[$server_file]['dateDownload']=date('Y-m-d H:i:s', $dateLoc);
|
||||
$tailleLoc=filesize($local_dir . $server_file);
|
||||
//echo date ('Y/m/d - H:i:s') ." - Taille du fichier local $server_file = $tailleLoc octets\n";
|
||||
}
|
||||
if ($tailleDist<>$tailleLoc) {
|
||||
if (ftp_get($conn_id, $local_dir. $server_file, $server_file, FTP_BINARY))
|
||||
//echo date ('Y/m/d - H:i:s')." - Fichier distant $server_file téléchargé avec succès".EOL;
|
||||
$nbFic++;
|
||||
else {
|
||||
if ($debug<>null) echo date ('Y/m/d - H:i:s')." - ERREUR : Fichier distant $server_file non téléchargé !".EOL;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fermeture de la connexion
|
||||
ftp_close($conn_id);
|
||||
return $nbFic;
|
||||
}
|
||||
|
||||
?>
|
3
library/framework/common/mail.php
Normal file
3
library/framework/common/mail.php
Normal file
@ -0,0 +1,3 @@
|
||||
<?php
|
||||
include_once(FWK_PATH.'mail/htmlMimeMail5.php');
|
||||
?>
|
219
library/framework/common/mysql.php
Normal file
219
library/framework/common/mysql.php
Normal file
@ -0,0 +1,219 @@
|
||||
<?php
|
||||
|
||||
class WDB {
|
||||
|
||||
private $host;
|
||||
private $database;
|
||||
private $user;
|
||||
private $password;
|
||||
private $con_id; // Connection ID with MySQL
|
||||
private $result;
|
||||
|
||||
public function __construct($database='', $host='', $user='', $password='') {
|
||||
|
||||
if ($host=='') $this->host=MYSQL_HOST;
|
||||
else $this->host=$host;
|
||||
if ($user=='') $this->user=MYSQL_USER;
|
||||
else $this->user=$user;
|
||||
if ($password=='') $this->password=MYSQL_PASS;
|
||||
else $this->password=$password;
|
||||
if ($database=='') $this->database=MYSQL_DEFAULT_DB;
|
||||
else $this->database=$database;
|
||||
|
||||
$this->con_id = mysql_pconnect($this->host, $this->user,
|
||||
$this->password);
|
||||
if (!($this->con_id === false)) {
|
||||
if (mysql_select_db($this->database, $this->con_id) === false) {
|
||||
echo date('Y/m/d - H:i:s') ." - ERREUR ".mysql_errno()." : Connection à la base de données impossible !".EOL;
|
||||
echo date ('Y/m/d - H:i:s'). mysql_error();
|
||||
die();
|
||||
}
|
||||
}
|
||||
return mysql_query("SET NAMES 'latin1';", $this->con_id);
|
||||
}
|
||||
|
||||
public function setCharSet($charSet) {
|
||||
return (mysql_query("SET CHARACTER SET $charSet;", $this->con_id));
|
||||
}
|
||||
|
||||
private function setDB() {
|
||||
return (mysql_query("USE $this->database;", $this->con_id));
|
||||
}
|
||||
|
||||
/** INSERTION d'un tableau dans une table.
|
||||
** Les index doivent avoir les mêmes noms que les champs.
|
||||
** @param string Table
|
||||
** @param array Valeurs insérer
|
||||
** @return int Dernière valeur de l'auto-incrément, 1 si pas d'auto-incrément et 0 si erreur
|
||||
**/
|
||||
public function insert($table, $toAdd, $debug=false){
|
||||
$this->setDB();
|
||||
$fields = implode(array_keys($toAdd), '`,`');
|
||||
foreach (array_values($toAdd) as $key=>$array_values)
|
||||
$tmp[$key]=checkaddslashes($array_values);
|
||||
|
||||
$values = "'".implode(array_values($tmp), "','")."'"; # better
|
||||
$values = str_replace("'NULL'", 'NULL', $values);
|
||||
$query = 'INSERT INTO `'.$table.'` (`'.$fields.'`) VALUES ('.$values.');';
|
||||
|
||||
|
||||
if ($debug) $tdeb=microtime_float();
|
||||
$res = mysql_query($query, $this->con_id);
|
||||
if ($res!==false)
|
||||
{
|
||||
if (mysql_insert_id()>0)
|
||||
$res=mysql_insert_id();
|
||||
else
|
||||
$res=true;
|
||||
}
|
||||
if ($debug) $this->trace($query, $res, $tdeb);
|
||||
return $res;
|
||||
}
|
||||
|
||||
public function update($table, $update, $where, $debug=false, $limit=0){
|
||||
$this->setDB();
|
||||
$fields = array_keys($update);
|
||||
$values = array_values($update);
|
||||
$i=0;
|
||||
$query='UPDATE `'.$table.'` SET ';
|
||||
while(isset($fields[$i])){
|
||||
if($i>0) { $query.=', '; }
|
||||
$query.=' `'.$fields[$i]."`='".checkaddslashes($values[$i])."'";
|
||||
$i++;
|
||||
}
|
||||
$query = str_replace("'NULL'", 'NULL', $query);
|
||||
$query.=' WHERE '.$where;
|
||||
if ($limit>0) $query.=" LIMIT $limit";
|
||||
if ($debug) $tdeb=microtime_float();
|
||||
$res=mysql_query($query, $this->con_id);
|
||||
if ($debug) $this->trace($query, $res, $tdeb);
|
||||
return $res;
|
||||
}
|
||||
|
||||
public function delete($table, $where, $debug=false) {
|
||||
$this->setDB();
|
||||
$query='DELETE FROM `'.$table.'` WHERE '.$where.' LIMIT 1;';
|
||||
if ($debug) $tdeb=microtime_float();
|
||||
$res=mysql_query($query, $this->con_id);
|
||||
if ($debug) $this->trace($query, $res, $tdeb);
|
||||
return $res;
|
||||
}
|
||||
|
||||
public function select($table, $fields, $where, $debug=false, $assoc=MYSQL_BOTH, $huge=false) {
|
||||
$this->setDB();
|
||||
if (mysql_select_db($this->database, $this->con_id) === false) {
|
||||
echo date('Y/m/d - H:i:s') ." - ERREUR ".mysql_errno()." : Connection à la base de données impossible !".EOL;
|
||||
echo date ('Y/m/d - H:i:s'). mysql_error();
|
||||
die();
|
||||
}
|
||||
$query="SELECT $fields FROM $table WHERE $where;";
|
||||
if ($debug) $tdeb=microtime_float();
|
||||
$this->result=mysql_query($query, $this->con_id);// or die(mysql_error());
|
||||
if (mysql_errno()) {
|
||||
$fpErr=fopen('/var/www/log/sqlerror.log','a');
|
||||
fwrite($fpErr, date('YmdHis'). ' - '.$query .EOL);
|
||||
fwrite($fpErr, date('YmdHis'). ' - '.mysql_errno() .' - '. mysql_error().EOL);
|
||||
return false;
|
||||
}
|
||||
// echo ;
|
||||
if (!$huge) {
|
||||
$tab=array();
|
||||
while ($ligne = mysql_fetch_array($this->result, $assoc))
|
||||
$tab[]=$ligne;
|
||||
|
||||
if ($debug) $this->trace($query, sizeof($tab), $tdeb);
|
||||
return $tab;
|
||||
} else {
|
||||
$nbRows=mysql_num_rows($this->result);
|
||||
if ($debug) $this->trace($query, $nbRows, $tdeb);
|
||||
return $nbRows;
|
||||
}
|
||||
}
|
||||
|
||||
public function fetch($assoc=MYSQL_BOTH) {
|
||||
return mysql_fetch_array($this->result, $assoc);
|
||||
}
|
||||
|
||||
public function trace($query, $res='', $tdeb=-1) {
|
||||
if (!$fp=fopen('mysql_insert.log', 'a'))
|
||||
return false;
|
||||
$errnum=mysql_errno($this->con_id);
|
||||
if ($tdeb>-1) $duree=substr(''.microtime_float()-$tdeb, 0, 5);
|
||||
else $duree='N/D';
|
||||
if (!fwrite($fp, date('Y/m/d - H:i:s') ." - $errnum - $res - $duree - $query\n"))
|
||||
return false;
|
||||
if (!fclose($fp))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Exécute la requête passé en paramètre **/
|
||||
public function query($query, $debug=false){
|
||||
$this->setDB();
|
||||
$this->result=mysql_query($query, $this->con_id);
|
||||
return $this->result;
|
||||
}
|
||||
|
||||
/** Retourne le nombre de records de la dernière requête de sélection **
|
||||
public function getNumRows() {
|
||||
return mysql_num_rows($this->con_id);
|
||||
}
|
||||
*/
|
||||
/** Retourne le libellé de la dernière erreur **/
|
||||
public function getLastErrorMsg() {
|
||||
return mysql_error($this->con_id);
|
||||
}
|
||||
/** Retourne le numéro de la dernière erreur **/
|
||||
public function getLastErrorNum() {
|
||||
return mysql_errno($this->con_id);
|
||||
}
|
||||
|
||||
/** Retourne le libellé et le numéro de la dernière erreur **/
|
||||
public function getLastError() {
|
||||
return mysql_error($this->con_id).' ('.mysql_errno($this->con_id).')';
|
||||
}
|
||||
|
||||
/** Retourne le nombre de lignes modifiées par la dernière requête **/
|
||||
public function getAffectedRows() {
|
||||
return mysql_affected_rows($this->con_id);
|
||||
}
|
||||
|
||||
/** Génère le fichier CSV pour la requete SQL
|
||||
**
|
||||
** @param string $query
|
||||
** @param string $fileCsv
|
||||
** @return bool
|
||||
*/
|
||||
public function exportCSV($query, $fileCsv, $sep=',', $eol=EOL) {
|
||||
$i=$c=0;
|
||||
$fp = fopen($fileCsv, 'w');
|
||||
if (!$fp) return false;
|
||||
|
||||
$res=$this->query($query);
|
||||
$nbLignes=mysql_num_rows($res);
|
||||
|
||||
while ($ligne=$this->fetch(MYSQL_ASSOC)) {
|
||||
if ($i==0) {
|
||||
$nbCols=count($ligne);
|
||||
foreach ($ligne as $libCol=>$col) {
|
||||
$c++;
|
||||
if ($c<$nbCols) fwrite($fp, str_replace($sep,' ', $libCol).$sep);
|
||||
else fwrite($fp, str_replace($sep,' ', $libCol));
|
||||
}
|
||||
fwrite($fp, $eol);
|
||||
}
|
||||
$c=0;
|
||||
foreach ($ligne as $libCol=>$col) {
|
||||
$c++;
|
||||
if ($c<$nbCols) fwrite($fp, str_replace($sep,' ', $col).$sep);
|
||||
else fwrite($fp, str_replace($sep,' ', $col));
|
||||
}
|
||||
fwrite($fp, $eol);
|
||||
$i++;
|
||||
}
|
||||
fclose($fp);
|
||||
return $nbLignes;//$this->getAffectedRows();
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
215
library/framework/common/rss.php
Normal file
215
library/framework/common/rss.php
Normal file
@ -0,0 +1,215 @@
|
||||
<?php
|
||||
/*
|
||||
Atom and RSS Extractor and Displayer
|
||||
(c) 2007 Scriptol.com - Licence Mozilla 1.1.
|
||||
commonlib.php
|
||||
*/
|
||||
class atomRss {
|
||||
|
||||
public $codeErreurHttp=0;
|
||||
private $Common_Content = array();
|
||||
|
||||
function RSS_Tags($item, $type)
|
||||
{
|
||||
$y = array();
|
||||
$y["title"] = $item->getElementsByTagName("title")->item(0)->firstChild->data;
|
||||
$y["link"] = $item->getElementsByTagName("link")->item(0)->firstChild->data;
|
||||
$y["description"] = $item->getElementsByTagName("description")->item(0)->firstChild->data;
|
||||
|
||||
$tnl = $item->getElementsByTagName("pubDate");
|
||||
if($tnl->length == 0)
|
||||
{
|
||||
$tnl = $item->getElementsByTagName("lastBuildDate");
|
||||
}
|
||||
if($tnl->length != 0)
|
||||
{
|
||||
$tnl =$tnl->item(0)->firstChild->data;
|
||||
}
|
||||
else
|
||||
$tnl = false;
|
||||
|
||||
$y["updated"] = $tnl;
|
||||
$y["type"] = $type;
|
||||
|
||||
array_push($this->Common_Content, $y);
|
||||
}
|
||||
|
||||
|
||||
function RSS_Channel($channel)
|
||||
{
|
||||
$items = $channel->getElementsByTagName("item");
|
||||
|
||||
// Processing channel
|
||||
|
||||
$this->RSS_Tags($channel, 0); // get description of channel, type 0
|
||||
|
||||
// Processing articles
|
||||
|
||||
foreach($items as $item)
|
||||
{
|
||||
$this->RSS_Tags($item, 1); // get description of article, type 1
|
||||
}
|
||||
}
|
||||
|
||||
function RSS_Retrieve($url)
|
||||
{
|
||||
$doc = new DOMDocument();
|
||||
$ret = $doc->load($url);
|
||||
if ($ret===false) {
|
||||
$page=getUrl($url,'','','',false,'','',3);
|
||||
$this->codeErreurHtml=$page['code'];
|
||||
if ($this->codeErreurHttp==302) {
|
||||
$url=$page['header']['Location'];
|
||||
$ret = $doc->load($url);
|
||||
}
|
||||
}
|
||||
|
||||
$channels = $doc->getElementsByTagName("channel");
|
||||
|
||||
$this->Common_Content = array();
|
||||
|
||||
foreach($channels as $channel)
|
||||
{
|
||||
$this->RSS_Channel($channel);
|
||||
}
|
||||
|
||||
return ( count($this->Common_Content) > 0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
function Atom_Tags($item)
|
||||
{
|
||||
$y = array();
|
||||
$y["title"] = $item->getElementsByTagName("title")->item(0)->firstChild->data;
|
||||
$y["link"] = $item->getElementsByTagName("link")->item(0)->getAttribute("href");
|
||||
$y["description"] = $item->getElementsByTagName("summary")->item(0)->firstChild->data;
|
||||
$y["updated"] = $item->getElementsByTagName("updated")->item(0)->firstChild->data;
|
||||
$y["type"] = 1;
|
||||
|
||||
array_push($this->Common_Content, $y);
|
||||
}
|
||||
|
||||
function Atom_Feed($doc)
|
||||
{
|
||||
$entries = $doc->getElementsByTagName("entry");
|
||||
|
||||
if($entries->length == 0) return false;
|
||||
|
||||
// Processing feed
|
||||
|
||||
$y = array();
|
||||
$y["title"] = $doc->getElementsByTagName("title")->item(0)->firstChild->data;
|
||||
$y["link"] = $doc->getElementsByTagName("link")->item(0)->getAttribute("href");
|
||||
$y["description"] = $doc->getElementsByTagName("subtitle")->item(0)->firstChild->data;
|
||||
$y["updated"] = $doc->getElementsByTagName("updated")->item(0)->firstChild->data;
|
||||
$y["type"] = 0;
|
||||
|
||||
array_push($this->Common_Content, $y);
|
||||
|
||||
// Processing articles
|
||||
|
||||
foreach($entries as $entry)
|
||||
{
|
||||
$this->Atom_Tags($entry); // get description of article, type 1
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
function Atom_Retrieve($url)
|
||||
{
|
||||
$doc = new DOMDocument();
|
||||
$doc->load($url);
|
||||
|
||||
$this->Common_Content = array();
|
||||
|
||||
return $this->Atom_Feed($doc);
|
||||
|
||||
}
|
||||
|
||||
|
||||
function loadRss($url, $size=200, $chanopt=true, $descopt=true, $dateopt=true)
|
||||
{
|
||||
$opened = false;
|
||||
$page = "";
|
||||
|
||||
if($this->Atom_Retrieve($url) === false)
|
||||
{
|
||||
if($this->RSS_Retrieve($url) === false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if($size > 0)
|
||||
{
|
||||
$size += 1; // add one for the channel
|
||||
$recents = array_slice($this->Common_Content, 0, $size);
|
||||
}
|
||||
//$tabFlux=array();
|
||||
return $recents;
|
||||
/*
|
||||
|
||||
foreach($recents as $article)
|
||||
{
|
||||
$type = $article["type"];
|
||||
|
||||
if($type == 0)
|
||||
{
|
||||
if($chanopt != true) continue;
|
||||
if($opened == true)
|
||||
{
|
||||
$page .="</ul>\n";
|
||||
$opened = false;
|
||||
}
|
||||
//$page .="<b>";
|
||||
}
|
||||
else
|
||||
{
|
||||
if($opened == false && $chanopt == true)
|
||||
{
|
||||
$page .= "<ul>\n";
|
||||
$opened = true;
|
||||
}
|
||||
}
|
||||
$title = $article["title"];
|
||||
$link = $article["link"];
|
||||
$page .= "<".$Common_Style."><a href=\"$link\">$title</a>";
|
||||
|
||||
if($descopt != false)
|
||||
{
|
||||
$description = $article["description"];
|
||||
if($description != false)
|
||||
{
|
||||
$page .= "<br>$description";
|
||||
}
|
||||
}
|
||||
if($dateopt != false)
|
||||
{
|
||||
$updated = $article["updated"];
|
||||
if($updated != false)
|
||||
{
|
||||
$page .= "<br /><font $Common_Date_Font>$updated</font>";
|
||||
}
|
||||
}
|
||||
$page .= "</".$Common_Style.">\n";
|
||||
|
||||
/*
|
||||
if($type == 0)
|
||||
{
|
||||
$page .="<br />";
|
||||
}
|
||||
*
|
||||
}
|
||||
|
||||
if($opened == true)
|
||||
{
|
||||
$page .="</ul>\n";
|
||||
}
|
||||
return $page."\n";
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
424
library/framework/common/strings.php
Normal file
424
library/framework/common/strings.php
Normal file
@ -0,0 +1,424 @@
|
||||
<?
|
||||
|
||||
define ('BEFORE', 0);
|
||||
define ('AFTER', 1);
|
||||
define ('BOTH', 2);
|
||||
define ('ALIGN_LEFT', 0);
|
||||
define ('ALIGN_RIGHT', 1);
|
||||
|
||||
|
||||
/**Initialisation d'une chaîne de caractère
|
||||
*
|
||||
* @param string $chaine Chaîne de caractère initiale
|
||||
* @param int $taille Taille de la chaîne de caractère à initialiser
|
||||
* @param string $caractere_pour_combler Caractère à utiliser pour combler la chaîne de caractère (espace par défaut)
|
||||
* @param string $align Aligner la chaîne de caractère à droite (right) ou à gauche (left, par défaut)
|
||||
* @return string
|
||||
*/
|
||||
function initstr($chaine, $taille, $caractere_pour_combler=' ', $align=ALIGN_LEFT) {
|
||||
if ($align==ALIGN_RIGHT) {
|
||||
$str2='';
|
||||
for ($i=0;$i<($taille-strlen($chaine));$i++)
|
||||
$str2.=$caractere_pour_combler;
|
||||
$str=$str2.$chaine;
|
||||
} else {
|
||||
if (strlen($chaine)>=$taille)
|
||||
return substr($chaine,0,$taille);
|
||||
$str=$chaine;
|
||||
for ($i=strlen($chaine);$i<$taille;$i++)
|
||||
$str = $str . $caractere_pour_combler;
|
||||
}
|
||||
return $str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajout d'anti-slashs s'il y a lieu en vu d'une insertion en BDD
|
||||
*
|
||||
* @param string $str Chaine de caractère
|
||||
* @return unknown
|
||||
*/
|
||||
|
||||
function checkaddslashes($str){
|
||||
return addslashes(preg_replace('/\\[^nrt\']/i', '\\', $str));
|
||||
}
|
||||
|
||||
function checkaddslashes2($str){
|
||||
if(strpos(str_replace("\'",''," $str"),"'")!=false)
|
||||
return addslashes($str);
|
||||
else
|
||||
return $str;
|
||||
}
|
||||
|
||||
function trimAccent ($strWithAccent) {
|
||||
$strWithAccent = htmlentities(strtolower($strWithAccent ));
|
||||
$strWithAccent = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $strWithAccent );
|
||||
$strWithAccent = preg_replace("/([^a-z0-9]+)/", " ", html_entity_decode($strWithAccent ));
|
||||
$strWithAccent = trim($strWithAccent , "-");
|
||||
return $strWithAccent;
|
||||
}
|
||||
|
||||
//function SRSaufVoyelle ($strIn, $mot1, $mot2) {
|
||||
function str_replace_except_voy($mot1, $mot2, $strIn, $rule=0) {
|
||||
$Voyelle=array('a','e','i','o','u','y', '1', '2', '3', '4');
|
||||
if ($mot1==$mot2) return $strIn;
|
||||
if (strpos($mot2,$mot1)===false)
|
||||
{
|
||||
//foreach ($Voyelle as $k => $voy)
|
||||
$posMot1=strpos($strIn, $mot1);
|
||||
while ($posMot1!==false) {
|
||||
$lettreAV=$strIn[$posMot1-1];
|
||||
$lettreAP=$strIn[$posMot1+strlen($mot1)];
|
||||
//echo "Lettre AV=$lettreAV<br/>";
|
||||
//echo "Lettre AP=$lettreAP<br/>";
|
||||
if ( ( $rule==0 && !in_array($lettreAV, $Voyelle) ) ||
|
||||
( $rule==1 && !in_array($lettreAP, $Voyelle) ) ||
|
||||
( $rule==2 && !in_array($lettreAV, $Voyelle) && !in_array($lettreAP, $Voyelle) ))
|
||||
$strIn=substr($strIn,0,$posMot1) . $mot2 . substr($strIn,$posMot1+strlen($mot1),strlen($strIn));
|
||||
//echo "Le Mot devient : $strIn<br/>";
|
||||
$posMot1=strpos($strIn, $mot1, $posMot1+strlen($mot1));
|
||||
}
|
||||
return $strIn;
|
||||
}
|
||||
//echo "Erreur : $mot2 contient $mot1 !<br>";
|
||||
return $strIn;
|
||||
}
|
||||
|
||||
/** Retourne le phonex d'un mot
|
||||
**/
|
||||
function phonex($strIn) {
|
||||
if ($strIn=='') return 0.0;
|
||||
$tabSonAIA=array('aina', 'eina', 'aima', 'eima');
|
||||
$tabSonAIE=array('ainr', 'eine', 'aime', 'eime');
|
||||
$tabSonAII=array('aini', 'eini', 'aimi', 'eimi');
|
||||
$tabSonAIO=array('aino', 'eino', 'aimo', 'eimo');
|
||||
$tabSonAIU=array('ainu', 'einu', 'aimu', 'eimu');
|
||||
$tabCarPhon=array('1', '2', '3', '4', '5', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'n', 'o', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z');
|
||||
|
||||
/** On traite tout en minuscule **/
|
||||
$strIn=strtolower($strIn);
|
||||
/** On remplace les 'Y' par des 'I' **/
|
||||
$strIn=str_replace('y', 'i', $strIn);
|
||||
/** On supprime les accents **/
|
||||
$strIn=trimAccent($strIn);
|
||||
/** On retire les 'H' muets sauf ceux précédés par 'C' ou 'S' **/
|
||||
$strIn = preg_replace ('/(?<![CS])H/', '', $strIn);
|
||||
/** On remplace les 'PH' par des 'F' **/
|
||||
$strIn=str_replace('ph', 'f', $strIn);
|
||||
/** On remplace les 'G' par des 'K' devant AN AM AIN AIM **/
|
||||
$strIn=str_replace('gan', 'kan', $strIn);
|
||||
$strIn=str_replace('gain', 'kain', $strIn);
|
||||
$strIn=str_replace('gam', 'kam4', $strIn);
|
||||
$strIn=str_replace('gaim', 'kaim', $strIn);
|
||||
/** On remplace le son AI **/
|
||||
for ($i=0; $i>4; $i++) {
|
||||
$strIn=str_replace($tabSonAIA[$i], 'yna', $strIn);
|
||||
$strIn=str_replace($tabSonAIE[$i], 'yne', $strIn);
|
||||
$strIn=str_replace($tabSonAII[$i], 'yni', $strIn);
|
||||
$strIn=str_replace($tabSonAIO[$i], 'yno', $strIn);
|
||||
$strIn=str_replace($tabSonAIU[$i], 'ynu', $strIn);
|
||||
}
|
||||
/** Remplacement des groupes de 3 lettres **/
|
||||
$strIn=str_replace('eau', 'o', $strIn);
|
||||
$strIn=str_replace('oua', '2', $strIn);
|
||||
$strIn=str_replace('ein', '4', $strIn);
|
||||
$strIn=str_replace('ain', '4', $strIn);
|
||||
/** Remplacement du son 'é' **/
|
||||
$strIn=str_replace('ai', 'y', $strIn);
|
||||
$strIn=str_replace('ei', 'y', $strIn);
|
||||
$strIn=str_replace('er', 'yr', $strIn);
|
||||
$strIn=str_replace('ess', 'yss', $strIn);
|
||||
$strIn=str_replace('et', 'yt', $strIn);
|
||||
$strIn=str_replace('ez', 'yz', $strIn);
|
||||
/** Remplacement des groupes de 2 lettres sauf si voyelle ou son (1 à 4) AVANT **/
|
||||
$strIn=str_replace_except_voy('an', '1', $strIn, BEFORE);
|
||||
$strIn=str_replace_except_voy('am', '1', $strIn, BEFORE);
|
||||
$strIn=str_replace_except_voy('en', '1', $strIn, BEFORE);
|
||||
$strIn=str_replace_except_voy('em', '1', $strIn, BEFORE);
|
||||
$strIn=str_replace_except_voy('in', '4', $strIn, BEFORE);
|
||||
/** Remplacement du son 'SCH' **/
|
||||
$strIn=str_replace('sch', '5', $strIn);
|
||||
/** Remplacement du 'S' sauf si voyelle ou son (1 à 4) avant ou après **/
|
||||
$strIn=str_replace_except_voy('in', '4', $strIn, BOTH);
|
||||
/** Remplacement de groupe de 2 lettres diverses **/
|
||||
$strIn=str_replace('oe', 'e', $strIn);
|
||||
$strIn=str_replace('eu', 'e', $strIn);
|
||||
$strIn=str_replace('au', 'o', $strIn);
|
||||
$strIn=str_replace('oi', '2', $strIn);
|
||||
$strIn=str_replace('oy', '2', $strIn);
|
||||
$strIn=str_replace('ou', '3', $strIn);
|
||||
$strIn=str_replace('ch', '5', $strIn);
|
||||
$strIn=str_replace('sh', '5', $strIn);
|
||||
$strIn=str_replace('ss', 's', $strIn);
|
||||
$strIn=str_replace('sc', 's', $strIn);
|
||||
/** Remplacement du 'C' par 'S' s'il est suivi d'un 'E' ou d'un 'I' **/
|
||||
$strIn=str_replace('ce', 'se', $strIn);
|
||||
$strIn=str_replace('ci', 'si', $strIn);
|
||||
/** Remplacement divers **/
|
||||
$strIn=str_replace('c', 'k', $strIn);
|
||||
$strIn=str_replace('q', 'k', $strIn);
|
||||
$strIn=str_replace('qu', 'k', $strIn);
|
||||
|
||||
$strIn=str_replace('ga', 'ka', $strIn);
|
||||
$strIn=str_replace('go', 'ko', $strIn);
|
||||
$strIn=str_replace('gu', 'ku', $strIn);
|
||||
$strIn=str_replace('gy', 'ky', $strIn);
|
||||
$strIn=str_replace('g2', 'k2', $strIn);
|
||||
$strIn=str_replace('g1', 'k1', $strIn);
|
||||
$strIn=str_replace('g3', 'k3', $strIn);
|
||||
|
||||
$strIn=str_replace('a', 'o', $strIn);
|
||||
$strIn=str_replace('d', 't', $strIn);
|
||||
$strIn=str_replace('p', 't', $strIn);
|
||||
$strIn=str_replace('j', 'g', $strIn);
|
||||
$strIn=str_replace('b', 'f', $strIn);
|
||||
$strIn=str_replace('v', 'f', $strIn);
|
||||
$strIn=str_replace('m', 'n', $strIn);
|
||||
|
||||
/** Supression des lettres dupliquées **/
|
||||
$let=$strIn[0];
|
||||
$strIn2=$let;
|
||||
for ($i=1; $i<strlen($strIn); $i++)
|
||||
{ if ($strIn==$let)
|
||||
continue;
|
||||
else {
|
||||
$let=$strIn[$i];
|
||||
$strIn2.=$strIn[$i];
|
||||
}
|
||||
}
|
||||
$strIn=$strIn2;
|
||||
|
||||
/** Supression des terminaisons **/
|
||||
$strIn2=substr($strIn,-1);
|
||||
if ($strIn2=='t' || $strIn2=='k' || $strIn2=='s' || $strIn2=='z')
|
||||
$strIn=substr($strIn,0,-1);
|
||||
|
||||
/** Supression des caractères non autorisés **/
|
||||
$j=10;
|
||||
$sout=array();
|
||||
for ($i=0; $i<strlen($strIn); $i++)
|
||||
{
|
||||
if ($j<1) break;
|
||||
for ($k=0; $k<22; $k++)
|
||||
{
|
||||
if ($strIn[$i]==$tabCarPhon[$k])
|
||||
{
|
||||
$sout[$j]=$k;
|
||||
$j--;
|
||||
}
|
||||
}
|
||||
}
|
||||
print_r($tabCarPhon);
|
||||
|
||||
/** Couversion en flottant **/
|
||||
$result=0.0;
|
||||
for ($j=10; $j>0; $j--)
|
||||
$result+=$sout[$j]*pow($j-1,10);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* CLASS soundex2
|
||||
* soundex2 French version
|
||||
* based on the algorithm described here : http://sqlpro.developpez.com/cours/soundex/ by Frédéric BROUARD
|
||||
*
|
||||
* author Johan Barbier <barbier_johan@hotmail.com>
|
||||
*/
|
||||
class csoundex2 {
|
||||
|
||||
/**
|
||||
* public sString
|
||||
* main string we work on
|
||||
*/
|
||||
var $sString = '';
|
||||
|
||||
/**
|
||||
* vowels replacement array
|
||||
*/
|
||||
var $aReplaceVoy1 = array (
|
||||
'E' => 'A',
|
||||
'I' => 'A',
|
||||
'O' => 'A',
|
||||
'U' => 'A'
|
||||
);
|
||||
|
||||
/**
|
||||
* consonnants replacement array
|
||||
*/
|
||||
var $aReplaceGrp1 = array (
|
||||
'GUI' => 'KI',
|
||||
'GUE' => 'KE',
|
||||
'GA' => 'KA',
|
||||
'GO' => 'KO',
|
||||
'GU' => 'K',
|
||||
'CA' => 'KA',
|
||||
'CO' => 'KO',
|
||||
'CU' => 'KU',
|
||||
'Q' => 'K',
|
||||
'CC' => 'K',
|
||||
'CK' => 'K'
|
||||
);
|
||||
|
||||
/**
|
||||
* other replacement array
|
||||
*/
|
||||
var $aReplaceGrp2 = array (
|
||||
'ASA' => 'AZA',
|
||||
'KN' => 'NN',
|
||||
'PF' => 'FF',
|
||||
'PH' => 'FF',
|
||||
'SCH' => 'SSS'
|
||||
);
|
||||
|
||||
/**
|
||||
* endings replacement array
|
||||
*/
|
||||
var $aEnd = array (
|
||||
'A',
|
||||
'T',
|
||||
'D',
|
||||
'S'
|
||||
);
|
||||
|
||||
/**
|
||||
* public function build
|
||||
* core function of the class, go through the whole process
|
||||
* @Param string sString : the string we want to check
|
||||
*/
|
||||
function build ($sString) {
|
||||
/**
|
||||
* let's check it's a real string...
|
||||
*/
|
||||
if (is_string ($sString) && !empty ($sString)) {
|
||||
$this -> sString = $sString;
|
||||
} else {
|
||||
trigger_error ('Parameter string must not be empty', E_USER_ERROR);
|
||||
}
|
||||
/**
|
||||
* remove starting and ending spaces
|
||||
*/
|
||||
$this -> sString = trim ($this -> sString);
|
||||
/**
|
||||
* remove special french characters
|
||||
*/
|
||||
$this -> trimAccent ();
|
||||
/**
|
||||
* string to upper case
|
||||
*/
|
||||
$this -> sString = strtoupper ($this -> sString );
|
||||
/**
|
||||
* let's remove every space in the string
|
||||
*/
|
||||
$this -> sString = str_replace (' ', '', $this -> sString);
|
||||
/**
|
||||
* let's remove every '-' in the string
|
||||
*/
|
||||
$this -> sString = str_replace ('-', '', $this -> sString);
|
||||
/**
|
||||
* let's process through the first replacement array
|
||||
*/
|
||||
$this -> arrReplace ($this -> aReplaceGrp1);
|
||||
/**
|
||||
* let's process through th vowels replacement
|
||||
*/
|
||||
$sChar = substr ($this -> sString, 0, 1);
|
||||
$this -> sString = substr ($this -> sString, 1, strlen ($this -> sString) - 1);
|
||||
$this -> arrReplace ($this -> aReplaceVoy1);
|
||||
$this -> sString = $sChar.$this -> sString;
|
||||
/**
|
||||
* let's process through the second replacement array
|
||||
*/
|
||||
$this -> arrReplace ($this -> aReplaceGrp2, true);
|
||||
/**
|
||||
* let's remove every 'H' but those prededed by a 'C' or an 'S'
|
||||
*/
|
||||
$this -> sString = preg_replace ('/(?<![CS])H/', '', $this -> sString);
|
||||
/**
|
||||
* let's remove every 'Y' but those preceded by an 'A'
|
||||
*/
|
||||
$this -> sString = preg_replace ('/(?<!A)Y/', '', $this -> sString);
|
||||
/**
|
||||
* remove endings in aEnd
|
||||
*/
|
||||
$length = strlen ($this -> sString) - 1;
|
||||
if (in_array ($this -> sString{$length}, $this -> aEnd)) {
|
||||
$this -> sString = substr ($this -> sString, 0, $length);
|
||||
}
|
||||
/**
|
||||
* let's remove every 'A', but the one at the beginning of the string, if any.
|
||||
*/
|
||||
$sChar = '';
|
||||
if ($this -> sString{0} === 'A') {
|
||||
$sChar = 'A';
|
||||
}
|
||||
$this -> sString = str_replace ('A', '', $this -> sString);
|
||||
$this -> sString = $sChar.$this -> sString;
|
||||
/**
|
||||
* let's have only 1 occurence of each letter
|
||||
*/
|
||||
$this -> sString = preg_replace( '/(.)\1/', '$1', $this -> sString );
|
||||
/**
|
||||
* let's have the final code : a 4 letters string
|
||||
*/
|
||||
$this -> getFinal ();
|
||||
}
|
||||
|
||||
/**
|
||||
* private function getFinal
|
||||
* gets the first 4 letters, pads the string with white space if the string length < 4
|
||||
*/
|
||||
function getFinal () {
|
||||
if (strlen ($this -> sString) < 4) {
|
||||
$this -> sString = str_pad ($this -> sString, 4, ' ', STR_PAD_RIGHT);
|
||||
} else {
|
||||
$this -> sString = substr ($this -> sString, 0, 4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* private function trimAccent
|
||||
* remove every special French letters
|
||||
*/
|
||||
function trimAccent () {
|
||||
$this -> sString = htmlentities(strtolower($this -> sString ));
|
||||
$this -> sString = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml|grave);/", "$1", $this -> sString );
|
||||
$this -> sString = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($this -> sString ));
|
||||
$this -> sString = trim($this -> sString , "-");
|
||||
}
|
||||
|
||||
/**
|
||||
* private function arrReplace
|
||||
* replacement method, given an array
|
||||
* @Param array tab : the replacement array to be used
|
||||
* @Param bool pref : if false, just replace keys by values; if true, do the same but only with prefix
|
||||
*/
|
||||
function arrReplace (array $tab, $pref = false) {
|
||||
$fromRep = array_keys ($tab);
|
||||
$toRep = array_values ($tab);
|
||||
if (false === $pref) {
|
||||
$this -> sString = str_replace ($fromRep, $toRep, $this -> sString);
|
||||
} else {
|
||||
foreach ($fromRep as $clef => $val) {
|
||||
$length = strlen ($val);
|
||||
if (substr ($this -> sString, 0, $length) === $val) {
|
||||
$this -> sString = substr_replace ($this -> sString, $toRep[$clef], 0, $length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function soundex2($str) {
|
||||
$soundex2 = new csoundex2();
|
||||
|
||||
$soundex2 -> build ($str);
|
||||
return $soundex2 -> sString;
|
||||
}
|
||||
|
||||
function htm2txt($str) {
|
||||
return trim(strip_tags( str_replace(chr(160), ' ',
|
||||
str_replace('œ', 'oe',
|
||||
str_replace('’', '\'', html_entity_decode($str, ENT_QUOTES))))));
|
||||
}
|
||||
?>
|
111
library/framework/common/xml_parser.php
Normal file
111
library/framework/common/xml_parser.php
Normal file
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
/*
|
||||
|
||||
XML Parser Class
|
||||
by Eric Rosebrock
|
||||
http://www.phpfreaks.com
|
||||
|
||||
Class originated from: kris@h3x.com AT: http://www.devdump.com/phpxml.php
|
||||
|
||||
Usage:
|
||||
|
||||
<?php
|
||||
include 'clsParseXML.php';
|
||||
|
||||
$xmlparse = &new ParseXML;
|
||||
$xml = $xmlparse->GetXMLTree('/path/to/xmlfile.xml');
|
||||
|
||||
echo "<pre>";
|
||||
print_r($xml);
|
||||
echo "</pre>";
|
||||
?>
|
||||
|
||||
The path to the XML file may be a local file or a URL.
|
||||
Returns the elements of the XML file into an array with
|
||||
it's subelements as keys and subarrays.
|
||||
|
||||
*/
|
||||
|
||||
class ParseXML{
|
||||
function GetChildren($vals, &$i) {
|
||||
$children = array(); // Contains node data
|
||||
if (isset($vals[$i]['value'])){
|
||||
$children['VALUE'] = $vals[$i]['value'];
|
||||
}
|
||||
|
||||
while (++$i < count($vals)){
|
||||
switch ($vals[$i]['type']){
|
||||
|
||||
case 'cdata':
|
||||
if (isset($children['VALUE'])){
|
||||
$children['VALUE'] .= $vals[$i]['value'];
|
||||
} else {
|
||||
$children['VALUE'] = $vals[$i]['value'];
|
||||
}
|
||||
break;
|
||||
|
||||
case 'complete':
|
||||
if (isset($vals[$i]['attributes'])) {
|
||||
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
|
||||
$index = count($children[$vals[$i]['tag']])-1;
|
||||
|
||||
if (isset($vals[$i]['value'])){
|
||||
$children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
|
||||
} else {
|
||||
$children[$vals[$i]['tag']][$index]['VALUE'] = '';
|
||||
}
|
||||
} else {
|
||||
if (isset($vals[$i]['value'])){
|
||||
$children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
|
||||
} else {
|
||||
$children[$vals[$i]['tag']][]['VALUE'] = '';
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'open':
|
||||
if (isset($vals[$i]['attributes'])) {
|
||||
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
|
||||
$index = count($children[$vals[$i]['tag']])-1;
|
||||
$children[$vals[$i]['tag']][$index] = array_merge($children[$vals[$i]['tag']][$index],$this->GetChildren($vals, $i));
|
||||
} else {
|
||||
$children[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'close':
|
||||
return $children;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function GetXMLTree($xmlloc){
|
||||
if (file_exists($xmlloc)){
|
||||
$data = implode('', file($xmlloc));
|
||||
} else {
|
||||
$fp = fopen($xmlloc,'r');
|
||||
while(!feof($fp)){
|
||||
$data = $data . fread($fp, 1024);
|
||||
}
|
||||
|
||||
fclose($fp);
|
||||
}
|
||||
|
||||
$parser = xml_parser_create('ISO-8859-1');
|
||||
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
|
||||
xml_parse_into_struct($parser, $data, $vals, $index);
|
||||
xml_parser_free($parser);
|
||||
|
||||
$tree = array();
|
||||
$i = 0;
|
||||
|
||||
if (isset($vals[$i]['attributes'])) {
|
||||
$tree[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
|
||||
$index = count($tree[$vals[$i]['tag']])-1;
|
||||
$tree[$vals[$i]['tag']][$index] = array_merge($tree[$vals[$i]['tag']][$index], $this->GetChildren($vals, $i));
|
||||
} else {
|
||||
$tree[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
|
||||
}
|
||||
return $tree;
|
||||
}
|
||||
}
|
281
library/framework/fwk.php
Normal file
281
library/framework/fwk.php
Normal file
@ -0,0 +1,281 @@
|
||||
<?
|
||||
define('FWK_PATH', '/var/www/framework/');
|
||||
include_once(FWK_PATH.'common/mysql.php');
|
||||
include_once(FWK_PATH.'common/strings.php');
|
||||
//include_once(FWK_PATH.'common/dates.php');
|
||||
|
||||
define ('REP_TEMP', '/tmp/');
|
||||
// Environnement : DEV ou PRD
|
||||
define ('ENV', 'DEV');
|
||||
define ('EOL', "\n");
|
||||
|
||||
define ('MODE_CLI', 1);
|
||||
define ('MODE_WWW', 2);
|
||||
define ('MODE_WS', 3);
|
||||
|
||||
if (@$_SERVER['argc']>0) define('MODE_EXEC', MODE_CLI);
|
||||
else define('MODE_EXEC', MODE_WS);
|
||||
/** @todo Gérer la distinction du mode WWW du WS
|
||||
else define('MODE_EXEC', MODE_WWW);
|
||||
*/
|
||||
|
||||
/** TimeStamp Unix
|
||||
** Si $onlyMiliSec=true, retourne juste les milisec du timestamp
|
||||
**/
|
||||
function microtime_float($onlyMiliSec=false) {
|
||||
list($usec, $sec) = explode(' ', microtime());
|
||||
if (!$onlyMiliSec)
|
||||
return ((float)$usec + (float)$sec);
|
||||
else
|
||||
return $usec;
|
||||
}
|
||||
|
||||
/** Fait une pause aléatoire entre 0 et 15 secondes par défaut
|
||||
**/
|
||||
function randsleep($min_sec=0, $max_sec=15) {
|
||||
sleep(rand($min_sec, $max_sec));
|
||||
}
|
||||
|
||||
/** Retourne la factorielle d'un nombre : 4! = 1*2*3*4 = 24
|
||||
**/
|
||||
function factorielle($nbr) {
|
||||
if($nbr === 0) // condition d'arret
|
||||
return 1;
|
||||
else
|
||||
return $nbr*factorielle($nbr-1);
|
||||
}
|
||||
|
||||
/** Vérification que la variable demandé respecte bien les règles passées en paramètres
|
||||
* @param mixed Variable à tester
|
||||
* @param int Longueur minimum en caractère de la variable
|
||||
* @param int Longueur mximum
|
||||
* @param char(1) Type de variable <b>A</b>:Alphanumérique / <b>N</b>:Numérique
|
||||
* @param mixed Message textuel d'erreur à afficher en cas d'erreur ou false
|
||||
* @return mixed true, false ou Message d'erreur passé en paramètre
|
||||
*/
|
||||
function valideData($variable, $taille_min, $taille_max, $type_variable, $erreur=false){
|
||||
if ( strlen((string)$variable) < $taille_min )
|
||||
return $erreur;
|
||||
|
||||
if ( strlen((string)$variable) > $taille_max )
|
||||
return $erreur;
|
||||
|
||||
if ( $type_variable == 'A' )
|
||||
if ( is_string($variable) == true )
|
||||
return true;
|
||||
else
|
||||
return $erreur;
|
||||
|
||||
elseif ( $type_variable == 'N')
|
||||
{
|
||||
for ($i=0; $i < strlen((string)$variable); $i++)
|
||||
{
|
||||
$car = substr((string)$variable,$i,1);
|
||||
if ($car<'0' || $car>'9')
|
||||
return $erreur;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return $erreur;
|
||||
}
|
||||
|
||||
function adapteOCtets($size) {
|
||||
$kb = 1024; // Kilobyte
|
||||
$mb = 1024 * $kb; // Megabyte
|
||||
$gb = 1024 * $mb; // Gigabyte
|
||||
$tb = 1024 * $gb; // Terabyte
|
||||
if($size==0) return '0';
|
||||
else if($size < $kb) return $size.'o';
|
||||
else if($size < $mb) return round($size/$kb,2).'ko';
|
||||
else if($size < $gb) return round($size/$mb,2).'Mo';
|
||||
else if($size < $tb) return round($size/$gb,2).'Go';
|
||||
else return round($size/$tb,2).'To';
|
||||
}
|
||||
|
||||
/**
|
||||
** Enregistrer une information dans la log
|
||||
**
|
||||
** @param string $debugLevel E=Error, W=Warning, N=Notice, I=Info, D=Debug
|
||||
** @param string $message Message d'erreur à inscrire dans la log
|
||||
** @param integer $line __LINE__
|
||||
** @param string $file __FILE__
|
||||
** @param string $function __FUNCTION__
|
||||
** @param string $class __CLASS___
|
||||
**/
|
||||
function debugLog($debugLevel, $message, $line, $file, $function, $class) {
|
||||
if (!file_exists('/var/www/log/debug.log')) {
|
||||
$fp=fopen('/var/www/log/debug.log', 'a');
|
||||
fwrite($fp, 'Date/Heure;Niveau;Script;Login;Password;Adresse IP;Action SOAP;Ligne;Fichier;Fonction;Classe;Domaine;POST DATA;Memory;Message'.EOL);
|
||||
} else
|
||||
$fp=fopen('/var/www/log/debug.log', 'a');
|
||||
fwrite($fp, date('Y/m/d-H:i:s') .';'. $debugLevel .';'. $_SERVER['PHP_SELF'] .';'. $_SERVER['PHP_AUTH_USER'] .';'. $_SERVER['PHP_AUTH_PW'] .';'.
|
||||
$_SERVER['REMOTE_ADDR'] .';'. $_SERVER['HTTP_SOAPACTION'] .';'.$line.';'. $file.';'. $function.';'. $class .';'.
|
||||
@gethostbyaddr($_SERVER['REMOTE_ADDR']) .';'. $HTTP_RAW_POST_DATA .';'. @memory_get_usage().';'. $message . EOL);
|
||||
fclose($fp);
|
||||
if ($debugLevel=='E'){
|
||||
if (!file_exists('/var/www/log/debugError.log')) {
|
||||
$fp=fopen('/var/www/log/debugError.log', 'a');
|
||||
fwrite($fp, 'Date/Heure;Niveau;Script;Login;Password;Adresse IP;Action SOAP;Ligne;Fichier;Fonction;Classe;Domaine;POST DATA;Message'.EOL);
|
||||
} else
|
||||
$fp=fopen('/var/www/log/debugError.log', 'a');
|
||||
fwrite($fp, date('Y/m/d-H:i:s') .';'. $debugLevel .';'. $_SERVER['PHP_SELF'] .';'. $_SERVER['PHP_AUTH_USER'] .';'. $_SERVER['PHP_AUTH_PW'] .';'.
|
||||
$_SERVER['REMOTE_ADDR'] .';'. $_SERVER['HTTP_SOAPACTION'] .';'.$line.';'. $file.';'. $function.';'. $class .';'.
|
||||
@gethostbyaddr($_SERVER['REMOTE_ADDR']) .';'. $HTTP_RAW_POST_DATA .';'. @memory_get_usage().';'. $message . EOL);
|
||||
fclose($fp);
|
||||
//die($message);
|
||||
}
|
||||
}
|
||||
|
||||
function prepareString($str) {
|
||||
$tabReplace=array();
|
||||
for($c=0;$c<32; $c++)
|
||||
$tabReplace[''.chr($c)]='';
|
||||
for($c=127;$c<256; $c++)
|
||||
$tabReplace[''.chr($c)]='';
|
||||
|
||||
return strtr(
|
||||
strtr(htmlentities(utf8_decode(strtr(strtr($str, 'àáâãäåæçèéêëìíîïðñòóôõöùúûüýÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝŸ…‘‹',
|
||||
"aaaaaaaceeeeiiiionooooouuuuyyAAAAAAACEEEEIIIIONOOOOOUUUUYY.''"), array('œ'=>'oe'))), ENT_QUOTES, 'ISO-8859-1'),array('€'=>'€','’'=>'"')),
|
||||
$tabReplace);
|
||||
//return */
|
||||
//return utf8_encode($str);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
** Déplacement d'un fichier. Retourne false en cas d'erreur.
|
||||
**
|
||||
** @param string $from
|
||||
** @param string $to
|
||||
** @return bool
|
||||
**/
|
||||
function move($from, $to) {
|
||||
return (copy($from, $to) and unlink($from));
|
||||
}
|
||||
|
||||
/** Converti une IP en nombre
|
||||
**
|
||||
** @param string $ip Adresse IP
|
||||
** @return integer
|
||||
**/
|
||||
function getIpNumber($ip) {
|
||||
$tab=explode('.', $ip);
|
||||
return (($tab[0]*256*256*256) + ($tab[1]*256*256) + ($tab[2]*256) + ($tab[3]));
|
||||
}
|
||||
|
||||
/** Vérifie si une IP est dans une plage du type 192.168.3.1-192.168.3.10
|
||||
**
|
||||
** @param string $plage_1 Plage IP de début
|
||||
** @param string $plage_2 Plage IP de fin
|
||||
** @param string $ip Adresse IP à tester
|
||||
** @return boolean
|
||||
**/
|
||||
function in_plage($plage_1,$plage_2,$ip){
|
||||
$ip2=getIpNumber($ip);
|
||||
if ($ip2>=getIpNumber($plage_1) && $ip2<=getIpNumber($plage_2))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Controle si une adresse IP est dans une liste des IP communiquées sous la forme 192.168.3.5-192.68.3.10;192.168.3.*;192.168.3.10
|
||||
**
|
||||
** @param string $strPlageIP La plage d'adresses IP
|
||||
** @param string $adresseIP L'adresse IP à tester
|
||||
** @return boolean
|
||||
**/
|
||||
function checkPlagesIp($strPlageIP, $adresseIP) {
|
||||
$connected=false;
|
||||
$tabIpAllowed=explode(';', trim($strPlageIP));
|
||||
if (count($tabIpAllowed)==1 && $tabIpAllowed[0]=='')
|
||||
$tabIpAllowed=array();
|
||||
|
||||
foreach ($tabIpAllowed as $ip) {
|
||||
$tabPlages=explode('-', $ip);
|
||||
// C'est une plage d'adresse '-'
|
||||
if (isset($tabPlages[1]))
|
||||
$connected=in_plage($tabPlages[0],$tabPlages[1],$adresseIP);
|
||||
else {
|
||||
// C'est une adresse avec ou sans masque '*'
|
||||
if (preg_match('/^'.str_replace('*','.*',str_replace('.','\.',$ip)).'$/', $adresseIP) )
|
||||
$connected=true;
|
||||
}
|
||||
if ($connected) break;
|
||||
}
|
||||
if (count($tabIpAllowed)==0) return false;
|
||||
elseif (!$connected) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @param string $in
|
||||
* @param string $out
|
||||
* @desc compressing the file with the bzip2-extension
|
||||
*/
|
||||
function bzip2 ($in, $out)
|
||||
{
|
||||
if (!file_exists ($in) || !is_readable ($in))
|
||||
return false;
|
||||
if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
|
||||
return false;
|
||||
|
||||
$in_file = fopen ($in, 'rb');
|
||||
$out_file = bzopen ($out.'.bz2', 'wb');
|
||||
|
||||
while (!feof ($in_file)) {
|
||||
$buffer = fgets ($in_file, 4096);
|
||||
bzwrite ($out_file, $buffer, 4096);
|
||||
}
|
||||
|
||||
fclose ($in_file);
|
||||
bzclose ($out_file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @param string $in
|
||||
* @param string $out
|
||||
* @desc uncompressing the file with the bzip2-extension
|
||||
*/
|
||||
function bunzip2 ($in, $out)
|
||||
{
|
||||
if (!file_exists ($in) || !is_readable ($in))
|
||||
return false;
|
||||
if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
|
||||
return false;
|
||||
|
||||
$in_file = bzopen ($in, "rb");
|
||||
$out_file = fopen ($out, "wb");
|
||||
|
||||
while ($buffer = bzread ($in_file, 4096)) {
|
||||
fwrite ($out_file, $buffer, 4096);
|
||||
}
|
||||
|
||||
bzclose ($in_file);
|
||||
fclose ($out_file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
class DomDocument2 extends DOMDocument {
|
||||
|
||||
function getValueFromTag($tagName) {
|
||||
$items=$this->getElementsByTagName($tagName);
|
||||
foreach ($items as $item) {
|
||||
|
||||
return utf8_decode($item->nodeValue);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
878
library/framework/mail/RFC822.php
Normal file
878
library/framework/mail/RFC822.php
Normal file
@ -0,0 +1,878 @@
|
||||
<?php
|
||||
/**
|
||||
) o------------------------------------------------------------------------------o
|
||||
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
|
||||
* | If you use the code commercially (or if you don't want to be restricted by |
|
||||
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
|
||||
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
|
||||
* o------------------------------------------------------------------------------o
|
||||
*
|
||||
* © Copyright 2005 Richard Heyes
|
||||
*/
|
||||
|
||||
/**
|
||||
* RFC 822 Email address list validation Utility
|
||||
*
|
||||
* What is it?
|
||||
*
|
||||
* This class will take an address string, and parse it into it's consituent
|
||||
* parts, be that either addresses, groups, or combinations. Nested groups
|
||||
* are not supported. The structure it returns is pretty straight forward,
|
||||
* and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
|
||||
* print_r() to view the structure.
|
||||
*
|
||||
* How do I use it?
|
||||
*
|
||||
* $address_string = 'My Group: "Richard Heyes" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
|
||||
* $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', TRUE)
|
||||
* print_r($structure);
|
||||
*/
|
||||
|
||||
class Mail_RFC822
|
||||
{
|
||||
/**
|
||||
* The address being parsed by the RFC822 object.
|
||||
* @private string $address
|
||||
*/
|
||||
private $address = '';
|
||||
|
||||
/**
|
||||
* The default domain to use for unqualified addresses.
|
||||
* @private string $default_domain
|
||||
*/
|
||||
private $default_domain = 'localhost';
|
||||
|
||||
/**
|
||||
* Should we return a nested array showing groups, or flatten everything?
|
||||
* @private boolean $nestGroups
|
||||
*/
|
||||
private $nestGroups = true;
|
||||
|
||||
/**
|
||||
* Whether or not to validate atoms for non-ascii characters.
|
||||
* @private boolean $validate
|
||||
*/
|
||||
private $validate = true;
|
||||
|
||||
/**
|
||||
* The array of raw addresses built up as we parse.
|
||||
* @private array $addresses
|
||||
*/
|
||||
private $addresses = array();
|
||||
|
||||
/**
|
||||
* The final array of parsed address information that we build up.
|
||||
* @private array $structure
|
||||
*/
|
||||
private $structure = array();
|
||||
|
||||
/**
|
||||
* The current error message, if any.
|
||||
* @private string $error
|
||||
*/
|
||||
private $error = null;
|
||||
|
||||
/**
|
||||
* An internal counter/pointer.
|
||||
* @private integer $index
|
||||
*/
|
||||
private $index = null;
|
||||
|
||||
/**
|
||||
* The number of groups that have been found in the address list.
|
||||
* @private integer $num_groups
|
||||
* @access public
|
||||
*/
|
||||
private $num_groups = 0;
|
||||
|
||||
/**
|
||||
* A variable so that we can tell whether or not we're inside a
|
||||
* Mail_RFC822 object.
|
||||
* @private boolean $mailRFC822
|
||||
*/
|
||||
private $mailRFC822 = true;
|
||||
|
||||
/**
|
||||
* A limit after which processing stops
|
||||
* @private int $limit
|
||||
*/
|
||||
private $limit = null;
|
||||
|
||||
|
||||
/**
|
||||
* Sets up the object. The address must either be set here or when
|
||||
* calling parseAddressList(). One or the other.
|
||||
*
|
||||
* @access public
|
||||
* @param string $address The address(es) to validate.
|
||||
* @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
|
||||
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
|
||||
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
|
||||
*
|
||||
* @return object Mail_RFC822 A new Mail_RFC822 object.
|
||||
*/
|
||||
function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
|
||||
{
|
||||
if (isset($address)) $this->address = $address;
|
||||
if (isset($default_domain)) $this->default_domain = $default_domain;
|
||||
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
|
||||
if (isset($validate)) $this->validate = $validate;
|
||||
if (isset($limit)) $this->limit = $limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Starts the whole process. The address must either be set here
|
||||
* or when creating the object. One or the other.
|
||||
*
|
||||
* @access public
|
||||
* @param string $address The address(es) to validate.
|
||||
* @param string $default_domain Default domain/host etc.
|
||||
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
|
||||
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
|
||||
*
|
||||
* @return array A structured array of addresses.
|
||||
*/
|
||||
function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
|
||||
{
|
||||
|
||||
if (!isset($this->mailRFC822)) {
|
||||
$obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
|
||||
return $obj->parseAddressList();
|
||||
}
|
||||
|
||||
if (isset($address)) $this->address = $address;
|
||||
if (isset($default_domain)) $this->default_domain = $default_domain;
|
||||
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
|
||||
if (isset($validate)) $this->validate = $validate;
|
||||
if (isset($limit)) $this->limit = $limit;
|
||||
|
||||
$this->structure = array();
|
||||
$this->addresses = array();
|
||||
$this->error = null;
|
||||
$this->index = null;
|
||||
|
||||
while ($this->address = $this->_splitAddresses($this->address)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->address === false || isset($this->error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reset timer since large amounts of addresses can take a long time to
|
||||
// get here
|
||||
set_time_limit(30);
|
||||
|
||||
// Loop through all the addresses
|
||||
for ($i = 0; $i < count($this->addresses); $i++){
|
||||
|
||||
if (($return = $this->_validateAddress($this->addresses[$i])) === false
|
||||
|| isset($this->error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->nestGroups) {
|
||||
$this->structure = array_merge($this->structure, $return);
|
||||
} else {
|
||||
$this->structure[] = $return;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->structure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits an address into seperate addresses.
|
||||
*
|
||||
* @access private
|
||||
* @param string $address The addresses to split.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _splitAddresses($address)
|
||||
{
|
||||
|
||||
if (!empty($this->limit) AND count($this->addresses) == $this->limit) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($this->_isGroup($address) && !isset($this->error)) {
|
||||
$split_char = ';';
|
||||
$is_group = true;
|
||||
} elseif (!isset($this->error)) {
|
||||
$split_char = ',';
|
||||
$is_group = false;
|
||||
} elseif (isset($this->error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Split the string based on the above ten or so lines.
|
||||
$parts = explode($split_char, $address);
|
||||
$string = $this->_splitCheck($parts, $split_char);
|
||||
|
||||
// If a group...
|
||||
if ($is_group) {
|
||||
// If $string does not contain a colon outside of
|
||||
// brackets/quotes etc then something's fubar.
|
||||
|
||||
// First check there's a colon at all:
|
||||
if (strpos($string, ':') === false) {
|
||||
$this->error = 'Invalid address: ' . $string;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now check it's outside of brackets/quotes:
|
||||
if (!$this->_splitCheck(explode(':', $string), ':'))
|
||||
return false;
|
||||
|
||||
// We must have a group at this point, so increase the counter:
|
||||
$this->num_groups++;
|
||||
}
|
||||
|
||||
// $string now contains the first full address/group.
|
||||
// Add to the addresses array.
|
||||
$this->addresses[] = array(
|
||||
'address' => trim($string),
|
||||
'group' => $is_group
|
||||
);
|
||||
|
||||
// Remove the now stored address from the initial line, the +1
|
||||
// is to account for the explode character.
|
||||
$address = trim(substr($address, strlen($string) + 1));
|
||||
|
||||
// If the next char is a comma and this was a group, then
|
||||
// there are more addresses, otherwise, if there are any more
|
||||
// chars, then there is another address.
|
||||
if ($is_group && substr($address, 0, 1) == ','){
|
||||
$address = trim(substr($address, 1));
|
||||
return $address;
|
||||
|
||||
} elseif (strlen($address) > 0) {
|
||||
return $address;
|
||||
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
|
||||
// If you got here then something's off
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for a group at the start of the string.
|
||||
*
|
||||
* @access private
|
||||
* @param string $address The address to check.
|
||||
* @return boolean Whether or not there is a group at the start of the string.
|
||||
*/
|
||||
function _isGroup($address)
|
||||
{
|
||||
// First comma not in quotes, angles or escaped:
|
||||
$parts = explode(',', $address);
|
||||
$string = $this->_splitCheck($parts, ',');
|
||||
|
||||
// Now we have the first address, we can reliably check for a
|
||||
// group by searching for a colon that's not escaped or in
|
||||
// quotes or angle brackets.
|
||||
if (count($parts = explode(':', $string)) > 1) {
|
||||
$string2 = $this->_splitCheck($parts, ':');
|
||||
return ($string2 !== $string);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A common function that will check an exploded string.
|
||||
*
|
||||
* @access private
|
||||
* @param array $parts The exloded string.
|
||||
* @param string $char The char that was exploded on.
|
||||
* @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
|
||||
*/
|
||||
function _splitCheck($parts, $char)
|
||||
{
|
||||
$string = $parts[0];
|
||||
|
||||
for ($i = 0; $i < count($parts); $i++) {
|
||||
if ($this->_hasUnclosedQuotes($string)
|
||||
|| $this->_hasUnclosedBrackets($string, '<>')
|
||||
|| $this->_hasUnclosedBrackets($string, '[]')
|
||||
|| $this->_hasUnclosedBrackets($string, '()')
|
||||
|| substr($string, -1) == '\\') {
|
||||
if (isset($parts[$i + 1])) {
|
||||
$string = $string . $char . $parts[$i + 1];
|
||||
} else {
|
||||
$this->error = 'Invalid address spec. Unclosed bracket or quotes';
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
$this->index = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a string has an unclosed quotes or not.
|
||||
*
|
||||
* @access private
|
||||
* @param string $string The string to check.
|
||||
* @return boolean True if there are unclosed quotes inside the string, false otherwise.
|
||||
*/
|
||||
function _hasUnclosedQuotes($string)
|
||||
{
|
||||
$string = explode('"', $string);
|
||||
$string_cnt = count($string);
|
||||
|
||||
for ($i = 0; $i < (count($string) - 1); $i++)
|
||||
if (substr($string[$i], -1) == '\\')
|
||||
$string_cnt--;
|
||||
|
||||
return ($string_cnt % 2 === 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a string has an unclosed brackets or not. IMPORTANT:
|
||||
* This function handles both angle brackets and square brackets;
|
||||
*
|
||||
* @access private
|
||||
* @param string $string The string to check.
|
||||
* @param string $chars The characters to check for.
|
||||
* @return boolean True if there are unclosed brackets inside the string, false otherwise.
|
||||
*/
|
||||
function _hasUnclosedBrackets($string, $chars)
|
||||
{
|
||||
$num_angle_start = substr_count($string, $chars[0]);
|
||||
$num_angle_end = substr_count($string, $chars[1]);
|
||||
|
||||
$this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
|
||||
$this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
|
||||
|
||||
if ($num_angle_start < $num_angle_end) {
|
||||
$this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
|
||||
return false;
|
||||
} else {
|
||||
return ($num_angle_start > $num_angle_end);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sub function that is used only by hasUnclosedBrackets().
|
||||
*
|
||||
* @access private
|
||||
* @param string $string The string to check.
|
||||
* @param integer &$num The number of occurences.
|
||||
* @param string $char The character to count.
|
||||
* @return integer The number of occurences of $char in $string, adjusted for backslashes.
|
||||
*/
|
||||
function _hasUnclosedBracketsSub($string, &$num, $char)
|
||||
{
|
||||
$parts = explode($char, $string);
|
||||
for ($i = 0; $i < count($parts); $i++){
|
||||
if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
|
||||
$num--;
|
||||
if (isset($parts[$i + 1]))
|
||||
$parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
|
||||
}
|
||||
|
||||
return $num;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to begin checking the address.
|
||||
*
|
||||
* @access private
|
||||
* @param string $address The address to validate.
|
||||
* @return mixed False on failure, or a structured array of address information on success.
|
||||
*/
|
||||
function _validateAddress($address)
|
||||
{
|
||||
$is_group = false;
|
||||
|
||||
if ($address['group']) {
|
||||
$is_group = true;
|
||||
|
||||
// Get the group part of the name
|
||||
$parts = explode(':', $address['address']);
|
||||
$groupname = $this->_splitCheck($parts, ':');
|
||||
$structure = array();
|
||||
|
||||
// And validate the group part of the name.
|
||||
if (!$this->_validatePhrase($groupname)){
|
||||
$this->error = 'Group name did not validate.';
|
||||
return false;
|
||||
} else {
|
||||
// Don't include groups if we are not nesting
|
||||
// them. This avoids returning invalid addresses.
|
||||
if ($this->nestGroups) {
|
||||
$structure = new stdClass;
|
||||
$structure->groupname = $groupname;
|
||||
}
|
||||
}
|
||||
|
||||
$address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
|
||||
}
|
||||
|
||||
// If a group then split on comma and put into an array.
|
||||
// Otherwise, Just put the whole address in an array.
|
||||
if ($is_group) {
|
||||
while (strlen($address['address']) > 0) {
|
||||
$parts = explode(',', $address['address']);
|
||||
$addresses[] = $this->_splitCheck($parts, ',');
|
||||
$address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
|
||||
}
|
||||
} else {
|
||||
$addresses[] = $address['address'];
|
||||
}
|
||||
|
||||
// Check that $addresses is set, if address like this:
|
||||
// Groupname:;
|
||||
// Then errors were appearing.
|
||||
if (!isset($addresses)){
|
||||
$this->error = 'Empty group.';
|
||||
return false;
|
||||
}
|
||||
|
||||
for ($i = 0; $i < count($addresses); $i++) {
|
||||
$addresses[$i] = trim($addresses[$i]);
|
||||
}
|
||||
|
||||
// Validate each mailbox.
|
||||
// Format could be one of: name <geezer@domain.com>
|
||||
// geezer@domain.com
|
||||
// geezer
|
||||
// ... or any other format valid by RFC 822.
|
||||
array_walk($addresses, array($this, 'validateMailbox'));
|
||||
|
||||
// Nested format
|
||||
if ($this->nestGroups) {
|
||||
if ($is_group) {
|
||||
$structure->addresses = $addresses;
|
||||
} else {
|
||||
$structure = $addresses[0];
|
||||
}
|
||||
|
||||
// Flat format
|
||||
} else {
|
||||
if ($is_group) {
|
||||
$structure = array_merge($structure, $addresses);
|
||||
} else {
|
||||
$structure = $addresses;
|
||||
}
|
||||
}
|
||||
|
||||
return $structure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a phrase.
|
||||
*
|
||||
* @access private
|
||||
* @param string $phrase The phrase to check.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _validatePhrase($phrase)
|
||||
{
|
||||
// Splits on one or more Tab or space.
|
||||
$parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
$phrase_parts = array();
|
||||
while (count($parts) > 0){
|
||||
$phrase_parts[] = $this->_splitCheck($parts, ' ');
|
||||
for ($i = 0; $i < $this->index + 1; $i++)
|
||||
array_shift($parts);
|
||||
}
|
||||
|
||||
for ($i = 0; $i < count($phrase_parts); $i++) {
|
||||
// If quoted string:
|
||||
if (substr($phrase_parts[$i], 0, 1) == '"') {
|
||||
if (!$this->_validateQuotedString($phrase_parts[$i]))
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Otherwise it's an atom:
|
||||
if (!$this->_validateAtom($phrase_parts[$i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate an atom which from rfc822 is:
|
||||
* atom = 1*<any CHAR except specials, SPACE and CTLs>
|
||||
*
|
||||
* If validation ($this->validate) has been turned off, then
|
||||
* validateAtom() doesn't actually check anything. This is so that you
|
||||
* can split a list of addresses up before encoding personal names
|
||||
* (umlauts, etc.), for example.
|
||||
*
|
||||
* @access private
|
||||
* @param string $atom The string to check.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _validateAtom($atom)
|
||||
{
|
||||
if (!$this->validate) {
|
||||
// Validation has been turned off; assume the atom is okay.
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for any char from ASCII 0 - ASCII 127
|
||||
if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for specials:
|
||||
if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for control characters (ASCII 0-31):
|
||||
if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate quoted string, which is:
|
||||
* quoted-string = <"> *(qtext/quoted-pair) <">
|
||||
*
|
||||
* @access private
|
||||
* @param string $qstring The string to check
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _validateQuotedString($qstring)
|
||||
{
|
||||
// Leading and trailing "
|
||||
$qstring = substr($qstring, 1, -1);
|
||||
|
||||
// Perform check.
|
||||
return !(preg_match('/(.)[\x0D\\\\"]/', $qstring, $matches) && $matches[1] != '\\');
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a mailbox, which is:
|
||||
* mailbox = addr-spec ; simple address
|
||||
* / phrase route-addr ; name and route-addr
|
||||
*
|
||||
* @access public
|
||||
* @param string &$mailbox The string to check.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function validateMailbox(&$mailbox)
|
||||
{
|
||||
// A couple of defaults.
|
||||
$phrase = '';
|
||||
$comment = '';
|
||||
|
||||
// Catch any RFC822 comments and store them separately
|
||||
$_mailbox = $mailbox;
|
||||
while (strlen(trim($_mailbox)) > 0) {
|
||||
$parts = explode('(', $_mailbox);
|
||||
$before_comment = $this->_splitCheck($parts, '(');
|
||||
if ($before_comment != $_mailbox) {
|
||||
// First char should be a (
|
||||
$comment = substr(str_replace($before_comment, '', $_mailbox), 1);
|
||||
$parts = explode(')', $comment);
|
||||
$comment = $this->_splitCheck($parts, ')');
|
||||
$comments[] = $comment;
|
||||
|
||||
// +1 is for the trailing )
|
||||
$_mailbox = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for($i=0; $i<count(@$comments); $i++){
|
||||
$mailbox = str_replace('('.$comments[$i].')', '', $mailbox);
|
||||
}
|
||||
$mailbox = trim($mailbox);
|
||||
|
||||
// Check for name + route-addr
|
||||
if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
|
||||
$parts = explode('<', $mailbox);
|
||||
$name = $this->_splitCheck($parts, '<');
|
||||
|
||||
$phrase = trim($name);
|
||||
$route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
|
||||
|
||||
if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false)
|
||||
return false;
|
||||
|
||||
// Only got addr-spec
|
||||
} else {
|
||||
// First snip angle brackets if present.
|
||||
if (substr($mailbox,0,1) == '<' && substr($mailbox,-1) == '>')
|
||||
$addr_spec = substr($mailbox,1,-1);
|
||||
else
|
||||
$addr_spec = $mailbox;
|
||||
|
||||
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false)
|
||||
return false;
|
||||
}
|
||||
|
||||
// Construct the object that will be returned.
|
||||
$mbox = new stdClass();
|
||||
|
||||
// Add the phrase (even if empty) and comments
|
||||
$mbox->personal = $phrase;
|
||||
$mbox->comment = isset($comments) ? $comments : array();
|
||||
|
||||
if (isset($route_addr)) {
|
||||
$mbox->mailbox = $route_addr['local_part'];
|
||||
$mbox->host = $route_addr['domain'];
|
||||
$route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
|
||||
} else {
|
||||
$mbox->mailbox = $addr_spec['local_part'];
|
||||
$mbox->host = $addr_spec['domain'];
|
||||
}
|
||||
|
||||
$mailbox = $mbox;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function validates a route-addr which is:
|
||||
* route-addr = "<" [route] addr-spec ">"
|
||||
*
|
||||
* Angle brackets have already been removed at the point of
|
||||
* getting to this function.
|
||||
*
|
||||
* @access private
|
||||
* @param string $route_addr The string to check.
|
||||
* @return mixed False on failure, or an array containing validated address/route information on success.
|
||||
*/
|
||||
function _validateRouteAddr($route_addr)
|
||||
{
|
||||
// Check for colon.
|
||||
if (strpos($route_addr, ':') !== false) {
|
||||
$parts = explode(':', $route_addr);
|
||||
$route = $this->_splitCheck($parts, ':');
|
||||
} else {
|
||||
$route = $route_addr;
|
||||
}
|
||||
|
||||
// If $route is same as $route_addr then the colon was in
|
||||
// quotes or brackets or, of course, non existent.
|
||||
if ($route === $route_addr){
|
||||
unset($route);
|
||||
$addr_spec = $route_addr;
|
||||
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Validate route part.
|
||||
if (($route = $this->_validateRoute($route)) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$addr_spec = substr($route_addr, strlen($route . ':'));
|
||||
|
||||
// Validate addr-spec part.
|
||||
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($route)) {
|
||||
$return['adl'] = $route;
|
||||
} else {
|
||||
$return['adl'] = '';
|
||||
}
|
||||
|
||||
$return = array_merge($return, $addr_spec);
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a route, which is:
|
||||
* route = 1#("@" domain) ":"
|
||||
*
|
||||
* @access private
|
||||
* @param string $route The string to check.
|
||||
* @return mixed False on failure, or the validated $route on success.
|
||||
*/
|
||||
function _validateRoute($route)
|
||||
{
|
||||
// Split on comma.
|
||||
$domains = explode(',', trim($route));
|
||||
|
||||
for ($i = 0; $i < count($domains); $i++) {
|
||||
$domains[$i] = str_replace('@', '', trim($domains[$i]));
|
||||
if (!$this->_validateDomain($domains[$i])) return false;
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a domain, though this is not quite what
|
||||
* you expect of a strict internet domain.
|
||||
*
|
||||
* domain = sub-domain *("." sub-domain)
|
||||
*
|
||||
* @access private
|
||||
* @param string $domain The string to check.
|
||||
* @return mixed False on failure, or the validated domain on success.
|
||||
*/
|
||||
function _validateDomain($domain)
|
||||
{
|
||||
// Note the different use of $subdomains and $sub_domains
|
||||
$subdomains = explode('.', $domain);
|
||||
|
||||
while (count($subdomains) > 0) {
|
||||
$sub_domains[] = $this->_splitCheck($subdomains, '.');
|
||||
for ($i = 0; $i < $this->index + 1; $i++)
|
||||
array_shift($subdomains);
|
||||
}
|
||||
|
||||
for ($i = 0; $i < count($sub_domains); $i++) {
|
||||
if (!$this->_validateSubdomain(trim($sub_domains[$i])))
|
||||
return false;
|
||||
}
|
||||
|
||||
// Managed to get here, so return input.
|
||||
return $domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a subdomain:
|
||||
* subdomain = domain-ref / domain-literal
|
||||
*
|
||||
* @access private
|
||||
* @param string $subdomain The string to check.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _validateSubdomain($subdomain)
|
||||
{
|
||||
if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
|
||||
if (!$this->_validateDliteral($arr[1])) return false;
|
||||
} else {
|
||||
if (!$this->_validateAtom($subdomain)) return false;
|
||||
}
|
||||
|
||||
// Got here, so return successful.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate a domain literal:
|
||||
* domain-literal = "[" *(dtext / quoted-pair) "]"
|
||||
*
|
||||
* @access private
|
||||
* @param string $dliteral The string to check.
|
||||
* @return boolean Success or failure.
|
||||
*/
|
||||
function _validateDliteral($dliteral)
|
||||
{
|
||||
return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate an addr-spec.
|
||||
*
|
||||
* addr-spec = local-part "@" domain
|
||||
*
|
||||
* @access private
|
||||
* @param string $addr_spec The string to check.
|
||||
* @return mixed False on failure, or the validated addr-spec on success.
|
||||
*/
|
||||
function _validateAddrSpec($addr_spec)
|
||||
{
|
||||
$addr_spec = trim($addr_spec);
|
||||
|
||||
// Split on @ sign if there is one.
|
||||
if (strpos($addr_spec, '@') !== false) {
|
||||
$parts = explode('@', $addr_spec);
|
||||
$local_part = $this->_splitCheck($parts, '@');
|
||||
$domain = substr($addr_spec, strlen($local_part . '@'));
|
||||
|
||||
// No @ sign so assume the default domain.
|
||||
} else {
|
||||
$local_part = $addr_spec;
|
||||
$domain = $this->default_domain;
|
||||
}
|
||||
|
||||
if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
|
||||
if (($domain = $this->_validateDomain($domain)) === false) return false;
|
||||
|
||||
// Got here so return successful.
|
||||
return array('local_part' => $local_part, 'domain' => $domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to validate the local part of an address:
|
||||
* local-part = word *("." word)
|
||||
*
|
||||
* @access private
|
||||
* @param string $local_part
|
||||
* @return mixed False on failure, or the validated local part on success.
|
||||
*/
|
||||
function _validateLocalPart($local_part)
|
||||
{
|
||||
$parts = explode('.', $local_part);
|
||||
|
||||
// Split the local_part into words.
|
||||
while (count($parts) > 0){
|
||||
$words[] = $this->_splitCheck($parts, '.');
|
||||
for ($i = 0; $i < $this->index + 1; $i++) {
|
||||
array_shift($parts);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate each word.
|
||||
for ($i = 0; $i < count($words); $i++) {
|
||||
if ($this->_validatePhrase(trim($words[$i])) === false) return false;
|
||||
}
|
||||
|
||||
// Managed to get here, so return the input.
|
||||
return $local_part;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an approximate count of how many addresses are
|
||||
* in the given string. This is APPROXIMATE as it only splits
|
||||
* based on a comma which has no preceding backslash. Could be
|
||||
* useful as large amounts of addresses will end up producing
|
||||
* *large* structures when used with parseAddressList().
|
||||
*
|
||||
* @param string $data Addresses to count
|
||||
* @return int Approximate count
|
||||
*/
|
||||
function approximateCount($data)
|
||||
{
|
||||
return count(preg_split('/(?<!\\\\),/', $data));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a email validating function seperate to the rest
|
||||
* of the class. It simply validates whether an email is of
|
||||
* the common internet form: <user>@<domain>. This can be
|
||||
* sufficient for most people. Optional stricter mode can
|
||||
* be utilised which restricts mailbox characters allowed
|
||||
* to alphanumeric, full stop, hyphen and underscore.
|
||||
*
|
||||
* @param string $data Address to check
|
||||
* @param boolean $strict Optional stricter mode
|
||||
* @return mixed False if it fails, an indexed array
|
||||
* username/domain if it matches
|
||||
*/
|
||||
function isValidInetAddress($data, $strict = false)
|
||||
{
|
||||
$regex = $strict ? '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i';
|
||||
if (preg_match($regex, trim($data), $matches)) {
|
||||
return array($matches[1], $matches[2]);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
1111
library/framework/mail/htmlMimeMail5.php
Normal file
1111
library/framework/mail/htmlMimeMail5.php
Normal file
File diff suppressed because it is too large
Load Diff
311
library/framework/mail/mimePart.php
Normal file
311
library/framework/mail/mimePart.php
Normal file
@ -0,0 +1,311 @@
|
||||
<?php
|
||||
/**
|
||||
* o------------------------------------------------------------------------------o
|
||||
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
|
||||
* | If you use the code commercially (or if you don't want to be restricted by |
|
||||
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
|
||||
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
|
||||
* o------------------------------------------------------------------------------o
|
||||
*
|
||||
* © Copyright Richard Heyes
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* Raw mime encoding class
|
||||
*
|
||||
* What is it?
|
||||
* This class enables you to manipulate and build
|
||||
* a mime email from the ground up.
|
||||
*
|
||||
* Why use this instead of mime.php?
|
||||
* mime.php is a userfriendly api to this class for
|
||||
* people who aren't interested in the internals of
|
||||
* mime mail. This class however allows full control
|
||||
* over the email.
|
||||
*
|
||||
* Eg.
|
||||
*
|
||||
* // Since multipart/mixed has no real body, (the body is
|
||||
* // the subpart), we set the body argument to blank.
|
||||
*
|
||||
* $params['content_type'] = 'multipart/mixed';
|
||||
* $email = new Mail_mimePart('', $params);
|
||||
*
|
||||
* // Here we add a text part to the multipart we have
|
||||
* // already. Assume $body contains plain text.
|
||||
*
|
||||
* $params['content_type'] = 'text/plain';
|
||||
* $params['encoding'] = '7bit';
|
||||
* $text = $email->addSubPart($body, $params);
|
||||
*
|
||||
* // Now add an attachment. Assume $attach is
|
||||
* the contents of the attachment
|
||||
*
|
||||
* $params['content_type'] = 'application/zip';
|
||||
* $params['encoding'] = 'base64';
|
||||
* $params['disposition'] = 'attachment';
|
||||
* $params['dfilename'] = 'example.zip';
|
||||
* $attach =& $email->addSubPart($body, $params);
|
||||
*
|
||||
* // Now build the email. Note that the encode
|
||||
* // function returns an associative array containing two
|
||||
* // elements, body and headers. You will need to add extra
|
||||
* // headers, (eg. Mime-Version) before sending.
|
||||
*
|
||||
* $email = $message->encode();
|
||||
* $email['headers'][] = 'Mime-Version: 1.0';
|
||||
*
|
||||
*
|
||||
* Further examples are available at http://www.phpguru.org
|
||||
*
|
||||
* TODO:
|
||||
* - Set encode() to return the $obj->encoded if encode()
|
||||
* has already been run. Unless a flag is passed to specifically
|
||||
* re-build the message.
|
||||
*
|
||||
* @author Richard Heyes <richard@phpguru.org>
|
||||
* @version $Revision: 1.3 $
|
||||
* @package Mail
|
||||
*/
|
||||
|
||||
class Mail_MIMEPart
|
||||
{
|
||||
/**
|
||||
* The encoding type of this part
|
||||
* @var string
|
||||
*/
|
||||
private $encoding;
|
||||
|
||||
/**
|
||||
* An array of subparts
|
||||
* @var array
|
||||
*/
|
||||
private $subparts;
|
||||
|
||||
/**
|
||||
* The output of this part after being built
|
||||
* @var string
|
||||
*/
|
||||
private $encoded;
|
||||
|
||||
/**
|
||||
* Headers for this part
|
||||
* @var array
|
||||
*/
|
||||
private $headers;
|
||||
|
||||
/**
|
||||
* The body of this part (not encoded)
|
||||
* @var string
|
||||
*/
|
||||
private $body;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* Sets up the object.
|
||||
*
|
||||
* @param $body - The body of the mime part if any.
|
||||
* @param $params - An associative array of parameters:
|
||||
* content_type - The content type for this part eg multipart/mixed
|
||||
* encoding - The encoding to use, 7bit, 8bit, base64, or quoted-printable
|
||||
* cid - Content ID to apply
|
||||
* disposition - Content disposition, inline or attachment
|
||||
* dfilename - Optional filename parameter for content disposition
|
||||
* description - Content description
|
||||
* charset - Character set to use
|
||||
* @access public
|
||||
*/
|
||||
public function __construct($body = '', $params = array())
|
||||
{
|
||||
if (!defined('MAIL_MIMEPART_CRLF')) {
|
||||
define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", true);
|
||||
}
|
||||
|
||||
foreach ($params as $key => $value) {
|
||||
switch ($key) {
|
||||
case 'content_type':
|
||||
$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
|
||||
break;
|
||||
|
||||
case 'encoding':
|
||||
$this->encoding = $value;
|
||||
$headers['Content-Transfer-Encoding'] = $value;
|
||||
break;
|
||||
|
||||
case 'cid':
|
||||
$headers['Content-ID'] = '<' . $value . '>';
|
||||
break;
|
||||
|
||||
case 'disposition':
|
||||
$headers['Content-Disposition'] = $value . (isset($dfilename) ? '; filename="' . $dfilename . '"' : '');
|
||||
break;
|
||||
|
||||
case 'dfilename':
|
||||
if (isset($headers['Content-Disposition'])) {
|
||||
$headers['Content-Disposition'] .= '; filename="' . $value . '"';
|
||||
} else {
|
||||
$dfilename = $value;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'description':
|
||||
$headers['Content-Description'] = $value;
|
||||
break;
|
||||
|
||||
case 'charset':
|
||||
if (isset($headers['Content-Type'])) {
|
||||
$headers['Content-Type'] .= '; charset="' . $value . '"';
|
||||
} else {
|
||||
$charset = $value;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Default content-type
|
||||
if (!isset($headers['Content-Type'])) {
|
||||
$headers['Content-Type'] = 'text/plain';
|
||||
}
|
||||
|
||||
// Default encoding
|
||||
if (!isset($this->encoding)) {
|
||||
$this->encoding = '7bit';
|
||||
}
|
||||
|
||||
// Assign stuff to member variables
|
||||
$this->encoded = array();
|
||||
$this->headers = $headers;
|
||||
$this->body = $body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes and returns the email. Also stores
|
||||
* it in the encoded member variable
|
||||
*
|
||||
* @return An associative array containing two elements,
|
||||
* body and headers. The headers element is itself
|
||||
* an indexed array.
|
||||
*/
|
||||
public function encode()
|
||||
{
|
||||
$encoded =& $this->encoded;
|
||||
|
||||
if (!empty($this->subparts)) {
|
||||
srand((double)microtime()*1000000);
|
||||
$boundary = '=_' . md5(uniqid(rand()) . microtime());
|
||||
$this->headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
|
||||
|
||||
// Add body parts to $subparts
|
||||
for ($i = 0; $i < count($this->subparts); $i++) {
|
||||
$headers = array();
|
||||
$tmp = $this->subparts[$i]->encode();
|
||||
foreach ($tmp['headers'] as $key => $value) {
|
||||
$headers[] = $key . ': ' . $value;
|
||||
}
|
||||
$subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'];
|
||||
}
|
||||
|
||||
$encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF .
|
||||
implode('--' . $boundary . MAIL_MIMEPART_CRLF, $subparts) .
|
||||
'--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
|
||||
} else {
|
||||
$encoded['body'] = $this->getEncodedData($this->body, $this->encoding) . MAIL_MIMEPART_CRLF;
|
||||
}
|
||||
|
||||
// Add headers to $encoded
|
||||
$encoded['headers'] =& $this->headers;
|
||||
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a subpart to current mime part and returns
|
||||
* a reference to it
|
||||
*
|
||||
* @param $body The body of the subpart, if any.
|
||||
* @param $params The parameters for the subpart, same
|
||||
* as the $params argument for constructor.
|
||||
* @return A reference to the part you just added.
|
||||
*/
|
||||
public function addSubPart($body, $params)
|
||||
{
|
||||
$this->subparts[] = new Mail_MIMEPart($body, $params);
|
||||
|
||||
return $this->subparts[count($this->subparts) - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns encoded data based upon encoding passed to it
|
||||
*
|
||||
* @param $data The data to encode.
|
||||
* @param $encoding The encoding type to use, 7bit, base64,
|
||||
* or quoted-printable.
|
||||
*/
|
||||
private function getEncodedData($data, $encoding)
|
||||
{
|
||||
switch ($encoding) {
|
||||
case '8bit':
|
||||
case '7bit':
|
||||
return $data;
|
||||
break;
|
||||
|
||||
case 'quoted-printable':
|
||||
return $this->quotedPrintableEncode($data);
|
||||
break;
|
||||
|
||||
case 'base64':
|
||||
return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
|
||||
break;
|
||||
|
||||
default:
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes data to quoted-printable standard.
|
||||
*
|
||||
* @param $input The data to encode
|
||||
* @param $line_max Optional max line length. Should
|
||||
* not be more than 76 chars
|
||||
*/
|
||||
private function quotedPrintableEncode($input , $line_max = 76)
|
||||
{
|
||||
$lines = preg_split("/\r?\n/", $input);
|
||||
$eol = MAIL_MIMEPART_CRLF;
|
||||
$escape = '=';
|
||||
$output = '';
|
||||
|
||||
while(list(, $line) = each($lines)){
|
||||
|
||||
$linlen = strlen($line);
|
||||
$newline = '';
|
||||
|
||||
for ($i = 0; $i < $linlen; $i++) {
|
||||
$char = substr($line, $i, 1);
|
||||
$dec = ord($char);
|
||||
|
||||
if (($dec == 32) AND ($i == ($linlen - 1))){ // convert space at eol only
|
||||
$char = '=20';
|
||||
|
||||
} elseif($dec == 9) {
|
||||
; // Do nothing if a tab.
|
||||
} elseif(($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
|
||||
$char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
|
||||
}
|
||||
|
||||
if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted
|
||||
$output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay
|
||||
$newline = '';
|
||||
}
|
||||
$newline .= $char;
|
||||
} // end of for
|
||||
$output .= $newline . $eol;
|
||||
}
|
||||
$output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
|
||||
return $output;
|
||||
}
|
||||
} // End of class
|
||||
?>
|
103
library/framework/mail/sendMail.php
Normal file
103
library/framework/mail/sendMail.php
Normal file
@ -0,0 +1,103 @@
|
||||
<?
|
||||
|
||||
function sendMail($from, $to, $subject, $text='', $html='', /*$priority='high', $tabImgFiles=array(), */$tabAttachedFiles=array())
|
||||
{
|
||||
//return true;
|
||||
$to=preg_split("/[\s,;]+/", $to);
|
||||
//die(print_r($to));
|
||||
|
||||
require_once('Mail.php');
|
||||
require_once('Mail/mime.php');
|
||||
|
||||
$headers=array( 'From'=>$from,
|
||||
'To'=>$to,
|
||||
'Subject'=>$subject,
|
||||
// 'Reply-To'=>$from,
|
||||
// 'Return-Path'=>$from,
|
||||
'Content-Transfer-Encoding'=>'8bit',
|
||||
'MIME-Version'=>'1.0',
|
||||
'Date'=>date('D, d M Y H:i:s O'),
|
||||
'Message-ID'=>'<'.md5(date('YmdHis')).'@mail.scores-decisions.com>',
|
||||
'X-Priority'=>3,
|
||||
'X-Mailer'=>'PHP v'.phpversion(),
|
||||
);
|
||||
/*
|
||||
# Boundry for marking the split & Multitype Headers
|
||||
$mime_boundary=md5(time());
|
||||
$headers .= ''.$eol;
|
||||
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
|
||||
$msg = "";
|
||||
*/
|
||||
$mime = new Mail_mime();
|
||||
$footer="";/*
|
||||
|
||||
_______________________________________________________________________
|
||||
Ce message et toutes les pièces jointes (ci-après le \"message\") sont établis a l'intention exclusive de ses destinataires.Si vous recevez ce message par erreur, merci de le détruire et d'en avertir immédiatement l'expéditeur par e-mail. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. Les communications sur Internet n'étant pas sécurisées, SCORES & DECISIONS S.A.S. informe qu'elle ne peut accepter aucune responsabilite quant au contenu de ce message.
|
||||
This mail message and attachments (the \"message\") are solely intended for the addressees. It is confidential in nature . If you receive this message in error, please delete it and immediately notify the sender by e-mail. Any use other than its intended purpose, dissemination or disclosure, either whole or partial, is prohibited except if formal approval is granted. As communication on the Internet is not secure, SCORES & DECISIONS S.A.S. does not accept responsability for the content of this message.
|
||||
|
||||
|
||||
";*/
|
||||
|
||||
if ($text<>'') $mime->setTXTBody($text.$footer);
|
||||
if ($html<>'') $mime->setHTMLBody($html);
|
||||
|
||||
foreach ($tabAttachedFiles as $file)
|
||||
$mime->addAttachment($file);
|
||||
|
||||
//do not ever try to call these lines in reverse order
|
||||
$body = $mime->get();
|
||||
$headers = $mime->headers($headers);
|
||||
|
||||
$params=array( 'host'=>'smtpauth.online.net', // SMTP_HOST
|
||||
'port'=>25, //SMTP_PORT,
|
||||
);
|
||||
$params=array( 'host'=>SMTP_HOST,
|
||||
'port'=>SMTP_PORT,
|
||||
//'debug'=>true,
|
||||
//'persist'=>true,
|
||||
);
|
||||
|
||||
if (SMTP_USER=='' && SMTP_PASS=='')
|
||||
$params['auth'] = false;
|
||||
else {
|
||||
$params['username'] = SMTP_USER;
|
||||
$params['password'] = SMTP_PASS;
|
||||
}/*
|
||||
$params['auth'] = true;
|
||||
$params['username'] = 'buzuk@scores-decisions.com';
|
||||
$params['password'] = 'catsysyo92';
|
||||
*/
|
||||
|
||||
$nbEssais=0;
|
||||
while (1) {
|
||||
// Create the mail object using the Mail::factory method
|
||||
$mail_object = Mail::factory('smtp', $params);
|
||||
// Trying to send the mail
|
||||
$send = $mail_object->send($to, $headers, $body);
|
||||
$nbEssais++;
|
||||
if (PEAR::isError($send)) {
|
||||
/** @todo tester les différents codes erreur **/
|
||||
echo date('Y-m-d H:i:s'). " sendMail.php - essai #$nbEssais : ".$send->getMessage().EOL;
|
||||
if (preg_match('/too many connections|421/i', $send->getMessage()))
|
||||
sleep($nbEssais);
|
||||
else {
|
||||
$strTo=implode(';', $to);
|
||||
file_put_contents( '/var/www/log/sendMailError.log',
|
||||
date('Y-m-d H:i:s')."\t#$nbEssais\t$strTo\t".$send->getMessage().EOL,
|
||||
FILE_APPEND);
|
||||
break;
|
||||
}
|
||||
|
||||
} else {
|
||||
/** Si nous sommes en mode CLI, alors on fait en sorte de ne pas atteindre
|
||||
la limite des 25 mails par minute (ramené à 100 / minute)
|
||||
**/
|
||||
if (MODE_EXEC==MODE_CLI) usleep(500000);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
?>
|
33
library/framework/mail/sendMailOld.php
Normal file
33
library/framework/mail/sendMailOld.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?
|
||||
|
||||
function sendMail($from, $to, $subject, $text='', $html='', $priority='high', $tabImgFiles=array(), $tabAttachedFiles=array())
|
||||
{
|
||||
|
||||
require_once("Mail.php");
|
||||
|
||||
$headers["From"] = $from;
|
||||
$headers["To"] = $to;
|
||||
$headers["Subject"] = $subject;
|
||||
|
||||
$body = $text;
|
||||
|
||||
$params["host"] = SMTP_HOST;
|
||||
$params["port"] = SMTP_PORT;
|
||||
if (SMTP_USER=='' && SMTP_PASS=='')
|
||||
$params["auth"] = false;
|
||||
else {
|
||||
$params["username"] = SMTP_USER;
|
||||
$params["password"] = SMTP_PASS;
|
||||
}
|
||||
|
||||
// Create the mail object using the Mail::factory method
|
||||
$mail_object = Mail::factory("smtp", $params);
|
||||
|
||||
$mail_object->send($to, $headers, $body);
|
||||
|
||||
if (PEAR::isError($mail_object))
|
||||
return $mail_object->getMessage();
|
||||
|
||||
return true;
|
||||
}
|
||||
?>
|
369
library/framework/mail/smtp.php
Normal file
369
library/framework/mail/smtp.php
Normal file
@ -0,0 +1,369 @@
|
||||
<?php
|
||||
/**
|
||||
) o------------------------------------------------------------------------------o
|
||||
* | This is HTMLMimeMail5. It is dual licensed as GPL and a commercial license. |
|
||||
* | If you use the code commercially (or if you don't want to be restricted by |
|
||||
* | the GPL license), you will need the commercial license. It's only £49 (GBP - |
|
||||
* | roughly $98 depending on the exchange rate) and helps me out a lot. Thanks. |
|
||||
* o------------------------------------------------------------------------------o
|
||||
*
|
||||
* © Copyright 2005 Richard Heyes
|
||||
*/
|
||||
|
||||
define('SMTP_STATUS_NOT_CONNECTED', 1, true);
|
||||
define('SMTP_STATUS_CONNECTED', 2, true);
|
||||
|
||||
class smtp
|
||||
{
|
||||
private $authenticated;
|
||||
private $connection;
|
||||
private $recipients;
|
||||
private $headers;
|
||||
private $timeout;
|
||||
private $errors;
|
||||
private $status;
|
||||
private $body;
|
||||
private $from;
|
||||
private $host;
|
||||
private $port;
|
||||
private $helo;
|
||||
private $auth;
|
||||
private $user;
|
||||
private $pass;
|
||||
|
||||
/**
|
||||
* Constructor function. Arguments:
|
||||
* $params - An assoc array of parameters:
|
||||
*
|
||||
* host - The hostname of the smtp server Default: localhost
|
||||
* port - The port the smtp server runs on Default: 25
|
||||
* helo - What to send as the HELO command Default: localhost
|
||||
* (typically the hostname of the
|
||||
* machine this script runs on)
|
||||
* auth - Whether to use basic authentication Default: FALSE
|
||||
* user - Username for authentication Default: <blank>
|
||||
* pass - Password for authentication Default: <blank>
|
||||
* timeout - The timeout in seconds for the call Default: 5
|
||||
* to fsockopen()
|
||||
*/
|
||||
public function __construct($params = array())
|
||||
{
|
||||
|
||||
if(!defined('CRLF'))
|
||||
define('CRLF', "\r\n", TRUE);
|
||||
|
||||
$this->authenticated = FALSE;
|
||||
$this->timeout = 5;
|
||||
$this->status = SMTP_STATUS_NOT_CONNECTED;
|
||||
$this->host = 'smtp.free.fr';
|
||||
$this->port = 25;
|
||||
$this->helo = 'srvsd01';
|
||||
$this->auth = FALSE;
|
||||
$this->user = '';
|
||||
$this->pass = '';
|
||||
$this->errors = array();
|
||||
|
||||
foreach($params as $key => $value){
|
||||
$this->$key = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect function. This will, when called
|
||||
* statically, create a new smtp object,
|
||||
* call the connect function (ie this function)
|
||||
* and return it. When not called statically,
|
||||
* it will connect to the server and send
|
||||
* the HELO command.
|
||||
*/
|
||||
public function connect($params = array())
|
||||
{
|
||||
if (!isset($this->status)) {
|
||||
$obj = new smtp($params);
|
||||
if($obj->connect()){
|
||||
$obj->status = SMTP_STATUS_CONNECTED;
|
||||
}
|
||||
|
||||
return $obj;
|
||||
|
||||
} else {
|
||||
$this->connection = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
|
||||
if (function_exists('socket_set_timeout')) {
|
||||
@socket_set_timeout($this->connection, 5, 0);
|
||||
}
|
||||
|
||||
$greeting = $this->get_data();
|
||||
if (is_resource($this->connection)) {
|
||||
return $this->auth ? $this->ehlo() : $this->helo();
|
||||
} else {
|
||||
$this->errors[] = 'Failed to connect to server: '.$errstr;
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which handles sending the mail.
|
||||
* Arguments:
|
||||
* $params - Optional assoc array of parameters.
|
||||
* Can contain:
|
||||
* recipients - Indexed array of recipients
|
||||
* from - The from address. (used in MAIL FROM:),
|
||||
* this will be the return path
|
||||
* headers - Indexed array of headers, one header per array entry
|
||||
* body - The body of the email
|
||||
* It can also contain any of the parameters from the connect()
|
||||
* function
|
||||
*/
|
||||
public function send($params = array())
|
||||
{
|
||||
foreach ($params as $key => $value) {
|
||||
$this->set($key, $value);
|
||||
}
|
||||
|
||||
if ($this->is_connected()) {
|
||||
|
||||
// Do we auth or not? Note the distinction between the auth variable and auth() function
|
||||
if ($this->auth AND !$this->authenticated) {
|
||||
if(!$this->auth())
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->mail($this->from);
|
||||
|
||||
if (is_array($this->recipients)) {
|
||||
foreach ($this->recipients as $value) {
|
||||
$this->rcpt($value);
|
||||
}
|
||||
} else {
|
||||
$this->rcpt($this->recipients);
|
||||
}
|
||||
|
||||
if (!$this->data()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Transparency
|
||||
$headers = str_replace(CRLF.'.', CRLF.'..', trim(implode(CRLF, $this->headers)));
|
||||
$body = str_replace(CRLF.'.', CRLF.'..', $this->body);
|
||||
$body = substr($body, 0, 1) == '.' ? '.'.$body : $body;
|
||||
|
||||
$this->send_data($headers);
|
||||
$this->send_data('');
|
||||
$this->send_data($body);
|
||||
$this->send_data('.');
|
||||
|
||||
$result = (substr(trim($this->get_data()), 0, 3) === '250');
|
||||
//$this->rset();
|
||||
return $result;
|
||||
} else {
|
||||
$this->errors[] = 'Not connected!';
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to implement HELO cmd
|
||||
*/
|
||||
private function helo()
|
||||
{
|
||||
if(is_resource($this->connection)
|
||||
AND $this->send_data('HELO '.$this->helo)
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = 'HELO command failed, output: ' . trim(substr(trim($error),3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to implement EHLO cmd
|
||||
*/
|
||||
private function ehlo()
|
||||
{
|
||||
if (is_resource($this->connection)
|
||||
AND $this->send_data('EHLO '.$this->helo)
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = 'EHLO command failed, output: ' . trim(substr(trim($error),3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to implement RSET cmd
|
||||
*/
|
||||
private function rset()
|
||||
{
|
||||
if (is_resource($this->connection)
|
||||
AND $this->send_data('RSET')
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = 'RSET command failed, output: ' . trim(substr(trim($error),3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to implement QUIT cmd
|
||||
*/
|
||||
private function quit()
|
||||
{
|
||||
if(is_resource($this->connection)
|
||||
AND $this->send_data('QUIT')
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '221' ){
|
||||
|
||||
fclose($this->connection);
|
||||
$this->status = SMTP_STATUS_NOT_CONNECTED;
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = 'QUIT command failed, output: ' . trim(substr(trim($error),3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to implement AUTH cmd
|
||||
*/
|
||||
private function auth()
|
||||
{
|
||||
if (is_resource($this->connection)
|
||||
AND $this->send_data('AUTH LOGIN')
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '334'
|
||||
AND $this->send_data(base64_encode($this->user)) // Send username
|
||||
AND substr(trim($error = $this->get_data()),0,3) === '334'
|
||||
AND $this->send_data(base64_encode($this->pass)) // Send password
|
||||
AND substr(trim($error = $this->get_data()),0,3) === '235' ){
|
||||
|
||||
$this->authenticated = true;
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = 'AUTH command failed: ' . trim(substr(trim($error),3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that handles the MAIL FROM: cmd
|
||||
*/
|
||||
private function mail($from)
|
||||
{
|
||||
if ($this->is_connected()
|
||||
AND $this->send_data('MAIL FROM:<'.$from.'>')
|
||||
AND substr(trim($this->get_data()), 0, 2) === '250' ) {
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that handles the RCPT TO: cmd
|
||||
*/
|
||||
private function rcpt($to)
|
||||
{
|
||||
if($this->is_connected()
|
||||
AND $this->send_data('RCPT TO:<'.$to.'>')
|
||||
AND substr(trim($error = $this->get_data()), 0, 2) === '25' ){
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = trim(substr(trim($error), 3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that sends the DATA cmd
|
||||
*/
|
||||
private function data()
|
||||
{
|
||||
if($this->is_connected()
|
||||
AND $this->send_data('DATA')
|
||||
AND substr(trim($error = $this->get_data()), 0, 3) === '354' ) {
|
||||
|
||||
return true;
|
||||
|
||||
} else {
|
||||
$this->errors[] = trim(substr(trim($error), 3));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to determine if this object
|
||||
* is connected to the server or not.
|
||||
*/
|
||||
private function is_connected()
|
||||
{
|
||||
return (is_resource($this->connection) AND ($this->status === SMTP_STATUS_CONNECTED));
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to send a bit of data
|
||||
*/
|
||||
private function send_data($data)
|
||||
{
|
||||
if(is_resource($this->connection)){
|
||||
return fwrite($this->connection, $data.CRLF, strlen($data)+2);
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get data.
|
||||
*/
|
||||
private function get_data()
|
||||
{
|
||||
$return = '';
|
||||
$line = '';
|
||||
$loops = 0;
|
||||
|
||||
if(is_resource($this->connection)){
|
||||
while((strpos($return, CRLF) === FALSE OR substr($line,3,1) !== ' ') AND $loops < 100){
|
||||
$line = fgets($this->connection, 512);
|
||||
$return .= $line;
|
||||
$loops++;
|
||||
}
|
||||
return $return;
|
||||
|
||||
}else
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a variable
|
||||
*/
|
||||
public function set($var, $value)
|
||||
{
|
||||
$this->$var = $value;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to return the errors array
|
||||
*/
|
||||
public function getErrors()
|
||||
{
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
|
||||
} // End of class
|
||||
?>
|
215
library/framework/sphinx/recherche.php
Normal file
215
library/framework/sphinx/recherche.php
Normal file
@ -0,0 +1,215 @@
|
||||
<?
|
||||
|
||||
include_once(FWK_PATH.'common/strings.php');
|
||||
include_once(FWK_PATH.'sphinx/sphinxapi2.php');
|
||||
|
||||
function search($index, $findMe, $tabFiltres=array(), $deb=0, $nbRep=20, $max=200, $any=false) {
|
||||
$deb=$deb*1;
|
||||
$nbRep=$nbRep*1;
|
||||
$max=$max*1;
|
||||
|
||||
debugLog('I',"Search Sphinx dans $index de $findMe ($deb, $nbRep, $max) avec ".implode(',',$tabFiltres),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
|
||||
$iDb=new WDB();
|
||||
/*
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer ( $host, $port );
|
||||
|
||||
$cl->SetWeights ( array ( 100, 1 ) );
|
||||
$cl->SetMatchMode ( $mode );
|
||||
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
|
||||
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
|
||||
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
|
||||
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
|
||||
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
|
||||
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
|
||||
|
||||
$res = $cl->Query ( $q, $index );
|
||||
*/
|
||||
|
||||
//$any = false; // si false $index='xxx'
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer (SPHINX_HOST, SPHINX_PORT);
|
||||
$cl->SetConnectTimeout ( 1 );
|
||||
$cl->SetLimits ($deb, $nbRep, $max);//0, $nbRep*10);
|
||||
//$cl->SetSortMode(SPH_SORT_ATTR_DESC, 'actif');//siege');
|
||||
if (substr($index,0,4)=='etab')
|
||||
$cl->SetSortMode(SPH_SORT_EXTENDED, 'rang DESC, actif DESC, siege DESC');//, nic DESC
|
||||
|
||||
//$cl->SetWeights ( array ( 100, 1 ) );
|
||||
//$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
|
||||
$cl->SetMatchMode (SPH_MATCH_EXTENDED);
|
||||
foreach ($tabFiltres as $nomFiltre => $valFiltre)
|
||||
$cl->SetFilter($nomFiltre, array(0=>$valFiltre));
|
||||
|
||||
$cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );
|
||||
//$cl->SetArrayResult ( true );
|
||||
|
||||
$res = $cl->Query ( $findMe, $index );
|
||||
|
||||
if ($res===false) {
|
||||
debugLog('I',"Search Sphinx : Pas de réponse pour $findMe avec ".implode(',',$tabFiltres).' ('.$cl->GetLastError() .')',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
return array( 'results'=>false,
|
||||
'nbRet'=>0,
|
||||
'nbTot'=>0,
|
||||
'duration'=>$res[time]);//return false;
|
||||
|
||||
} else { // Le moteur est opérationel
|
||||
if ( $cl->GetLastWarning() ) {
|
||||
debugLog('I',"Search Sphinx : Warning pour $findMe - ".$cl->GetLastWarning(),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
|
||||
}
|
||||
/* print "Query '$findMe' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
|
||||
print "Query stats :\n";
|
||||
if ( is_array($res["words"]) )
|
||||
foreach ( $res["words"] as $word => $info )
|
||||
print " - '$word' found $info[hits] times in $info[docs] documents\n";
|
||||
print "\n";*/
|
||||
debugLog('I',"'Search Sphinx dans $index de $findMe (Filtre=".implode(',',$tabFiltres)."), Deb=$deb, nbRep=$nbRep, max=$max, any=$any",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
// debugLog('I',"Search Sphinx dans $index ". print_r($tabFiltres, true));
|
||||
|
||||
$tabRet=array();
|
||||
if ( @is_array($res['matches'])) { // il y a des données à renvoyer
|
||||
if (substr($index,0,4)=='etab') { // Recherche par étab
|
||||
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne
|
||||
$listeEtab=$iDb->select('etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, e.actif",
|
||||
"id=$doc LIMIT 0,1", true);
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
//'NafEtabLib'=>$etab['LibNafEt'],
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
//'NafEntLib'=>$etab['LibNafEt'],
|
||||
);
|
||||
}
|
||||
} else { // Recherche par dirigeant
|
||||
$findMe4=trim(substr($findMe,0,4));
|
||||
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne dirigeant
|
||||
/*$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
|
||||
"d.dateEffet, d.fonction, d.depart, e.actif",
|
||||
"d.id=$doc AND d.id=b.id AND b.siren=e.siren AND (d.nom LIKE '%$findMe4%' OR d.prenom LIKE '%$findMe4%' OR d.nomUsage LIKE '%$findMe4%' OR d.rs LIKE '%$findMe4%') LIMIT 0,1", true);
|
||||
if (count($listeEtab)==0)
|
||||
$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
|
||||
"d.dateEffet, d.fonction, d.depart, e.actif",
|
||||
"d.id=$doc AND d.id=b.id AND b.siren=e.siren LIMIT 0,1", true);
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
'rs'=>$etab['rs'],
|
||||
'nomD'=>$etab['nom'],
|
||||
'prenom'=>$etab['prenom'],
|
||||
'nomUsage'=>$etab['nomUsage'],
|
||||
'dateEffet'=>$etab['dateEffet'],
|
||||
'fonction'=>$etab['fonction'],
|
||||
'depart'=>$etab['depart'],
|
||||
);
|
||||
}
|
||||
*/
|
||||
//print_r($tabRet);
|
||||
//die();
|
||||
$listeEtab=$iDb->select('rncs_dirigeants d, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, /*d.rs,*/ d.nom, d.prenom, /*d.nomUsage,*/ d.naissance_date, d.naissance_lieu, ".
|
||||
"d.fonction_lib, /*d.depart,*/ e.actif",
|
||||
"d.id=$doc AND d.siren=e.siren AND e.siege=1 ORDER BY e.actif DESC LIMIT 0,1", true);
|
||||
//die(print_r($listeEtab));
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
'rs'=>'',//$etab['rs'],
|
||||
'nomD'=>$etab['nom'],
|
||||
'prenom'=>$etab['prenom'],
|
||||
'nomUsage'=>'',//$etab['nomUsage'],
|
||||
'dateEffet'=>'',//$etab['dateEffet'],
|
||||
'fonction'=>$etab['fonction_lib'],
|
||||
'depart'=>0,//$etab['depart'],
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
debugLog('I','Search Sphinx : Retourne '. $res[total].'/'. $res[total_found] .' en '.$res[time] .'secondes',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
return array( 'results'=>$tabRet,
|
||||
'nbRet'=>$res[total],
|
||||
'nbTot'=>$res[total_found],
|
||||
'duration'=>$res[time],
|
||||
);
|
||||
}
|
||||
?>
|
231
library/framework/sphinx/recherche2.php
Normal file
231
library/framework/sphinx/recherche2.php
Normal file
@ -0,0 +1,231 @@
|
||||
<?
|
||||
|
||||
include_once(FWK_PATH.'common/strings.php');
|
||||
include_once(FWK_PATH.'sphinx/sphinxapi2.php');
|
||||
|
||||
function search2($index, $findMe, $tabFiltres=array(), $deb=0, $nbRep=20, $max=200, $any=false) {
|
||||
$deb=$deb*1;
|
||||
$nbRep=$nbRep*1;
|
||||
$max=$max*1;
|
||||
|
||||
debugLog('I',"Search Sphinx dans $index de $findMe ($deb, $nbRep, $max) avec ".implode(',',$tabFiltres),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
|
||||
$iDb=new WDB();
|
||||
/*
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer ( $host, $port );
|
||||
|
||||
$cl->SetWeights ( array ( 100, 1 ) );
|
||||
$cl->SetMatchMode ( $mode );
|
||||
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
|
||||
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
|
||||
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
|
||||
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
|
||||
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
|
||||
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
|
||||
|
||||
$res = $cl->Query ( $q, $index );
|
||||
*/
|
||||
|
||||
//$any = false; // si false $index='xxx'
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer (SPHINX_HOST, SPHINX_PORT);
|
||||
$cl->SetConnectTimeout ( 1 );
|
||||
$cl->SetLimits ($deb, $nbRep, $max);//0, $nbRep*10);
|
||||
//$cl->SetSortMode(SPH_SORT_ATTR_DESC, 'actif');//siege');
|
||||
if (substr($index,0,4)=='etab')
|
||||
$cl->SetSortMode(SPH_SORT_EXTENDED, 'rang DESC, actif DESC, siege DESC');//, nic DESC
|
||||
|
||||
//$cl->SetWeights ( array ( 100, 1 ) );
|
||||
//$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
|
||||
$cl->SetMatchMode (SPH_MATCH_EXTENDED);
|
||||
foreach ($tabFiltres as $nomFiltre => $valFiltre)
|
||||
$cl->SetFilter($nomFiltre, array(0=>$valFiltre));
|
||||
|
||||
$cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );
|
||||
//$cl->SetArrayResult ( true );
|
||||
|
||||
$res = $cl->Query ( $findMe, $index );
|
||||
//@sendMail('production@scores-decisions.com', 'ylenaour@scores-decisions.com', "Debug", print_r($res,true)) ;
|
||||
if ($res===false) {
|
||||
debugLog('I',"Search Sphinx : Pas de réponse pour $findMe avec ".implode(',',$tabFiltres).' ('.$cl->GetLastError() .')',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
return array( 'results'=>false,
|
||||
'nbRet'=>0,
|
||||
'nbTot'=>0,
|
||||
'duration'=>$res[time]);//return false;
|
||||
|
||||
} else { // Le moteur est opérationel
|
||||
if ( $cl->GetLastWarning() ) {
|
||||
debugLog('I',"Search Sphinx : Warning pour $findMe - ".$cl->GetLastWarning(),__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
|
||||
}
|
||||
/* print "Query '$findMe' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
|
||||
print "Query stats :\n";
|
||||
if ( is_array($res["words"]) )
|
||||
foreach ( $res["words"] as $word => $info )
|
||||
print " - '$word' found $info[hits] times in $info[docs] documents\n";
|
||||
print "\n";*/
|
||||
debugLog('I',"'Search Sphinx dans $index de $findMe (Filtre=".implode(',',$tabFiltres)."), Deb=$deb, nbRep=$nbRep, max=$max, any=$any",__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
// debugLog('I',"Search Sphinx dans $index ". print_r($tabFiltres, true));
|
||||
|
||||
$tabRet=array();
|
||||
if ( @is_array($res['matches'])) { // il y a des données à renvoyer
|
||||
if (substr($index,0,4)=='etab') { // Recherche par étab
|
||||
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne
|
||||
$listeEtab=$iDb->select('etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, e.actif",
|
||||
"id=$doc LIMIT 0,1", true);
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
//'NafEtabLib'=>$etab['LibNafEt'],
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
//'NafEntLib'=>$etab['LibNafEt'],
|
||||
);
|
||||
}
|
||||
} elseif ($index=='idx_histo') {
|
||||
foreach ( $res['matches'] as $doc => $docinfo ) {
|
||||
$listeEtab=$iDb->select('histobodacc.bodacc_ocr',
|
||||
"'Histo' as Loc, id, nomFichier, annee1, bod, texte",
|
||||
"id=$doc");
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Fichier'=>$etab['nomFichier'],
|
||||
'Annee'=>$etab['annee1'],
|
||||
'Code'=>$etab['bod'],
|
||||
'Texte'=>$etab['texte'],
|
||||
);
|
||||
}
|
||||
} else { // Recherche par dirigeant
|
||||
$findMe4=trim(substr($findMe,0,4));
|
||||
foreach ( $res['matches'] as $doc => $docinfo ) { // On balaye chaque ligne dirigeant
|
||||
/*$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
|
||||
"d.dateEffet, d.fonction, d.depart, e.actif",
|
||||
"d.id=$doc AND d.id=b.id AND b.siren=e.siren AND (d.nom LIKE '%$findMe4%' OR d.prenom LIKE '%$findMe4%' OR d.nomUsage LIKE '%$findMe4%' OR d.rs LIKE '%$findMe4%') LIMIT 0,1", true);
|
||||
if (count($listeEtab)==0)
|
||||
$listeEtab=$iDb->select('bodacc_dirigeants d, bodacc_detail b, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, d.rs, d.nom, d.prenom, d.nomUsage, ".
|
||||
"d.dateEffet, d.fonction, d.depart, e.actif",
|
||||
"d.id=$doc AND d.id=b.id AND b.siren=e.siren LIMIT 0,1", true);
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
'rs'=>$etab['rs'],
|
||||
'nomD'=>$etab['nom'],
|
||||
'prenom'=>$etab['prenom'],
|
||||
'nomUsage'=>$etab['nomUsage'],
|
||||
'dateEffet'=>$etab['dateEffet'],
|
||||
'fonction'=>$etab['fonction'],
|
||||
'depart'=>$etab['depart'],
|
||||
);
|
||||
}
|
||||
*/
|
||||
//print_r($tabRet);
|
||||
//die();
|
||||
$listeEtab=$iDb->select('rncs_dirigeants d, etablissements e',
|
||||
"'Etab' as Loc, e.id, e.source, e.source_id, e.triCode, e.autre_id, e.siren, e.nic, e.siege, ".
|
||||
"e.raisonSociale, e.enseigne, e.sigle, e.adr_num, e.adr_btq, e.adr_typeVoie, e.adr_libVoie, ".
|
||||
"e.adr_comp, e.adr_cp, e.adr_ville, e.tel, e.fax, e.cj, e.ape_etab, e.ape_entrep, ".
|
||||
"CONCAT(e.siren, e.nic) as siret, /*d.rs,*/ d.nom, d.prenom, /*d.nomUsage,*/ d.naissance_date, d.naissance_lieu, ".
|
||||
"d.fonction_lib, /*d.depart,*/ e.actif",
|
||||
"d.id=$doc AND d.siren=e.siren AND e.siege=1 ORDER BY e.actif DESC LIMIT 0,1", true);
|
||||
//die(print_r($listeEtab));
|
||||
$etab=$listeEtab[0];
|
||||
$tabRet[]=array( 'Localisation'=>$etab['Loc'],
|
||||
'id'=>$doc,
|
||||
'Pertinence'=>$docinfo['weight'],
|
||||
'Siret'=>$etab['siret'],
|
||||
'Siege'=>$etab['siege'],
|
||||
'Nom'=>$etab['raisonSociale'],
|
||||
'Sigle'=>$etab['sigle'],
|
||||
'Enseigne'=>$etab['enseigne'],
|
||||
'Adresse'=>trim($etab['adr_num'] .' '.
|
||||
$etab['adr_btq'] .' '.
|
||||
$etab['adr_typeVoie'] .' '.
|
||||
$etab['adr_libVoie'] .' '.
|
||||
$etab['adr_comp']),
|
||||
'CP'=>$etab['adr_cp'],
|
||||
'Ville'=>$etab['adr_ville'],
|
||||
'Tel'=>$etab['tel'],
|
||||
'Fax'=>$etab['fax'],
|
||||
'FJ'=>$etab['cj'],
|
||||
'Siren'=>$etab['siren'],
|
||||
'Nic'=>$etab['nic'],
|
||||
'Actif'=>$etab['actif'],
|
||||
'NafEtab'=>$etab['ape_etab'], // Etablissement
|
||||
'NafEnt'=>$etab['ape_entrep'], // Entreprise
|
||||
'rs'=>'',//$etab['rs'],
|
||||
'nomD'=>$etab['nom'],
|
||||
'prenom'=>$etab['prenom'],
|
||||
'nomUsage'=>'',//$etab['nomUsage'],
|
||||
'dateEffet'=>'',//$etab['dateEffet'],
|
||||
'fonction'=>$etab['fonction_lib'],
|
||||
'depart'=>0,//$etab['depart'],
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
debugLog('I','Search Sphinx : Retourne '. $res[total].'/'. $res[total_found] .' en '.$res[time] .'secondes',__LINE__,__FILE__, __FUNCTION__, __CLASS__);
|
||||
return array( 'results'=>$tabRet,
|
||||
'nbRet'=>$res[total],
|
||||
'nbTot'=>$res[total_found],
|
||||
'duration'=>$res[time],
|
||||
'words'=>$res['words'],
|
||||
);
|
||||
}
|
||||
?>
|
1063
library/framework/sphinx/sphinxapi.php
Normal file
1063
library/framework/sphinx/sphinxapi.php
Normal file
File diff suppressed because it is too large
Load Diff
1187
library/framework/sphinx/sphinxapi2.php
Normal file
1187
library/framework/sphinx/sphinxapi2.php
Normal file
File diff suppressed because it is too large
Load Diff
1628
library/framework/sphinx/sphinxapi3.php
Normal file
1628
library/framework/sphinx/sphinxapi3.php
Normal file
File diff suppressed because it is too large
Load Diff
187
library/framework/sphinx/test/index.php
Normal file
187
library/framework/sphinx/test/index.php
Normal file
@ -0,0 +1,187 @@
|
||||
<?
|
||||
if (!isset($_REQUEST['typeRecherche']) || ( $_REQUEST['typeRecherche']<>'exacte' &&
|
||||
$_REQUEST['typeRecherche']<>'approx') )
|
||||
$_REQUEST['typeRecherche']='exacte';
|
||||
|
||||
if (!isset($_REQUEST['nbRep']) || $_REQUEST['nbRep']<25 || $_REQUEST['nbRep']>200 )
|
||||
$_REQUEST['nbRep']=25;
|
||||
if (!isset($_REQUEST['nom'])) $_REQUEST['nom']='';
|
||||
if (!isset($_REQUEST['prenom'])) $_REQUEST['prenom']='';
|
||||
if (!isset($_REQUEST['codePostal'])) $_REQUEST['codePostal']='';
|
||||
?>
|
||||
<form action="./?action=rechercher" method="POST">
|
||||
<input type="hidden" name="submitted" value="1">
|
||||
<table>
|
||||
<tr><td><i>Informations sur la personne</i></td><td> </td></tr>
|
||||
<tr><td><b>NOM *</b></td><td><input type="text" name="nom" value="<?=$_REQUEST['nom']?>"></td></tr>
|
||||
<tr><td>Prénom *</td><td><input type="text" name="prenom" value="<?=$_REQUEST['prenom']?>"></td></tr>
|
||||
<tr><td>Département ou Code Postal de résidence *</td><td><input type="text" name="codePostal" value="<?=$_REQUEST['codePostal']?>"></td></tr>
|
||||
<tr><td>Civilité</td><td><input type="radio" name="civilite" value="Mlle"> Mlle
|
||||
<input type="radio" name="civilite" value="Mme"> Mme
|
||||
<input type="radio" name="civilite" value="M"> M</td></tr>
|
||||
<tr><td>Date de Naissance *</td><td><input type="text" name="naissJJ" size="3" maxlength="2"> / <input type="text" name="naissMM" size="3" maxlength="2"> / <input type="text" name="naissAA" size="5" maxlength="4"></td></tr>
|
||||
<tr><td>Ville de Naissance</td><td><input type="text" name="naissVille"></td></tr>
|
||||
<tr><td>Département de Naissance</td><td><input type="text" name="naissDept"></td></tr>
|
||||
<tr><td>Pays de Naissance</td><td><input type="text" name="naissPays"></td></tr>
|
||||
<tr><td>Adresse de résidence *</td><td><input type="text" name="adresse"></td></tr>
|
||||
<tr><td>Ville de résidence *</td><td><input type="text" name="adresseVille"></td></tr>
|
||||
<tr><td>Montant du crédit demandé *</td><td><input type="text" name="creditDemande"></td></tr>
|
||||
<tr><td>SIREN si entrepreneur individuel</td><td><input type="text" name="siren"></td></tr>
|
||||
<tr><td>RIB</td><td><input type="text" name="siren"></td></tr>
|
||||
<tr><td>Téléphone Domicile</td><td><input type="text" name="telephoneMaison"> <i>Liste rouge <input type="radio" name="listeRouge" value="Oui"> Oui <input type="radio" name="listeRouge" value="Non"> Non</td></tr>
|
||||
<tr><td>Téléphone Professionel</td><td><input type="text" name="telephonePro"></td></tr>
|
||||
<tr><td>Téléphone Portable</td><td><input type="text" name="telephonePort"></td></tr>
|
||||
<tr><td><i>Informations complémentaires</i></td><td> </td></tr>
|
||||
<tr><td>Nom de l'employeur</td><td><input type="text" name="employeurNom"></td></tr>
|
||||
<tr><td>Adresse de l'employeur</td><td><input type="text" name="employeurAdresse"></td></tr>
|
||||
<tr><td>Code Postal de l'employeur</td><td><input type="text" name="employeurCP"></td></tr>
|
||||
<tr><td>Ville de l'employeur</td><td><input type="text" name="employeurVille"></td></tr>
|
||||
<tr><td> </td><td> </td></tr>
|
||||
<tr><td>Type de recherche</td><td><input type="radio" <?if ($_REQUEST['typeRecherche']=='exacte') echo 'CHECKED';?> name="typeRecherche" value="exacte">Exacte <input type="radio" <?if ($_REQUEST['typeRecherche']=='approx') echo 'CHECKED';?> name="typeRecherche" value="approx">Approchante</td></tr>
|
||||
<tr><td>Nombre de résultats</td><td><select name="nbRep"><option value="25">25</option><option value="50">50</option><option value="100">100</option><option value="200">200</option></select></td></tr>
|
||||
</table>
|
||||
<input type="submit" value="Valider"> <input type="reset" value="RAZ">
|
||||
</form>
|
||||
<?php
|
||||
include_once('/var/www/includes/mysql.php');
|
||||
$con = mysql_pconnect('localhost', 'root', 'bzh4231*');
|
||||
if (!($con === false)) {
|
||||
if (mysql_select_db('npaipp', $con) === false)
|
||||
die('Could not select database: ' . mysql_error());
|
||||
}
|
||||
|
||||
require ( "sphinxapi.php" );
|
||||
|
||||
//die ( "usage: php -f test.php [--any] <word [word [word [...]]]> [--group <group>] [-p <port>] [-i <index>]\n" );
|
||||
|
||||
$q = $_REQUEST['nom'].' '.$_REQUEST['prenom'];
|
||||
$any = false; // si false $index='xxx'
|
||||
$port = 3312;
|
||||
if ($_REQUEST['typeRecherche']=='exacte')
|
||||
$index="annuaire_pp";
|
||||
else
|
||||
$index="annuaire_pp_shx";
|
||||
$nbRep=$_REQUEST['nbRep'];
|
||||
|
||||
////////////
|
||||
// do query
|
||||
////////////
|
||||
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer ( "localhost", $port );
|
||||
$cl->SetLimits (0, $nbRep);
|
||||
$cl->SetWeights ( array ( 100, 1 ) );
|
||||
$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
|
||||
if ( isset($_REQUEST['codePostal']) && $_REQUEST['codePostal']<>'' ) {
|
||||
$tailleCP=strlen($_REQUEST['codePostal']);
|
||||
if ($tailleCP>1 && $tailleCP<4) $cl->SetFilter("departement", array(0=>$_REQUEST['codePostal']));
|
||||
elseif ($tailleCP==5) $cl->SetFilter("codepostal", array(0=>$_REQUEST['codePostal']));
|
||||
}
|
||||
if ( isset($_REQUEST['telephoneMaison']) && $_REQUEST['telephoneMaison']<>'' ) {
|
||||
$cl->SetFilter("tel", array(0=>$_REQUEST['telephoneMaison']));
|
||||
}
|
||||
$res = $cl->Query ( $q, $index );
|
||||
|
||||
////////////////
|
||||
// print me out
|
||||
////////////////
|
||||
|
||||
if ( $res===false )
|
||||
{
|
||||
print "Query failed: " . $cl->GetLastError() . ".\n";
|
||||
|
||||
} else
|
||||
{
|
||||
if ( $cl->GetLastWarning() )
|
||||
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
|
||||
|
||||
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.<br/>";
|
||||
print "<h3>Query stats</h3><ul>";
|
||||
if ( is_array($res["words"]) )
|
||||
foreach ( $res["words"] as $word => $info )
|
||||
print "<li>'$word' found $info[hits] times in $info[docs] documents</li>";
|
||||
print "</ul>";
|
||||
|
||||
if ( is_array($res["matches"]) )
|
||||
{
|
||||
$n = 1;
|
||||
print "<h3>Reponses :</h3><ul>";
|
||||
foreach ( $res["matches"] as $doc => $docinfo )
|
||||
{
|
||||
// print "<li>$n. doc_id=$doc, weight=$docinfo[weight]<br/>";
|
||||
// foreach ( $res["attrs"] as $attrname => $attrtype )
|
||||
// {
|
||||
$info=mysql_select('particuliers', 'Nom, Adresse, CodePostal, Ville, Tel, Fax', "id=$doc");
|
||||
$personne=$info[0];
|
||||
echo '<li><i>'. $n .'.</i> '. $personne['Nom'] .' ('. $docinfo[weight] .' %)<br/>';
|
||||
echo $personne['Adresse'] .'<br/>';
|
||||
echo $personne['CodePostal'] .' '. $personne['Ville'] .'<br/>';
|
||||
if ($personne['Tel']<>'') echo 'Tél : '.$personne['Tel'].'<br/>';
|
||||
if ($personne['Fax']<>'') echo 'Fax : '.$personne['Fax'].'<br/>';
|
||||
echo "</li>\n";
|
||||
$n++;
|
||||
|
||||
/* $value = $docinfo["attrs"][$attrname];
|
||||
if ( $attrtype==SPH_ATTR_TIMESTAMP )
|
||||
$value = date ( "Y-m-d H:i:s", $value );
|
||||
print ", $attrname=$value";
|
||||
}
|
||||
print "</li>";*/
|
||||
//$n++;
|
||||
}
|
||||
print "</ul>";
|
||||
}
|
||||
echo '<!--';
|
||||
print_r($res);
|
||||
echo '-->';
|
||||
|
||||
if ($_POST['submitted']) {
|
||||
print_r($_POST);
|
||||
|
||||
/* Actions à effectuer :
|
||||
|
||||
// 1. Vérification de l'existance du NOM, Prénom et Adresse dans Annuaire (/30 points)
|
||||
1.1. Si NOM+Prénom à l'adresse ==> OK 30 points
|
||||
1.2. Si NOM sans prénom à l'adresse ==> OK 25 points
|
||||
1.3. Si quelqu'un dans annuaire à l'adresse 10 points
|
||||
1.4. Si pas d'adresse 0 point
|
||||
|
||||
// Si 1.2 ==> 2
|
||||
// Si 1.3 ==> 2 + 3
|
||||
// Si 1.4 ==> 2 + 3 + 4
|
||||
|
||||
// 2. Vérifier si le prénom existe dans la table des prénoms (/ 3 points)
|
||||
2.1. Si le prénom existe OK 2 points
|
||||
2.2. Sinon valeur approchante 1 point
|
||||
2.3. Sinon ?????????? 0 point
|
||||
|
||||
// 3. Vérifier si le nom existe dans la table des noms (/ 3 points)
|
||||
1.1. Si le nom existe OK 2 points
|
||||
1.2. Sinon valeur approchante 1 point
|
||||
1.3. Sinon 0 point
|
||||
|
||||
// 4. Recherche de l'existance de l'adresse / ville (/ 5 points)
|
||||
2.1. Si adresse complète existe 5 points
|
||||
2.2. Si adresse sans n° 3 points
|
||||
2.3. Si approchant 2 points
|
||||
2.4. Si ville sans l'adresse 0 point
|
||||
|
||||
//10. Vérifier si le prénom est logique avec les l'age moyen des personnes portant ce prénom (/ 3 points)
|
||||
2.4.1. Si logique OK 2 points
|
||||
2.4.2. Si approchant 1 point
|
||||
2.4.3. Sinon 0 point
|
||||
|
||||
|
||||
3.3.1 Vérification dans le pages blanches
|
||||
|
||||
// 3. Si un téléphone est communiqué et qu'absence de liste rouge : (30 points)
|
||||
3.1. Vérifier la concordance NOM, Prénom, Adresse, Téléphonesi OK 30 point
|
||||
|
||||
Enregistrer chaque requête
|
||||
et les informations communqiuées par le client
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
157
library/framework/sphinx/test/test.php
Normal file
157
library/framework/sphinx/test/test.php
Normal file
@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
//
|
||||
// $Id: test.php 1103 2008-01-24 18:42:57Z shodan $
|
||||
//
|
||||
|
||||
require ( "sphinxapi.php" );
|
||||
|
||||
//////////////////////
|
||||
// parse command line
|
||||
//////////////////////
|
||||
|
||||
// for very old PHP versions, like at my home test server
|
||||
if ( is_array($argv) && !isset($_SERVER["argv"]) )
|
||||
$_SERVER["argv"] = $argv;
|
||||
unset ( $_SERVER["argv"][0] );
|
||||
|
||||
// build query
|
||||
if ( !is_array($_SERVER["argv"]) || empty($_SERVER["argv"]) )
|
||||
{
|
||||
print ( "Usage: php -f test.php [OPTIONS] query words\n\n" );
|
||||
print ( "Options are:\n" );
|
||||
print ( "-h, --host <HOST>\tconnect to searchd at host HOST\n" );
|
||||
print ( "-p, --port\t\tconnect to searchd at port PORT\n" );
|
||||
print ( "-i, --index <IDX>\tsearch through index(es) specified by IDX\n" );
|
||||
print ( "-s, --sortby <CLAUSE>\tsort matches by 'CLAUSE' in sort_extended mode\n" );
|
||||
print ( "-S, --sortexpr <EXPR>\tsort matches by 'EXPR' DESC in sort_expr mode\n" );
|
||||
print ( "-a, --any\t\tuse 'match any word' matching mode\n" );
|
||||
print ( "-b, --boolean\t\tuse 'boolean query' matching mode\n" );
|
||||
print ( "-e, --extended\t\tuse 'extended query' matching mode\n" );
|
||||
print ( "-ph,--phrase\t\tuse 'exact phrase' matching mode\n" );
|
||||
print ( "-f, --filter <ATTR>\tfilter by attribute 'ATTR' (default is 'group_id')\n" );
|
||||
print ( "-v, --value <VAL>\tadd VAL to allowed 'group_id' values list\n" );
|
||||
print ( "-g, --groupby <EXPR>\tgroup matches by 'EXPR'\n" );
|
||||
print ( "-gs,--groupsort <EXPR>\tsort groups by 'EXPR'\n" );
|
||||
print ( "-d, --distinct <ATTR>\tcount distinct values of 'ATTR''\n" );
|
||||
print ( "-l, --limit <COUNT>\tretrieve COUNT matches (default: 20)\n" );
|
||||
exit;
|
||||
}
|
||||
|
||||
$args = array();
|
||||
foreach ( $_SERVER["argv"] as $arg )
|
||||
$args[] = $arg;
|
||||
|
||||
$q = "";
|
||||
$mode = SPH_MATCH_ALL;
|
||||
$host = "localhost";
|
||||
$port = 3312;
|
||||
$index = "*";
|
||||
$groupby = "";
|
||||
$groupsort = "@group desc";
|
||||
$filter = "group_id";
|
||||
$filtervals = array();
|
||||
$distinct = "";
|
||||
$sortby = "";
|
||||
$limit = 20;
|
||||
$ranker = SPH_RANK_PROXIMITY_BM25;
|
||||
for ( $i=0; $i<count($args); $i++ )
|
||||
{
|
||||
$arg = $args[$i];
|
||||
|
||||
if ( $arg=="-h" || $arg=="--host" ) $host = $args[++$i];
|
||||
else if ( $arg=="-p" || $arg=="--port" ) $port = (int)$args[++$i];
|
||||
else if ( $arg=="-i" || $arg=="--index" ) $index = $args[++$i];
|
||||
else if ( $arg=="-s" || $arg=="--sortby" ) { $sortby = $args[++$i]; $sortexpr = ""; }
|
||||
else if ( $arg=="-S" || $arg=="--sortexpr" ) { $sortexpr = $args[++$i]; $sortby = ""; }
|
||||
else if ( $arg=="-a" || $arg=="--any" ) $mode = SPH_MATCH_ANY;
|
||||
else if ( $arg=="-b" || $arg=="--boolean" ) $mode = SPH_MATCH_BOOLEAN;
|
||||
else if ( $arg=="-e" || $arg=="--extended" ) $mode = SPH_MATCH_EXTENDED;
|
||||
else if ( $arg=="-e2" ) $mode = SPH_MATCH_EXTENDED2;
|
||||
else if ( $arg=="-ph"|| $arg=="--phrase" ) $mode = SPH_MATCH_PHRASE;
|
||||
else if ( $arg=="-f" || $arg=="--filter" ) $filter = $args[++$i];
|
||||
else if ( $arg=="-v" || $arg=="--value" ) $filtervals[] = $args[++$i];
|
||||
else if ( $arg=="-g" || $arg=="--groupby" ) $groupby = $args[++$i];
|
||||
else if ( $arg=="-gs"|| $arg=="--groupsort" ) $groupsort = $args[++$i];
|
||||
else if ( $arg=="-d" || $arg=="--distinct" ) $distinct = $args[++$i];
|
||||
else if ( $arg=="-l" || $arg=="--limit" ) $limit = (int)$args[++$i];
|
||||
else if ( $arg=="-r" )
|
||||
{
|
||||
$arg = strtolower($args[++$i]);
|
||||
if ( $arg=="bm25" ) $ranker = SPH_RANK_BM25;
|
||||
if ( $arg=="none" ) $ranker = SPH_RANK_NONE;
|
||||
if ( $arg=="wordcount" )$ranker = SPH_RANK_WORDCOUNT;
|
||||
}
|
||||
else
|
||||
$q .= $args[$i] . " ";
|
||||
}
|
||||
|
||||
////////////
|
||||
// do query
|
||||
////////////
|
||||
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer ( $host, $port );
|
||||
$cl->SetWeights ( array ( 100, 1 ) );
|
||||
$cl->SetMatchMode ( $mode );
|
||||
if ( count($filtervals) ) $cl->SetFilter ( $filter, $filtervals );
|
||||
if ( $groupby ) $cl->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );
|
||||
if ( $sortby ) $cl->SetSortMode ( SPH_SORT_EXTENDED, $sortby );
|
||||
if ( $sortexpr ) $cl->SetSortMode ( SPH_SORT_EXPR, $sortexpr );
|
||||
if ( $distinct ) $cl->SetGroupDistinct ( $distinct );
|
||||
if ( $limit ) $cl->SetLimits ( 0, $limit, ( $limit>1000 ) ? $limit : 1000 );
|
||||
$cl->SetRankingMode ( $ranker );
|
||||
$cl->SetArrayResult ( true );
|
||||
$res = $cl->Query ( $q, $index );
|
||||
|
||||
////////////////
|
||||
// print me out
|
||||
////////////////
|
||||
|
||||
if ( $res===false )
|
||||
{
|
||||
print "Query failed: " . $cl->GetLastError() . ".\n";
|
||||
|
||||
} else
|
||||
{
|
||||
if ( $cl->GetLastWarning() )
|
||||
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
|
||||
|
||||
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
|
||||
print "Query stats:\n";
|
||||
if ( is_array($res["words"]) )
|
||||
foreach ( $res["words"] as $word => $info )
|
||||
print " '$word' found $info[hits] times in $info[docs] documents\n";
|
||||
print "\n";
|
||||
|
||||
if ( is_array($res["matches"]) )
|
||||
{
|
||||
$n = 1;
|
||||
print "Matches:\n";
|
||||
foreach ( $res["matches"] as $docinfo )
|
||||
{
|
||||
print "$n. doc_id=$docinfo[id], weight=$docinfo[weight]";
|
||||
foreach ( $res["attrs"] as $attrname => $attrtype )
|
||||
{
|
||||
$value = $docinfo["attrs"][$attrname];
|
||||
if ( $attrtype & SPH_ATTR_MULTI )
|
||||
{
|
||||
$value = "(" . join ( ",", $value ) .")";
|
||||
} else
|
||||
{
|
||||
if ( $attrtype==SPH_ATTR_TIMESTAMP )
|
||||
$value = date ( "Y-m-d H:i:s", $value );
|
||||
}
|
||||
print ", $attrname=$value";
|
||||
}
|
||||
print "\n";
|
||||
$n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// $Id: test.php 1103 2008-01-24 18:42:57Z shodan $
|
||||
//
|
||||
|
||||
?>
|
53
library/framework/sphinx/test/test2.php
Normal file
53
library/framework/sphinx/test/test2.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
//
|
||||
// $Id: test2.php 910 2007-11-16 11:43:46Z shodan $
|
||||
//
|
||||
|
||||
require ( "sphinxapi.php" );
|
||||
|
||||
$docs = array
|
||||
(
|
||||
"this is my test text to be highlighted, and for the sake of the testing we need to pump its length somewhat",
|
||||
"another test text to be highlighted, below limit",
|
||||
"test number three, without phrase match",
|
||||
"final test, not only without phrase match, but also above limit and with swapped phrase text test as well",
|
||||
);
|
||||
$words = "test text";
|
||||
$index = "test1";
|
||||
$opts = array
|
||||
(
|
||||
"before_match" => "<b>",
|
||||
"after_match" => "</b>",
|
||||
"chunk_separator" => " ... ",
|
||||
"limit" => 60,
|
||||
"around" => 3,
|
||||
);
|
||||
|
||||
foreach ( array(0,1) as $exact )
|
||||
{
|
||||
$opts["exact_phrase"] = $exact;
|
||||
print "exact_phrase=$exact\n";
|
||||
|
||||
$cl = new SphinxClient ();
|
||||
$res = $cl->BuildExcerpts ( $docs, $index, $words, $opts );
|
||||
if ( !$res )
|
||||
{
|
||||
die ( "ERROR: " . $cl->GetLastError() . ".\n" );
|
||||
} else
|
||||
{
|
||||
$n = 0;
|
||||
foreach ( $res as $entry )
|
||||
{
|
||||
$n++;
|
||||
print "n=$n, res=$entry\n";
|
||||
}
|
||||
print "\n";
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// $Id: test2.php 910 2007-11-16 11:43:46Z shodan $
|
||||
//
|
||||
|
||||
?>
|
44
library/framework/sphinx/test/test2_old.php
Normal file
44
library/framework/sphinx/test/test2_old.php
Normal file
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
//
|
||||
// $Id: test2.php,v 1.4 2006/11/26 12:24:21 shodan Exp $
|
||||
//
|
||||
|
||||
require ( "sphinxapi.php" );
|
||||
|
||||
$docs = array
|
||||
(
|
||||
"this is my test text to be highlighted",
|
||||
"this is another test text to be highlighted",
|
||||
);
|
||||
$words = "test text";
|
||||
$index = "test1";
|
||||
$opts = array
|
||||
(
|
||||
"before_match" => "<b>",
|
||||
"after_match" => "</b>",
|
||||
"chunk_separator" => " ... ",
|
||||
"limit" => 400,
|
||||
"around" => 15
|
||||
);
|
||||
|
||||
|
||||
$cl = new SphinxClient ();
|
||||
$res = $cl->BuildExcerpts ( $docs, $index, $words, $opts );
|
||||
if ( !$res )
|
||||
{
|
||||
die ( "ERROR: " . $cl->GetLastError() . ".\n" );
|
||||
} else
|
||||
{
|
||||
foreach ( $res as $entry )
|
||||
{
|
||||
$n++;
|
||||
print "n=$n, res=$entry\n";
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// $Id: test2.php,v 1.4 2006/11/26 12:24:21 shodan Exp $
|
||||
//
|
||||
|
||||
?>
|
108
library/framework/sphinx/test/test_old.php
Normal file
108
library/framework/sphinx/test/test_old.php
Normal file
@ -0,0 +1,108 @@
|
||||
#!/usr/bin/php -q
|
||||
<?php
|
||||
|
||||
//
|
||||
// $Id: test.php,v 1.12 2006/11/26 12:24:21 shodan Exp $
|
||||
//
|
||||
|
||||
require ( "sphinxapi.php" );
|
||||
|
||||
//////////////////////
|
||||
// parse command line
|
||||
//////////////////////
|
||||
|
||||
// for very old PHP versions, like at my home test server
|
||||
if ( is_array($argv) && !isset($_SERVER["argv"]) )
|
||||
$_SERVER["argv"] = $argv;
|
||||
unset ( $_SERVER["argv"][0] );
|
||||
|
||||
// build query
|
||||
if ( !is_array($_SERVER["argv"]) || empty($_SERVER["argv"]) )
|
||||
die ( "usage: php -f test.php [--any] <word [word [word [...]]]> [--group <group>] [-p <port>] [-i <index>]\n" );
|
||||
|
||||
$args = array();
|
||||
foreach ( $_SERVER["argv"] as $arg )
|
||||
$args[] = $arg;
|
||||
|
||||
$q = "";
|
||||
$any = false;
|
||||
$groups = array();
|
||||
$port = 3312;
|
||||
$index = "*";
|
||||
for ( $i=0; $i<count($args); $i++ )
|
||||
{
|
||||
if ( $args[$i]=="--any" )
|
||||
{
|
||||
$any = true;
|
||||
} else if ( $args[$i]=="--group" )
|
||||
{
|
||||
$groups[] = (int)$args[++$i];
|
||||
} else if ( $args[$i]=="-p" )
|
||||
{
|
||||
$port = (int)$args[++$i];
|
||||
} else if ( $args[$i]=="-i" )
|
||||
{
|
||||
$index = $args[++$i];
|
||||
} else
|
||||
{
|
||||
$q .= $args[$i] . " ";
|
||||
}
|
||||
}
|
||||
|
||||
////////////
|
||||
// do query
|
||||
////////////
|
||||
|
||||
$cl = new SphinxClient ();
|
||||
$cl->SetServer ( "localhost", $port );
|
||||
$cl->SetWeights ( array ( 100, 1 ) );
|
||||
$cl->SetMatchMode ( $any ? SPH_MATCH_ANY : SPH_MATCH_ALL );
|
||||
if ( count($groups) )
|
||||
$cl->SetFilter ( "group_id", $groups );
|
||||
$res = $cl->Query ( $q, $index );
|
||||
|
||||
////////////////
|
||||
// print me out
|
||||
////////////////
|
||||
|
||||
if ( $res===false )
|
||||
{
|
||||
print "Query failed: " . $cl->GetLastError() . ".\n";
|
||||
|
||||
} else
|
||||
{
|
||||
if ( $cl->GetLastWarning() )
|
||||
print "WARNING: " . $cl->GetLastWarning() . "\n\n";
|
||||
|
||||
print "Query '$q' retrieved $res[total] of $res[total_found] matches in $res[time] sec.\n";
|
||||
print "Query stats:\n";
|
||||
if ( is_array($res["words"]) )
|
||||
foreach ( $res["words"] as $word => $info )
|
||||
print " '$word' found $info[hits] times in $info[docs] documents\n";
|
||||
print "\n";
|
||||
|
||||
if ( is_array($res["matches"]) )
|
||||
{
|
||||
$n = 1;
|
||||
print "Matches:\n";
|
||||
foreach ( $res["matches"] as $doc => $docinfo )
|
||||
{
|
||||
print "$n. doc_id=$doc, weight=$docinfo[weight]";
|
||||
foreach ( $res["attrs"] as $attrname => $attrtype )
|
||||
{
|
||||
$value = $docinfo["attrs"][$attrname];
|
||||
if ( $attrtype==SPH_ATTR_TIMESTAMP )
|
||||
$value = date ( "Y-m-d H:i:s", $value );
|
||||
print ", $attrname=$value";
|
||||
}
|
||||
print "\n";
|
||||
$n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// $Id: test.php,v 1.12 2006/11/26 12:24:21 shodan Exp $
|
||||
//
|
||||
|
||||
?>
|
Loading…
x
Reference in New Issue
Block a user