<?php
/**
 * Implementation of some utilities functions
 *
 * @package Library
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * Utilities for help with XHTML forms, strings, etc..
 * 
 * @package Library
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
class Utils
{

    /**
     * Get parameters which was send to server from client as asoc. array, remove
     * elements with same key as keys in filter array
     *
     * @param array $filter hash with filtered keys
     * @return string XHTML page
     */
    public static function getHTTPParamsFiltered($filter)
    {
        $params=self::getHTTPParams();

        foreach($params as $key=>$val) {
            if (in_array($key,$filter)) continue;
            $newArr[$key]=$val; 
        }
        return isset($newArr) ? $newArr : null; 
    }  

    /**
     * get parameters which was send to server from client as asoc. array
     * @param array $filter hash with filtered keys 
     * @return array parameters
     */
    public static function getHTTPParams()
    {
        $method=isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : "";

        switch ($method) {
        case "POST" :
            return $_POST;
            break;  
        case "GET" :
            return $_GET;
            break;
        default:
            throw new Exception(__METHOD__.": unknow HTTP request method"); 
            break;
        }
    }

    /**
     * filter array elements by regular expression for key
     *
     * @param array $arr original array
     * @return array filtered array
     */
    public static function filterArrByKeyRegexp($arr,$pattern)
    {
        $retarr=array();
        foreach($arr as $key => $val) {
            if (preg_match($pattern,$key)) {
                $retarr[$key]=$val;
            }
        }
        return $retarr;
    }

    /**
     * Nice truncate the string.
     *
     * If a text length is beyond a certain $length and append with an ellipses or custom text
     * @param string $str string to truncate
     * @param int $length the number of characters allowed before truncating
     * @param $append is appended to the truncated string
     */
    public static function niceTruncate($str, $length = 40, $append = '&#8230;')
    {
        return iconv_strlen($str,'UTF-8') > $length ? trim(iconv_substr($str, 0, $length,'UTF-8')) . $append : $str;
    }

    /**
     * Remove all elements with concrete value from the array.
     *
     * Find the keys of the element with $elemVal value and remove it
     * @param arrayref $arr reference to array, from that we want to remove
     * @param mixed $elemVal a value for the removing entry
     * @param bool strict strict check for comparsion
     */
    public static function arrayRemove(array &$arr, $elemVal, $strict=false)
    {
        $keys = array_keys($arr,$elemVal,$strict);
        foreach($keys as $sKey) {
            unset($arr[$sKey]);
        }
    }

    public static function renameKey(array &$arr, $oldKey, $newKey)
    {
        if (!array_key_exists($oldKey,$arr))
            throw new Exception("key $oldkey doesn't exist in the array");

        $val=$arr[$oldKey];
        unset($arr[$oldKey]);
        $arr[$newKey]=$val;
    }

    public static function recursiveToObjectCast(array $arr)
    {
        foreach($arr as $key=>$item) {
            if (is_array($item)) $arr[$key]=self::recursiveToObjectCast($item);
        }
        return $obj=(object)$arr;
    }

    /**
     * Makes friendly like :-) URL
     * @param string $str the utf-8 encoded string, for which we want URL
     * @return string seo friendly URL
     */
    public static function friendlyUrl($str) {
        $urlIso = iconv('utf-8','iso-8859-2',$str);
        $url = self::cs_iso2ascii($urlIso);
        //doesn't work with glibc like iconv
        //$url = iconv("ISO-8859-2", "ascii//TRANSLIT", $str);
        $url = strtolower($url);
        $url = preg_replace('/[^-a-z0-9_ ]+/', '', $url);
        $url = str_replace(' ', '-', $url);
        $url = preg_replace('/-{2,}/','-',$url);
        $url = trim($url, "-");
        return $url;
    }

    /**
     * Coverts  ISO-8859-2 to ASCII for diacritic chars
     * @param string $str string in ISO-8859-2 encoding
     * @return string in ASCII encoding
     * @copyright Copyright David Grundl http://latrine.cz
     */
    public static function cs_iso2ascii($s)
    {
        return strtr($s,
            "\xe1\xe4\xe8\xef\xe9\xec\xed\xb5\xe5\xf2\xf3\xf6\xf5\xf4\xf8\xe0\xb9\xbb\xfa\xf9\xfc\xfb\xfd\xbe\xc1\xc4\xc8\xcf\xc9\xcc\xcd\xa5\xc5\xd2\xd3\xd6\xd5\xd4\xd8\xc0\xa9\xab\xda\xd9\xdc\xdb\xdd\xae",
            "aacdeeillnoooorrstuuuuyzAACDEEILLNOOOORRSTUUUUYZ"
        );
    }

    /**
     * Gets non-validated messages from the input filter as the array with strings for every input
     * index.
     * Can be simple used with FlashMessenger
     * @param Zend_Filter_Input $input
     * @return array
     */
    public static function getMessagesOneArray($input)
    {
        $messages=array();
        $valMessages=$input->getMessages();
        foreach($valMessages as $dataName=>$msgArr) {
            $oneMsg=$dataName . ": ";
            foreach($msgArr as $msg) $oneMsg.=$msg ." ";
            $messages[] = trim($oneMsg);
        }
        return $messages;
    }

    /**
     * Returns month name for a specific month number. It fices behavior for
     * cs_CZ, when we need "Leden" which is in the stand-alone tree instead of
     * "Ledna" which is in format tree.
     *
     * @param int $monthNum month number (1-12)
     * @param Zend_Locale $locale    
     */
    public static function getMonthFirstCaseName($monthNum,Zend_Locale $locale)
    {
        if ($locale->getLanguage() == "cs") {
            $list = Zend_Locale::getTranslationList("Month",$locale,array('gregorian', 'stand-alone', 'wide'));
        } else {
            $list = Zend_Locale::getTranslationList("Month",$locale,array('gregorian', 'format', 'wide'));
        }

        if (isset($list[$monthNum])) {
            return $list[$monthNum];
        }

        throw new Exception("unknow month name for month number: $monthNum");
    }

    /**
     * Filters empty element from the array.
     * @param arrayref arr
     */
    public static function arrayFilterEmpty(&$arr)
    {
        foreach($arr as $key=>$val) {
            if (empty($val)) unset($arr[$key]);
        }
    }

}
