Import make_firstname_case from diogenes
[platal.git] / include / xorg.misc.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 function quoted_printable_encode($input, $line_max = 76) {
23 $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
24 $eol = "\n";
25 $linebreak = "=0D=0A=\n ";
26 $escape = "=";
27 $output = "";
28
29 foreach ($lines as $j => $line) {
30 $linlen = strlen($line);
31 $newline = "";
32 for($i = 0; $i < $linlen; $i++) {
33 $c = $line{$i};
34 $dec = ord($c);
35 if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
36 // convert space at eol only
37 $c = "=20";
38 } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
39 // always encode "\t", which is *not* required
40 $c = $escape.strtoupper(sprintf("%02x",$dec));
41 }
42 if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
43 $output .= $newline.$escape.$eol;
44 $newline = " ";
45 }
46 $newline .= $c;
47 } // end of for
48 $output .= $newline;
49 if ($j<count($lines)-1) $output .= $linebreak;
50 }
51 return trim($output);
52 }
53
54 /** vérifie si une adresse email est bien formatée
55 * ATTENTION, cette fonction ne doit pas être appelée sur une chaîne ayant subit un addslashes (car elle accepte le "'" qui rait alors un "\'"
56 * @param $email l'adresse email a verifier
57 * @return BOOL
58 */
59 function isvalid_email($email) {
60 // la rfc2822 authorise les caractères "a-z", "0-9", "!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", "^", "_", `", "{", "|", "}", "~" aussi bien dans la partie locale que dans le domaine.
61 // Pour la partie locale, on réduit cet ensemble car il n'est pas utilisé.
62 // Pour le domaine, le système DNS limite à [a-z0-9.-], on y ajoute le "_" car il est parfois utilisé.
63 return preg_match("/^[a-z0-9_.'+-]+@[a-z0-9._-]+\.[a-z]{2,4}$/i", $email);
64 }
65
66 /** vérifie si une adresse email convient comme adresse de redirection
67 * @param $email l'adresse email a verifier
68 * @return BOOL
69 */
70 function isvalid_email_redirection($email) {
71 return isvalid_email($email) &&
72 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
73 }
74
75 /** Remove accent from a string and replace them by the nearest letter
76 */
77 global $lc_convert, $uc_convert;
78 $lc_convert = array('é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
79 'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a', 'å' => 'a', 'ã' => 'a',
80 'ï' => 'i', 'î' => 'i', 'ì' => 'i', 'í' => 'i',
81 'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o', 'ø' => 'o',
82 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
83 'ç' => 'c', 'ñ' => 'n');
84 $uc_convert = array('É' => 'E', 'È' => 'E', 'Ë' => 'E', 'Ê' => 'E',
85 'Á' => 'A', 'À' => 'A', 'Ä' => 'A', 'Â' => 'A', 'Å' => 'A', 'Ã' => 'A',
86 'Ï' => 'I', 'Î' => 'I', 'Ì' => 'I', 'Í' => 'I',
87 'Ô' => 'O', 'Ö' => 'O', 'Ò' => 'O', 'Ó' => 'O', 'Õ' => 'O', 'Ø' => 'O',
88 'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
89 'Ç' => 'C', 'Ñ' => 'N');
90
91 function replace_accent($string)
92 {
93 global $lc_convert, $uc_convert;
94 $string = strtr($string, $lc_convert);
95 return strtr($string, $uc_convert);
96 }
97
98 /* Un soundex en français posté par Frédéric Bouchery
99 Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
100 C'est une bonne démonstration de la force des expressions régulières compatible Perl.
101 trouvé sur http://expreg.com/voirsource.php?id=40&type=Chaines%20de%20caract%E8res */
102 function soundex_fr($sIn)
103 {
104 // Si il n'y a pas de mot, on sort immédiatement
105 if ( $sIn === '' ) return ' ';
106 // On met tout en minuscule
107 $sIn = strtoupper( $sIn );
108 // On supprime les accents
109 global $uc_convert;
110 $accents = $uc_convert;
111 $accents['Ç'] = 'S';
112 $accents['¿'] = 'E';
113 $sIn = strtr( $sIn, $accents);
114 // On supprime tout ce qui n'est pas une lettre
115 $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
116 // Si la chaîne ne fait qu'un seul caractère, on sort avec.
117 if ( strlen( $sIn ) === 1 ) return $sIn . ' ';
118 // on remplace les consonnances primaires
119 $convIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'CA', 'CO', 'CU', 'Q', 'CC', 'CK' );
120 $convOut = array( 'KI', 'KE', 'KA', 'KO', 'K', 'KA', 'KO', 'KU', 'K', 'K', 'K' );
121 $sIn = str_replace( $convIn, $convOut, $sIn );
122 // on remplace les voyelles sauf le Y et sauf la première par A
123 $sIn = preg_replace( '`(?<!^)[EIOU]`', 'A', $sIn );
124 // on remplace les préfixes puis on conserve la première lettre
125 // et on fait les remplacements complémentaires
126 $convIn = array( '`^KN`', '`^(PH|PF)`', '`^MAC`', '`^SCH`', '`^ASA`', '`(?<!^)KN`', '`(?<!^)(PH|PF)`', '`(?<!^)MAC`', '`(?<!^)SCH`', '`(?<!^)ASA`' );
127 $convOut = array( 'NN', 'FF', 'MCC', 'SSS', 'AZA', 'NN', 'FF', 'MCC', 'SSS', 'AZA' );
128 $sIn = preg_replace( $convIn, $convOut, $sIn );
129 // suppression des H sauf CH ou SH
130 $sIn = preg_replace( '`(?<![CS])H`', '', $sIn );
131 // suppression des Y sauf précédés d'un A
132 $sIn = preg_replace( '`(?<!A)Y`', '', $sIn );
133 // on supprime les terminaisons A, T, D, S
134 $sIn = preg_replace( '`[ATDS]$`', '', $sIn );
135 // suppression de tous les A sauf en tête
136 $sIn = preg_replace( '`(?!^)A`', '', $sIn );
137 // on supprime les lettres répétitives
138 $sIn = preg_replace( '`(.)\1`u', '$1', $sIn );
139 // on ne retient que 4 caractères ou on complète avec des blancs
140 return substr( $sIn . ' ', 0, 4);
141 }
142
143 /** met les majuscules au debut de chaque atome du prénom
144 * @param $prenom le prénom à formater
145 * return STRING le prénom avec les majuscules
146 */
147 function make_firstname_case($prenom) {
148 $prenom = strtolower($prenom);
149 $pieces = explode('-',$prenom);
150
151 foreach ($pieces as $piece) {
152 $subpieces = explode("'",$piece);
153 $usubpieces="";
154 foreach ($subpieces as $subpiece)
155 $usubpieces[] = ucwords($subpiece);
156 $upieces[] = implode("'",$usubpieces);
157 }
158 return implode('-',$upieces);
159 }
160
161
162 function make_forlife($prenom,$nom,$promo) {
163 $prenomUS = replace_accent(trim($prenom));
164 $nomUS = replace_accent(trim($nom));
165
166 $forlife = strtolower($prenomUS.".".$nomUS.".".$promo);
167 $forlife = str_replace(" ","-",$forlife);
168 $forlife = str_replace("'","",$forlife);
169 return $forlife;
170 }
171
172 function check_ip($level)
173 {
174 if (empty($_SERVER['REMOTE_ADDR'])) {
175 return false;
176 }
177 if (empty($_SESSION['check_ip'])) {
178 $ips = array();
179 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
180 $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
181 }
182 $ips[] = $_SERVER['REMOTE_ADDR'];
183 foreach ($ips as &$ip) {
184 $ip = "ip='$ip'";
185 }
186 $res = XDB::query('SELECT state
187 FROM ip_watch
188 WHERE ' . implode(' OR ', $ips) . '
189 ORDER BY state DESC');
190 if ($res->numRows()) {
191 $_SESSION['check_ip'] = $res->fetchOneCell();
192 } else {
193 $_SESSION['check_ip'] = 'safe';
194 }
195 }
196 $test = array();
197 switch ($level) {
198 case 'unsafe': $test[] = 'unsafe';
199 case 'dangerous': $test[] = 'dangerous';
200 case 'ban': $test[] = 'ban'; break;
201 default: return false;
202 }
203 return in_array($_SESSION['check_ip'], $test);
204 }
205
206 function check_email($email, $message)
207 {
208 $res = XDB::query("SELECT state, description
209 FROM emails_watch
210 WHERE state != 'safe' AND email = {?}", $email);
211 if ($res->numRows()) {
212 send_warning_mail($message);
213 return true;
214 }
215 return false;
216 }
217
218 function check_redirect($red = null)
219 {
220 require_once 'emails.inc.php';
221 if (is_null($red)) {
222 $red = new Redirect(S::v('uid'));
223 }
224 $_SESSION['no_redirect'] = !$red->other_active('');
225 $_SESSION['mx_failures'] = $red->get_broken_mx();
226
227 }
228
229 function send_warning_mail($title)
230 {
231 $mailer = new PlMailer();
232 $mailer->setFrom("webmaster@polytechnique.org");
233 $mailer->addTo("hotliners@staff.polytechnique.org");
234 $mailer->setSubject("[Plat/al Security Alert] $title");
235 $mailer->setTxtBody("Identifiants de session :\n" . var_export($_SESSION, true) . "\n\n"
236 ."Identifiants de connexion :\n" . var_export($_SERVER, true));
237 $mailer->send();
238 }
239
240 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
241 ?>