Close #132 and add soundex search for quick search
[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 {
24 $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
25 $eol = "\n";
26 $linebreak = "=0D=0A=\n ";
27 $escape = "=";
28 $output = "";
29
30 foreach ($lines as $j => $line) {
31 $linlen = strlen($line);
32 $newline = "";
33 for($i = 0; $i < $linlen; $i++) {
34 $c = $line{$i};
35 $dec = ord($c);
36 if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
37 // convert space at eol only
38 $c = "=20";
39 } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
40 // always encode "\t", which is *not* required
41 $c = $escape.strtoupper(sprintf("%02x",$dec));
42 }
43 if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
44 $output .= $newline.$escape.$eol;
45 $newline = " ";
46 }
47 $newline .= $c;
48 } // end of for
49 $output .= $newline;
50 if ($j<count($lines)-1) $output .= $linebreak;
51 }
52 return trim($output);
53 }
54
55 /** vérifie si une adresse email est bien formatée
56 * 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 "\'"
57 * @param $email l'adresse email a verifier
58 * @return BOOL
59 */
60 function isvalid_email($email) {
61 // la rfc2822 authorise les caractères "a-z", "0-9", "!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", "^", "_", `", "{", "|", "}", "~" aussi bien dans la partie locale que dans le domaine.
62 // Pour la partie locale, on réduit cet ensemble car il n'est pas utilisé.
63 // Pour le domaine, le système DNS limite à [a-z0-9.-], on y ajoute le "_" car il est parfois utilisé.
64 return preg_match("/^[a-z0-9_.'+-]+@[a-z0-9._-]+\.[a-z]{2,4}$/i", $email);
65 }
66
67 /** vérifie si une adresse email convient comme adresse de redirection
68 * @param $email l'adresse email a verifier
69 * @return BOOL
70 */
71 function isvalid_email_redirection($email) {
72 return isvalid_email($email) &&
73 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
74 }
75
76 /** Check if the string is utf8
77 */
78 function is_utf8($s)
79 {
80 return @iconv('utf-8', 'utf-8', $s) == $s;
81 }
82
83
84 /** genere une chaine aleatoire de 22 caracteres ou moins
85 * @param $len longueur souhaitée, 22 par défaut
86 * @return la chaine aleatoire qui contient les caractères [A-Za-z0-9+/]
87 */
88 function rand_token($len = 22)
89 {
90 $len = max(2, $len);
91 $len = min(50, $len);
92 $fp = fopen('/dev/urandom', 'r');
93 // $len * 2 is certainly an overkill,
94 // but HEY, reading 40 bytes from /dev/urandom is not that slow !
95 $token = fread($fp, $len * 2);
96 fclose($fp);
97 $token = base64_encode($token);
98 $token = preg_replace("![Il10O+/]!", "", $token);
99 $token = substr($token,0,$len);
100 return $token;
101 }
102
103 /** genere une chaine aleatoire convenable pour une url
104 * @param $len longueur souhaitée, 22 par défaut
105 * @return la chaine aleatoire
106 */
107 function rand_url_id($len = 22)
108 {
109 return rand_token($len);
110 }
111
112
113 /** genere une chaine aleatoire convenable pour un mot de passe
114 * @return la chaine aleatoire
115 */
116 function rand_pass()
117 {
118 return rand_token(8);
119 }
120
121 /** Remove accent from a string and replace them by the nearest letter
122 */
123 global $lc_convert, $uc_convert;
124 $lc_convert = array('é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
125 'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a', 'å' => 'a', 'ã' => 'a',
126 'ï' => 'i', 'î' => 'i', 'ì' => 'i', 'í' => 'i',
127 'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o', 'ø' => 'o',
128 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
129 'ç' => 'c', 'ñ' => 'n');
130 $uc_convert = array('É' => 'E', 'È' => 'E', 'Ë' => 'E', 'Ê' => 'E',
131 'Á' => 'A', 'À' => 'A', 'Ä' => 'A', 'Â' => 'A', 'Å' => 'A', 'Ã' => 'A',
132 'Ï' => 'I', 'Î' => 'I', 'Ì' => 'I', 'Í' => 'I',
133 'Ô' => 'O', 'Ö' => 'O', 'Ò' => 'O', 'Ó' => 'O', 'Õ' => 'O', 'Ø' => 'O',
134 'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
135 'Ç' => 'C', 'Ñ' => 'N');
136
137 function replace_accent($string)
138 {
139 global $lc_convert, $uc_convert;
140 $string = strtr($string, $lc_convert);
141 return strtr($string, $uc_convert);
142 }
143
144 /** creates a username from a first and last name
145 *
146 * @param $prenom the firstname
147 * @param $nom the last name
148 *
149 * return STRING the corresponding username
150 */
151 function make_username($prenom,$nom) {
152 /* on traite le prenom */
153 $prenomUS=replace_accent(trim($prenom));
154 $prenomUS=stripslashes($prenomUS);
155
156 /* on traite le nom */
157 $nomUS=replace_accent(trim($nom));
158 $nomUS=stripslashes($nomUS);
159
160 // calcul du login
161 $username = strtolower($prenomUS.".".$nomUS);
162 $username = str_replace(" ","-",$username);
163 $username = str_replace("'","",$username);
164 return $username;
165 }
166
167 /* Un soundex en français posté par Frédéric Bouchery
168 Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
169 C'est une bonne démonstration de la force des expressions régulières compatible Perl.
170 trouvé sur http://expreg.com/voirsource.php?id=40&type=Chaines%20de%20caract%E8res */
171 function soundex_fr($sIn)
172 {
173 static $convVIn, $convVOut, $convGuIn, $convGuOut, $accents;
174 if (!isset($convGuIn)) {
175 global $uc_convert;
176 $convGuIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'SC', 'CA', 'CO', 'CU', 'QU', 'Q', 'CC', 'CK', 'G', 'ST', 'PH');
177 $convGuOut = array( 'KI', 'KE', 'KA', 'KO', 'KU', 'SK', 'KA', 'KO', 'KU', 'K', 'K', 'K', 'K', 'J', 'T', 'F');
178 $convVIn = array( '/E?(AU)/', '/([EA])?I([NM])([^EAIOUY]|$)/', '/[AE]O?[NM]([^AEIOUY]|$)/',
179 '/[EA][IY]([NM]?[^NM]|$)/', '/(^|[^OEUIA])(OEU|OE|EU)([^OEUIA]|$)/', '/OI/',
180 '/(ILLE?|I)/', '/O(U|W)/', '/O[NM]($|[^EAOUIY])/',
181 '/([^AEIOUY])[^AEIOUYLKTP]([UAO])([^AEIOUY])/', '/([^AEIOUY]|^)([AUO])[^AEIOUYKTP]([^AEIOUY])/', '/^KN/',
182 '/^PF/', '/(SC|S|C)H/', '/^C|C$/',
183 '/C/', '/Z$/', '/(?!^)Z+/');
184 $convVOut = array( 'O', '1\3', 'A\1',
185 'E\1', '\1\2', 'O',
186 'Y', 'U', 'O\1',
187 '\1\2\3', '\1\2\3', 'N',
188 'F', '9', 'K',
189 'S', 'SE', 'S');
190 $accents = $uc_convert;
191 $accents['Ç'] = 'S';
192 $accents['¿'] = 'E';
193 }
194 // Si il n'y a pas de mot, on sort immédiatement
195 if ( $sIn === '' ) return ' ';
196 // On met tout en minuscule
197 $sIn = strtoupper( $sIn );
198 // On supprime les accents
199 $sIn = strtr( $sIn, $accents);
200 // On supprime tout ce qui n'est pas une lettre
201 $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
202 // Si la chaîne ne fait qu'un seul caractère, on sort avec.
203 if ( strlen( $sIn ) === 1 ) return $sIn . ' ';
204 // on remplace les consonnances primaires
205 $sIn = str_replace( $convGuIn, $convGuOut, $sIn );
206 // on supprime les lettres répétitives
207 $sIn = preg_replace( '`(.)\1`', '$1', $sIn );
208 // on réinterprète les voyelles
209 $sIn = preg_replace( $convVIn, $convVOut, $sIn);
210 $sIn = strtr($sIn, 'H', '');
211 // on supprime les terminaisons T, D, S, X (et le L qui précède si existe)
212 $sIn = preg_replace( '`L?[TDSX]$`', '', $sIn );
213 // on supprime les E, A et Y qui ne sont pas en première position
214 $sIn = preg_replace( '`(?!^)Y([^AEOU]|$)`', '\1', $sIn);
215 $sIn = preg_replace( '`(?!^)([EA])`', '', $sIn);
216 return substr( $sIn . ' ', 0, 4);
217 }
218
219 /** met les majuscules au debut de chaque atome du prénom
220 * @param $prenom le prénom à formater
221 * return STRING le prénom avec les majuscules
222 */
223 function make_firstname_case($prenom)
224 {
225 $prenom = strtolower($prenom);
226 $pieces = explode('-',$prenom);
227
228 foreach ($pieces as $piece) {
229 $subpieces = explode("'",$piece);
230 $usubpieces="";
231 foreach ($subpieces as $subpiece)
232 $usubpieces[] = ucwords($subpiece);
233 $upieces[] = implode("'",$usubpieces);
234 }
235 return implode('-',$upieces);
236 }
237
238
239 function make_forlife($prenom,$nom,$promo) {
240 $prenomUS = replace_accent(trim($prenom));
241 $nomUS = replace_accent(trim($nom));
242
243 $forlife = strtolower($prenomUS.".".$nomUS.".".$promo);
244 $forlife = str_replace(" ","-",$forlife);
245 $forlife = str_replace("'","",$forlife);
246 return $forlife;
247 }
248
249 function check_ip($level)
250 {
251 if (empty($_SERVER['REMOTE_ADDR'])) {
252 return false;
253 }
254 if (empty($_SESSION['check_ip'])) {
255 $ips = array();
256 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
257 $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
258 }
259 $ips[] = $_SERVER['REMOTE_ADDR'];
260 foreach ($ips as &$ip) {
261 $ip = "ip='$ip'";
262 }
263 $res = XDB::query('SELECT state
264 FROM ip_watch
265 WHERE ' . implode(' OR ', $ips) . '
266 ORDER BY state DESC');
267 if ($res->numRows()) {
268 $_SESSION['check_ip'] = $res->fetchOneCell();
269 } else {
270 $_SESSION['check_ip'] = 'safe';
271 }
272 }
273 $test = array();
274 switch ($level) {
275 case 'unsafe': $test[] = 'unsafe';
276 case 'dangerous': $test[] = 'dangerous';
277 case 'ban': $test[] = 'ban'; break;
278 default: return false;
279 }
280 return in_array($_SESSION['check_ip'], $test);
281 }
282
283 function check_email($email, $message)
284 {
285 $res = XDB::query("SELECT state, description
286 FROM emails_watch
287 WHERE state != 'safe' AND email = {?}", $email);
288 if ($res->numRows()) {
289 send_warning_mail($message);
290 return true;
291 }
292 return false;
293 }
294
295 function check_account()
296 {
297 return S::v('watch');
298 }
299
300 function check_redirect($red = null)
301 {
302 require_once 'emails.inc.php';
303 if (is_null($red)) {
304 $red = new Redirect(S::v('uid'));
305 }
306 $_SESSION['no_redirect'] = !$red->other_active('');
307 $_SESSION['mx_failures'] = $red->get_broken_mx();
308 }
309
310 function send_warning_mail($title)
311 {
312 $mailer = new PlMailer();
313 $mailer->setFrom("webmaster@polytechnique.org");
314 $mailer->addTo("hotliners@staff.polytechnique.org");
315 $mailer->setSubject("[Plat/al Security Alert] $title");
316 $mailer->setTxtBody("Identifiants de session :\n" . var_export($_SESSION, true) . "\n\n"
317 ."Identifiants de connexion :\n" . var_export($_SERVER, true));
318 $mailer->send();
319 }
320
321 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
322 ?>