<?php
/*======================================================================*\
|| #################################################################### ||
|| # Country Flags for XenForo                                        # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright © 2015 Snog. All Rights Reserved.                      # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| #                     http://snogssite.com                         # ||
|| #################################################################### ||
\*======================================================================*/

class Snog_CountryFlags_Install
{
	public static function install($installedAddon)
	{
		if(!function_exists('bcadd'))
		{
			throw new XenForo_Exception('BC Math is either not installed on your server or PHP is not compiled with it enabled.', true);
		}

		if(!function_exists('curl_init'))
		{
			throw new XenForo_Exception('cURL is either not installed on your server or is not configured for use with PHP.', true);
		}

		if(!function_exists('gzopen'))
		{
			throw new XenForo_Exception('Gzip is either not installed on your server or is not configured for use with PHP.', true);
		}

		$folderpath = XenForo_Helper_File::getExternalDataPath() . DIRECTORY_SEPARATOR . 'countryflags';

		if (!is_dir($folderpath))
		{
			throw new XenForo_Exception('The data/countryflags folder does not exist. Be sure you uploaded all of the files to their proper locations.', true);
		}

		if (!is_writable($folderpath))
		{
			throw new XenForo_Exception('The data/countryflags folder is not able to be written to. Change the permissions to world writable (777)', true);
		}

		// JUST A TEST TO BE SURE cURL CAN CONNECT TO THE OUTSIDE WORLD - NOTHING MORE THAN THAT
		$url = 'http://google.com';
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_exec($ch);
		$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if($retcode !== 0)
		{
			if (!self::checkExist('xf_user','snog_flag'))
			{
				$db = XenForo_Application::get('db');
				$db->query("ALTER TABLE `xf_user` 
					ADD `snog_flag` varchar(3) NOT NULL DEFAULT '' COLLATE utf8_general_ci");
			}

			if (!self::checkExist('xf_user_privacy','snog_flag_view'))
			{
				$db = XenForo_Application::get('db');
				$db->query("ALTER TABLE `xf_user_privacy` 
					ADD `snog_flag_view` enum('everyone','members','none') NOT NULL default 'everyone' COLLATE utf8_general_ci");
			}

			// COUNTRY FIELD DROPPED IN VERSION 1.2.2
			if (self::checkExist('xf_user','snog_country'))
			{
				$db = XenForo_Application::get('db');
				$db->query("ALTER TABLE `xf_user` DROP `snog_country`");
			}

			$patha = realpath(__DIR__);
			$path = $folderpath . DIRECTORY_SEPARATOR . 'GeoLite2-Country.mmdb.gz';
			$pathf = str_ireplace('.gz','',$path);
			$ch = curl_init ('http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz');
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
			$raw=curl_exec($ch);
			if(!curl_errno($ch))
			{
				$fp = fopen($path,'w');
				fwrite($fp, $raw);
				fclose($fp);
				sleep(2);
				$buffer = 4096;
				$zip = gzopen($path, 'rb');

				if($zip !== false)
				{
					$fp = fopen($pathf, 'wb'); 

					while(!gzeof($zip))
					{
						fwrite($fp, gzread($zip, $buffer));
					}  

					fclose($fp);
					gzclose($zip);
					unlink($path);
					curl_close ($ch);
				}else{
					curl_close ($ch);
					throw new XenForo_Exception('Error downloading and extracting GeoLite2 database.', true);
				}
			}else{
				curl_close ($ch);
				throw new XenForo_Exception('Error downloading and extracting GeoLite2 database.', true);
			}
		}else{
			throw new XenForo_Exception('cURL in not able to connect to the outside world. Check your server configuration.', true);
		}
	}
	
	public static function uninstall()
	{
		$db = XenForo_Application::get('db');
		$db->query("ALTER TABLE `xf_user` DROP `snog_flag`");
		$db->query("ALTER TABLE `xf_user_privacy` DROP `snog_flag_view`");
	}

	public static function checkExist($table, $field)
	{
		$db = XenForo_Application::get('db');
		if ($db->fetchRow('SHOW columns FROM `' . $table . '` WHERE Field = ?', $field)) {
			return true;
		}else{
			return false;
		}
	}
}