Remove debugging stuff.
[platal.git] / include / misc.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 // Use native function if it's available (>= PHP5.3)
23 if (!function_exists('quoted_printable_encode')) {
24 function quoted_printable_encode($input, $line_max = 76)
25 {
26 $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
27 $eol = "\n";
28 $linebreak = "=0D=0A=\n ";
29 $escape = "=";
30 $output = "";
31
32 foreach ($lines as $j => $line) {
33 $linlen = strlen($line);
34 $newline = "";
35 for($i = 0; $i < $linlen; $i++) {
36 $c = $line{$i};
37 $dec = ord($c);
38 if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
39 // convert space at eol only
40 $c = "=20";
41 } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
42 // always encode "\t", which is *not* required
43 $c = $escape.strtoupper(sprintf("%02x",$dec));
44 }
45 if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
46 $output .= $newline.$escape.$eol;
47 $newline = " ";
48 }
49 $newline .= $c;
50 } // end of for
51 $output .= $newline;
52 if ($j<count($lines)-1) $output .= $linebreak;
53 }
54 return trim($output);
55 }
56 }
57
58 /** genere une chaine aleatoire de 22 caracteres ou moins
59 * @param $len longueur souhaitée, 22 par défaut
60 * @return la chaine aleatoire qui contient les caractères [A-Za-z0-9+/]
61 */
62 function rand_token($len = 22)
63 {
64 $len = max(2, $len);
65 $len = min(50, $len);
66 $fp = fopen('/dev/urandom', 'r');
67 // $len * 2 is certainly an overkill,
68 // but HEY, reading 40 bytes from /dev/urandom is not that slow !
69 $token = fread($fp, $len * 2);
70 fclose($fp);
71 $token = base64_encode($token);
72 $token = preg_replace("![Il10O+/]!", "", $token);
73 $token = substr($token,0,$len);
74 return $token;
75 }
76
77 /** genere une chaine aleatoire convenable pour une url
78 * @param $len longueur souhaitée, 22 par défaut
79 * @return la chaine aleatoire
80 */
81 function rand_url_id($len = 22)
82 {
83 return rand_token($len);
84 }
85
86
87 /** genere une chaine aleatoire convenable pour un mot de passe
88 * @return la chaine aleatoire
89 */
90 function rand_pass()
91 {
92 return rand_token(8);
93 }
94
95 /** Remove accent from a string and replace them by the nearest letter
96 */
97 global $lc_convert, $uc_convert;
98 $lc_convert = array('é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
99 'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a', 'å' => 'a', 'ã' => 'a',
100 'ï' => 'i', 'î' => 'i', 'ì' => 'i', 'í' => 'i',
101 'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o', 'ø' => 'o',
102 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
103 'ç' => 'c', 'ñ' => 'n');
104 $uc_convert = array('É' => 'E', 'È' => 'E', 'Ë' => 'E', 'Ê' => 'E',
105 'Á' => 'A', 'À' => 'A', 'Ä' => 'A', 'Â' => 'A', 'Å' => 'A', 'Ã' => 'A',
106 'Ï' => 'I', 'Î' => 'I', 'Ì' => 'I', 'Í' => 'I',
107 'Ô' => 'O', 'Ö' => 'O', 'Ò' => 'O', 'Ó' => 'O', 'Õ' => 'O', 'Ø' => 'O',
108 'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
109 'Ç' => 'C', 'Ñ' => 'N');
110
111 function replace_accent($string)
112 {
113 global $lc_convert, $uc_convert;
114 $string = strtr($string, $lc_convert);
115 return strtr($string, $uc_convert);
116 }
117
118 /* Un soundex en français posté par Frédéric Bouchery
119 Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
120 C'est une bonne démonstration de la force des expressions régulières compatible Perl.
121 trouvé sur http://expreg.com/voirsource.php?id=40&type=Chaines%20de%20caract%E8res */
122 function soundex_fr($sIn)
123 {
124 static $convVIn, $convVOut, $convGuIn, $convGuOut, $accents;
125 if (!isset($convGuIn)) {
126 global $uc_convert, $lc_convert;
127 $convGuIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'SCI', 'SCE', 'SC', 'CA', 'CO',
128 'CU', 'QU', 'Q', 'CC', 'CK', 'G', 'ST', 'PH');
129 $convGuOut = array( 'KI', 'KE', 'KA', 'KO', 'K', 'SI', 'SE', 'SK', 'KA', 'KO',
130 'KU', 'K', 'K', 'K', 'K', 'J', 'T', 'F');
131 $convVIn = array( '/E?(AU)/', '/([EA])?[UI]([NM])([^EAIOUY]|$)/', '/[AE]O?[NM]([^AEIOUY]|$)/',
132 '/[EA][IY]([NM]?[^NM]|$)/', '/(^|[^OEUIA])(OEU|OE|EU)([^OEUIA]|$)/', '/OI/',
133 '/(ILLE?|I)/', '/O(U|W)/', '/O[NM]($|[^EAOUIY])/', '/(SC|S|C)H/',
134 '/([^AEIOUY1])[^AEIOUYLKTPNR]([UAO])([^AEIOUY])/', '/([^AEIOUY]|^)([AUO])[^AEIOUYLKTP]([^AEIOUY1])/', '/^KN/',
135 '/^PF/', '/C([^AEIOUY]|$)/',
136 '/C/', '/Z$/', '/(?<!^)Z+/', '/ER$/', '/H/', '/W/');
137 $convVOut = array( 'O', '1\3', 'A\1',
138 'E\1', '\1E\3', 'O',
139 'Y', 'U', 'O\1', '9',
140 '\1\2\3', '\1\2\3', 'N',
141 'F', 'K\1',
142 'S', 'SE', 'S', 'E', '', 'V');
143 $accents = $uc_convert + $lc_convert;
144 $accents['Ç'] = 'S';
145 $accents['¿'] = 'E';
146 }
147 // Si il n'y a pas de mot, on sort immédiatement
148 if ( $sIn === '' ) return ' ';
149 // On supprime les accents
150 $sIn = strtr( $sIn, $accents);
151 // On met tout en minuscule
152 $sIn = strtoupper( $sIn );
153 // On supprime tout ce qui n'est pas une lettre
154 $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
155 // Si la chaîne ne fait qu'un seul caractère, on sort avec.
156 if ( strlen( $sIn ) === 1 ) return $sIn . ' ';
157 // on remplace les consonnances primaires
158 $sIn = str_replace( $convGuIn, $convGuOut, $sIn );
159 // on supprime les lettres répétitives
160 $sIn = preg_replace( '`(.)\1`', '$1', $sIn );
161 // on réinterprète les voyelles
162 $sIn = preg_replace( $convVIn, $convVOut, $sIn);
163 // on supprime les terminaisons T, D, S, X (et le L qui précède si existe)
164 $sIn = preg_replace( '`L?[TDX]S?$`', '', $sIn );
165 // on supprime les E, A et Y qui ne sont pas en première position
166 $sIn = preg_replace( '`(?!^)Y([^AEOU]|$)`', '\1', $sIn);
167 $sIn = preg_replace( '`(?!^)[EA]`', '', $sIn);
168 return substr( $sIn . ' ', 0, 4);
169 }
170
171 /** Convert ip to uint (to store it in a database)
172 */
173 function ip_to_uint($ip)
174 {
175 $part = explode('.', $ip);
176 if (count($part) != 4) {
177 return null;
178 }
179 $v = 0;
180 $fact = 0x1000000;
181 for ($i = 0 ; $i < 4 ; ++$i) {
182 $v += $fact * $part[$i];
183 $fact >>= 8;
184 }
185 return $v;
186 }
187
188 /** Convert uint to ip (to build a human understandable ip)
189 */
190 function uint_to_ip($uint)
191 {
192 return long2ip($uint);
193 }
194
195 /** Converts DateTime / string / timestamp to DateTime object
196 */
197 function make_datetime($date)
198 {
199 if ($date instanceof DateTime) {
200 return $date;
201 } elseif (preg_match('/^\d{14}$/', $date) || preg_match('/^\d{8}$/', $date)) {
202 return new DateTime($date);
203 } elseif (is_int($date) || is_numeric($date)) {
204 return new DateTime("@$date");
205 } else {
206 try {
207 $d = new DateTime($date);
208 return $d;
209 } catch (Exception $e) {
210 return null;
211 }
212 }
213 }
214
215 /** Here to allow clean date formats instead of PHP's erroneous system...
216 * Format :
217 * %a: Mon...Sun
218 * %A: Monday...Sunday
219 * %d: day, two digits
220 * %e: day, space before single digits
221 * %j: day of year
222 * %u: day of week (1 for monday, 7 for sunday)
223 * %w: day of week (0 for sunday, 6 for saturday)
224 *
225 * //%U: week number (first week is that with the first sunday)
226 * //%V: week number (ISO 8601-1988: first week is that with at least 4 week days)
227 * %W: week number (first week is that with the first monday)
228 *
229 * %b: Jan...Dec
230 * %B: January...December
231 * %h: = %b
232 * %m: month, two digits
233 *
234 * %C: century, two digits
235 * %g: year, two digits (ISO 8601-1988)
236 * %G: %g with four digits
237 * %y: year, two digits
238 * %Y: year, four digits
239 *
240 * %H: hour, two digits, 24h format
241 * %h: hour, two digits, 12h format
242 * %l: hour, two digits, space before single, 12h format
243 * %M: minute, two digits
244 * %p: AM/PM
245 * %P: am/pm
246 * %r: %I:%M:%S %p
247 * %R: %H:%M
248 * %S: second, two digits
249 * %T: %H:%M:%S
250 * %z: timezone (offset)
251 * %Z: timezone (abbrev)
252 *
253 * %x: %e %B %Y
254 * %X: %T
255 * %s: unix timestamp
256 * %%: %
257 */
258 function format_datetime($date, $format)
259 {
260 $format = str_replace(array('%X', '%x', '%R', '%r', '%T', '%%'),
261 array('%T', '%e %B %Y', '%H:%M', '%I:%M:%S %p', '%H:%M:%S', '%%'),
262 $format);
263
264 $date = make_datetime($date);
265 $yy = (int) $date->format('Y');
266 // if ($yy > 1901 && $yy < 2038) {
267 // return strftime($format, $date->format('U'));
268 // } else {
269 $w = (int) $date->format('w');
270 $u = $w;
271 if ($u == 0) {
272 $u = 7;
273 }
274 $weekday = new DateTime('2010-05-' . (10 + $u));
275 $aa = strftime('%A', $weekday->format('U'));
276 $a = strftime('%a', $weekday->format('U'));
277
278 $m = $date->format('m');
279 $monthday = new DateTime('2010-' . $m . '-01');
280 $bb = strftime('%B', $monthday->format('U'));
281 $b = strftime('%b', $monthday->format('U'));
282 $y = $date->format('y');
283
284 $j = $date->format('z'); // Day of year
285 $d = $date->format('d'); // Day of month, 2 digits
286 $e = $date->format('j'); // Day of month, leanding space
287 if (strlen($e) == 1) {
288 $e = ' ' . $e;
289 }
290
291 $yy = "$yy";
292 $cc = substr($yy, 0, 2); // Century
293 $ww = $date->format('W'); // Week number
294
295 $hh = $date->format('H'); // Hour, 24h
296 $h = $date->format('h'); // Hour, 12h
297 $l = $date->format('g'); // Hour, 12h with leading space
298 if (strlen($l) == 1) {
299 $l = ' ' . $l;
300 }
301
302 $mm = $date->format('i'); // Minutes
303 $p = $date->format('A'); // AM/PM
304 $pp = $date->format('a'); // am/pm
305 $ss = $date->format('s'); // Seconds
306
307 $s = $date->format('U'); // Timestamp
308 $zz = $date->format('T'); // Timezone abbrev
309 $z = $date->format('Z'); // Timezone offset
310
311 $txt = str_replace(
312 array('%a', '%A', '%d', '%e', '%j', '%u', '%w',
313 '%W', '%b', '%B', '%h', '%m', '%C', '%y', '%Y',
314 '%H', '%h', '%l', '%M', '%p', '%P', '%S', '%z', '%Z',
315 '%%'),
316 array($a, $aa, $d, $e, $j, $u, $w,
317 $ww, $b, $bb, $b, $m, $cc, $y, $yy,
318 $hh, $h, $l, $mm, $p, $pp, $ss, $z, $zz,
319 '%'),
320 $format);
321
322 return $txt;
323 // }
324 }
325
326 /** Get the first n characters of the string
327 */
328 function left($string, $count)
329 {
330 return substr($string, 0, $count);
331 }
332
333 /** Get the last n characters of the string
334 */
335 function right($string, $count)
336 {
337 return substr($string, -$count);
338 }
339
340 /** Check if a string is a prefix for another one.
341 */
342 function starts_with($string, $prefix, $caseSensitive = true)
343 {
344 $prefixLen = strlen($prefix);
345 if (strlen($string) < $prefixLen) {
346 return false;
347 }
348 $part = left($string, $prefixLen);
349 if ($caseSensitive) {
350 return strcmp($prefix, $part) === 0;
351 } else {
352 return strcasecmp($prefix, $part) === 0;
353 }
354 }
355
356 /** Check if a string is a suffix for another one.
357 */
358 function ends_with($string, $suffix, $caseSensitive = true)
359 {
360 $suffixLen = strlen($suffix);
361 if (strlen($string) < $suffixLen) {
362 return false;
363 }
364 $part = right($string, $suffixLen);
365 if ($caseSensitive) {
366 return strcmp($suffix, $part) === 0;
367 } else {
368 return strcasecmp($suffix, $part) === 0;
369 }
370 }
371
372
373 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
374 ?>