<?php
class Helper {
	public static function formatLanguage($lang_id, $encode = true) {
		$languages = Yii::app()->params["languages"];
		$lang = isset($languages[$lang_id]) ? $languages[$lang_id] . " (". $lang_id .")" : $lang_id;
		return $encode ? CHtml::encode($lang) : $lang;
	}

	public static function getLastElement(array $array, $diff = 1) {
		if (count($array) < $diff)
			return null;
		$keys = array_keys($array);
		return $array[$keys[count($keys) - $diff]];
	}

	public static function slug($text, $default = null) {
		$text = preg_replace('~[^\\pL\d]+~ui', '-', $text);
		$text = trim($text, '-');
		$text = mb_strtolower($text);
		if (empty($text)) {
			return $default;
		}
		return $text;
	}

	public static function proportion ($total, $num) {
		return $total > 0 ? round($num * 100 / $total, 2) : 0;
	}

	public static function generateRandomString($length = 12) {
		return substr(str_shuffle(sha1(uniqid().microtime(true))), 0, $length);
	}

	public static function getInstalledUrl() {
		return preg_replace("(https?://)", "", Yii::app() -> getBaseUrl(true));
	}

	public static function mb_ucfirst($string) {
		$first = mb_strtoupper(mb_substr($string, 0, 1));
		$second = mb_substr($string, 1);
		return $first . $second;
	}

	public static function cropText($text, $length, $separator = '...') {
		return mb_strlen($text) > $length ? mb_substr($text, 0, $length). $separator : $text;
	}

    /*
     * thelonglongdomain.com -> thelong...ain.com
     */
    public static function cropDomain($domain, $length=24, $separator='...') {
        if(mb_strlen($domain)<$length) {
            return $domain;
        }
        $sepLength=mb_strlen($separator);
        $backLen=6;
        $availableLen=$length-$sepLength-$backLen; // 20-3-6=11
        $firstPart=mb_substr($domain, 0, $availableLen);
        $lastPart=mb_substr($domain, -$backLen);
        return $firstPart.$separator.$lastPart;
    }

	public static function _v($a, $k, $d = null) {
		return isset($a[$k]) ? $a[$k] : $d;
	}

	public static function curl($url) {
		$ch = curl_init($url);
		$html = self::curl_exec($ch);
		curl_close($ch);
		return $html;
	}

	public static function curl_exec($ch, &$maxredirect = null) {
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);

			$user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5)".
					" Gecko/20041107 Firefox/1.0";
			curl_setopt($ch, CURLOPT_USERAGENT, $user_agent );

			$mr = $maxredirect === null ? 5 : intval($maxredirect);
			if (ini_get('open_basedir') == '' && (ini_get('safe_mode') == 'Off' || ini_get('safe_mode')=='')) {
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
					curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
			} else {
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
					if ($mr > 0)
					{
							$original_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
							$newurl = $original_url;

							$rch = curl_copy_handle($ch);

							curl_setopt($rch, CURLOPT_HEADER, true);
							curl_setopt($rch, CURLOPT_NOBODY, true);
							curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
							curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
							do
							{
									curl_setopt($rch, CURLOPT_URL, $newurl);
									$header = curl_exec($rch);
									if (curl_errno($rch)) {
											$code = 0;
									} else {
											$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
											if ($code == 301 || $code == 302) {
													preg_match('/Location:(.*?)\n/i', $header, $matches);
													$newurl = trim(array_pop($matches));
													// if no scheme is present then the new url is a
													// relative path and thus needs some extra care
													if(!preg_match("/^https?:/i", $newurl)){
															$newurl = $original_url . $newurl;
													}
											} else {
													$code = 0;
											}
									}
							} while ($code && --$mr);

							curl_close($rch);

							if (!$mr)
							{
									if ($maxredirect === null)
											return false;
									else
											$maxredirect = 0;

									return false;
							}
							curl_setopt($ch, CURLOPT_URL, $newurl);
					}
			}
			return curl_exec($ch);
	}

	public static function time_elapsed_string($datetime, $full = false) {
		$now = new DateTime;
		$ago = new DateTime($datetime);
		$diff = $now->diff($ago);
		if (isset($diff)) {
			$string = array(
			'y' => array(
				"one"=>"{One} year ago",
				"many"=>"{Many} years ago",
			),
			'm' => array(
				"one"=>"{One} month ago",
				"many"=>"{Many} months ago",
			),
			'd' => array(
				"one"=>"{One} day ago",
				"many"=>"{Many} days ago",
			),
			'h' => array(
				"one"=>"{One} hour ago",
				"many"=>"{Many} hours ago",
			),
			'i' => array(
				"one"=>"{One} minute ago",
				"many"=>"{Many} minutes ago",
			),
		);
		foreach ($string as $k => &$v) {
			if ($diff->$k) {
				//$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
				if($diff->$k > 1) {
					$v=Yii::t("post", $v['many'], array(
						"{Many}"=>$diff->$k
					));
				} else {
					$v=Yii::t("post", $v['one'], array(
						"{One}"=>$diff->$k
					));
				}
			} else {
				unset($string[$k]);
			}
		}
		if (!$full)
			$string = array_slice($string, 0, 1);
		return $string ? implode(', ', $string) : Yii::t("post", 'Just now');
		} else {
			return 0;
		}
	}

    public static function f($number, $decimal=0) {
        return number_format($number, $decimal, ',', '.');
    }
    public static function p($number) {
			return strtr(Yii::app()->params['pricePattern'], array(
				'{currency}'=>Yii::app()->params['currency'],
				'{price}'=>self::f($number, 2),
			));
    }

    public static function getFlagUrl($country_code) {
        $country=ECountryList::getInstance(Yii::app()->language);
        $country_code=strtolower($country_code);
        if($country_code=='uk') {
            $country_code='gb';
        }
        $flag_path=Yii::app()->basePath.'/../images/flags/'.$country_code.'.png';
        if(file_exists($flag_path)) {
            $src=Yii::app() -> getBaseUrl(true).'/images/flags/'.$country_code.'.png';
            return CHtml::image($src, $country->getCountryName($country_code), array(
							"alt"=>Helper::mb_ucfirst($country->getCountryName($country_code)),
            ));
        } else {
            return null;
        }
    }

    public static function alexaSpeed($num) {
        if($num==0) { return null; }
        if($num < 50) {
            return Yii::t("website", "{Percent} of sites are faster", array(
                "{Percent}"=>100-$num."%",
            ));
        } else {
            return Yii::t("website", "{Percent} of sites are slower", array(
                "{Percent}"=>$num."%",
            ));
        }
    }

		public static $brandUrl=null;
    public static function getBrandUrl() {
				if(empty(self::$brandUrl)) {
					self::$brandUrl=ucfirst(self::getInstalledUrl());
				}
        return self::$brandUrl;
    }

    public static function trimDomain($domain) {
			$domain=trim($domain);
			$domain=trim($domain, "/");
			$domain=mb_strtolower($domain);
			$domain = preg_replace("#^(https?://)#i", "", $domain);
			$domain = preg_replace("#^www\.#i", "", $domain);
			return $domain;
    }

    public static function checkDoFollowLink($domain) {
			Yii::import("application.library.LinkFinder");
			$finder = new LinkFinder();
			$finder->setUrl('http://'.$domain);
			$finder->setLike(true);
			$finder->setHref(self::getInstalledUrl());
			return $finder->exists();
    }

		public static function getSummaryText($pgNr, $total, $perPage) {
			$start=($pgNr-1)*$perPage+1;
			$end=$start+$perPage-1;
			if($end>$total) {
				$end=$total;
				$start=$end-$total+1;
			}
			return $total == "0" ? Yii::t("misc", "Nothing found") : Yii::t('misc','Displaying {start}-{end} of {count} results.', array(
				'{start}'=>$start,
				'{end}'=>$end,
				'{count}'=>$total,
			));
		}

		public static function highlightWordPart($str, $keyword) {
			$pattern="#\p{L}*?".preg_quote($keyword, "#")."\p{L}*#ui";
			return preg_replace($pattern, '<span class="highlight">$0</span>', $str);
		}
}