Enabler PHP natives assertion in debug and use Platal::assert() as a
[platal.git] / include / misc.inc.php
index 3cd88c8..b60045d 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2008 Polytechnique.org                              *
+ *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-function quoted_printable_encode($input, $line_max = 76)
-{
-    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
-    $eol = "\n";
-    $linebreak = "=0D=0A=\n    ";
-    $escape = "=";
-    $output = "";
+// Use native function if it's available (>= PHP5.3)
+if (!function_exists('quoted_printable_encode')) {
+    function quoted_printable_encode($input, $line_max = 76)
+    {
+        $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
+        $eol = "\n";
+        $linebreak = "=0D=0A=\n    ";
+        $escape = "=";
+        $output = "";
 
-    foreach ($lines as $j => $line) {
-        $linlen = strlen($line);
-        $newline = "";
-        for($i = 0; $i < $linlen; $i++) {
-            $c = $line{$i};
-            $dec = ord($c);
-            if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
-                // convert space at eol only
-                $c = "=20";
-            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
-                // always encode "\t", which is *not* required
-                $c = $escape.strtoupper(sprintf("%02x",$dec));
-            }
-            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
-                $output .= $newline.$escape.$eol;
-                $newline = "    ";
-            }
-            $newline .= $c;
-        } // end of for
-        $output .= $newline;
-        if ($j<count($lines)-1) $output .= $linebreak;
+        foreach ($lines as $j => $line) {
+            $linlen = strlen($line);
+            $newline = "";
+            for($i = 0; $i < $linlen; $i++) {
+                $c = $line{$i};
+                $dec = ord($c);
+                if ( ($dec == 32) && ($i == ($linlen - 1)) ) {
+                    // convert space at eol only
+                    $c = "=20";
+                } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
+                    // always encode "\t", which is *not* required
+                    $c = $escape.strtoupper(sprintf("%02x",$dec));
+                }
+                if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
+                    $output .= $newline.$escape.$eol;
+                    $newline = "    ";
+                }
+                $newline .= $c;
+            } // end of for
+            $output .= $newline;
+            if ($j<count($lines)-1) $output .= $linebreak;
+        }
+        return trim($output);
     }
-    return trim($output);
-}
-
-/** vérifie si une adresse email convient comme adresse de redirection
- * @param $email l'adresse email a verifier
- * @return BOOL
- */
-function isvalid_email_redirection($email)
-{
-    return isvalid_email($email) &&
-        !preg_match("/@(polytechnique\.(org|edu)|melix\.(org|net)|m4x\.org)$/", $email);
 }
 
 /** genere une chaine aleatoire de 22 caracteres ou moins
@@ -122,30 +115,6 @@ function replace_accent($string)
     return strtr($string, $uc_convert);
 }
 
-/** creates a username from a first and last name
- *
- * @param $prenom the firstname
- * @param $nom the last name
- *
- * return STRING the corresponding username
- */
-function make_username($prenom,$nom)
-{
-    /* on traite le prenom */
-    $prenomUS=replace_accent(trim($prenom));
-    $prenomUS=stripslashes($prenomUS);
-
-    /* on traite le nom */
-    $nomUS=replace_accent(trim($nom));
-    $nomUS=stripslashes($nomUS);
-
-    // calcul du login
-    $username = strtolower($prenomUS.".".$nomUS);
-    $username = str_replace(" ","-",$username);
-    $username = str_replace("'","",$username);
-    return $username;
-}
-
 /* Un soundex en français posté par Frédéric Bouchery
    Voici une adaptation en PHP de la fonction soundex2 francisée de Frédéric BROUARD (http://sqlpro.developpez.com/Soundex/).
    C'est une bonne démonstration de la force des expressions régulières compatible Perl.
@@ -199,37 +168,6 @@ function soundex_fr($sIn)
     return substr( $sIn . '    ', 0, 4);
 }
 
-/** met les majuscules au debut de chaque atome du prénom
- * @param $prenom le prénom à formater
- * return STRING le prénom avec les majuscules
- */
-function make_firstname_case($prenom)
-{
-    $prenom = strtolower($prenom);
-    $pieces = explode('-',$prenom);
-
-    foreach ($pieces as $piece) {
-        $subpieces = explode("'",$piece);
-        $usubpieces="";
-        foreach ($subpieces as $subpiece)
-            $usubpieces[] = ucwords($subpiece);
-        $upieces[] = implode("'",$usubpieces);
-    }
-    return implode('-',$upieces);
-}
-
-
-function make_forlife($prenom, $nom, $promo)
-{
-    $prenomUS = replace_accent(trim($prenom));
-    $nomUS    = replace_accent(trim($nom));
-
-    $forlife = strtolower($prenomUS.".".$nomUS.".".$promo);
-    $forlife = str_replace(" ","-",$forlife);
-    $forlife = str_replace("'","",$forlife);
-    return $forlife;
-}
-
 /** Convert ip to uint (to store it in a database)
  */
 function ip_to_uint($ip)
@@ -254,5 +192,211 @@ function uint_to_ip($uint)
     return long2ip($uint);
 }
 
+/** Converts DateTime / string / timestamp to DateTime object
+ */
+function make_datetime($date)
+{
+    if ($date instanceof DateTime) {
+        return $date;
+    } elseif (preg_match('/^\d{14}$/', $date) || preg_match('/^\d{8}$/', $date)) {
+        return new DateTime($date);
+    } elseif (is_int($date) || is_numeric($date)) {
+        return new DateTime("@$date");
+    } else {
+        try {
+            $list = explode('/', $date);
+            if (count($list) == 3) {
+                $date = $list[1] . '/' . $list[0] . '/' . $list[2];
+            }
+            // FIXME: On PHP < 5.3, parsing error are reported using an error,
+            //        not an exception. Thus count the number of error to detect
+            //        errors.
+            $errors = @count($GLOBALS['pl_errors']);
+            $d = new DateTime($date);
+            if (@count($GLOBALS['pl_errors']) > $errors) {
+                return null;
+            }
+            return $d;
+        } catch (Exception $e) {
+            return null;
+        }
+    }
+}
+
+/** Here to allow clean date formats instead of PHP's erroneous system...
+ * Format :
+ * %a: Mon...Sun
+ * %A: Monday...Sunday
+ * %d: day, two digits
+ * %e: day, space before single digits
+ * %j: day of year
+ * %u: day of week (1 for monday, 7 for sunday)
+ * %w: day of week (0 for sunday, 6 for saturday)
+ *
+ * //%U: week number (first week is that with the first sunday)
+ * //%V: week number (ISO 8601-1988: first week is that with at least 4 week days)
+ * %W: week number (first week is that with the first monday)
+ *
+ * %b: Jan...Dec
+ * %B: January...December
+ * %h: = %b
+ * %m: month, two digits
+ *
+ * %C: century, two digits
+ * %g: year, two digits (ISO 8601-1988)
+ * %G: %g with four digits
+ * %y: year, two digits
+ * %Y: year, four digits
+ *
+ * %H: hour, two digits, 24h format
+ * %h: hour, two digits, 12h format
+ * %l: hour, two digits, space before single, 12h format
+ * %M: minute, two digits
+ * %p: AM/PM
+ * %P: am/pm
+ * %r: %I:%M:%S %p
+ * %R: %H:%M
+ * %S: second, two digits
+ * %T: %H:%M:%S
+ * %z: timezone (offset)
+ * %Z: timezone (abbrev)
+ *
+ * %x: %e %B %Y
+ * %X: %T
+ * %s: unix timestamp
+ * %%: %
+ */
+function format_datetime($date, $format)
+{
+    $format = str_replace(array('%X', '%x', '%R', '%r', '%T', '%%'),
+                     array('%T', '%e %B %Y', '%H:%M', '%I:%M:%S %p', '%H:%M:%S', '%%'),
+                     $format);
+
+    $date = make_datetime($date);
+    $yy = (int) $date->format('Y');
+//    if ($yy > 1901 && $yy < 2038) {
+//        return strftime($format, $date->format('U'));
+//    } else {
+        $w = (int) $date->format('w');
+        $u = $w;
+        if ($u == 0) {
+            $u = 7;
+        }
+        $weekday = new DateTime('2010-05-' . (10 + $u));
+        $aa = strftime('%A', $weekday->format('U'));
+        $a = strftime('%a', $weekday->format('U'));
+
+        $m = $date->format('m');
+        $monthday = new DateTime('2010-' . $m . '-01');
+        $bb = strftime('%B', $monthday->format('U'));
+        $b = strftime('%b', $monthday->format('U'));
+        $y = $date->format('y');
+
+        $j  = $date->format('z'); // Day of year
+        $d  = $date->format('d'); // Day of month, 2 digits
+        $e  = $date->format('j'); // Day of month, leanding space
+        if (strlen($e) == 1) {
+            $e = ' ' . $e;
+        }
+
+        $yy = "$yy";
+        $cc = substr($yy, 0, 2); // Century
+        $ww = $date->format('W'); // Week number
+
+        $hh = $date->format('H'); // Hour, 24h
+        $h  = $date->format('h'); // Hour, 12h
+        $l  = $date->format('g'); // Hour, 12h with leading space
+        if (strlen($l) == 1) {
+            $l = ' ' . $l;
+        }
+
+        $mm = $date->format('i'); // Minutes
+        $p  = $date->format('A'); // AM/PM
+        $pp = $date->format('a'); // am/pm
+        $ss = $date->format('s'); // Seconds
+
+        $s  = $date->format('U'); // Timestamp
+        $zz = $date->format('T'); // Timezone abbrev
+        $z  = $date->format('Z'); // Timezone offset
+
+        $txt = str_replace(
+            array('%a', '%A', '%d', '%e', '%j', '%u', '%w',
+                  '%W', '%b', '%B', '%h', '%m', '%C', '%y', '%Y',
+                  '%H', '%h', '%l', '%M', '%p', '%P', '%S', '%z', '%Z',
+                  '%%'),
+            array($a, $aa, $d, $e, $j, $u, $w,
+                  $ww, $b, $bb, $b, $m, $cc, $y, $yy,
+                  $hh, $h, $l, $mm, $p, $pp, $ss, $z, $zz,
+                  '%'),
+            $format);
+
+        return $txt;
+//    }
+}
+
+/** Get the first n characters of the string
+ */
+function left($string, $count)
+{
+    return substr($string, 0, $count);
+}
+
+/** Get the last n characters of the string
+ */
+function right($string, $count)
+{
+    return substr($string, -$count);
+}
+
+/** Check if a string is a prefix for another one.
+ */
+function starts_with($string, $prefix, $caseSensitive = true)
+{
+    $prefixLen = strlen($prefix);
+    if (strlen($string) < $prefixLen) {
+        return false;
+    }
+    $part = left($string, $prefixLen);
+    if ($caseSensitive) {
+        return strcmp($prefix, $part) === 0;
+    } else {
+        return strcasecmp($prefix, $part) === 0;
+    }
+}
+
+/** Check if a string is a suffix for another one.
+ */
+function ends_with($string, $suffix, $caseSensitive = true)
+{
+    $suffixLen = strlen($suffix);
+    if (strlen($string) < $suffixLen) {
+        return false;
+    }
+    $part = right($string, $suffixLen);
+    if ($caseSensitive) {
+        return strcmp($suffix, $part) === 0;
+    } else {
+        return strcasecmp($suffix, $part) === 0;
+    }
+}
+
+/** Check if the input data can be seen as an integer.
+ */
+function can_convert_to_integer($data)
+{
+    return is_int($data) || ctype_digit($data);
+}
+
+/** Interpret the input data as an integer or return false.
+ */
+function to_integer($data)
+{
+    if (!can_convert_to_integer($data)) {
+        return false;
+    }
+    return intval($data);
+}
+
+
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
 ?>