<?php

if (!function_exists('random_string')) {
    function random_string($type = 'alnum', $len = 8)
    {
        switch ($type) {
            case 'basic'    :
                return mt_rand();
                break;
            case 'alnum'    :
            case 'numeric'    :
            case 'nozero'    :
            case 'alpha'    :

                switch ($type) {
                    case 'alpha'    :
                        $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'alnum'    :
                        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'numeric'    :
                        $pool = '0123456789';
                        break;
                    case 'nozero'    :
                        $pool = '123456789';
                        break;
                }

                $str = '';
                for ($i = 0; $i < $len; $i++) {
                    $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
                }
                return $str;
                break;
            case 'unique'    :
            case 'md5'        :
                return md5(uniqid(mt_rand()));
                break;
            case 'encrypt'    :
            case 'sha1'    :
                return sha1(uniqid(mt_rand(), true));
                break;
        }
    }
}

if (!function_exists('make_replacements')) {
    function make_replacements($phrase, array $replace)
    {
        foreach ($replace as $key => $value) {
            $phrase = str_replace('{'.$key.'}', $value, $phrase);
        }

        return $phrase;
    }
}

if (!function_exists('yes_no')) {
    function yes_no($value)
    {
        if ($value == true) {
            return "yes";
        } else {
            return "no";
        }
    }
}

if (!function_exists('abbreviate')) {
    function abbreviate($string)
    {
        $abbreviation = "";
        $string = ucwords($string);
        $words = explode(" ", "$string");
        foreach ($words as $word) {
            if (!$word) {
                continue;
            }
            $abbreviation .= $word[0];
        }
        return $abbreviation;
    }
}

if (!function_exists('get_to_text_area')) {
    function get_to_text_area($content)
    {
        if (empty($content)) {
            return $content;
        }

        return str_replace("<br/>", "\n", $content);
    }
}

if (!function_exists('get_from_text_area')) {
    function get_from_text_area($content)
    {
        if (empty($content)) {
            return $content;
        }

        $final_content = str_replace("\r\n", "<br/>", $content);
        return str_replace("\n", "<br/>", $final_content);
    }
}

if (!function_exists('urlize')) {
    function urlize($s)
    {

        $s = utf8_decode($s);
        $s = _convert_high_ascii($s);  ## convert high-ASCII chars to 7bit.
        $s = strtolower($s);           ## lower-case.
        $s = strip_tags($s);       ## remove HTML tags.
        $s = preg_replace('!&[^;\s]+;!', '', $s);
        $s = preg_replace('!&[^;\s]+;!', '', $s);         ## remove HTML entities.
        $s = preg_replace('![^\w\s-]!', '', $s);           ## remove non-word/space chars.
        $s = preg_replace('![\s_]+!', '-', $s);               ## change space chars to underscores.
        $s = urlencode($s);
        return $s;
    }
}


//@todo when possible review this to improve performance
if (!function_exists('_convert_high_ascii')) {
    function _convert_high_ascii($s)
    {
        $HighASCII = array(
            "!\xc0!" => 'A',    # A`
            "!\xe0!" => 'a',    # a`
            "!\xc1!" => 'A',    # A'
            "!\xe1!" => 'a',    # a'
            "!\xc2!" => 'A',    # A^
            "!\xe2!" => 'a',    # a^
            "!\xc4!" => 'Ae',   # A:
            "!\xe4!" => 'ae',   # a:
            "!\xc3!" => 'A',    # A~
            "!\xe3!" => 'a',    # a~
            "!\xc8!" => 'E',    # E`
            "!\xe8!" => 'e',    # e`
            "!\xc9!" => 'E',    # E'
            "!\xe9!" => 'e',    # e'
            "!\xca!" => 'E',    # E^
            "!\xea!" => 'e',    # e^
            "!\xcb!" => 'Ee',   # E:
            "!\xeb!" => 'ee',   # e:
            "!\xcc!" => 'I',    # I`
            "!\xec!" => 'i',    # i`
            "!\xcd!" => 'I',    # I'
            "!\xed!" => 'i',    # i'
            "!\xce!" => 'I',    # I^
            "!\xee!" => 'i',    # i^
            "!\xcf!" => 'Ie',   # I:
            "!\xef!" => 'ie',   # i:
            "!\xd2!" => 'O',    # O`
            "!\xf2!" => 'o',    # o`
            "!\xd3!" => 'O',    # O'
            "!\xf3!" => 'o',    # o'
            "!\xd4!" => 'O',    # O^
            "!\xf4!" => 'o',    # o^
            "!\xd6!" => 'Oe',   # O:
            "!\xf6!" => 'oe',   # o:
            "!\xd5!" => 'O',    # O~
            "!\xf5!" => 'o',    # o~
            "!\xd8!" => 'Oe',   # O/
            "!\xf8!" => 'oe',   # o/
            "!\xd9!" => 'U',    # U`
            "!\xf9!" => 'u',    # u`
            "!\xda!" => 'U',    # U'
            "!\xfa!" => 'u',    # u'
            "!\xdb!" => 'U',    # U^
            "!\xfb!" => 'u',    # u^
            "!\xdc!" => 'Ue',   # U:
            "!\xfc!" => 'ue',   # u:
            "!\xc7!" => 'C',    # ,C
            "!\xe7!" => 'c',    # ,c
            "!\xd1!" => 'N',    # N~
            "!\xf1!" => 'n',    # n~
            "!\xdf!" => 'ss'
        );
        $find = array_keys($HighASCII);
        $replace = array_values($HighASCII);
        $s = preg_replace($find, $replace, $s);
        return $s;
    }
}

if (!function_exists('cut_string')) {
    function cut_string($value, $cut_point, $suffix = "")
    {
        if (empty($value) || trim($value) == "") {
            return $value;
        }

        if (strlen($value) <= $cut_point) {
            return $value;
        }

        $final_value = mb_substr($value, 0, $cut_point - strlen($suffix));
        $last_space_pos = strripos($final_value, " ");
        if ($last_space_pos === false) {
            return $final_value.$suffix;
        }

        return mb_substr($final_value, 0, $last_space_pos).$suffix;
    }
}

if (!function_exists('get_values_string')) {
    function get_values_string($values)
    {
        $titles = array();
        foreach ($values as $value) {
            array_push($titles, $value->title);
        }
        return concat_strings($titles);
    }
}

if (!function_exists('concat_strings')) {
    function concat_strings($strings, $with_commercial_e = true)
    {
        $glue = ", ";
        $size = count($strings);
        if (empty($strings)) {
            return "";
        }

        if ($with_commercial_e && $size > 1) {
            $last = array_pop($strings);
            $start = join($glue, $strings);
            return "{$start} & {$last}";
        } else {
            return join($glue, $strings);
        }
    }
}


/**
 * Helper to import wp content
 *
 * @param  mixed  $pee
 * @param  mixed  $br
 * @return mixed
 */
if (!function_exists('wpautop')) {
    function wpautop($pee, $br = true)
    {
        $pre_tags = array();

        if (trim($pee) === '') {
            return '';
        }

        $pee = $pee."\n"; // just to make things a little easier, pad the end

        if (strpos($pee, '<pre') !== false) {
            $pee_parts = explode('</pre>', $pee);
            $last_pee = array_pop($pee_parts);
            $pee = '';
            $i = 0;

            foreach ($pee_parts as $pee_part) {
                $start = strpos($pee_part, '<pre');

                // Malformed html?
                if ($start === false) {
                    $pee .= $pee_part;
                    continue;
                }

                $name = "<pre wp-pre-tag-$i></pre>";
                $pre_tags[$name] = mb_substr($pee_part, $start).'</pre>';

                $pee .= mb_substr($pee_part, 0, $start).$name;
                $i++;
            }

            $pee .= $last_pee;
        }

        $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
        // Space things out a little
        $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
        $pee = preg_replace('!(<'.$allblocks.'[^>]*>)!', "\n$1", $pee);
        $pee = preg_replace('!(</'.$allblocks.'>)!', "$1\n\n", $pee);
        $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
        if (strpos($pee, '<object') !== false) {
            $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
            $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
        }
        $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
        // make paragraphs, including one at the end
        $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
        $pee = '';
        foreach ($pees as $tinkle) {
            $pee .= '<p>'.trim($tinkle, "\n")."</p>\n";
        }
        $pee = preg_replace('|<p>\s*</p>|', '',
            $pee); // under certain strange conditions it could create a P of entirely whitespace
        $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
        $pee = preg_replace('!<p>\s*(</?'.$allblocks.'[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
        $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
        $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
        $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
        $pee = preg_replace('!<p>\s*(</?'.$allblocks.'[^>]*>)!', "$1", $pee);
        $pee = preg_replace('!(</?'.$allblocks.'[^>]*>)\s*</p>!', "$1", $pee);
        if ($br) {
            $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
            $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
            $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
        }
        $pee = preg_replace('!(</?'.$allblocks.'[^>]*>)\s*<br />!', "$1", $pee);
        $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
        $pee = preg_replace("|\n</p>$|", '</p>', $pee);

        if (!empty($pre_tags)) {
            $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
        }

        return $pee;
    }

    /**
     * Newline preservation help function for wpautop
     *
     * @param  array  $matches  preg_replace_callback matches array
     * @return string
     * @since 3.1.0
     * @access private
     *
     */
    function _autop_newline_preservation_helper($matches)
    {
        return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
    }
}

if (!function_exists('email_protect')) {
    function email_protect($email)
    {
        if (!$email) {
            return "";
        }

        $emailArray = explode('@', $email);
        if (sizeOf($emailArray) != 2) {
            return $email;
        }
        return $emailArray[0].'@<span style="display: none;">no-where</span>'.$emailArray[1];
    }
}
if (!function_exists('enc_char')) {
    function enc_char($char)
    {
        $cnum = ord($char);
        if ($cnum == 122) {
            return ('a');
        }
        if ($cnum >= 97 && $cnum < 122) {
            return chr($cnum + 1);
        } else {
            return $char;
        }
    }
}

if (!function_exists('enc_str')) {
    function enc_str($str)
    {
        $outStr = "";
        for ($i = 0; $i < strlen($str); $i++) {
            $outStr .= enc_char($str[$i]);
        }
        return $outStr;
    }
}
if (!function_exists('enc_mailto')) {
    function enc_mailto($email)
    {
        if (!$email) {
            return "";
        }

        $emailArray = explode('@', $email);
        if (sizeOf($emailArray) != 2) {
            return $email;
        }

        return "javascript:linkContact('".enc_str($emailArray[1])."','".enc_str($emailArray[0])."')";
    }
}

if (!function_exists('email_link')) {
    function email_link($email)
    {
        if (!$email) {
            return "";
        }

        $emailArray = explode('@', $email);
        if (sizeOf($emailArray) != 2) {
            return $email;
        }
        return $emailArray[0].'@<span style="display: none;">no-where</span>'.$emailArray[1];
    }
}
if (!function_exists('email_link_tag')) {
    function email_link_tag($email, $classes = false)
    {
        return '<a '.($classes ? 'class="'.$classes.'" ' : '').'href="'.enc_mailto($email).'">'.email_protect($email).'</a>';
    }
}

if (!function_exists('flag_file_name')) {
    function flag_file_name($locale)
    {
        $localeParts = explode('-', $locale);
        if (sizeof($localeParts) == 1) {
            return $locale . '.png';
        }
        if (sizeof($localeParts) == 2) {
            return strtolower($localeParts[1]) . '.png';
        }
        return 'no-flag.png';
    }
}

if (!function_exists('lang_code_to_iso')) {
    function lang_code_to_iso($code) {
        if (empty($code)) {
            return '';
        }
        $parts = explode('-', $code);
        if (sizeof($parts) == 2) {
            return $parts[0] . '-' . strtoupper($parts[1]);
        }
        return $code;
    }
}

if (!function_exists('co2_subscript')) {
    function co2_subscript($string) {
        if (empty($string)) {
            return '';
        }
        return preg_replace('/\bCO2\b/i', 'CO<sub>2</sub>', $string);
    }
}
