* Copyright 2001-2012 Strangecode, LLC * * This file is part of The Strangecode Codebase. * * The Strangecode Codebase is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * The Strangecode Codebase is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * The Strangecode Codebase. If not, see . */ /** * Utilities.inc.php */ /** * Print variable dump. * * @param mixed $var The variable to dump. * @param bool $display Print the dump in
 tags or hide it in html comments (non-CLI only).
 * @param  bool     $var_dump   Use var_dump instead of print_r.
 * @param  string   $file       Value of __FILE__.
 * @param  string   $line       Value of __LINE__
 */
function dump($var, $display=false, $var_dump=false, $file='', $line='')
{
    if ($app->cli) {
        echo "DUMP FROM: $file $line\n";
    } else {
        echo $display ? "\n
DUMP $file $line
\n" : "\n\n";
    }
}

/*
* Log a PHP variable to javascript console. Relies on getDump(), below.
*
* @access   public
* @param    mixed   $var      The variable to dump.
* @param    string  $prefix   A short note to print before the output to make identifying output easier.
* @param    string  $file     The value of __FILE__.
* @param    string  $line     The value of __LINE__.
* @return   null
* @author   Quinn Comendant 
*/
function jsDump($var, $prefix='jsDump', $file='-', $line='-')
{
    if (!empty($var)) {
        ?>
        
        
*/
function getDump($var, $serialize=false)
{
    ob_start();
    print_r($var);
    $d = ob_get_contents();
    ob_end_clean();
    return $serialize ? preg_replace('/\s+/m', ' ', $d) : $d;
}

/**
 * Return dump as cleaned text. Useful for dumping data into emails.
 *
 * @param  array    $var        Variable to dump.
 * @param  strong   $indent     A string to prepend indented lines (tab for example).
 * @return string Dump of var.
 */
function fancyDump($var, $indent='')
{
    $output = '';
    if (is_array($var)) {
        foreach ($var as $k=>$v) {
            $k = ucfirst(mb_strtolower(str_replace(array('_', '  '), ' ', $k)));
            if (is_array($v)) {
                $output .= sprintf("\n%s%s: %s\n", $indent, $k, fancyDump($v, $indent . $indent));
            } else {
                $output .= sprintf("%s%s: %s\n", $indent, $k, $v);
            }
        }
    } else {
        $output .= sprintf("%s%s\n", $indent, $var);
    }
    return $output;
}

/**
 * Returns text with appropriate html translations (a smart wrapper for htmlspecialchars()).
 *
 * @param  string $text             Text to clean.
 * @param  bool   $preserve_html    If set to true, oTxt will not translate <, >, ", or '
 *                                  characters into HTML entities. This allows HTML to pass through undisturbed.
 * @return string                   HTML-safe text.
 */
function oTxt($text, $preserve_html=false)
{
    $app =& App::getInstance();

    $search = array();
    $replace = array();

    // Make converted ampersand entities into normal ampersands (they will be done manually later) to retain HTML entities.
    $search['retain_ampersand']     = '/&/';
    $replace['retain_ampersand']    = '&';

    if ($preserve_html) {
        // Convert characters that must remain non-entities for displaying HTML.
        $search['retain_left_angle']       = '/</';
        $replace['retain_left_angle']      = '<';

        $search['retain_right_angle']      = '/>/';
        $replace['retain_right_angle']     = '>';

        $search['retain_single_quote']     = '/'/';
        $replace['retain_single_quote']    = "'";

        $search['retain_double_quote']     = '/"/';
        $replace['retain_double_quote']    = '"';
    }

    // & becomes &. Exclude any occurrence where the & is followed by a alphanum or unicode character.
    $search['ampersand']        = '/&(?![\w\d#]{1,10};)/';
    $replace['ampersand']       = '&';

    return preg_replace($search, $replace, htmlspecialchars($text, ENT_QUOTES, $app->getParam('character_set')));
}

/**
 * Returns text with stylistic modifications. Warning: this will break some HTML attributes!
 * TODO: Allow a string such as this to be passed: Click here
 *
 * @param  string   $text Text to clean.
 * @return string         Cleaned text.
 */
function fancyTxt($text)
{
    $search = array();
    $replace = array();

    // "double quoted text"  becomes  “double quoted text”
    $search['double_quotes']    = '/(^|[^\w=])(?:"|"|"|"|“)([^"]+?)(?:"|"|"|"|”)([^\w]|$)/ms'; // " is the same as " and " and "
    $replace['double_quotes']   = '$1“$2”$3';

    // text's apostrophes  become  text’s apostrophes
    $search['apostrophe']       = '/(\w)(?:\'|'|')(\w)/ms';
    $replace['apostrophe']      = '$1’$2';

    // 'single quoted text'  becomes  ‘single quoted text’
    $search['single_quotes']    = '/(^|[^\w=])(?:\'|'|‘)([^\']+?)(?:\'|'|’)([^\w]|$)/ms';
    $replace['single_quotes']   = '$1‘$2’$3';

    // plural posessives' apostrophes become posessives’
    $search['apostrophes']      = '/(s)(?:\'|'|')(\s)/ms';
    $replace['apostrophes']     = '$1’$2';

    // em--dashes  become em—dashes
    $search['em_dash']          = '/(\s*[^!<-])--([^>-]\s*)/';
    $replace['em_dash']         = '$1—$2';

    return preg_replace($search, $replace, $text);
}

/*
* Finds all URLs in text and hyperlinks them.
*
* @access   public
* @param    string  $text   Text to search for URLs.
* @param    bool    $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'.
* @param    mixed   $length Number of characters to truncate URL, or NULL to disable truncating.
* @param    string  $delim  Delimiter to append, indicate truncation.
* @return   string          Same input text, but URLs hyperlinked.
* @author   Quinn Comendant 
* @version  2.0
* @since    22 Mar 2015 23:29:04
*/
function hyperlinkTxt($text, $strict=false, $length=null, $delim='…')
{
    // A list of schemes we allow at the beginning of a URL.
    $schemes = 'mailto:|tel:|skype:|callto:|facetime:|bitcoin:|geo:|magnet:\?|sip:|sms:|xmpp:|view-source:(?:https?://)?|[\w-]{2,}://';

    // Capture the full URL into the first match and only the first X characters into the second match.
    // This will match URLs not preceeded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com)
    // Valid URL characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
    $regex = '@
        \b                              # Start with a word-boundary.
        (?|`|[\w-]{2}://)     # Negative look-behind to exclude URLs already in  tag, Markdown quoted, or double SCHEME://
        (                               # Begin match 1
            (                           # Begin match 2
                (?:%s)                  # URL starts with known scheme or www. if strict = false
                [^\s/$.?#]+             # Any domain-valid characters
                [^\s"`<>]{1,%s}         # Match 2 is limited to a maximum of LENGTH valid URL characters
            )
            [^\s"`<>]*                  # Match 1 continues with any further valid URL characters
            ([^\P{Any}\s…<>«»"—–%s])    # Final character not a space or common end-of-sentence punctuation (.,:;?!, etc). Using double negation set, see http://stackoverflow.com/a/4786560/277303
        )
        @Suxi
    ';
    $regex = sprintf($regex,
        ($strict ? $schemes : $schemes . '|www\.'), // Strict=false adds "www." to the list of allowed start-of-URL.
        ($length ? $length : ''),
        ($strict ? '' : '?!.,:;)\'-') // Strict=false excludes some "URL-valid" characters from the last character of URL. (Hyphen must remain last character in this class.)
    );

    // Use a callback function to decide when to append the delim.
    // Also encode special chars with oTxt().
    return preg_replace_callback($regex, function ($m) use ($length, $delim) {
        $url = $m[1];
        $truncated_url = $m[2] . $m[3];
        $absolute_url = preg_replace('!^www\.!', 'http://www.', $url);
        if (is_null($length) || $url == $truncated_url) {
            // If not truncating, or URL was not truncated.
            // Remove http schemas, and any single trailing / to make the display URL.
            $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], $url);
            return sprintf('%s', oTxt($absolute_url), $display_url);
        } else {
            // Truncated URL.
            // Remove http schemas, and any single trailing / to make the display URL.
            $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], trim($truncated_url));
            return sprintf('%s%s', oTxt($absolute_url), $display_url, $delim);
        }
    }, $text);
}

/**
 * Applies a class to search terms to highlight them ala google results.
 *
 * @param  string   $text   Input text to search.
 * @param  string   $search String of word(s) that will be highlighted.
 * @param  string   $class  CSS class to apply.
 * @return string           Text with searched words wrapped in .
 */
function highlightWords($text, $search, $class='sc-highlightwords')
{
    $words = preg_split('/[^\w]/', $search, -1, PREG_SPLIT_NO_EMPTY);

    $search = array();
    $replace = array();

    foreach ($words as $w) {
        if ('' != trim($w)) {
            $search[] = '/\b(' . preg_quote($w) . ')\b/i';
            $replace[] = '$1';
        }
    }

    return empty($replace) ? $text : preg_replace($search, $replace, $text);
}

/**
 * Generates a hexadecimal html color based on provided word.
 *
 * @access public
 * @param  string $text  A string for which to convert to color.
 * @return string  A hexadecimal html color.
 */
function getTextColor($text, $method=1, $n=0.87)
{
    $hash = md5($text);
    $rgb = array(
        mb_substr($hash, 0, 1),
        mb_substr($hash, 1, 1),
        mb_substr($hash, 2, 1),
        mb_substr($hash, 3, 1),
        mb_substr($hash, 4, 1),
        mb_substr($hash, 5, 1),
    );

    switch ($method) {
    case 1 :
    default :
        // Reduce all hex values slightly to avoid all white.
        array_walk($rgb, create_function('&$v', "\$v = dechex(round(hexdec(\$v) * $n));"));
        break;
    case 2 :
        foreach ($rgb as $i => $v) {
            if (hexdec($v) > hexdec('c')) {
                $rgb[$i] = dechex(hexdec('f') - hexdec($v));
            }
        }
        break;
    }

    return join('', $rgb);
}

/**
 * Encodes a string into unicode values 128-255.
 * Useful for hiding an email address from spambots.
 *
 * @access  public
 * @param   string   $text   A line of text to encode.
 * @return  string   Encoded text.
 */
function encodeAscii($text)
{
    $output = '';
    $num = mb_strlen($text);
    for ($i=0; $i<$num; $i++) {
        $output .= sprintf('&#%03s', ord($text{$i}));
    }
    return $output;
}

/**
 * Encodes an email into a "user at domain dot com" format.
 *
 * @access  public
 * @param   string   $email   An email to encode.
 * @param   string   $at      Replaces the @.
 * @param   string   $dot     Replaces the ..
 * @return  string   Encoded email.
 */
function encodeEmail($email, $at=' at ', $dot=' dot ')
{
    $search = array('/@/', '/\./');
    $replace = array($at, $dot);
    return preg_replace($search, $replace, $email);
}

/**
 * Truncates "a really long string" into a string of specified length
 * at the beginning: "…long string"
 * at the middle: "a rea…string"
 * or at the end: "a really…".
 *
 * The regular expressions below first match and replace the string to the specified length and position,
 * and secondly they remove any whitespace from around the delimiter (to avoid "this … " from happening).
 *
 * @access  public
 * @param   string  $str    Input string
 * @param   int     $len    Maximum string length.
 * @param   string  $where  Where to cut the string. One of: 'start', 'middle', or 'end'.
 * @return  string          Truncated output string.
 * @author  Quinn Comendant 
 * @since   29 Mar 2006 13:48:49
 */
function truncate($str, $len=50, $where='end', $delim='…')
{
    $dlen = mb_strlen($delim);
    if ($len <= $dlen || mb_strlen($str) <= $dlen) {
        return substr($str, 0, $len);
    }
    $part1 = floor(($len - $dlen) / 2);
    $part2 = ceil(($len - $dlen) / 2);

    if ($len > ini_get('pcre.backtrack_limit')) {
        $app =& App::getInstance();
        $app->logMsg(sprintf('Asked to truncate string len of %s > pcre.backtrack_limit of %s', $len, ini_get('pcre.backtrack_limit')), LOG_DEBUG, __FILE__, __LINE__);
        ini_set('pcre.backtrack_limit', $len);
    }

    switch ($where) {
    case 'start' :
        return preg_replace(array(sprintf('/^.{%s,}(.{%s})$/su', $dlen + 1, $part1 + $part2), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array($delim . '$1', $delim), $str);

    case 'middle' :
        return preg_replace(array(sprintf('/^(.{%s}).{%s,}(.{%s})$/su', $part1, $dlen + 1, $part2), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array('$1' . $delim . '$2', $delim), $str);

    case 'end' :
    default :
        return preg_replace(array(sprintf('/^(.{%s}).{%s,}$/su', $part1 + $part2, $dlen + 1), sprintf('/\s*%s{%s,}\s*/su', preg_quote($delim), $dlen)), array('$1' . $delim, $delim), $str);
    }
}

/*
* A substitution for the missing mb_ucfirst function.
*
* @access   public
* @param    string  $string The string
* @return   string          String with upper-cased first character.
* @author   Quinn Comendant 
* @version  1.0
* @since    06 Dec 2008 17:04:01
*/
if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1, mb_strlen($string));
    }
}

/*
* A substitution for the missing mb_strtr function.
*
* @access   public
* @param    string  $string The string
* @param    string  $from   String of characters to translate from
* @param    string  $to     String of characters to translate to
* @return   string          String with translated characters.
* @author   Quinn Comendant 
* @version  1.0
* @since    20 Jan 2013 12:33:26
*/
if (!function_exists('mb_strtr')) {
    function mb_strtr($string, $from, $to)
    {
        return str_replace(mb_split('.', $from), mb_split('.', $to), $string);
    }
}

/*
* A substitution for the missing mb_str_pad function.
*
* @access   public
* @param    string  $input      The string that receives padding.
* @param    string  $pad_length Total length of resultant string.
* @param    string  $pad_string The string to use for padding
* @param    string  $pad_type   Flags STR_PAD_RIGHT or STR_PAD_LEFT or STR_PAD_BOTH
* @return   string          String with translated characters.
* @author   Quinn Comendant 
* @version  1.0
* @since    20 Jan 2013 12:33:26
*/
if (!function_exists('mb_str_pad')) {
    function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
        $diff = strlen($input) - mb_strlen($input);
        return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
    }
}

/*
* Converts a string into a URL-safe slug, removing spaces and non word characters.
*
* @access   public
* @param    string  $str    String to convert.
* @return   string          URL-safe slug.
* @author   Quinn Comendant 
* @version  1.0
* @since    18 Aug 2014 12:54:29
*/
function URLSlug($str)
{
    $slug = preg_replace(array('/\W+/u', '/^-+|-+$/'), array('-', ''), $str);
    $slug = strtolower($slug);
    return $slug;
}

/**
 * Return a human readable disk space measurement. Input value measured in bytes.
 *
 * @param       int    $size        Size in bytes.
 * @param       int    $unit        The maximum unit
 * @param       int    $format      The return string format
 * @author      Aidan Lister 
 * @author      Quinn Comendant 
 * @version     1.2.0
 */
function humanFileSize($size, $format='%01.2f %s', $max_unit=null, $multiplier=1024)
{
    // Units
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $ii = count($units) - 1;

    // Max unit
    $max_unit = array_search((string) $max_unit, $units);
    if ($max_unit === null || $max_unit === false) {
        $max_unit = $ii;
    }

    // Loop
    $i = 0;
    while ($max_unit != $i && $size >= $multiplier && $i < $ii) {
        $size /= $multiplier;
        $i++;
    }

    return sprintf($format, $size, $units[$i]);
}

/*
* Returns a human readable amount of time for the given amount of seconds.
*
* 45 seconds
* 12 minutes
* 3.5 hours
* 2 days
* 1 week
* 4 months
*
* Months are calculated using the real number of days in a year: 365.2422 / 12.
*
* @access   public
* @param    int $seconds Seconds of time.
* @param    string $max_unit Key value from the $units array.
* @param    string $format Sprintf formatting string.
* @return   string Value of units elapsed.
* @author   Quinn Comendant 
* @version  1.0
* @since    23 Jun 2006 12:15:19
*/
function humanTime($seconds, $max_unit=null, $format='%01.1f')
{
    // Units: array of seconds in the unit, singular and plural unit names.
    $units = array(
        'second' => array(1, _("second"), _("seconds")),
        'minute' => array(60, _("minute"), _("minutes")),
        'hour' => array(3600, _("hour"), _("hours")),
        'day' => array(86400, _("day"), _("days")),
        'week' => array(604800, _("week"), _("weeks")),
        'month' => array(2629743.84, _("month"), _("months")),
        'year' => array(31556926.08, _("year"), _("years")),
        'decade' => array(315569260.8, _("decade"), _("decades")),
        'century' => array(3155692608, _("century"), _("centuries")),
    );

    // Max unit to calculate.
    $max_unit = isset($units[$max_unit]) ? $max_unit : 'year';

    $final_time = $seconds;
    $final_unit = 'second';
    foreach ($units as $k => $v) {
        if ($seconds >= $v[0]) {
            $final_time = $seconds / $v[0];
            $final_unit = $k;
        }
        if ($max_unit == $final_unit) {
            break;
        }
    }
    $final_time = sprintf($format, $final_time);
    return sprintf('%s %s', $final_time, (1 == $final_time ? $units[$final_unit][1] : $units[$final_unit][2]));
}

/**
 * Removes non-latin characters from file name, using htmlentities to convert known weirdos into regular squares.
 *
 * @access  public
 * @param   string  $file_name  A name of a file.
 * @return  string              The same name, but cleaned.
 */
function cleanFileName($file_name)
{
    $app =& App::getInstance();

    $file_name = preg_replace(array(
        '/&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml|caron);/ui',
        '/&(?:amp);/ui',
        '/[&;]+/u',
        '/[^a-zA-Z0-9()@._=+-]+/u',
        '/^_+|_+$/u'
    ), array(
        '$1',
        'and',
        '',
        '_',
        ''
    ), htmlentities($file_name, ENT_NOQUOTES | ENT_IGNORE, $app->getParam('character_set')));
    return mb_substr($file_name, 0, 250);
}

/**
 * Returns the extension of a file name, or an empty string if none exists.
 *
 * @access  public
 * @param   string  $file_name  A name of a file, with extension after a dot.
 * @return  string              The value found after the dot
 */
function getFilenameExtension($file_name)
{
    preg_match('/.*?\.(\w+)$/i', trim($file_name), $ext);
    return isset($ext[1]) ? $ext[1] : '';
}

/*
* Convert a php.ini value (8M, 512K, etc), into integer value of bytes.
*
* @access   public
* @param    string  $val    Value from php config, e.g., upload_max_filesize.
* @return   int             Value converted to bytes as an integer.
* @author   Quinn Comendant 
* @version  1.0
* @since    20 Aug 2014 14:32:41
*/
function phpIniGetBytes($val)
{
    $val = trim(ini_get($val));
    if ($val != '') {
        $last = strtolower($val{strlen($val) - 1});
    } else {
        $last = '';
    }
    switch ($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return (int)$val;
}

/**
 * Tests the existence of a file anywhere in the include path.
 * Replaced by stream_resolve_include_path() in PHP 5 >= 5.3.2
 *
 * @param   string  $file   File in include path.
 * @return  mixed           False if file not found, the path of the file if it is found.
 * @author  Quinn Comendant 
 * @since   03 Dec 2005 14:23:26
 */
function fileExistsIncludePath($file)
{
    $app =& App::getInstance();

    foreach (explode(PATH_SEPARATOR, get_include_path()) as $path) {
        $fullpath = $path . DIRECTORY_SEPARATOR . $file;
        if (file_exists($fullpath)) {
            $app->logMsg(sprintf('Found file "%s" at path: %s', $file, $fullpath), LOG_DEBUG, __FILE__, __LINE__);
            return $fullpath;
        } else {
            $app->logMsg(sprintf('File "%s" not found in include_path: %s', $file, get_include_path()), LOG_DEBUG, __FILE__, __LINE__);
            return false;
        }
    }
}

/**
 * Returns stats of a file from the include path.
 *
 * @param   string  $file   File in include path.
 * @param   mixed   $stat   Which statistic to return (or null to return all).
 * @return  mixed           Value of requested key from fstat(), or false on error.
 * @author  Quinn Comendant 
 * @since   03 Dec 2005 14:23:26
 */
function statIncludePath($file, $stat=null)
{
    // Open file pointer read-only using include path.
    if ($fp = fopen($file, 'r', true)) {
        // File opened successfully, get stats.
        $stats = fstat($fp);
        fclose($fp);
        // Return specified stats.
        return is_null($stat) ? $stats : $stats[$stat];
    } else {
        return false;
    }
}

/*
* Writes content to the specified file. This function emulates the functionality of file_put_contents from PHP 5.
* It makes an exclusive lock on the file while writing.
*
* @access   public
* @param    string  $filename   Path to file.
* @param    string  $content    Data to write into file.
* @return   bool                Success or failure.
* @author   Quinn Comendant 
* @since    11 Apr 2006 22:48:30
*/
function filePutContents($filename, $content)
{
    $app =& App::getInstance();

    // Open file for writing and truncate to zero length.
    if ($fp = fopen($filename, 'w')) {
        if (flock($fp, LOCK_EX)) {
            if (!fwrite($fp, $content, mb_strlen($content))) {
                $app->logMsg(sprintf('Failed writing to file: %s', $filename), LOG_ERR, __FILE__, __LINE__);
                fclose($fp);
                return false;
            }
            flock($fp, LOCK_UN);
        } else {
            $app->logMsg(sprintf('Could not lock file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
            fclose($fp);
            return false;
        }
        fclose($fp);
        // Success!
        $app->logMsg(sprintf('Wrote to file: %s', $filename), LOG_DEBUG, __FILE__, __LINE__);
        return true;
    } else {
        $app->logMsg(sprintf('Could not open file for writing: %s', $filename), LOG_ERR, __FILE__, __LINE__);
        return false;
    }
}

/**
 * If $var is net set or null, set it to $default. Otherwise leave it alone.
 * Returns the final value of $var. Use to find a default value of one is not available.
 *
 * @param  mixed $var       The variable that is being set.
 * @param  mixed $default   What to set it to if $val is not currently set.
 * @return mixed            The resulting value of $var.
 */
function setDefault(&$var, $default='')
{
    if (!isset($var)) {
        $var = $default;
    }
    return $var;
}

/**
 * Like preg_quote() except for arrays, it takes an array of strings and puts
 * a backslash in front of every character that is part of the regular
 * expression syntax.
 *
 * @param  array $array    input array
 * @param  array $delim    optional character that will also be escaped.
 * @return array    an array with the same values as $array1 but shuffled
 */
function pregQuoteArray($array, $delim='/')
{
    if (!empty($array)) {
        if (is_array($array)) {
            foreach ($array as $key=>$val) {
                $quoted_array[$key] = preg_quote($val, $delim);
            }
            return $quoted_array;
        } else {
            return preg_quote($array, $delim);
        }
    }
}

/**
 * Converts a PHP Array into encoded URL arguments and return them as an array.
 *
 * @param  mixed $data        An array to transverse recursively, or a string
 *                            to use directly to create url arguments.
 * @param  string $prefix     The name of the first dimension of the array.
 *                            If not specified, the first keys of the array will be used.
 * @return array              URL with array elements as URL key=value arguments.
 */
function urlEncodeArray($data, $prefix='', $_return=true)
{
    // Data is stored in static variable.
    static $args;

    if (is_array($data)) {
        foreach ($data as $key => $val) {
            // If the prefix is empty, use the $key as the name of the first dimension of the "array".
            // ...otherwise, append the key as a new dimension of the "array".
            $new_prefix = ('' == $prefix) ? urlencode($key) : $prefix . '[' . urlencode($key) . ']';
            // Enter recursion.
            urlEncodeArray($val, $new_prefix, false);
        }
    } else {
        // We've come to the last dimension of the array, save the "array" and its value.
        $args[$prefix] = urlencode($data);
    }

    if ($_return) {
        // This is not a recursive execution. All recursion is complete.
        // Reset static var and return the result.
        $ret = $args;
        $args = array();
        return is_array($ret) ? $ret : array();
    }
}

/**
 * Converts a PHP Array into encoded URL arguments and return them in a string.
 *
 * @param  mixed $data        An array to transverse recursively, or a string
 *                            to use directly to create url arguments.
 * @param  string $prefix     The name of the first dimension of the array.
 *                            If not specified, the first keys of the array will be used.
 * @return string url         A string ready to append to a url.
 */
function urlEncodeArrayToString($data, $prefix='')
{

    $array_args = urlEncodeArray($data, $prefix);
    $url_args = '';
    $delim = '';
    foreach ($array_args as $key=>$val) {
        $url_args .= $delim . $key . '=' . $val;
        $delim = ini_get('arg_separator.output');
    }
    return $url_args;
}

/**
 * Fills an array with the result from a multiple ereg search.
 * Courtesy of Bruno - rbronosky@mac.com - 10-May-2001
 *
 * @param  mixed $pattern   regular expression needle
 * @param  mixed $string   haystack
 * @return array    populated with each found result
 */
function eregAll($pattern, $string)
{
    do {
        if (!mb_ereg($pattern, $string, $temp)) {
             continue;
        }
        $string = str_replace($temp[0], '', $string);
        $results[] = $temp;
    } while (mb_ereg($pattern, $string, $temp));
    return $results;
}

/**
 * Prints the word "checked" if a variable is set, and optionally matches
 * the desired value, otherwise prints nothing,
 * used for printing the word "checked" in a checkbox form input.
 *
 * @param  mixed $var     the variable to compare
 * @param  mixed $value   optional, what to compare with if a specific value is required.
 */
function frmChecked($var, $value=null)
{
    if (func_num_args() == 1 && $var) {
        // 'Checked' if var is true.
        echo ' checked="checked" ';
    } else if (func_num_args() == 2 && $var == $value) {
        // 'Checked' if var and value match.
        echo ' checked="checked" ';
    } else if (func_num_args() == 2 && is_array($var)) {
        // 'Checked' if the value is in the key or the value of an array.
        if (isset($var[$value])) {
            echo ' checked="checked" ';
        } else if (in_array($value, $var)) {
            echo ' checked="checked" ';
        }
    }
}

/**
 * prints the word "selected" if a variable is set, and optionally matches
 * the desired value, otherwise prints nothing,
 * otherwise prints nothing, used for printing the word "checked" in a
 * select form input
 *
 * @param  mixed $var     the variable to compare
 * @param  mixed $value   optional, what to compare with if a specific value is required.
 */
function frmSelected($var, $value=null)
{
    if (func_num_args() == 1 && $var) {
        // 'selected' if var is true.
        echo ' selected="selected" ';
    } else if (func_num_args() == 2 && $var == $value) {
        // 'selected' if var and value match.
        echo ' selected="selected" ';
    } else if (func_num_args() == 2 && is_array($var)) {
        // 'selected' if the value is in the key or the value of an array.
        if (isset($var[$value])) {
            echo ' selected="selected" ';
        } else if (in_array($value, $var)) {
            echo ' selected="selected" ';
        }
    }
}

/**
 * Adds slashes to values of an array and converts the array to a comma
 * delimited list. If value provided is a string return the string
 * escaped.  This is useful for putting values coming in from posted
 * checkboxes into a SET column of a database.
 *
 *
 * @param  array $in      Array to convert.
 * @return string         Comma list of array values.
 */
function escapedList($in, $separator="', '")
{
    $db =& DB::getInstance();

    if (is_array($in) && !empty($in)) {
        return join($separator, array_map(array($db, 'escapeString'), $in));
    } else {
        return $db->escapeString($in);
    }
}

/**
 * Converts a human string date into a SQL-safe date.  Dates nearing
 * infinity use the date 2038-01-01 so conversion to unix time format
 * remain within valid range.
 *
 * @param  array $date     String date to convert.
 * @param  array $format   Date format to pass to date().
 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
 * @return string          SQL-safe date.
 */
function strToSQLDate($date, $format='Y-m-d H:i:s')
{
    // Translate the human string date into SQL-safe date format.
    if (empty($date) || mb_strpos($date, '0000-00-00') !== false || strtotime($date) === -1 || strtotime($date) === false || strtotime($date) === null) {
        // Return a string of zero time, formatted the same as $format.
        return strtr($format, array(
            'Y' => '0000',
            'm' => '00',
            'd' => '00',
            'H' => '00',
            'i' => '00',
            's' => '00',
        ));
    } else {
        return date($format, strtotime($date));
    }
}

/**
 * If magic_quotes_gpc is in use, run stripslashes() on $var. If $var is an
 * array, stripslashes is run on each value, recursively, and the stripped
 * array is returned.
 *
 * @param  mixed $var   The string or array to un-quote, if necessary.
 * @return mixed        $var, minus any magic quotes.
 */
function dispelMagicQuotes($var, $always=false)
{
    static $magic_quotes_gpc;

    if (!isset($magic_quotes_gpc)) {
        $magic_quotes_gpc = get_magic_quotes_gpc();
    }

    if ($always || $magic_quotes_gpc) {
        if (!is_array($var)) {
            $var = stripslashes($var);
        } else {
            foreach ($var as $key=>$val) {
                if (is_array($val)) {
                    $var[$key] = dispelMagicQuotes($val, $always);
                } else {
                    $var[$key] = stripslashes($val);
                }
            }
        }
    }
    return $var;
}

/**
 * Get a form variable from GET or POST data, stripped of magic
 * quotes if necessary.
 *
 * @param string $var (optional) The name of the form variable to look for.
 * @param string $default (optional) The value to return if the
 *                                   variable is not there.
 * @return mixed      A cleaned GET or POST if no $var specified.
 * @return string     A cleaned form $var if found, or $default.
 */
function getFormData($var=null, $default=null)
{
    $app =& App::getInstance();

    if ('POST' == getenv('REQUEST_METHOD') && is_null($var)) {
        return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
    } else if ('GET' == getenv('REQUEST_METHOD') && is_null($var)) {
        return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
    }
    if (isset($_POST[$var])) {
        return dispelMagicQuotes($_POST[$var], $app->getParam('always_dispel_magicquotes'));
    } else if (isset($_GET[$var])) {
        return dispelMagicQuotes($_GET[$var], $app->getParam('always_dispel_magicquotes'));
    } else {
        return $default;
    }
}

function getPost($var=null, $default=null)
{
    $app =& App::getInstance();

    if (is_null($var)) {
        return dispelMagicQuotes($_POST, $app->getParam('always_dispel_magicquotes'));
    }
    if (isset($_POST[$var])) {
        return dispelMagicQuotes($_POST[$var], $app->getParam('always_dispel_magicquotes'));
    } else {
        return $default;
    }
}

function getGet($var=null, $default=null)
{
    $app =& App::getInstance();
    if (is_null($var)) {
        return dispelMagicQuotes($_GET, $app->getParam('always_dispel_magicquotes'));
    }
    if (isset($_GET[$var])) {
        return dispelMagicQuotes($_GET[$var], $app->getParam('always_dispel_magicquotes'));
    } else {
        return $default;
    }
}

/*
* Sets a $_GET or $_POST variable.
*
* @access   public
* @param    string  $key    The key of the request array to set.
* @param    mixed   $val    The value to save in the request array.
* @return   void
* @author   Quinn Comendant 
* @version  1.0
* @since    01 Nov 2009 12:25:29
*/
function putFormData($key, $val)
{
    if ('POST' == getenv('REQUEST_METHOD')) {
        $_POST[$key] = $val;
    } else if ('GET' == getenv('REQUEST_METHOD')) {
        $_GET[$key] = $val;
    }
}

/**
 * Signs a value using md5 and a simple text key. In order for this
 * function to be useful (i.e. secure) the salt must be kept secret, which
 * means keeping it as safe as database credentials. Putting it into an
 * environment variable set in httpd.conf is a good place.
 *
 * @access  public
 * @param   string  $val    The string to sign.
 * @param   string  $salt   (Optional) A text key to use for computing the signature.
 * @param   string  $length (Optional) The length of the added signature. Longer signatures are safer. Must match the length passed to verifySignature() for the signatures to match.
 * @return  string  The original value with a signature appended.
 */
function addSignature($val, $salt=null, $length=18)
{
    $app =& App::getInstance();

    if ('' == trim($val)) {
        $app->logMsg(sprintf('Cannot add signature to an empty string.', null), LOG_INFO, __FILE__, __LINE__);
        return '';
    }

    if (!isset($salt)) {
        $salt = $app->getParam('signing_key');
    }

    switch ($app->getParam('signing_method')) {
    case 'sha512+base64':
        return $val . '-' . mb_substr(preg_replace('/[^\w]/', '', base64_encode(hash('sha512', $val . $salt, true))), 0, $length);

    case 'md5':
    default:
        return $val . '-' . mb_strtolower(mb_substr(md5($salt . md5($val . $salt)), 0, $length));
    }
}

/**
 * Strips off the signature appended by addSignature().
 *
 * @access  public
 * @param   string  $signed_val     The string to sign.
 * @return  string  The original value with a signature removed.
 */
function removeSignature($signed_val)
{
    if (empty($signed_val) || mb_strpos($signed_val, '-') === false) {
        return '';
    }
    return mb_substr($signed_val, 0, mb_strrpos($signed_val, '-'));
}

/**
 * Verifies a signature appended to a value by addSignature().
 *
 * @access  public
 * @param   string  $signed_val A value with appended signature.
 * @param   string  $salt       (Optional) A text key to use for computing the signature.
 * @param   string  $length (Optional) The length of the added signature.
 * @return  bool    True if the signature matches the var.
 */
function verifySignature($signed_val, $salt=null, $length=18)
{
    // Strip the value from the signed value.
    $val = removeSignature($signed_val);
    // If the signed value matches the original signed value we consider the value safe.
    if ('' != $signed_val && $signed_val == addSignature($val, $salt, $length)) {
        // Signature verified.
        return true;
    } else {
        $app =& App::getInstance();
        $app->logMsg(sprintf('Failed signature (%s should be %s)', $signed_val, addSignature($val, $salt, $length)), LOG_DEBUG, __FILE__, __LINE__);
        return false;
    }
}

/**
 * Sends empty output to the browser and flushes the php buffer so the client
 * will see data before the page is finished processing.
 */
function flushBuffer()
{
    echo str_repeat('          ', 205);
    flush();
}

/**
 * Adds email address to mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
 *
 * @access  public
 * @param   string  $email     Email address to add.
 * @param   string  $list      Name of list to add to.
 * @param   bool    $send_welcome_message   True to send welcome message to subscriber.
 * @return  bool    True on success, false on failure.
 */
function mailmanAddMember($email, $list, $send_welcome_message=false)
{
    $app =& App::getInstance();

    $add_members = '/usr/lib/mailman/bin/add_members';
    // FIXME: checking of executable is disabled.
    if (true || is_executable($add_members) && is_readable($add_members)) {
        $welcome_msg = $send_welcome_message ? 'y' : 'n';
        exec(sprintf("/bin/echo '%s' | /usr/bin/sudo %s -r - --welcome-msg=%s --admin-notify=n '%s'", escapeshellarg($email), escapeshellarg($add_members), $welcome_msg, escapeshellarg($list)), $stdout, $return_code);
        if (0 == $return_code) {
            $app->logMsg(sprintf('Mailman add member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
            return true;
        } else {
            $app->logMsg(sprintf('Mailman add member failed for list: %s, user: %s, with message: %s', $list, $email, getDump($stdout)), LOG_WARNING, __FILE__, __LINE__);
            return false;
        }
    } else {
        $app->logMsg(sprintf('Mailman add member program not executable: %s', $add_members), LOG_ALERT, __FILE__, __LINE__);
        return false;
    }
}

/**
 * Removes email address from mailman mailing list. Requires /etc/sudoers entry for apache to sudo execute add_members.
 * Don't forget to allow php_admin_value open_basedir access to "/var/mailman/bin".
 *
 * @access  public
 * @param   string  $email     Email address to add.
 * @param   string  $list      Name of list to add to.
 * @param   bool    $send_user_ack   True to send goodbye message to subscriber.
 * @return  bool    True on success, false on failure.
 */
function mailmanRemoveMember($email, $list, $send_user_ack=false)
{
    $app =& App::getInstance();

    $remove_members = '/usr/lib/mailman/bin/remove_members';
    // FIXME: checking of executable is disabled.
    if (true || is_executable($remove_members) && is_readable($remove_members)) {
        $userack = $send_user_ack ? '' : '--nouserack';
        exec(sprintf("/usr/bin/sudo %s %s --noadminack '%s' '%s'", escapeshellarg($remove_members), $userack, escapeshellarg($list), escapeshellarg($email)), $stdout, $return_code);
        if (0 == $return_code) {
            $app->logMsg(sprintf('Mailman remove member success for list: %s, user: %s', $list, $email), LOG_INFO, __FILE__, __LINE__);
            return true;
        } else {
            $app->logMsg(sprintf('Mailman remove member failed for list: %s, user: %s, with message: %s', $list, $email, $stdout), LOG_WARNING, __FILE__, __LINE__);
            return false;
        }
    } else {
        $app->logMsg(sprintf('Mailman remove member program not executable: %s', $remove_members), LOG_ALERT, __FILE__, __LINE__);
        return false;
    }
}

/*
* Returns the remote IP address, taking into consideration proxy servers.
*
* If strict checking is enabled, we will only trust REMOTE_ADDR or an HTTP header
* value if REMOTE_ADDR is a trusted proxy (configured as an array in $cfg['trusted_proxies']).
*
* @access   public
* @param    bool $dolookup            Resolve to IP to a hostname?
* @param    bool $trust_all_proxies   Should we trust any IP address set in HTTP_* variables? Set to FALSE for secure usage.
* @return   mixed Canonicalized IP address (or a corresponding hostname if $dolookup is true), or false if no IP was found.
* @author   Alix Axel 
* @author   Corey Ballou 
* @author   Quinn Comendant 
* @version  1.0
* @since    12 Sep 2014 19:07:46
*/
function getRemoteAddr($dolookup=false, $trust_all_proxies=true)
{
    global $cfg;

    if (!isset($_SERVER['REMOTE_ADDR'])) {
        // In some cases this won't be set, e.g., CLI scripts.
        return null;
    }

    // Use an HTTP header value only if $trust_all_proxies is true or when REMOTE_ADDR is in our $cfg['trusted_proxies'] array.
    // $cfg['trusted_proxies'] is an array of proxy server addresses we expect to see in REMOTE_ADDR.
    if ($trust_all_proxies || isset($cfg['trusted_proxies']) && is_array($cfg['trusted_proxies']) && in_array($_SERVER['REMOTE_ADDR'], $cfg['trusted_proxies'], true)) {
        // Then it's probably safe to use an IP address value set in an HTTP header.
        // Loop through possible IP address headers.
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED') as $key) {
            // Loop through and if
            if (array_key_exists($key, $_SERVER)) {
                foreach (explode(',', $_SERVER[$key]) as $addr) {
                    $addr = canonicalIPAddr(trim($addr));
                    if (false !== filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        return $dolookup && '' != $addr ? gethostbyaddr($addr) : $addr;
                    }
                }
            }
        }
    }

    $addr = canonicalIPAddr(trim($_SERVER['REMOTE_ADDR']));
    return $dolookup && $addr ? gethostbyaddr($addr) : $addr;
}

/*
* Converts an ipv4 IP address in hexadecimal form into canonical form (i.e., it removes the prefix).
*
* @access   public
* @param    string  $addr   IP address.
* @return   string          Canonical IP address.
* @author   Sander Steffann 
* @author   Quinn Comendant 
* @version  1.0
* @since    15 Sep 2012
*/
function canonicalIPAddr($addr)
{
    // Known prefix
    $v4mapped_prefix_bin = pack('H*', '00000000000000000000ffff');

    // Parse
    $addr_bin = inet_pton($addr);

    // Check prefix
    if (substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) {
        // Strip prefix
        $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin));
    }

    // Convert back to printable address in canonical form
    return inet_ntop($addr_bin);
}

/**
 * Tests whether a given IP address can be found in an array of IP address networks.
 * Elements of networks array can be single IP addresses or an IP address range in CIDR notation
 * See: http://en.wikipedia.org/wiki/Classless_inter-domain_routing
 *
 * @access  public
 * @param   string  IP address to search for.
 * @param   array   Array of networks to search within.
 * @return  mixed   Returns the network that matched on success, false on failure.
 */
function ipInRange($addr, $networks)
{
    if (!is_array($networks)) {
        $networks = array($networks);
    }

    $addr_binary = sprintf('%032b', ip2long($addr));
    foreach ($networks as $network) {
        if (preg_match('![\d\.]{7,15}/\d{1,2}!', $network)) {
            // IP is in CIDR notation.
            list($cidr_ip, $cidr_bitmask) = explode('/', $network);
            $cidr_ip_binary = sprintf('%032b', ip2long($cidr_ip));
            if (mb_substr($addr_binary, 0, $cidr_bitmask) === mb_substr($cidr_ip_binary, 0, $cidr_bitmask)) {
               // IP address is within the specified IP range.
               return $network;
            }
        } else {
            if ($addr === $network) {
               // IP address exactly matches.
               return $network;
            }
        }
    }

    return false;
}

/**
 * If the given $url is on the same web site, return true. This can be used to
 * prevent from sending sensitive info in a get query (like the SID) to another
 * domain.
 *
 * @param  string $url    the URI to test.
 * @return bool True if given $url is our domain or has no domain (is a relative url), false if it's another.
 */
function isMyDomain($url)
{
    static $urls = array();

    if (!isset($urls[$url])) {
        if (!preg_match('|https?://[\w.]+/|', $url)) {
            // If we can't find a domain we assume the URL is local (i.e. "/my/url/path/" or "../img/file.jpg").
            $urls[$url] = true;
        } else {
            $urls[$url] = preg_match('|https?://[\w.]*' . preg_quote(getenv('HTTP_HOST'), '|') . '|i', $url);
        }
    }
    return $urls[$url];
}

/**
 * Takes a URL and returns it without the query or anchor portion
 *
 * @param  string $url   any kind of URI
 * @return string        the URI with ? or # and everything after removed
 */
function stripQuery($url)
{
    return preg_replace('/[?#].*$/', '', $url);
}

/**
 * Returns a fully qualified URL to the current script, including the query.
 *
 * @return string    a full url to the current script
 */
function absoluteMe()
{
    $protocol = ('on' == getenv('HTTPS')) ? 'https://' : 'http://';
    return $protocol . getenv('HTTP_HOST') . getenv('REQUEST_URI');
}

/**
 * Compares the current url with the referring url.
 *
 * @param  bool $exclude_query  Remove the query string first before comparing.
 * @return bool                 True if the current URL is the same as the referring URL, false otherwise.
 */
function refererIsMe($exclude_query=false)
{
    if ($exclude_query) {
        return (stripQuery(absoluteMe()) == stripQuery(getenv('HTTP_REFERER')));
    } else {
        return (absoluteMe() == getenv('HTTP_REFERER'));
    }
}

/*
* Returns true if the given URL resolves to a resource with a HTTP 200 header response.
*
* @access   public
* @param    string  $url    URL to a file.
* @return   bool            True if the resource exists, false otherwise.
* @author   Quinn Comendant 
* @version  1.0
* @since    02 May 2015 15:10:09
*/
function httpExists($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    return '200' == curl_getinfo($ch, CURLINFO_HTTP_CODE);
}