Fix session bootstrap
[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 /** Remove accent from a string and replace them by the nearest letter
85 */
86 global $lc_convert, $uc_convert;
87 $lc_convert = array('é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
88 'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a', 'å' => 'a', 'ã' => 'a',
89 'ï' => 'i', 'î' => 'i', 'ì' => 'i', 'í' => 'i',
90 'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o', 'ø' => 'o',
91 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
92 'ç' => 'c', 'ñ' => 'n');
93 $uc_convert = array('É' => 'E', 'È' => 'E', 'Ë' => 'E', 'Ê' => 'E',
94 'Á' => 'A', 'À' => 'A', 'Ä' => 'A', 'Â' => 'A', 'Å' => 'A', 'Ã' => 'A',
95 'Ï' => 'I', 'Î' => 'I', 'Ì' => 'I', 'Í' => 'I',
96 'Ô' => 'O', 'Ö' => 'O', 'Ò' => 'O', 'Ó' => 'O', 'Õ' => 'O', 'Ø' => 'O',
97 'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
98 'Ç' => 'C', 'Ñ' => 'N');
99
100 function replace_accent($string)
101 {
102 global $lc_convert, $uc_convert;
103 $string = strtr($string, $lc_convert);
104 return strtr($string, $uc_convert);
105 }
106
107 /** creates a username from a first and last name
108 *
109 * @param $prenom the firstname
110 * @param $nom the last name
111 *
112 * return STRING the corresponding username
113 */
114 function make_username($prenom,$nom) {
115 /* on traite le prenom */
116 $prenomUS=replace_accent(trim($prenom));
117 $prenomUS=stripslashes($prenomUS);
118
119 /* on traite le nom */
120 $nomUS=replace_accent(trim($nom));
121 $nomUS=stripslashes($nomUS);
122
123 // calcul du login
124 $username = strtolower($prenomUS.".".$nomUS);
125 $username = str_replace(" ","-",$username);
126 $username = str_replace("'","",$username);
127 return $username;
128 }
129
130 /* Un soundex en français posté par Frédéric Bouchery
131 Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
132 C'est une bonne démonstration de la force des expressions régulières compatible Perl.
133 trouvé sur http://expreg.com/voirsource.php?id=40&type=Chaines%20de%20caract%E8res */
134 function soundex_fr($sIn)
135 {
136 // Si il n'y a pas de mot, on sort immédiatement
137 if ( $sIn === '' ) return ' ';
138 // On met tout en minuscule
139 $sIn = strtoupper( $sIn );
140 // On supprime les accents
141 global $uc_convert;
142 $accents = $uc_convert;
143 $accents['Ç'] = 'S';
144 $accents['¿'] = 'E';
145 $sIn = strtr( $sIn, $accents);
146 // On supprime tout ce qui n'est pas une lettre
147 $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
148 // Si la chaîne ne fait qu'un seul caractère, on sort avec.
149 if ( strlen( $sIn ) === 1 ) return $sIn . ' ';
150 // on remplace les consonnances primaires
151 $convIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'CA', 'CO', 'CU', 'Q', 'CC', 'CK' );
152 $convOut = array( 'KI', 'KE', 'KA', 'KO', 'K', 'KA', 'KO', 'KU', 'K', 'K', 'K' );
153 $sIn = str_replace( $convIn, $convOut, $sIn );
154 // on remplace les voyelles sauf le Y et sauf la première par A
155 $sIn = preg_replace( '`(?<!^)[EIOU]`', 'A', $sIn );
156 // on remplace les préfixes puis on conserve la première lettre
157 // et on fait les remplacements complémentaires
158 $convIn = array( '`^KN`', '`^(PH|PF)`', '`^MAC`', '`^SCH`', '`^ASA`', '`(?<!^)KN`', '`(?<!^)(PH|PF)`', '`(?<!^)MAC`', '`(?<!^)SCH`', '`(?<!^)ASA`' );
159 $convOut = array( 'NN', 'FF', 'MCC', 'SSS', 'AZA', 'NN', 'FF', 'MCC', 'SSS', 'AZA' );
160 $sIn = preg_replace( $convIn, $convOut, $sIn );
161 // suppression des H sauf CH ou SH
162 $sIn = preg_replace( '`(?<![CS])H`', '', $sIn );
163 // suppression des Y sauf précédés d'un A
164 $sIn = preg_replace( '`(?<!A)Y`', '', $sIn );
165 // on supprime les terminaisons A, T, D, S
166 $sIn = preg_replace( '`[ATDS]$`', '', $sIn );
167 // suppression de tous les A sauf en tête
168 $sIn = preg_replace( '`(?!^)A`', '', $sIn );
169 // on supprime les lettres répétitives
170 $sIn = preg_replace( '`(.)\1`u', '$1', $sIn );
171 // on ne retient que 4 caractères ou on complète avec des blancs
172 return substr( $sIn . ' ', 0, 4);
173 }
174
175 /** met les majuscules au debut de chaque atome du prénom
176 * @param $prenom le prénom à formater
177 * return STRING le prénom avec les majuscules
178 */
179 function make_firstname_case($prenom) {
180 $prenom = strtolower($prenom);
181 $pieces = explode('-',$prenom);
182
183 foreach ($pieces as $piece) {
184 $subpieces = explode("'",$piece);
185 $usubpieces="";
186 foreach ($subpieces as $subpiece)
187 $usubpieces[] = ucwords($subpiece);
188 $upieces[] = implode("'",$usubpieces);
189 }
190 return implode('-',$upieces);
191 }
192
193
194 function make_forlife($prenom,$nom,$promo) {
195 $prenomUS = replace_accent(trim($prenom));
196 $nomUS = replace_accent(trim($nom));
197
198 $forlife = strtolower($prenomUS.".".$nomUS.".".$promo);
199 $forlife = str_replace(" ","-",$forlife);
200 $forlife = str_replace("'","",$forlife);
201 return $forlife;
202 }
203
204 function check_ip($level)
205 {
206 if (empty($_SERVER['REMOTE_ADDR'])) {
207 return false;
208 }
209 if (empty($_SESSION['check_ip'])) {
210 $ips = array();
211 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
212 $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
213 }
214 $ips[] = $_SERVER['REMOTE_ADDR'];
215 foreach ($ips as &$ip) {
216 $ip = "ip='$ip'";
217 }
218 $res = XDB::query('SELECT state
219 FROM ip_watch
220 WHERE ' . implode(' OR ', $ips) . '
221 ORDER BY state DESC');
222 if ($res->numRows()) {
223 $_SESSION['check_ip'] = $res->fetchOneCell();
224 } else {
225 $_SESSION['check_ip'] = 'safe';
226 }
227 }
228 $test = array();
229 switch ($level) {
230 case 'unsafe': $test[] = 'unsafe';
231 case 'dangerous': $test[] = 'dangerous';
232 case 'ban': $test[] = 'ban'; break;
233 default: return false;
234 }
235 return in_array($_SESSION['check_ip'], $test);
236 }
237
238 function check_email($email, $message)
239 {
240 $res = XDB::query("SELECT state, description
241 FROM emails_watch
242 WHERE state != 'safe' AND email = {?}", $email);
243 if ($res->numRows()) {
244 send_warning_mail($message);
245 return true;
246 }
247 return false;
248 }
249
250 function check_account()
251 {
252 return S::v('watch');
253 }
254
255 function check_redirect($red = null)
256 {
257 require_once 'emails.inc.php';
258 if (is_null($red)) {
259 $red = new Redirect(S::v('uid'));
260 }
261 $_SESSION['no_redirect'] = !$red->other_active('');
262 $_SESSION['mx_failures'] = $red->get_broken_mx();
263 }
264
265 function send_warning_mail($title)
266 {
267 $mailer = new PlMailer();
268 $mailer->setFrom("webmaster@polytechnique.org");
269 $mailer->addTo("hotliners@staff.polytechnique.org");
270 $mailer->setSubject("[Plat/al Security Alert] $title");
271 $mailer->setTxtBody("Identifiants de session :\n" . var_export($_SESSION, true) . "\n\n"
272 ."Identifiants de connexion :\n" . var_export($_SERVER, true));
273 $mailer->send();
274 }
275
276 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
277 ?>