49f9c00ff0589865e4a7094e89c5136b5faf5b5d
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 function quoted_printable_encode($input, $line_max = 76)
24 $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
26 $linebreak = "=0D=0A=\n ";
30 foreach ($lines as $j => $line) {
31 $linlen = strlen($line);
33 for($i = 0; $i < $linlen; $i++
) {
36 if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
37 // convert space at eol only
39 } elseif ( ($dec == 61) ||
($dec < 32 ) ||
($dec > 126) ) {
40 // always encode "\t", which is *not* required
41 $c = $escape.strtoupper(sprintf("%02x",$dec));
43 if ( (strlen($newline) +
strlen($c)) >= $line_max ) { // CRLF is not counted
44 $output .= $newline.$escape.$eol;
50 if ($j<count($lines)-1) $output .= $linebreak;
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
60 function isvalid_email($email)
62 // la rfc2822 authorise les caractères "a-z", "0-9", "!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", "^", "_", `", "{", "|", "}", "~" aussi bien dans la partie locale que dans le domaine.
63 // Pour la partie locale, on réduit cet ensemble car il n'est pas utilisé.
64 // Pour le domaine, le système DNS limite à [a-z0-9.-], on y ajoute le "_" car il est parfois utilisé.
65 return preg_match("/^[a-z0-9_.'+-]+@[a-z0-9._-]+\.[a-z]{2,4}$/i", $email);
68 /** vérifie si une adresse email convient comme adresse de redirection
69 * @param $email l'adresse email a verifier
72 function isvalid_email_redirection($email)
74 return isvalid_email($email) &&
75 !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
78 /** genere une chaine aleatoire de 22 caracteres ou moins
79 * @param $len longueur souhaitée, 22 par défaut
80 * @return la chaine aleatoire qui contient les caractères [A-Za-z0-9+/]
82 function rand_token($len = 22)
86 $fp = fopen('/dev/urandom', 'r');
87 // $len * 2 is certainly an overkill,
88 // but HEY, reading 40 bytes from /dev/urandom is not that slow !
89 $token = fread($fp, $len * 2);
91 $token = base64_encode($token);
92 $token = preg_replace("![Il10O+/]!", "", $token);
93 $token = substr($token,0,$len);
97 /** genere une chaine aleatoire convenable pour une url
98 * @param $len longueur souhaitée, 22 par défaut
99 * @return la chaine aleatoire
101 function rand_url_id($len = 22)
103 return rand_token($len);
107 /** genere une chaine aleatoire convenable pour un mot de passe
108 * @return la chaine aleatoire
112 return rand_token(8);
115 /** Remove accent from a string and replace them by the nearest letter
117 global $lc_convert, $uc_convert;
118 $lc_convert = array('é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
119 'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a', 'å' => 'a', 'ã' => 'a',
120 'ï' => 'i', 'î' => 'i', 'ì' => 'i', 'í' => 'i',
121 'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o', 'ø' => 'o',
122 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
123 'ç' => 'c', 'ñ' => 'n');
124 $uc_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');
131 function replace_accent($string)
133 global $lc_convert, $uc_convert;
134 $string = strtr($string, $lc_convert);
135 return strtr($string, $uc_convert);
138 /** creates a username from a first and last name
140 * @param $prenom the firstname
141 * @param $nom the last name
143 * return STRING the corresponding username
145 function make_username($prenom,$nom)
147 /* on traite le prenom */
148 $prenomUS=replace_accent(trim($prenom));
149 $prenomUS=stripslashes($prenomUS);
151 /* on traite le nom */
152 $nomUS=replace_accent(trim($nom));
153 $nomUS=stripslashes($nomUS);
156 $username = strtolower($prenomUS.".".$nomUS);
157 $username = str_replace(" ","-",$username);
158 $username = str_replace("'","",$username);
162 /* Un soundex en français posté par Frédéric Bouchery
163 Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
164 C'est une bonne démonstration de la force des expressions régulières compatible Perl.
165 trouvé sur http://expreg.com/voirsource.php?id=40&type=Chaines%20de%20caract%E8res */
166 function soundex_fr($sIn)
168 static $convVIn, $convVOut, $convGuIn, $convGuOut, $accents;
169 if (!isset($convGuIn)) {
170 global $uc_convert, $lc_convert;
171 $convGuIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'SC', 'CA', 'CO', 'CU', 'QU', 'Q', 'CC', 'CK', 'G', 'ST', 'PH');
172 $convGuOut = array( 'KI', 'KE', 'KA', 'KO', 'KU', 'SK', 'KA', 'KO', 'KU', 'K', 'K', 'K', 'K', 'J', 'T', 'F');
173 $convVIn = array( '/E?(AU)/', '/([EA])?[UI]([NM])([^EAIOUY]|$)/', '/[AE]O?[NM]([^AEIOUY]|$)/',
174 '/[EA][IY]([NM]?[^NM]|$)/', '/(^|[^OEUIA])(OEU|OE|EU)([^OEUIA]|$)/', '/OI/',
175 '/(ILLE?|I)/', '/O(U|W)/', '/O[NM]($|[^EAOUIY])/', '/(SC|S|C)H/',
176 '/([^AEIOUY1])[^AEIOUYLKTP]([UAO])([^AEIOUY])/', '/([^AEIOUY]|^)([AUO])[^AEIOUYLKTP]([^AEIOUY1])/', '/^KN/',
177 '/^PF/', '/C([^AEIOUY]|$)/',
178 '/C/', '/Z$/', '/(?<!^)Z+/', '/ER$/', '/H/');
179 $convVOut = array( 'O', '1\3', 'A\1',
181 'Y', 'U', 'O\1', '9',
182 '\1\2\3', '\1\2\3', 'N',
184 'S', 'SE', 'S', 'E', '');
185 $accents = $uc_convert +
$lc_convert;
189 // Si il n'y a pas de mot, on sort immédiatement
190 if ( $sIn === '' ) return ' ';
191 // On supprime les accents
192 $sIn = strtr( $sIn, $accents);
193 // On met tout en minuscule
194 $sIn = strtoupper( $sIn );
195 // On supprime tout ce qui n'est pas une lettre
196 $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
197 // Si la chaîne ne fait qu'un seul caractère, on sort avec.
198 if ( strlen( $sIn ) === 1 ) return $sIn . ' ';
199 // on remplace les consonnances primaires
200 $sIn = str_replace( $convGuIn, $convGuOut, $sIn );
201 // on supprime les lettres répétitives
202 $sIn = preg_replace( '`(.)\1`', '$1', $sIn );
203 // on réinterprète les voyelles
204 $sIn = preg_replace( $convVIn, $convVOut, $sIn);
205 // on supprime les terminaisons T, D, S, X (et le L qui précède si existe)
206 $sIn = preg_replace( '`L?[TDSX]$`', '', $sIn );
207 // on supprime les E, A et Y qui ne sont pas en première position
208 $sIn = preg_replace( '`(?!^)Y([^AEOU]|$)`', '\1', $sIn);
209 $sIn = preg_replace( '`(?!^)[EA]`', '', $sIn);
210 return substr( $sIn . ' ', 0, 4);
213 /** met les majuscules au debut de chaque atome du prénom
214 * @param $prenom le prénom à formater
215 * return STRING le prénom avec les majuscules
217 function make_firstname_case($prenom)
219 $prenom = strtolower($prenom);
220 $pieces = explode('-',$prenom);
222 foreach ($pieces as $piece) {
223 $subpieces = explode("'",$piece);
225 foreach ($subpieces as $subpiece)
226 $usubpieces[] = ucwords($subpiece);
227 $upieces[] = implode("'",$usubpieces);
229 return implode('-',$upieces);
233 function make_forlife($prenom, $nom, $promo)
235 $prenomUS = replace_accent(trim($prenom));
236 $nomUS = replace_accent(trim($nom));
238 $forlife = strtolower($prenomUS.".".$nomUS.".".$promo);
239 $forlife = str_replace(" ","-",$forlife);
240 $forlife = str_replace("'","",$forlife);
244 function check_ip($level)
246 if (empty($_SERVER['REMOTE_ADDR'])) {
249 if (empty($_SESSION['check_ip'])) {
251 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
252 $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
254 $ips[] = $_SERVER['REMOTE_ADDR'];
255 foreach ($ips as &$ip) {
256 $ip = "ip LIKE " . XDB
::escape($ip);
258 $res = XDB
::query('SELECT state
260 WHERE ' . implode(' OR ', $ips) . '
261 ORDER BY state DESC');
262 if ($res->numRows()) {
263 $_SESSION['check_ip'] = $res->fetchOneCell();
265 $_SESSION['check_ip'] = 'safe';
270 case 'unsafe': $test[] = 'unsafe';
271 case 'dangerous': $test[] = 'dangerous';
272 case 'ban': $test[] = 'ban'; break;
273 default: return false
;
275 return in_array($_SESSION['check_ip'], $test);
278 function check_email($email, $message)
280 $res = XDB
::query("SELECT state, description
282 WHERE state != 'safe' AND email = {?}", $email);
283 if ($res->numRows()) {
284 send_warning_mail($message);
290 function check_account()
292 return S
::v('watch');
295 function check_redirect($red = null
)
297 require_once 'emails.inc.php';
299 $red = new Redirect(S
::v('uid'));
301 $_SESSION['no_redirect'] = !$red->other_active('');
302 $_SESSION['mx_failures'] = $red->get_broken_mx();
305 function send_warning_mail($title)
307 $mailer = new PlMailer();
308 $mailer->setFrom("webmaster@polytechnique.org");
309 $mailer->addTo("hotliners@staff.polytechnique.org");
310 $mailer->setSubject("[Plat/al Security Alert] $title");
311 $mailer->setTxtBody("Identifiants de session :\n" . var_export($_SESSION, true
) . "\n\n"
312 ."Identifiants de connexion :\n" . var_export($_SERVER, true
));
316 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: