<?php
/**
* LayerSlider v5.1.2 - Responsive Slideshow Module http://layerslider.webshopworks.com
*
*  @author    WebshopWorks <info@webshopworks.com>
*  @copyright 2015 WebshopWorks
*  @license   One Domain Licence
*/

if (!defined('_PS_VERSION_'))
	exit;

define('LS_INCLUDE', 1);
define('LS_PLUGIN_VERSION', '5.1.2');
define('LS_ROOT_PATH', _PS_MODULE_DIR_.'layerslider/base/');
define('LS_CSS_PATH', _PS_MODULE_DIR_.'layerslider/views/css/base/');
define('LS_IMG_PATH', _PS_MODULE_DIR_.'layerslider/views/img/base/');
define('LS_JS_PATH', _PS_MODULE_DIR_.'layerslider/views/js/base/');
define('LS_ROOT_URL', __PS_BASE_URI__.'modules/layerslider/base/' );

class Sdb
{
	public static function update($table, $data, $where)
	{
		$data = (array)$data;
		$vals = array();
		foreach ($data as $key => $val)
			$vals[] = is_string($val) ? "$key='$val'" : "$key=$val";

		return Db::getInstance()->execute('UPDATE '._DB_PREFIX_.$table.' SET '.implode(', ', $vals).' WHERE '.$where);
	}

	public static function insert($table, $data)
	{
		$data = (array)$data;
		$vals = array();
		foreach ($data as $val)
			$vals[] = is_string($val) ? "'$val'" : $val;

		return Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.$table.' ('.implode(', ', array_keys($data)).') VALUES('.implode(', ', $vals).')');
	}
}

require_once LS_ROOT_PATH.'wp/hooks.php';
require_once LS_ROOT_PATH.'classes/class.ls.sliders.php';

if (!defined('NL'))
	define('NL', "\r\n");
if (!defined('TAB'))
	define('TAB', "\t");

function get_option($option, $default = false)
{
	$option = str_replace('-', '_', $option);
	$res = Configuration::get('LAYERSLIDER_'.Tools::strtoupper($option));
	return $res === false ? $default : Tools::jsonDecode($res, true);
}

function update_option($option, $value)
{
	$option = str_replace('-', '_', $option);
	Configuration::updateValue('LAYERSLIDER_'.Tools::strtoupper($option), Tools::jsonEncode($value));
	return $value;
}

function ls_load_google_fonts()
{
	// Get font list
	$fonts = get_option('ls-google-fonts', array());

	// Check fonts if any
	if (!empty($fonts) && is_array($fonts))
	{
		$ls_fonts = array();
		foreach ($fonts as $item)
		{
			if (!$item['admin'])
				$ls_fonts[] = $item['param'];
			else
				$ls_fonts[] = $item['param'];
		}
		$ls_fonts = implode('|', $ls_fonts);

		$query_args = array(
			'family' => $ls_fonts,
			'subset' => 'latin,latin-ext',
		);

		return 'https://fonts.googleapis.com/css?family='.$query_args['family'].'&subset='.$query_args['subset'];
	}
}

if (!function_exists('__'))
{
	function __($a, $b)
	{
		return $a;
	}
}

if (!function_exists('_e'))
{
	function _e($a, $b)
	{
		echo $a;
	}
}

function wp_nonce_url($actionurl, $action = -1, $name = '_wpnonce')
{
	$actionurl = str_replace( '&amp;', '&', $actionurl );
	return $actionurl;
}

function wp_nonce_field($action = -1, $name = '_wpnonce', $referer = true, $echo = true)
{
	$name = htmlspecialchars($name);
	$nonce_field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.$action.'" />';

	if ($echo)
		echo $nonce_field;

	return $nonce_field;
}

define('MINUTE_IN_SECONDS', 60);
define('HOUR_IN_SECONDS', 60 * MINUTE_IN_SECONDS);
define('DAY_IN_SECONDS', 24 * HOUR_IN_SECONDS);
define('WEEK_IN_SECONDS', 7 * DAY_IN_SECONDS);
define('YEAR_IN_SECONDS', 365 * DAY_IN_SECONDS);

function _n($single, $plural, $number, $domain = 'default')
{
	return $number > 1 ? $plural : $single;
}

function human_time_diff($from, $to = '')
{
	if (empty($to))
		$to = time();

	$diff = (int)abs($to - $from);

	if ($diff < HOUR_IN_SECONDS)
	{
		$mins = round($diff / MINUTE_IN_SECONDS);
		if ($mins <= 1)
			$mins = 1;
		$since = sprintf(_n('%s min', '%s mins', $mins), $mins);
	}
	elseif ($diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS)
	{
		$hours = round($diff / HOUR_IN_SECONDS);
		if ($hours <= 1)
			$hours = 1;
		$since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
	}
	elseif ($diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS)
	{
		$days = round($diff / DAY_IN_SECONDS);
		if ($days <= 1)
			$days = 1;
		$since = sprintf(_n('%s day', '%s days', $days), $days);
	}
	elseif ($diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS)
	{
		$weeks = round($diff / WEEK_IN_SECONDS);
		if ($weeks <= 1)
			$weeks = 1;
		$since = sprintf(_n('%s week', '%s weeks', $weeks), $weeks);
	}
	elseif ($diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS)
	{
		$months = round($diff / (30 * DAY_IN_SECONDS));
		if ($months <= 1)
			$months = 1;
		$since = sprintf(_n('%s month', '%s months', $months), $months);
	}
	elseif ($diff >= YEAR_IN_SECONDS)
	{
		$years = round($diff / YEAR_IN_SECONDS);
		if ($years <= 1)
			$years = 1;
		$since = sprintf(_n('%s year', '%s years', $years), $years);
	}

	return $since;
}

function is_multisite()
{
	return false;
}

function get_user_meta()
{
	return false;
}
function add_user_meta()
{
	return false;
}

class LSScreen
{
	public static $tabs = array();
	public $base = '';

	public function __construct($view)
	{
		$view = Tools::strtolower($view);
		switch ($view)
		{
			case 'adminlayerslideredit':
				$this->base = 'edit';
				break;
			case 'adminlayerslider':
				$this->base = 'layerslider';
				break;
			case 'adminlayerslidertransition':
				$this->base = 'ls-transition-builder';
				break;
			case 'adminlayersliderskin':
				$this->base = 'ls-skin-editor';
				break;
			case 'adminlayersliderstyle':
				$this->base = 'ls-style-editor';
				break;
		}
	}

	public function add_help_tab($tab)
	{
		self::$tabs[] = $tab;
	}

	public static function addHelp()
	{
		require_once LS_ROOT_PATH.'wp/help.php'; ?>
		<div class="metabox-prefs" id="screen-meta">
			<div class="no-sidebar" id="contextual-help-wrap" style="display:none">
				<div id="contextual-help-back"></div>
				<div id="contextual-help-columns">
					<div class="contextual-help-tabs">
						<ul>
						<?php foreach (self::$tabs as $tab)
						{?>
							<li id="tab-link-<?php echo $tab['id'] ?>">
								<a href="#tab-panel-<?php echo $tab['id'] ?>"><?php echo $tab['title'] ?></a>
							</li>
						<?php
						}?>
						</ul>
					</div>
					<div class="contextual-help-tabs-wrap">
					<?php foreach (self::$tabs as $tab)
					{?>
						<div class="help-tab-content" id="tab-panel-<?php echo $tab['id'] ?>">
							<?php echo $tab['content'] ?>
						</div>
					<?php
					}?>
					</div>
				</div>
			</div>
		</div>
		<div id="screen-meta-links">
			<div class="screen-meta-toggle" id="contextual-help-link-wrap">
				<a class="show-settings screen-meta-active" id="contextual-help-link" href="#contextual-help-wrap">Help</a>
			</div>
		</div>
		<?php
	}
}

function add_filter($filter, $func)
{
	switch ($filter)
	{
		case 'contextual_help':
			$screen = new LSScreen(Tools::getValue('controller'));
			call_user_func($func, 0, 0, $screen);
			break;
	}
}
function has_filter()
{
	return false;
}
function get_categories()
{
	return false;
}
function get_tags()
{
	return false;
}
function get_taxonomies()
{
	return false;
}
function wp_upload_dir()
{
	return array(
		'basedir' => _PS_IMG_DIR_,
		'baseurl' => _PS_IMG_
	);
}

function get_allowed_mime_types()
{
	return array(
		'jpg|jpeg|jpe' => 'image/jpeg',
		'gif' => 'image/gif',
		'png' => 'image/png',
		'bmp' => 'image/bmp',
		'tif|tiff' => 'image/tiff',
		'ico' => 'image/x-icon',
		'asf|asx' => 'video/x-ms-asf',
		'wmv' => 'video/x-ms-wmv',
		'wmx' => 'video/x-ms-wmx',
		'wm' => 'video/x-ms-wm',
		'avi' => 'video/avi',
		'divx' => 'video/divx',
		'flv' => 'video/x-flv',
		'mov|qt' => 'video/quicktime',
		'mpeg|mpg|mpe' => 'video/mpeg',
		'mp4|m4v' => 'video/mp4',
		'ogv' => 'video/ogg',
		'webm' => 'video/webm',
		'mkv' => 'video/x-matroska',
		'txt|asc|c|cc|h' => 'text/plain',
		'csv' => 'text/csv',
		'tsv' => 'text/tab-separated-values',
		'ics' => 'text/calendar',
		'rtx' => 'text/richtext',
		'css' => 'text/css',
		'htm|html' => 'text/html',
		'mp3|m4a|m4b' => 'audio/mpeg',
		'ra|ram' => 'audio/x-realaudio',
		'wav' => 'audio/wav',
		'ogg|oga' => 'audio/ogg',
		'mid|midi' => 'audio/midi',
		'wma' => 'audio/x-ms-wma',
		'wax' => 'audio/x-ms-wax',
		'mka' => 'audio/x-matroska',
		'rtf' => 'application/rtf',
		'js' => 'application/javascript',
		'pdf' => 'application/pdf',
		'class' => 'application/java',
		'tar' => 'application/x-tar',
		'zip' => 'application/zip',
		'gz|gzip' => 'application/x-gzip',
		'rar' => 'application/rar',
		'7z' => 'application/x-7z-compressed',
		'doc' => 'application/msword',
		'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
		'wri' => 'application/vnd.ms-write',
		'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
		'mdb' => 'application/vnd.ms-access',
		'mpp' => 'application/vnd.ms-project',
		'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
		'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
		'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
		'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
		'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
		'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
		'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
		'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
		'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
		'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
		'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
		'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
		'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
		'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
		'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
		'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
		'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
		'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
		'odt' => 'application/vnd.oasis.opendocument.text',
		'odp' => 'application/vnd.oasis.opendocument.presentation',
		'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
		'odg' => 'application/vnd.oasis.opendocument.graphics',
		'odc' => 'application/vnd.oasis.opendocument.chart',
		'odb' => 'application/vnd.oasis.opendocument.database',
		'odf' => 'application/vnd.oasis.opendocument.formula',
		'wp|wpd' => 'application/wordperfect',
		'key' => 'application/vnd.apple.keynote',
		'numbers' => 'application/vnd.apple.numbers',
		'pages' => 'application/vnd.apple.pages'
	);
}

function get_home_path()
{
	return _PS_ROOT_DIR_;
}

function layerslider_builder_convert_numbers(&$item, $key)
{
	if (is_numeric($item))
		$item = (float)$item;
}

/**
* Sanitizes a filename replacing whitespace with dashes
*
* Removes special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trim period, dash and underscore from beginning
* and end of filename.
*
* @since 2.1.0
*
* @param string $filename The filename to be sanitized
* @return string The sanitized filename
*/
function sanitize_file_name($filename)
{
	$filename_raw = $filename;
	$special_chars = array('?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', '\'', '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', chr(0));
	$special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
	$filename = str_replace($special_chars, '', $filename);
	$filename = preg_replace('/[\s-]+/', '-', $filename);
	$filename = trim($filename, '.-_');

	return $filename;
}

class Posts
{
	public function getPostTypes()
	{
		return false;
	}
}

function wp_check_filetype($filename, $mimes = null)
{
	if (empty($mimes))
		$mimes = get_allowed_mime_types();
	$type = false;
	$ext = false;
	foreach ($mimes as $ext_preg => $mime_match)
	{
		$ext_preg = '!\.('.$ext_preg.')$!i';
		if (preg_match($ext_preg, $filename, $ext_matches))
		{
			$type = $mime_match;
			$ext = $ext_matches[1];
			break;
		}
	}

	return compact( 'ext', 'type' );
}

$uploads = wp_upload_dir();
if (file_exists($uploads['basedir'].'/layerslider.custom.transitions.js'))
	Tools::addJS($uploads['baseurl'].'/layerslider.custom.transitions.js');

if (file_exists($uploads['basedir'].'/layerslider.custom.css'))
	Tools::addCSS($uploads['baseurl'].'/layerslider.custom.css');

function base64_url_encode($input)
{
	return strtr(call_user_func('base64_encode', $input), '+/=', '-_,');
}

function layerslider_check_unit($str)
{
	if (strstr($str, 'px') == false && strstr($str, '%') == false)
		return $str.'px';
	else
		return $str;
}

function layerslider_convert_urls($arr)
{
	// Layer BG
	if (strpos($arr['properties']['background'], 'http://') !== false)
		$arr['properties']['background'] = parse_url($arr['properties']['background'], PHP_URL_PATH);

	// Layer Thumb
	if (strpos($arr['properties']['thumbnail'], 'http://') !== false)
		$arr['properties']['thumbnail'] = parse_url($arr['properties']['thumbnail'], PHP_URL_PATH);

	// Image sublayers
	foreach ($arr['sublayers'] as $sublayerkey => $sublayer)

		if ($sublayer['type'] == 'img')
			if (strpos($sublayer['image'], 'http://') !== false)
				$arr['sublayers'][$sublayerkey]['image'] = parse_url($sublayer['image'], PHP_URL_PATH);

	return $arr;
}

function ls_get_hooks()
{
	return array(
		'' => __('- None -', 'LayerSlider'),
		'displayTop' => __('Top of pages', 'LayerSlider'),
		'displayBanner' => __('Banner', 'LayerSlider'),
		'displayNav' => __('Navigation', 'LayerSlider'),
		'displayTopColumn' => __('Top column blocks', 'LayerSlider'),
		'displayLeftColumn' => __('Left column blocks', 'LayerSlider'),
		'displayRightColumn' => __('Right column blocks', 'LayerSlider'),
		'displayFooter' => __('Footer', 'LayerSlider'),
		'displayHome' => __('Homepage content', 'LayerSlider'),
		'displayHomeTop' => __('Home Top', 'LayerSlider'),
		'displayHomeTab' => __('Home Page Tabs', 'LayerSlider'),
		'displayHomeTabContent' => __('Home Page Tabs Content', 'LayerSlider'),
		'displayHomeBottom' => __('Home Bottom', 'LayerSlider'),
		'displayHomeVeryBottom' => __('Home Very Bottom', 'LayerSlider'),
		'displayProductTab' => __('Tabs on product page', 'LayerSlider'),
		'displayProductTabContent' => __('Tabs content on the product page', 'LayerSlider'),
		'displayLeftColumnProduct' => __('New elements on the product page (left column)', 'LayerSlider'),
		'displayRightColumnProduct' => __('New elements on the product page (right column)', 'LayerSlider'),
		'displayFooterProduct' => __('Product footer', 'LayerSlider'),
		'displayStBlogHome' => __('Blog Home', 'LayerSlider'),
		'displayStBlogLeftColumn' => __('Blog Left Column', 'LayerSlider'),
		'displayStBlogRightColumn' => __('Blog Right Column', 'LayerSlider'),
		'displayAnywhere' => __('Anywhere', 'LayerSlider')
	);
}