<?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;

class LSImportUtil
{
	/**
		* The managed ZipArchieve instance.
	 */
	private $zip;

	/**
	 * Target folders
	 */
	private $target_dir, $target_url, $tmp_dir;

	private $imported = array();

	public function __construct($archive, $name = null)
	{
		if (empty($name))
			$name = $archive;

		$type = wp_check_filetype(basename($name), array('zip' => 'application/zip', 'json' => 'application/json'));

		if (!empty($type['ext']) && $type['ext'] == 'zip')
		{
			if (class_exists('ZipArchive'))
			{
				$this->zip = new ZipArchive;

				if ($this->zip->open($archive))
				{
					if ($this->unpack())
					{
						$this->id = array();
						foreach (glob($this->tmp_dir.'/*', GLOB_ONLYDIR) as $dir)
						{
							$this->imported = array();
							$this->uploadMedia($dir);

							if (file_exists($dir.'/settings.json'))
								$this->id[] = (int)$this->addSlider($dir.'/settings.json');

						}

						$this->cleanup();
						return true;
					}

					$this->zip->close();
				}
			}
			else
			{
				$context = Context::getContext();
				$context->cookie->ls_error = 'ZipArchive isn\'t available';
				Tools::redirectAdmin($context->link->getAdminLink('AdminLayerSlider'));
			}

		}
		elseif (!empty($type['ext']) && $type['ext'] == 'json')
		{
			$data = call_user_func('base64_decode', Tools::file_get_contents($archive));

			if (!$parsed = Tools::jsonDecode($data, true))
				$parsed = unserialize($data);

			if (is_array($parsed))
			{
				$this->id = array();
				foreach ($parsed as $item)
				{
					if (is_string($item))
						$item = Tools::jsonDecode($item, true);

					$this->id[0] = (int)LSSliders::add($item['properties']['title'], $item);
				}
			}
		}

		return false;
	}

	public function unpack()
	{
		$uploads = wp_upload_dir();

		if (is_writable($uploads['basedir']))
		{
			$this->target_dir = $target_dir = $uploads['basedir'].'/layerslider';
			$this->target_url = $uploads['baseurl'].'/layerslider';
			$this->tmp_dir = $tmp_dir = $uploads['basedir'].'/layerslider/tmp';

			if (!file_exists($target_dir))
				mkdir($target_dir, 0755);
			if (!file_exists($target_dir))
				mkdir($target_dir, 0755);

			if ($this->zip->extractTo($tmp_dir))
				return true;

		}

		return false;
	}

	public function uploadMedia($dir = null)
	{
		if (empty($dir) || !is_string($dir) || !file_exists($dir.'/uploads'))
			return false;

		$target_dir = $this->target_dir.'/'.basename($dir);
		if (!file_exists($target_dir))
			mkdir($target_dir, 0755);

		foreach (glob($dir.'/uploads/*') as $file_path)
		{
			$fileName = sanitize_file_name(basename($file_path));

			$target_file = $target_dir.'/'.$fileName;

			$filetype = wp_check_filetype($fileName, null);

			if (!empty($filetype['ext']) && $filetype['ext'] != 'php')
			{
				rename($file_path, $target_file);

				$this->imported[$fileName] = array('url' => $this->target_url.'/'.basename($dir).'/'.$fileName);
			}
		}

		return true;
	}

	public function deleteDir($dir_path)
	{
		if (!is_dir($dir_path))
			return false;

		if (Tools::substr($dir_path, Tools::strlen($dir_path) - 1, 1) != '/')
			$dir_path .= '/';

		$files = glob($dir_path.'*', GLOB_MARK);
		foreach ($files as $file)
		{
			if (is_dir($file))
				$this->deleteDir($file);
			else

				unlink($file);

		}
		rmdir($dir_path);
	}

	public function addSlider($file)
	{
		$data = Tools::jsonDecode(Tools::file_get_contents($file), true);
		$title = $data['properties']['title'];

		if (!empty($data['properties']['backgroundimage']))
			$data['properties']['backgroundimage'] = $this->attachURLForImage($data['properties']['backgroundimage']);

		if (!empty($data['properties']['yourlogo']))
		{
			$data['properties']['yourlogoId'] = '';
			$data['properties']['yourlogo'] = $this->attachURLForImage($data['properties']['yourlogo']);
		}

		if (!empty($data['layers']) && is_array($data['layers']))
		{
			foreach ($data['layers'] as &$slide)
			{
				if (!empty($slide['properties']['background']))
				{
					$slide['properties']['backgroundId'] = '';
					$slide['properties']['background'] = $this->attachURLForImage($slide['properties']['background']);
				}

				if (!empty($slide['properties']['thumbnail']))
				{
					$slide['properties']['thumbnailId'] = '';
					$slide['properties']['thumbnail'] = $this->attachURLForImage($slide['properties']['thumbnail']);
				}

				if (!empty($slide['sublayers']) && is_array($slide['sublayers']))
				{
					foreach ($slide['sublayers'] as &$layer)
					{
						if (!empty($layer['image']))
						{
							$layer['imageId'] = '';
							$layer['image'] = $this->attachURLForImage($layer['image']);
						}
					}
				}
			}
		}

		return LSSliders::add($title, $data);
	}

	public function attachURLForImage($file = '#')
	{
		if (isset($this->imported[basename($file)]))
			return $this->imported[basename($file)]['url'];

		return $file;
	}

	public function cleanup()
	{
		$this->deleteDir($this->tmp_dir);
	}
}

?>