<?php
defined('BASEPATH') OR exit('No direct script access allowed');

function truncate($string,$length)  {
	$string = trim(strip_tags($string));
	if (strlen($string) > $length) {
		$string = substr($string,0,$length).'...';
	}
	return $string;
}

function clearString($data) {
    $data = stripslashes(trim($data));
	$data = strip_tags($data);
	$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
	return $data;
}

function xssClean($data) {
	$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
	return $data;
}

function isAlphaSpaces($val) {
	return (bool) preg_match("/^([a-zA-Z ])+$/i", $val);
}

function isAlpha($val) {
	return (bool) preg_match("/^([a-zA-Z])+$/i", $val);
}

function isAlphaNumSpaces($val) {
	return (bool) preg_match("/^([a-zA-Z0-9 ])+$/i", $val);
}

function isAlphaNum($val) {
	return (bool) preg_match("/^([a-zA-Z0-9])+$/i", $val);
}

function validEmail($email) {
	return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? true : false;	
}

function pageUrl() {
	return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

function getDomain($url) {
	if(preg_match("#https?://#", $url) === 0) {
		$url = 'http://' . $url;
	}
	return strtolower(str_ireplace('www.', '', parse_url($url, PHP_URL_HOST)));
}

function getDomainName($url) {
	$url = (preg_match("#https?://#", $url) === 0 ? 'http://' . $url : $url);
	$host = strtolower(str_ireplace('www.', '', parse_url($url, PHP_URL_HOST)));
	$hostArr = explode(".",$host);
	$count = count($hostArr);
	if($count >= 3) {
		return $hostArr[1];
	}
	return $hostArr[0];
}

function formatSizeUnits($bytes) {
	if ($bytes >= 1073741824) {
		$bytes = number_format($bytes / 1073741824, 2) . ' GB';
	}
	elseif ($bytes >= 1048576) {
		$bytes = number_format($bytes / 1048576, 2) . ' MB';
	}
	elseif ($bytes >= 1024) {
		$bytes = number_format($bytes / 1024, 2) . ' KB';
	}
	elseif ($bytes > 1)	{
		$bytes = $bytes . ' bytes';
	}
	elseif ($bytes == 1) {
		$bytes = $bytes . ' byte';
	}
	else {
		$bytes = '0 bytes';
	}
	return $bytes;
}

function getRemoteContents($url) {
	$result = false;
	if(extension_loaded('curl') === true) {
		$USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, $USER_AGENT);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_URL, $url);
		$result = curl_exec($ch);
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		unset($ch);	
	}
	return $result;
}

function getStringBetween($string,$start,$end) {
	$string = " " . $string;
	$ini = strpos($string, $start);
	$eni = strpos($string, $end);
	if ($ini == 0 || $eni == 0) return "";
	$ini+= strlen($start);
	$len = strpos($string, $end, $ini) - $ini;
	return substr($string, $ini, $len);
}

function replace_between($str, $needle_start, $needle_end, $replacement) {
    $pos = strpos($str, $needle_start);
    $start = $pos === false ? 0 : $pos + strlen($needle_start);

    $pos = strpos($str, $needle_end, $start);
    $end = $pos === false ? strlen($str) : $pos;

    return substr_replace($str, $replacement, $start, $end - $start);
}

function replaceSourceJson($string, $replace)
{
    $search = "/[^{source_info}](.*)[^{\/end_source_info}]/";
    
    return preg_replace($search,$replace,$string);
}

function getIpAddress() {
	switch(true) {
		case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
		case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
		case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
		default : return $_SERVER['REMOTE_ADDR'];
    }
}

function httpsStatus() {
	if(isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') {
		return true;
	}
	else if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
		return true;
	}
	else if(isset($_SERVER['HTTP_FRONT_END_HTTPS']) && $_SERVER['HTTP_FRONT_END_HTTPS'] === 'on') {
		return true;
	}
	else if(isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https') {
		return true;
	}
	return false;
}

function generatePermalink($entry)  {
	$permalink = strtolower(strip_tags($entry));
	if (!mb_check_encoding($permalink, "UTF-8")) {
		$permalink = preg_replace('/[^a-z0-9]/i', ' ', $permalink);
		$permalink = trim(preg_replace("/[[:blank:]]+/", " ", $permalink));
		$permalink = strtolower(str_replace(" ", "-", $permalink));	
	}
	else {
		$permalink = trim($entry);
		$permalink = str_replace(" ", "-", $permalink);
	}
	$permalink = cleanPermalink($permalink);
	return strtolower($permalink);
}

function cleanPermalink($permalink)  {
	$to_clean  = array("#","%","&","$","*","{","}","(",")","@","^","|","/",";",".",",","`","!","\\",":","<",">","?","/","+",'"',"'");
	$permalink = str_replace(" ", "-", $permalink);
	foreach ($to_clean as $symbol) {
		$permalink = str_replace($symbol, "", $permalink);
	}
	while (strpos($permalink, '--') != false) {
		$permalink = str_replace("--", "-", $permalink);
	}
	$permalink = rtrim($permalink, "-");
	$permalink = ltrim($permalink, "-");
	if ($permalink != "-") {
		return $permalink;
	}
	else {
		return "";
	}
}

function showLanguageVar($languageValues,$index,$strongTag = false) {
	if(isset($languageValues[$index])) {
		$value = $languageValues[$index];
		if($strongTag == true) {
			$value = str_replace("*{*","<strong>",$value);
			$value = str_replace("*}*","</strong>",$value);
		}
		return $value;
	}
	return null;
}

function get_all_sources()
{
    $sources = array();
    
    
    $lib_path = APPPATH . "libraries/";            
    $files = scandir($lib_path);
    
    $ignore_files = array(".", "..", "index.html", "sources");
    foreach($files as $file)
    {
        if(in_array($file, $ignore_files)) continue;

        $content      = file_get_contents($lib_path . $file);
        $json         = getStringBetween($content, "{source_info}", "{end_source_info}");
        $source_info  = json_decode($json, TRUE);

        
        $file_name_parts = explode(".", $file);
        
        $json_path = APPPATH . "libraries/sources/".$file_name_parts[0].".json";
       
        if(file_exists($json_path))
        {
            $content = file_get_contents($json_path);        
            $source_json  = json_decode($content, TRUE);
            $source_info = array_merge($source_info, $source_json);
        }
        else
        {
            $default_data = array("order" => "1", "icon" => ( strtolower($file_name_parts[0]) . ".png") , "status" => "1", "linkCacheTime" => "3600" );
            file_put_contents($json_path, json_encode($default_data));
            $source_info = array_merge($source_info, $default_data);
        }       
         
        $sources[$file_name_parts[0]] = $source_info;                 
    }       
    
    $sources = array_sort($sources, "order");   
    return $sources;
}

function get_source_info($source_name)
{
    $source_info = array();
    
    $lib_path = APPPATH . "libraries/" . ucfirst($source_name).".php";   
    
    if(file_exists($lib_path))
    {
        $content      = file_get_contents($lib_path);
        $json         = getStringBetween($content, "{source_info}", "{end_source_info}");
        
        $source_info  = json_decode($json, TRUE);
        
        $json_path     = APPPATH . "libraries/sources/" . ucfirst($source_name).".json";
    
        if(file_exists($json_path))
        {
            $content      = file_get_contents($json_path);        
            $json_info  = json_decode($content, TRUE);
            $source_info = array_merge($source_info, $json_info);
        }        
    }
    
    return $source_info;   
}

function update_source_info($source_name, $data)
{
    $lib_path     = APPPATH . "libraries/sources/" . ucfirst($source_name) .".json";   
    
    if(file_exists($lib_path))
    {
        $content      = file_get_contents($lib_path);        
        $source_info  = json_decode($content, TRUE);

        $source_info = array_merge($source_info, $data);        
        file_put_contents($lib_path, json_encode($source_info));

        return 1;
    } 
    else 
    {
        return 0;
    }    
}

function array_sort($array, $on, $order=SORT_ASC){

    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
                break;
            case SORT_DESC:
                arsort($sortable_array);
                break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

function get_final_domain_name($domain)
{
    $domain = strtolower($domain);
    
    if($domain == "break") $domain = "Breakvid";
    if($domain == "9gag") $domain = "Ninegag";
    
    return $domain;
}

function call_curl_req($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_exec($ch);
    $filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);    
    curl_close($ch);
    return $filesize;
}