<?php

class Functions
{
    public static function replaceParams($content, $params)
    {
        $replacements = array();
        foreach ($params as $k => $v) {
            $replacements['{{'.strtoupper($k).'}}'] = $v;
        }
        $content = strtr($content, $replacements);

        return $content;
    }
    public static function full_copy($source, $target, $level = -1)
    {
		if (!file_exists($source)) {
			return;
		}
        if (is_dir($source)) {
            if (!file_exists($target)) {
                @mkdir($target);
            }
            $d = dir($source);
            while (false !== ($entry = $d->read())) {
                if ($entry == '.' || $entry == '..') {
                    continue;
                }
                $Entry = $source.'/'.$entry;
                if (is_dir($Entry)) {
                    if ($level === -1 || $level > 0) {
                        if ($level > 0) {
                            --$level;
                        }
                        self::full_copy($Entry, $target.'/'.$entry, $level);
                    }
                    continue;
                }
                copy($Entry, $target.'/'.$entry);
            }

            $d->close();
        } else {
            copy($source, $target);
        }
    }

    public static function getSystemTimeZone()
    {
        $local_date = new DateTime(date('Y-m-d h:i:s'));
        $gm_date = new DateTime(gmdate('Y-m-d h:i:s'));
        $diff = $local_date->diff($gm_date);
        $h_diff = $diff->h;
        echo date('Y-m-d H:i:s').' '.gmdate('Y-m-d h:i:s');

        return timezone_name_from_abbr('', $h_diff * 3600);
    }
    public static function stripUnicode($str)
    {
        if (!$str) {
            return false;
        }
        $unicode = array(
          'a' => 'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
          'd' => 'đ',
          'e' => 'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
          'i' => 'í|ì|ỉ|ĩ|ị',
          'o' => 'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
          'u' => 'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
          'y' => 'ý|ỳ|ỷ|ỹ|ỵ',
       );
        foreach ($unicode as $nonUnicode => $uni) {
            $str = preg_replace("/($uni)/i", $nonUnicode, $str);
        }

        return $str;
    }

    public static function validateDate($date, $format = 'Y-m-d H:i:s')
    {
        $d = DateTime::createFromFormat($format, $date);

        return $d && $d->format($format) == $date;
    }
    public static function limit_text($text, $limit)
    {
        if (str_word_count($text, 0) > $limit) {
            $words = str_word_count($text, 2);
            $pos = array_keys($words);
            $text = substr($text, 0, $pos[$limit]).'...';
        }

        return $text;
    }
    public static function extractImage($content)
    {
        $doc = new DOMDocument();
        @$doc->loadHTML($content);

        $tags = $doc->getElementsByTagName('img');
        $tag = false;
        foreach ($tags as $t) {
            $tag = $t;
            break;
        }
        if ($tag != false) {
            return $tag->getAttribute('src');
        }

        return false;
    }
    public static function apache_request_headers()
    {
        if (!function_exists('apache_request_headers')) {
            $arh = array();
            $rx_http = '/\AHTTP_/';
            foreach ($_SERVER as $key => $val) {
                if (preg_match($rx_http, $key)) {
                    $arh_key = preg_replace($rx_http, '', $key);
                    $rx_matches = array();
                    $rx_matches = explode('_', $arh_key);
                    if (count($rx_matches) > 0 and strlen($arh_key) > 2) {
                        foreach ($rx_matches as $ak_key => $ak_val) {
                            $rx_matches[$ak_key] = ucfirst($ak_val);
                        }
                        $arh_key = implode('-', $rx_matches);
                    }
                    $arh[$arh_key] = $val;
                }
            }

            return($arh);
        } else {
            return apache_request_headers();
        }
    }
    public static function getServerSecret()
    {
        if (!defined('SERVER_SECRET_KEY')) {
            define('SERVER_SECRET_KEY', 'DFDFDSFdfdfdfdfdfdfdsfdDFDFDDFDFDFDFDF');
        }

        return SERVER_SECRET_KEY;
    }

    public static function getCSSTextFormArray($css)
    {
        $s = '';
        foreach ($css as $item) {
            if (isset($item['selector'])) {
                $s .= $item['selector'].'{';
                if (isset($item['selector_body'])) {
                    foreach ($item['selector_body'] as $bodyitem) {
                        if (isset($bodyitem['property']) && isset($bodyitem['value'])) {
                            if ($bodyitem['property'] != '' && $bodyitem['value'] != '') {
                                $s .= $bodyitem['property'].':'.$bodyitem['value'].';';
                            }
                        }
                    }
                    $s .= '}';
                }
            }
        }

        return $s;
    }
    public static function readCSSContentFromFile($relative_path)
    {
        if (!file_exists($relative_path)) {
            return;
        }
        $file = file_get_contents($relative_path);

        return self::parseCSS($file);
    }
    public static function readCSSContentFromFile2($relative_path)
    {
        if (!file_exists($relative_path)) {
            return;
        }
        $file = file_get_contents($relative_path);

        return self::parseCSS2($file);
    }
    public static function parseCSS2($css)
    {
        $Sabberworm = Yii::getPathOfAlias('application.classes.PHP-CSS-Parser.lib.Sabberworm');
        Yii::setPathOfAlias('Sabberworm', $Sabberworm);

        $sMyId = '#my_id';
        $oParser = new Sabberworm\CSS\Parser($css);
        $oCss = $oParser->parse();
        print $oCss->render();

        return array();
    }
    public static function parseCSS($css)
    {
        $parser = new CSSParser($css);

        return $parser->parse();
    }
    public static function getModuleSelector($skin, $slt)
    {
        $class = get_class($skin);
        $name = $skin->name;
        $format = $skin->format;
        $selectors = explode(',', $slt);
        $selector = '';
        $sep = '';
        foreach ($selectors as $s) {
            if ($class == 'SkinPreset') {
                $module_name = $skin->module_type->name;
                $selector .= $sep.'.module-'.$module_name.''.'.a_'.$name.'_'.$format.' '.$s;
                $sep = ',';
            } else {
                $module_name = $skin->type;
                $selector .= $sep.'.module-'.$module_name.''.'.b_'.$name.'_'.$format.' '.$s;
                $sep = ',';
            }
        }

        return $selector;
    }
    public static function array_to_str(&$tab)
    {
        // This function return a string description of an array.
        // Format (_ == space):
        // |_array(
        // |__key1 => scal1, key2 => scal2, ...
        // |__key3 =>
        // |___array(
        // |____key1 => scal1, ...
        // |___),
        // |__key4 => scal4, ...
        // |_)

          static $indent = '';

        $oldindent = $indent;
        $indent   .= '  ';
        $sep = '';

        $str = $indent."array(\n";
        $last_is_array = false;
        $k = 0;

        reset($tab);

        while (list($key, $val) = each($tab)) {
            // The separator treatment
            if (($last_is_array) || (is_array($val) && ($k !== 0))) {
                $str .= $sep."\n";
            } else {
                $str .= $sep;
            }

            // The key treatment
            if (preg_match(':^[0-9]+$:', $key)) {
                if ($key !== $k) {
                    $str .= (((is_array($val)) || ($k === 0) || ($last_is_array)) ? "$indent  " : '')
                       ."$key =>".((is_array($val)) ? "\n" : ' ');
                } else {
                    $str .= ($k === 0) ? (is_array($val) ? '' : "$indent  ") : '';
                }
            } else {
                $str .= (((is_array($val)) || ($k === 0) || ($last_is_array)) ? "$indent  " : '')
                     ."\"$key\" =>".((is_array($val)) ? "\n" : ' ');
            }

            // The value treatment
            $last_is_array = false;
            if (is_array($val)) {
                $str .= self::array_to_str($val);
                $last_is_array = true;
                $sep = ',';
            } else {
                $str .= (preg_match(':^[0-9]+$:', $val) ? $val : "\"$val\"");
                $sep = ', ';
            }
            ++$k;
        }
        $str .= "\n$indent)";
        $indent = $oldindent;

        return $str;
    }
    public static function removeCSS($css, $modules)
    {
        $arr = array();
        $arr = array_merge($arr, $css);
        if (sizeof($modules) == 0) {
            return $arr;
        }
        for ($i = 0; $i < sizeof($css);++$i) {
            $cs = $css[$i];
            $selector = $cs['selector'];
            $flag = false;
            foreach ($modules as $m) {
                $sp = strpos($selector, $m);
                if ($sp !== false) {
                    $flag = true;
                    break;
                }
            }
            if ($flag === true) {
                unset($arr[$i]);
            }
        }

        return $arr;
    }
    public static function parseSkinHtml($html)
    {
        $rs = array();
        if (!isset($html)) {
            return $rs;
        }
        $blocks = explode('}', $html);
        $len = sizeof($blocks);
        for ($i = 0; $i < $len; ++$i) {
            $pair = explode('{', $blocks[$i]);
            if (sizeof($pair) < 2) {
                continue;
            }
            $r = array();
            $label = trim($pair[0]);
            $r['label'] = Yii::app()->lang->term($label);
            $r['controls'] = self::parseSkinHtmlBlock($pair[1]);
            $rs[] = $r;
        }

        return $rs;
    }
    private static function parseSkinHtmlBlock($html)
    {
        $rs = array();
        $declarations = explode(';', $html);
        $len = sizeof($declarations);
        for ($i = 0; $i < $len; ++$i) {
            $loc = strpos($declarations[$i], ':');
            $property = trim(substr($declarations[$i], 0, $loc));
            $value = trim(substr($declarations[$i], $loc + 1));
            if ($property != '' && $value != '') {
                $rs[$property] = $value;
            }
        }

        return $rs;
    }
	public static function ar_toObject($ar)
    {
        $record = $ar->attributes;
        $relations = $ar->relations();
        foreach ($relations as $name => $relation) {
			
            if (isset($ar->$name)) {
                $relationValue = $ar->$name;
                if (is_array($relationValue)) {
                    $record[$name] = array();
                    foreach ($relationValue as $v) {
                        $record[$name][] = $v->attributes;
                    }
                } elseif (isset($relationValue->attributes)) {
                    $record[$name] = $relationValue->attributes;
                }
				else
					$record[$name] = $relationValue;	
            }
        }

        return $record;
    }
	
}
