PHP Classes
Icontem

File: ilaria.php


  Search   All class groups All class groups   Latest entries Latest entries   Top 10 charts Top 10 charts   Newsletter Newsletter   Blog Blog   Forums Forums   Help FAQ Help FAQ  
  Login   Register  
Recommend this page to a friend! ReTweet ReTweet Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Giulio Bai  >  Ilaria  >  ilaria.php  
File: ilaria.php
Role: Class source
Content type: text/plain
Description: Main class file
Class: Ilaria
General purpose functions for Web development
 

Contents

Class file image Download
<?php

class Ilaria
{
    var $package;
    
    var $version;
    
    var $functions;
    
    var $include_path;
    
    
    function Ilaria ()
    {
        $this->package = "ILARIA - I Love Avoiding Repetitions In Applications";
        
        $this->version = 1.0;
        
        /**
         * DATES_TIME     : 11
         * FILES          : 7
         * MISC           : 9
         * NUMBERS_ARRAYS : 3
         * TEXT           : 11
         * VALIDATIONS    : 9
         */
        $this->functions = 50;
        
        $this->include_path = "include/";
    }
    
    
    
    
    
    // DATES - TIME
    
    /**
     * A simple html/pjp formatted calendar which returns the date as
     * a unix timestamp when the required day is selected.
     * Also allows for setting of time in the 24h format.
     *
     * @author Kris Dover <krisdover@hotmail.com>
     * @from http://php.net/date
     *
     * @return void
     */
    function calendar ()
    {
        $sel_date = isset($_REQUEST['sel_date']) ? $_REQUEST['sel_date'] : time();
        
        if (isset($_POST['hrs']))
        {
            $t = getdate($sel_date);
            $sel_date = mktime($_POST['hrs'], $_POST['mins'], $t['seconds'], $t['mon'], $t['mday'], $t['year']);
        }
        
        $t = getdate($sel_date);
        
        $start_date = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], 1, $t['year']);
        $start_date -= 86400 * date('w', $start_date);
        
        $prev_year = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], $t['mday'], $t['year'] - 1);
        $prev_month = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'] - 1, $t['mday'], $t['year']);
        
        $next_year = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], $t['mday'], $t['year'] + 1);
        $next_month = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'] + 1, $t['mday'], $t['year']);
        
        ?>
        
        <form method="post">
            <table width="180" border="0" cellspacing="1" 
                    style="border: 1px solid black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: x-small; text-align: center">
                <tr> 
                    <td width="14%" bgcolor="#66FF99">
                        <a href="?sel_date=<?= $prev_year ?>" style="text-decoration: none" title="Prevous Year">&lt;&lt;</a>
                    </td>
                    
                    <td width="14%" bgcolor="#66FF99">
                        <a href="?sel_date=<?= $prev_month ?>" style="text-decoration: none" title="Prevous Month">&lt;</a>
                    </td>
                    
                    <td colspan="3" bgcolor="#66FF99">
                        <?= date('M Y', $sel_date) ?>
                    </td>
                    
                    <td width="14%" bgcolor="#66FF99">
                        <a href="?sel_date=<?= $next_month ?>" style="text-decoration: none" title="Next Month">&gt;</a>
                    </td>
                    
                    <td width="14%" bgcolor="#66FF99">
                        <a href="?sel_date=<?= $next_year ?>" style="text-decoration: none" title="Next Year">&gt;&gt;</a>
                    </td>
                </tr>
                
                <tr> 
                    <td bgcolor="#0099FF">Sun</td>
                    <td bgcolor="#0099FF">Mon</td>
                    <td width="14%" bgcolor="#0099FF">Tue</td>
                    <td width="14%" bgcolor="#0099FF">Wed</td>
                    <td width="14%" bgcolor="#0099FF">Thu</td>
                    <td bgcolor="#0099FF">Fri</td>
                    <td bgcolor="#0099FF">Sat</td>
                </tr>
                
                <?php
                
                $day = 1;
                
                for ($i=$start_date; $day<=42; $i+=86400, $day++)
                {
                    if ($day % 7 == 1)
                    {
                        echo "<tr>\n";
                    }
                        
                    if ($t['mon'] == date('n', $i ))
                    {
                        if ($i == $sel_date)
                        {
                            echo ' <td bgcolor="gold">'. date('j', $i) ."</td>\n";
                        }
                        else
                        {
                            echo ' <td><a href="?sel_date='. $i .'" style="text-decoration: none">'. date('j', $i) ."</a></td>\n";
                        }
                    }
                    else
                    {
                        echo ' <td ><a href="?sel_date='. $i .'" style="text-decoration: none"><font  color="silver">'. date('j', $i) ."</font></a></td>\n";                
                    }
                    
                    if ($day % 7 == 0)
                    {
                        echo "</tr>\n";
                    }
                }
                
                ?>
                
                <tr>
                    <td colspan="7" align="left" bgcolor="silver">Time:
                        <select name="hrs" onchange="document.forms[0].submit()">
                        <?php
                            for ($i=0; $i<24; $i++)
                            {
                                echo '   <option '. (date('G', $sel_date)==$i ? 'selected':'') .'>'. sprintf('%02d', $i) ."</option>\n";
                            }
                        ?>
                        </select>:
                        
                        <select name="mins" onchange="document.forms[0].submit()">
                        <?php
                            for ($i=0; $i<60; $i++)
                            {
                                echo '   <option '. (date('i', $sel_date)==$i ? 'selected':'') .'>'. sprintf('%02d', $i) ."</option>\n";
                            }
                        ?>
                        </select> hrs
                        
                        <input type="hidden" name="sel_date" value="<?= $sel_date ?>">    
                    </td>
                </tr>
            </table>
        </form>
        
        <?php
    }
    
    /**
     * Converts a date to number of days
     *
     * @from PEAR
     *
     * @param   int $day    the day of the month
     * @param   int $month  the month
     * @param   int $year   the year
     * @return  int         the number of days since that date
     */
    function date2days($day, $month, $year)
    {
        $century = substr($year, 0, 2);
        $year = substr($year, 2, 2);
        
        if ($month > 2)
        {
            $month -= 3;
        }
        else
        {
            $month += 9;
            
            if ($year)
            {
                $year --;
            }
            else
            {
                $year = 99;
                $century --;
            }
        }
        
        return (floor((146097 * $century) / 4 ) +
                floor((1461 * $year) / 4 ) +
                floor((153 * $month + 2) / 5 ) +
                $day + 1721119);
    }
    


    /**
     * Returns an array containing all the parameters of a date
     * 
     * @param   string $time_format     time format to split
     * @param   string $separator       the separator used in the date string
     * @return  array                   array containing all the parts of the date
     */
    function get_date_array ($time_format, $separator)
    {
        return explode($separator, date($time_format));
    }
    
    
    
    /**
     * Gets all month names
     *
     * @param   bool    $abbr   if NOT set names are full-length ones [default: false]
     * @param   int     $year   the current year [default: 2007]
     * @return  array           array with names ordered by months' position in the year
     */
    function get_months_names($abbr = 0, $year = 2007)
    {
        $months = array();
        
        for ($i=1; $i<13; $i++)
        {
            $month = strftime('%B', mktime(0, 0, 0, $i, 1, $year));
            
            if ($abbr)
            {
                $month = substr($month, 0, 3);
            }
            
            $months[$i] = $month;
        }
        
        return $months;
    }



    /**
     * Gets a single month name
     *
     * @param   bool    $abbr   if NOT set names are full-length ones [default: false]
     * @param   int     $year   the current year [default: 2007]
     * @return  string          the month name
     */
    function get_month_name($month, $abbr = 0, $year = 2007)
    {
        $months = $this->get_months_names($abbr, $year);
        
        return $months[$month];
    }



    /**
     * Gets all weekday names
     *
     * @param   bool    $abbr   if NOT set names are full-length ones [default: false]
     * @param   int     $year   the current year [default: 2007]
     * @return  array           array with names ordered by days' position in the week
     */
    function get_weekdays_names($abbr = 0, $year = 2007)
    {
        for ($i=1; $i<8; $i++)
        {
            $weekday = strftime('%A', mktime(0, 0, 0, 1, $i, $year));
            
            if ($abbr)
            {
                $weekday = substr($weekday, 0, 3);
            }
            
            $weekdays[$i] = $weekday;
        }
        
        return $weekdays;
    }



    /**
     * Gets a single weekday name
     *
     * @param   int     $day    the number of the day in the week 
     * @param   bool    $abbr   if NOT set names are full-length ones [default: false]
     * @param   int     $year   the current year [default: 2007]
     * @return                  string the day name
     */
    function get_weekday_name($day, $abbr = 0, $year = 2007)
    {
        $weekdays = $this->get_weekdays_name($abbr, $year);
        
        return $weekdays[$day];
    }
    
    
    
    /**
     * What time is it?
     *
     * @param   string  $time_format    the format you want the time in [default: H:i:s]
     * @return  string                  the current time
     */
    function get_time($time_format = "H:i:s")
    {
        return date($time_format);
    }
    
    
    /**
     * Gets the current day
     *
     * @param   bool    $name   literal (1) or numeric (0) expression [default: 0]
     * @param   bool    $abbr   determines if the literal result must be shorten [default: 1]
     * @return  mixed           the current day expressed by a number or its own name
     */
    function this_day ($name = 0, $abbr = 1)
    {
        $day = date("d");
        
        if ($name)
        {
            $day = $this->get_weekday_name($day, $abbr);
        }
        
        return $day;
    }


    /**
     * Gets the current month
     *
     * @param   bool    $name   literal (1) or numeric (0) expression [default: 0]
     * @param   bool    $abbr   determines if the literal result must be shorten [default: 1]
     * @return  mixed           the current month expressed by a number or its own name
     */
    function this_month ($name = 0, $abbr = 1)
    {
        $month = date("m");
        
        if ($name)
        {
            $day = $this->get_weekday_name($month, $abbr);
        }
        
        return $month;
    }
    
    
    /**
     * Gets the current year
     *
     * @param   bool    $abbr   determines if the literal result must be shorten [default: 0]
     * @return  mixed           the current year in 2/4 figures
     */
    function this_year ($abbr = 0)
    {
        $format = "Y";
        
        if ($abbr)
        {
            $format = "y";
        }
        
        $year = date($format);
                
        return $year;
    }




    // FILES
    
    /**
     * Deletes a directory after have empty it [recursive]
     *
     * @param   string  $directory  the path to the directory
     * @return  void
     */
    function deldir($directory)
    {
        $directory_contents = scandir($directory);
        
        foreach ($directory_contents as $item)
        {
            if (is_dir($directory . $item) && $item != '.' && $item != '..')
            {
               $this->deldir($directory . $item . '/');
            }
            elseif (file_exists($directory . $item) && $item != '.' && $item != '..')
            {
               unlink($directory . $item);
            }
            
        }
        
        rmdir($directory);
    }
    
    
    
    /**
     * Deletes all file in a certain location [recursive]
     *
     * @param   string  $source the path to delete files from
     * @return  bool            0 on failure, 1 otherwise
     */
    function delfiles($source)
    {
        $folder = opendir($source);
        
        while ($file = readdir($folder))
        {
            if ($file == '.' || $file == '..')
            {
            
            }
            
            if (is_dir($source . '/' . $file))
            {
                $this->delfiles($source . '/' . $file);
            }
            else
            {
                unlink($source . '/' . $file);
                
                return 0;
            }
        }
        
        closedir($folder);
        rmdir($source);
        
        return 1;
    }
    
    
    
    /**
     * Copies a directory and its content to another location
     *
     * @param   string  $srcdir     the path to the source directory
     * @param   string  $dstdir     the destination path
     * @param   bool    $verbose    If true, prints out some message [default: false]
     * @return  int                 0 on failure
     */ 
    function dircopy($srcdir, $dstdir, $verbose = false)
    {
        $num = 0;
        
        if (!is_dir($dstdir))
        {
            mkdir($dstdir);
        }
        
        if ($curdir = opendir($srcdir))
        {
            while ($file = readdir($curdir))
            {
                if ($file != '.' && $file != '..')
                {
                    $srcfile = $srcdir . '\\' . $file;
                    $dstfile = $dstdir . '\\' . $file;
                    
                    if (is_file($srcfile))
                    {
                        if (is_file($dstfile))
                        {
                            $ow = filemtime($srcfile) - filemtime($dstfile);
                        }
                        else
                        {
                            $ow = 1;
                        }
                        
                        if ($ow > 0)
                        {
                            if ($verbose)
                            {
                                echo "Copying '$srcfile' to '$dstfile'...";
                            }
                            
                            if (copy($srcfile, $dstfile))
                            {
                                touch($dstfile, filemtime($srcfile));
                                
                                $num ++;
                                if ($verbose)
                                {
                                    echo "OK\n";
                                }
                            }
                            else
                            {
                                return 0;
                            }
                        }
                    }
                    else if (is_dir($srcfile))
                    {
                        $num += $this->dircopy($srcfile, $dstfile, $verbose);
                    }
                }
            }
            
            closedir($curdir);
        }
        
        return $num;
    }
    
    
    
    /**
     * Gets the file extension
     *
     * @param   string  $file_name  the file name
     * @return  string              the extension (without the dot [.])
     */
    function get_ext($file_name)
    {
        $efile_name = explode('.', $file_name);
        $ext = $efile_name[count($efile_name) - 1];
        
        return $ext;
    }



    /**
     * Prints a list of all the files contained in a directory
     *
     * @param   string  $path   the path containing the files to list
     * @return  mixed           0 on failure, else the array of files
     */
    function list_files($path)
    {
        $files = array();
        $fileNames = array();
        $sortedFiles = array();
        $i = 0;
        
        if (is_dir($path))
        {
            if ($dh = opendir($path))
            {
                while (($file = readdir($dh)) !== false)
                {
                    if ($file == "." || $file == "..")
                    {
                        continue;
                    }
                    
                    $fullpath = $path . "/" . $file;
                    
                    $fkey = strtolower($file);   
                    
                    while (array_key_exists($fkey, $fileNames))
                    {
                        $fkey .= " ";
                    }
                    
                    $a = stat($fullpath);
                    
                    $files[$fkey]['size'] = $a['size'];
                    
                    if ($a['size'] == 0)
                    {
                        $files[$fkey]['sizetext'] = "-";
                    }
                    elseif ($a['size'] > 1024)
                    {
                        $files[$fkey]['sizetext'] = (ceil($a['size'] / 1024 * 100) / 100) . " K";
                    }
                    elseif ($a['size'] > 1024 * 1024)
                    {
                        $files[$fkey]['sizetext'] = (ceil($a['size'] / (1024 * 1024) * 100) / 100) . " Mb";
                    }
                    else
                    {
                        $files[$fkey]['sizetext'] = $a['size'] . " bytes";
                    }
                    
                    $files[$fkey]['name'] = $file;
                    
                    $files[$fkey]['type'] = filetype($fullpath);
                    
                    $fileNames[$i++] = $fkey;
                }   
                
                closedir($dh);
            }
            else
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
        
        sort($fileNames, SORT_STRING);
        
        $i = 0;    
        
        foreach($fileNames as $f)
        {
            $sortedFiles[$i++] = $files[$f];
        }
        
        return $sortedFiles;
    }



    /**
     * Unzips files in an archive by using the ZipFolder class
     *
     * @param   string  $zipfile        name of the file to unzip
     * @param   string  $savepath       path to where save the archive contents
     * @param   string  $target_dirname path to the extract directory
     * @param   bool    $del            if 1 deletes the archive saved in $savepath [default: 1]
     * @return                          void
     */
    function UnZipThem($zipfile, $savepath, $target_dirname, $del = 1)
    {
        include_once($this->include_path . "ZipFolder.php");
        
        $unzipper = new ZipFolder;
        
        // Set the load path of the compressed archive
        $unzipper->setSavePath($savepath);
        
        // Set the zip file to be uncompressed
        $unzipper->setFile($zipfile);
        
        // Set the name of the folder where the zip file will be uncompressed
        $unzipper->setFolder($target_dirname);
        
        // Set the save path of the uncompressed archive
        $unzipper->setSavePath($savepath);
        
        // Once the parameters have been set we will uncompress the zip file
        $unzipper->openZip();
        
        if ($del)
        {
            // After the zip folder has been uncompressed we will delete it
            $unzipper->eraseZip();
        }
    } 
    
    
    /**
     * Alternative to scandir for php4
     *
     * @author Aryel <aryel@redtwilight.com.br>
     * @from http://www.php.net/manual/en/function.scandir.php
     */
    function php4_scandir($dir,$listDirectories=false, $skipDots=true) {
        $dirArray = array();
        
        if ($handle = opendir($dir))
        {
            while (false !== ($file = readdir($handle)))
            {
                if (($file != "." && $file != "..") || $skipDots == true)
                {
                    if ($listDirectories == false)
                    {
                        if (is_dir($file))
                        {
                            continue;
                        }
                    }
                    
                    array_push($dirArray,basename($file));
                }
            }
            
            closedir($handle);
        }
        
        return $dirArray;
    }
    
    
    

    // MISC
    
    function random_color()
    {
        $chars = "abcdef0123456789";
        
    	srand((double)microtime() * 1000000);
        
        $color = '';
        
        for ($i=0; $i<6; $i++)
        {
            $num = rand(0, 15);
            $tmp = substr($chars, $num, 1);
            
            $color .= $tmp;
        }
        
    	return "#" . $color;
    }
    
    
    
    function put_contents($filename, $contents)
    {
        $file = @fopen($filename, "w");
        
        if (!$file)
        {
            return false;
        }
        else
        {
            fwrite($file, $contents);
            fclose($file);
            
            return true;
        }
    }



    function bbcode($text){ 
        $text = nl2br(htmlspecialchars($text)); 
        
        $search = array( 
                        '`\[b\](.+?)\[/b\]`is', 
                        '`\[i\](.+?)\[/i\]`is', 
                        '`\[u\](.+?)\[/u\]`is', 
                        '`\[strike\](.+?)\[/strike\]`is', 
                        '`\[color=#([0-9]{6})\](.+?)\[/color\]`is', 
                        '`\[email\](.+?)\[/email\]`is', 
                        '`\[img\](.+?)\[/img\]`is', 
                        '`\[url=([a-z0-9]+://)([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*?)?)\](.*?)\[/url\]`si', 
                        '`\[url\]([a-z0-9]+?://){1}([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)\[/url\]`si', 
                        '`\[url\]((www|ftp)\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*?)?)\[/url\]`si', 
                        '`\[quote\](.+?)\[/quote\]`is', 
                        '`\[code](.+?)\[/code\]`is'
                ); 
                
        $replace =  array(
                        '<strong>\\1</strong>', 
                        '<em>\\1</em>', 
                        '<span style="border-bottom: 1px dotted">\\1</span>', 
                        '<strike>\\1</strike>', 
                        '<span style="color:#\1;">\2</span>', 
                        '<a href="mailto:\1">\1</a>', 
                        '<img src="\1" alt="" />', 
                        '<a href="\1\2">\6</a>', 
                        '<a href="\1\2">\1\2</a>', 
                        '<a href="http://\1">\1</a>',
                        '<strong>Quote:</strong><blockquote><em>\1</em></blockquote>', 
                        '<pre>\\1</pre>', 
                ); 
                
        $text = preg_replace($search, $replace , $text); 
        
        return $text;
    }
 


    /**
     * Converts money amounts from EUROS to another currency and viceversa
     *
     * @param	float	$value	value to convert
     * @param	string	$way	the type of conversion
     *                      		AUD : Australian Dollars
     *                      		CAD : Canadian Dollars
     *                      		CHF : Swiss ...
     *                      		EUR : Euros
     *                      		CNY : Chinese Y...
     *                      		DKK : Denemark Korona
     *                      		GBP : Great Britain Pounds
     *                      		HKD : ...?
     *                      		HUF : Hungarian F...
     *                      		INR : ...?
     *                      		JPY : Japanese Yens
     *                     		MXN : Mexican N...
     *                      		MYN : Malaysian N...
     *                      		NOK : Norway Korona
     *                      		NZD : New Zeland Dollars
     *                      		RUB : Russian B...
     *                      		SEK : ...?
     *                      		SGB : ...?
     *                      		THB : Thailandia B...
     *                      		USD : United States Dollars
     *                      		ZAR : ..?
     *              		use the format "eur-[other_value]" or "[other_value]-eur" [default: eur-usd]
     * @param	float	$cval	1 euro is equal to this amount of money in the other currency [default: NULL]
     * @return	float		money amont converted!
     */
    function cconv($value, $way = "eur-usd", $cval = NULL)
    {
        if (is_numeric($value))
        {
            $way = strtolower($way);
            
            switch ($way)
            {
                case "eur-usd" :
                case "usd-eur" :
                    if (is_null($cval))
                    {
                        $cval =  1.35;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-jpy" :
                case "jpy-eur" :
                    if (is_null($cval))
                    {
                        $cval =  160.9;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-gbp" :
                case "gbp-eur" :
                    if (is_null($cval))
                    {
                        $cval =  0.;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-aud" :
                case "aud-eur" :
                    if (is_null($cval))
                    {
                        $cval =  1.63;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-cad" :
                case "cad-eur" :
                    if (is_null($cval))
                    {
                        $cval =  1.53;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-chf" :
                case "chf-eur" :
                    if (is_null($cval))
                    {
                        $cval =  1.64;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-cny" :
                case "cny-eur" :
                    if (is_null($cval))
                    {
                        $cval =  10.49;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-dkk" :
                case "dkk-eur" :
                    if (is_null($cval))
                    {
                        $cval =  7.45;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-hkd" :
                case "hkd-eur" :
                    if (is_null($cval))
                    {
                        $cval =  10.62;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-huf" :
                case "huf-eur" :
                    if (is_null($cval))
                    {
                        $cval =  246.2;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-inr" :
                case "inr-eur" :
                    if (is_null($cval))
                    {
                        $cval =  246.2;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-mxn" :
                case "mxn-eur" :
                    if (is_null($cval))
                    {
                        $cval =  14.96;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-myr" :
                case "myr-eur" :
                    if (is_null($cval))
                    {
                        $cval =  4.659;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-nok" :
                case "nok-eur" :
                    if (is_null($cval))
                    {
                        $cval =  8.111;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-nzd" :
                case "nzd-eur" :
                    if (is_null($cval))
                    {
                        $cval =  1.827;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-rub" :
                case "rub-eur" :
                    if (is_null($cval))
                    {
                        $cval =  34.99;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-sek" :
                case "sek-eur" :
                    if (is_null($cval))
                    {
                        $cval =  9.207;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-sgd" :
                case "sgd-eur" :
                    if (is_null($cval))
                    {
                        $cval =  2.056;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
               
                case "eur-thb" :
                case "thb-eur" :
                    if (is_null($cval))
                    {
                        $cval =  44.11;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                case "eur-zar" :
                case "zar-eur" :
                    if (is_null($cval))
                    {
                        $cval =  9.598;
                    }
                    
                    if (substr_count($way, "eur-") == 1)
                        $rc = $value * $cval;
                        break;
                    
                    $rc = $value / $cval;
                    
                    break;
                
                default:
                    $rc = 0;
                    break;
            }
        }
        else
        {        
            $rc = 0;
        }
        
        return $rc;
    }
    
    
    
    /**
     * URL completition
     *
     * @param 	string 	$url		the URL to complete
     * @param 	string 	$protocol	default protocol to add [default: "http://"]
     * @return 	string 			the complete URL
     */
    function complete_url($url, $protocol = "http://")
    {
        if (substr_count($url, "://") == 0)
            $url = $protocol . $url;
            
        if (substr_count($url, "://www.") == 0)
            $url = substr_replace($url, "www.", strpos($url, ":")+3, 0);
        
        return $url;
    }



    /**
     * Creates a unique hash id string
     *
     * @param	bool	$with_time	if set the timestamp will be added to the code [defaul: true]
     * @return 	string 			the id string
     */
    function id_code($with_time = true)
    {
        $string = $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'];
        
        if ($with_time)
        {
            mt_srand((double)microtime() * 1000000);
            $time = md5(mt_rand());
        }
        else
        {
            $time = "";
        }
        
        return md5($string . $time);
    }


    
    /**
     * Return the size of an image
     *
     * @param	string	$image	path to the image
     * @param	string	$format	switch between bytes(b), megabytes(m), gigabytes(g)
     * @return	int 		size in bytes (-1 on error)
     */
    function image_size($image)
    {
        if (file_exists($image))
        {
            $a_size = getimagesize($image, $format = NULL);
            $size = $a_size[3];
            
            switch($format)
            {
                case "k" :
                    $size /= pow(1024, 1);
                    break;
                
                case "m" :
                    $size /= pow(1024, 2);
                    break;
                
                case "g" :
                    $size /= pow(1024, 3);
                    break;
                
                default :
                    break;
            }
        }
        else
        {
            $size = -1;
        }
        
        return $size;
    }



    /**
     * Converts RGB colors to their decimal value
     *
     * @param	string	$rgb	RGB color value
     * @return	string		the color in decimal code
     */
    function rgb2dec($rgb)
    {
        $color = array();
        $hex = "";
        
        ereg("([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})", strtoupper($rgb), $color);
        
        if ($color[0])
            $hex = hexdec($color[1]) . hexdec($color[2]) . hexdec($color[3]);
        
        return $hex;
    }
    
    

    /**
     * Shows an error message and vary the level of danger
     *
     * @param	string	$id		id of the error or name of the method
     * @param	string	$message	error message [default: An unknow error has occurred!"]
     * @param	string	$text 		the format of the error
     *                      			!id!        => $id
     *                          		!message!   => $message
     *                      			!level!     => $level
     *                                  [default: (!id!) !message! - Level !level!]
     * @param	bool	$level		1 to stop the execution, 0 to go on [default: 1]
     * @return 				void
     */
    function show_error($id, $message = "An unknown error has occurred!",
                        $text = "(!id!) !message! - Level !level!",
                        $level = 1)
    {
        $search  = array("!id!", "!message!", "!level!");
        $replace = array($id,     $message,    $level);
         
        $error = str_ireplace($search, $replace, $text);
        
        if ($level)
        {
            die($error);
        }
        else
        {
            echo $error;
        }
    }




    // NUMBERS - ARRAYS

    /**
     * Search a needle in a multi array [recursive]
     *
     * @param	string	$needle		the item to look for
     * @param	array	$haystack	the multi array to search in
     * @return	bool 			true if the needle is there, 0 otherwise
     */
    function in_multi_array($needle, $haystack)
    {
        if (is_array($haystack))
        {
            if (in_array($needle, $haystack))
            {
                return true;
            }
            else
            {
                for ($i=0; $i<sizeof($haystack); $i++)
                {
                    if (is_array($haystack[$i]))
                    {
                        if ($this->in_multi_array($needle, $haystack[$i]))
                        {
                            return true;
                        }
                    }
                }
            }
        }
        
        return false;
    }
    
    
    
    /**
     * Adds a certain number of zeros depending on the length the number should have
     *
     * @param	numeric	$number	the number
     * @param	int	$places	the numerb of symbols the number should be composed of
     * @return	numeric		the number with some leading zeros
     */
    function leading_zeros($number, $places)
    {
        if (is_numeric($number))
        {
            $leading = "";
            
            for ($i=1; $i<=$places; $i++)
            {
                $ceiling = pow(10, $i);
                
                if ($number < $ceiling)
                {
                    $zeros = $places - $i;
                    
                    for ($j=1; $j<=$zeros; $j++)
                    {
                        $leading .= "0";
                    }
                    
                    $i = $places + 1;
                }
            }
            
            $value = $leading . $number;
        }
        else
        {
            $value = $value;
        }
        
        return $value;
    }
   
   
    
    /**
     * Adds the english ordinal suffix to a number
     *
     * @param	int	$number	the number
     * @param	bool	$sup	if 1 displays the suffix using the <sup> HTML tag [default: 0]
     * @return	string		the number with suffix
     */
    function ordinal_suffix($number, $sup = 0)
    {
        if (is_numeric($number))
        {
            if (substr($value, -2, 2) == 11 || substr($value, -2, 2) == 12 || substr($value, -2, 2) == 13)
                $suffix = "th";
            
            switch (substr($value, -1, 1))
            {
                case 1:
                    $suffix = "st";
                    break;
                case 2:
                    $suffix = "nd";
                    break;
                case 3:
                    $suffix = "rd";
                    break;
                default:
                    $suffix = "th";
                    break;
            }
            
            if ($sup)
                $suffix = "<sup>" . $suffix . "</sup>";
        }
        else
        {
            return 0;
        }
        
        return $number . $suffix;
    }
    
    
    
    /**
     * Removes magic quotes
     *
     * @param	array	$array
     * @return		void
     */
    function remove_magic_quotes(&$array)
    {
        if(!get_magic_quotes_gpc())
        {
            return;
        }
        
        foreach($array as $key => $value)
        {
            if(is_array($value))
            {
                $this->remove_magic_quotes($value);
            }
            else
            {
                $array[$key] = stripslashes($value);
            }
        }
    }




    // TEXT
    
    /**
     * Cleans the start and end of a string from a character
     *
     * @param	string	$string	the string to clean
     * @param	string	$rms	the text to delete from the beginning
     * @param	string	$rml	the text to delete from the end
     * @return	string		the string
     */
    function clean($string, $rms, $rml)
    {
	$s = strlen($rms);
	$l = strlen($rml);
        
	do {
	    if (substr($string, 0, $s) == $rms)
                $string = substr($string, $s);
	} while (substr($string, 0, $s) == $rms);
        
	do {
	    if (substr($string, -$l, $l) == $rml)
                $string = substr($string, 0, -$l);
	} while (substr($string, -$l, $l) == $rml);
        
        
	return $string;
    }
    
    
    
    /**
     * Decodes a text with many algorithms many times
     *
     * @param	string	$text 	the text to decode
     * @param	string	$mode 	the sequence of decryption methods separated by commas [,]
     *                     		G      : gEncryption method using the class gEncrypter
     *                     		base64 : base64 decoding algorithm
     *                     		uu     : decryption using the function uudecode()
     *                     	[default: G]
     * @param	string	$key	the key to use separated by commas [,]
     * 				one for each "G" you put in the sequence
     * 				[gEncrypter only] [default: ilarvet]
     * @return	string 		the text finally decrypted
     */
    function decode($text, $mode = "G", $key = "ilarvet")
    {
        $exmode = explode(",", $mode);
        $exkey = explode(",", $key);
        
        $kcount = 0;
        $dec = $text;
        
        for ($i=0; $i<count($exmode); $i++)
        {
            $exmode[$i] = trim($exmode[$i]);
            
            switch (strtolower($exmode[$i]))
            {
                case "g":
                    include_once($this->include_path . "gEncrypter.php");
                    $e = new gEncrypter;
                    $dec = $e->gED($dec, $exkey[$kcount]);
                    $kcount ++;
                    break;
                    
                case "base64":
                    $dec = base64_decode($dec);
                    break;
                
                case "uu":
                    $dec = convert_uudecode($dec);
                    break;
                    
                default:
                    break;
            }
        }
        
        return $dec;
    }
    
    
    
    /**
     * Draws a frame around the text
     *
     * @param	string	$text 	the text to be "framed"
     * @param	string	$top 	top symbol of the frame [default: "="]
     * @param	string	$bottom	bottom symbol of the frame [default: "="]
     * @param	string	$left	the left symbol of the frame [default: "|"]
     * @param	string	$right	the right symbol of the frame [default: "|"]
     * @return	string 		the new framed text
     */
    function drawframe($text, $top = "=", $bottom = "=", $left = "|", $right = "|")
    {
        $l = strlen($text);
        $tframe = "";
        $bframe = "";
        
        for ($i=0; $i<$l; $i++)
        {
            $tframe .= $top;
            $bframe .= $bottom;
        }
        
        $tframe .= "\n";
        $bframe .= "\n";
        
        $string = $tframe . $left . " " . $text . " " . $right . "\n" . $bframe;
        
        return $string;        
    }
    
    
    
    /**
     * Encodes a text with many algorithms many times
     *
     * @param	string	$text 	the text to encode
     * @param	string	$mode 	the sequence of encryption methods separated by commas [,]
     *                     		G      : gEncryption method using the class gEncrypter
     *                     		base64 : base64 encoding algorithm
     *                     		uu     : encryption using the function uuencode()
     *                     	[default: G]
     * @param	string	$key	the key to use separated by commas [,]
     * 				one for each "G" you put in the sequence
     * 				[gEncrypter only] [default: ilarvet]
     * @return	string 		the text heavy encrypted
     */
    function encode($text, $mode = "G", $key = "ilarvet")
    {
        $exmode = explode(",", $mode);
        $exkey = explode(",", $key);
        
        $kcount = 0;        
        $enc = $text;
        
        for ($i=0; $i<count($exmode); $i++)
        {
            $exmode[$i] = trim($exmode[$i]);
            
            switch (strtolower($exmode[$i]))
            {
                case "g":
                    include_once($this->include_path . "gEncrypter.php");
                    $e = new gEncrypter;
                    $enc = $e->gED($enc, $exkey[$kcount]);
                    $kcount ++;
                    break;
                    
                case "base64":
                    $enc = base64_encode($enc);
                    break;
                    
                case "uu":
                    $enc = convert_uuencode($enc);
                    break;
                    
                default:
                    break;
            }
        }
    }
    
    
    
    /**
     * Fills spaces with a given symbol
     *
     * @param	string 	$text 		the text with spaces
     * @param	string 	$fillwith	the symbol to fill spaces with [default: "+"]
     * @return	string 			the text witout spaces
     */
    function fill_spaces($text, $fillwith = "+")
    {
        $text = htmlentities($text);
        $text = str_replace("&nbsp;", $fillwith, $text);
        $text = str_replace("&#160;", $fillwith, $text);
        $text = str_replace(" ", $fillwith, $text);
        
        return $text;
    }
    
    
    
    /**
     * Makes links from strings containing URLs
     *
     * @param	string	$text	the text to scan
     * @return	string		the text with URLs linked
     */
    function make_links($text)
    {
        $text = preg_replace("/(http:\/\/|mailto:|www.|ftp:\/\/)([^\s,]*)/i", "<a href='$1$2'>$1$2</a>", $text);
        
        return $text;
    }
    
    
    
    /**
     * Convert the given text to a javascript compatible one
     *
     * @param	string	$text	the original text
     * @return	string		the js-compatible string
     */
    function make_js($text)
    {
        $text = str_replace("'","\\'", $text);
        $text = str_replace("\"","&quot;", $text);
        
        return $text;
    }



    /**
     * Removes all whitespaces in a string
     *
     * @param	string	$text	the text with spaces
     * @return	string		the text without spaces
     */
    function rm_spaces($text)
    {
        $text = htmlentities($text);
        $text = str_replace("&nbsp;", "", $text);
        $text = str_replace("&#160;", "", $text);
        $text = str_replace(" ", "", $text);
        
        return $text;
    }
    
    
    
    /**
     * Shorten the text to the passed length
     *
     * @param	string	$text		text to shorten
     * @param	int	$length		max lenght of the text
     * @param	string	$complete	completes the text with this [default: ...]
     * @return	array			array composed of   'base' : base text
     *                                 			    'more' : cut text
     */
    function shorten($text, $length, $complete = "...")
    {
        $rc = array();
        
        if (strlen($text) > $length)
        {
            $rc['base'] = substr($text, 0, $length) . $complete;
            $rc['more'] = substr($text, $length, -(strlen($rc['base']) - strlen($complete)));
        }
        else
        {
            $rc['base'] = $text;
            $rc['more'] = "";
        }
        
        return $rc;
    }
    
    
    
    /**
     * Emulates the strleft function
     *
     * @param	string	$s1	the first string
     * @param	string	$s2	the second string
     * @return 			string
     */
    function strleft($s1, $s2)
    {
        return substr($s1, 0, strpos($s1, $s2));
    }




    // VALIDATIONS  

    /**
     * Checks a phone number
     *
     * @param	string	$phone	phone number to check
     * @param	int	$length	the length of a phone number [default: 9]
     * @return 	bool		right or not?
     */
    function check_phone($number, $length = 9)
    {       
        // Only numbers
        $regexp = '^[[:digit:]]+$';
        
        if (!preg_match($regexp, $number) || strlen($nember) != $length)
        {
            return true;
        }
        
        return false;
    }



    /**
     * Checks a zip code
     *
     * @param	string	$zip	zip code to check
     * @return	bool 		true if the code is right, false otherwise
     */
    function check_zip($zip)
    {
        // Zip code format may be different depending on your country
        $regexp = '^[0-9]{5}(-[0-9]{4})?$';
        
        if (eregi($regexp, $zip))
        {
            return true;
        }
        
        return false;
    }



    /**
     * Checks email addresses
     *
     * @from Some package I don't remember
     * 
     * @param	string	$address	the email address
     * @return	bool			true if the address is valid
     */
    function check_email($address)
    {
        $address = trim($address);
        
        $regexp = "/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+($known_doms)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i";
        
        $known_doms  = "ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba";
        $known_doms .= "|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca";
        $known_doms .= "|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy";
        $known_doms .= "|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm";
        $known_doms .= "|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw";
        $known_doms .= "|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm";
        $known_doms .= "|jo|jobs|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls";
        $known_doms .= "|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt";
        $known_doms .= "|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np";
        $known_doms .= "|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw";
        $known_doms .= "|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so";
        $known_doms .= "|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|travel|tt|tv";
        $known_doms .= "|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt";
        $known_doms .= "|yu|za|zm|zw";
        
        if (preg_match($regexp, $address))
        {
            return true;
        }
        
        return false;
    }



    /**
     * Domain name validation
     *
     * @param	string	$domain	the domain name
     * @param	string	$tld	top level domain [default: NULL]
     * @return	bool 		valid (true) or not (false)
     */
    function check_domain($domain, $tld = NULL)
    {
        $length = strlen($domain);
        $dot = substr_count($domain, ".");
        
        if ((substr($domain, ($length - strlen($tld) - 1) == $tld)) &&
            ($dot > 0) &&
            ($length <= ($dot * 63)) &&
            (!preg_match('/[^a-z0-9\._\-]/i', $domain))
            )
        {
            return true;
        }
        
        return false;
    }



    /**
     * IP address checker
     *
     * @param	string	$address	the IP address to validate
     * @return	bool 			true if valid, false otherwise
     */
    function check_IP($address)
    {
        if ((strlen($address) < 16) && (!preg_match('/[^0-9\.]/', $address)))
        {
            $ip = explode(".", $address);
            
            if (count($ip) == 4)
            {
                for ($i=0; $i<4; $i++)
                {
                    if ((strlen($ip[$i])==0) || ($ip[$i]<0) || ($ip[$i]>255))
                    {
                        return false;
                    }
                }
                
                return true;
            }
        }
        
        return false;
    }

	
        
    /**
     * Check if a text has some HTML tags
     *
     * @param 	string 	$text 	text to check
     * @return 	bool 		true if html tags are present
     */
    function check_HTMLTags($text)
    {
        if (!preg_match('/[<]/', $text))
        {
            return true;
        }
        
        return false;
    }

 

    /**
     * Checks for username validity
     *
     * Only alpha-numeric, _ and - (but not as first sign) are allowed by default
     *
     * @param 	string 	$username   	    the username to check
     * @param 	int 	$min_length min	    length of the username [default: 3]
     * @param 	int 	$max_length max     length of the username [default: 30]
     * @param 	bool 	$allow_upper_case   if set allows uppercase names [default: true]
     * @return 	bool 			    is the username valid? (true = yes)
     */
    function check_username($username, $min_length = 3, $max_length = 30, $uppercase = true)
    {        
        if (strlen($username) < $min_length || $username > $max_length)
        {
            return false;
        }
        
        if ($upper_case)
        {
            $regexp='/[^A-Za-z0-9\_\-]/';
        }
        else
        {
            $regexp='/[^a-z0-9\_\-]/';
        }
        
        if (preg_match($regexp, $username))
        {
            return false;
        }
        
        return true;
    }



    /**
     * Which browser are we using?
     *
     * @return	string   i = Internet Explorer
     * 			 k = Konqueror
     *                   m = Mozilla and brothers/sisters
     *			 n = Netscape
     *			 o = Opera
     *			 u = unknown
     */
    function check_browser()
    {            
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        
        if      (substr_count($agent, "gecko") > 0)     $browser = "m";
        else if (substr_count($agent, "konqueror") > 0) $browser = "k";
        else if (substr_count($agent, "opera") > 0)     $browser = "o";
        else if (substr_count($agent, "mozilla") > 0)   $browser = "n";
        else if (substr_count($agent, "msie") > 0)      $browser = "i";
        else                                            $browser = "u";
        
        return $browser;
    }

    /**
     * Which platform are we working on?
     *
     * @return	char l = Linux
     *               m = Mac
     *               o = OS/2
     *               u = unknown
     *		     w = Windows		    
     *	             x = Unix
     */
    function check_os()
    {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        
        if      (substr_count($agent, "unix") > 0)  $os = "x";
        else if (substr_count($agent, "linux") > 0) $os = "l";
        else if (substr_count($agent, "mac") > 0)   $os = "m";
        else if (substr_count($agent, "os/2") > 0)  $os = "o";
        else if (substr_count($agent, "win") > 0)   $os = "w";
        else                                        $os = "u";
        
        return $os;
    }
    
}

?>

 
  Advertise on this site Advertise on this site   Site map Site map   Statistics Statistics   Site tips Site tips   Privacy policy Privacy policy   Contact Contact  

For more information send a message to :
info at phpclasses dot org.
Copyright (c) Icontem 1999-2009 PHP Classes - PHP Class Scripts
  PHP Book Reviews - Reviews of books and other products