<?php

function encodeEmoji($match)
{
    return str_replace(array('[', ']', '"'), '', json_encode($match));
}

function decodeEmoji($text)
{
    if (!$text) {
        return '';
    }

    $text = $text[0];
    $decode = json_decode($text, true);
    if ($decode) {
        return $decode;
    }

    $text = '["' . $text . '"]';
    $decode = json_decode($text);
    if (count($decode) == 1) {
        return $decode[0];
    }
    return $text;
}

function convertEmoji($text, $op = '')
{
    if ($op == "ENCODE") {
        return preg_replace_callback('/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{1F000}-\x{1FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F9FF}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F9FF}][\x{1F000}-\x{1FEFF}]?/u', "encodeEmoji", $text);
    } else {
        return preg_replace_callback('/(\\\u[0-9a-f]{4})+/', "decodeEmoji", $text);
    }
}

function getMetaDescription($viewVars)
{
    if (is_array($viewVars)) {
        if (empty($viewVars['Skin_Content'])) {
            return '';
        } else {
            getClearText($viewVars['Skin_Content']);
        }
    } else {
        return getClearText($viewVars);
    }
}

function getClearText($str)
{
    $text = substr(strip_tags($str), 0, 10000);
    $splited = explode(' ', $text);
    $cut = array_slice($splited, ceil(count($splited) / 5), ceil(count($splited) / 5) + 170);
    foreach ($cut as $k => $c) {
        $pattern = '/[\x{1100}-\x{11FF}\x{3130}-\x{318F}\x{AC00}-\x{D7AF}]+/u';
        preg_match_all($pattern, $c, $match);
        $cut[$k] = is_array($match[0]) ? implode(' ', $match[0]) : $match[0];
    }
    return implode(' ', array_filter($cut));
}

function getMetaTitle($translate)
{
    $page = explode('/', uri_string());
    return $translate[$page[count($page) - 1]];
}

function cleanUrl($string)
{
    $string = preg_replace('/[^\x{1100}-\x{11FF}\x{3130}-\x{318F}\x{AC00}-\x{D7AF}\-a-zA-Z0-9]+/u', '', str_replace(' ', '-', trim($string)));
    $string = preg_replace('/(u[0-9a-f]{4})+/', "", $string);
    $string = stripall(['--', '--'], '-', trim($string));
    $string = substr($string, 0, 1) == '-' ? substr($string, 1) : $string;
    return substr($string, -1) == '-' ? substr($string, 0, -1) : $string;
}

function stripall($values, $replace, $string)
{
    foreach ($values as $value) {
        while (strpos($string, $value)) {
            $string = str_replace($value, $replace, $string);
            stripall($values, $replace, $string);
        }
    }
    return $string;
}

function imgSrc($img)
{
    if (is_array($img)) {
        $path = $img[1];
        return '<img src=' . (strpos($img[0], '"') ? '"' : "'") . getPathWithHost($path, true);
    } else {
        return getPathWithHost($img, true);
    }
}

function contentImgSrc($content)
{
    $content = stripslashes(html_entity_decode($content));
    return preg_replace_callback("/<img[^>]*?src *= *[\"']?([^\"']*)/i", 'imgSrc', $content);
}

function getPathWithHost($path, $https = true)
{
    $path = trim($path);
    $host = ENVIRONMENT == 'development' ? 'crossmap.christiandaily.co.kr' : $_SERVER['HTTP_HOST'];
    if ($path) {
        return strpos($path, '://') ? $path : 'http' . ($https ? 's' : '') . '://' . $host . '/static' . (substr($path, 0, 1) != '/' ? '/' . $path : $path);
    }
    return '';
}

function array_flatten($array)
{
    if (!is_array($array)) {
        return false;
    }
    $result = array();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $result = array_merge($result, array_flatten($value));
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

function time_elapsed_string($datetime, $full = false)
{
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => '년',
        'm' => '개월',
        'w' => '주',
        'd' => '일',
        'h' => '시간',
        'i' => '분',
        's' => '초',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? '' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) {
        $string = array_slice($string, 0, 1);
    }

    return $string ? implode(', ', $string) . ' 전' : '방금전';
}

function param($key)
{
    return get_instance()->param($key);
}

function go($go, $msg = '')
{
    echo '<script>' . ($msg ? 'alert("' . $msg . '");' : '') . 'location.href="' . $go . '"</script>';
}
