<?php
/**
 * CSVI General helper
 *
 * @package 	CSVIVirtueMart
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: csvi.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * Helper class for the component
 * @package CSVIVirtueMart
 */
class CsviHelper {

	/**
	 * Combine 2 arrays and update existing values
	 *
	 * @copyright
	 * @author 		Amund
	 * @todo
	 * @see 		http://www.php.net/manual/en/function.array-merge.php#95294
	 * @access 		private
	 * @param 		array	$a	The array to update
	 * @param		array	$b	The array with new values
	 * @return 		array	combined array with all values
	 * @since 		3.0
	 */
	public function arrayExtend($a, $b) {
		foreach($b as $k=>$v) {
			if( is_array($v) ) {
				if( !isset($a[$k]) ) {
					$a[$k] = $v;
				} else {
					$a[$k] = self::arrayExtend($a[$k], $v);
				}
			} else {
				$a[$k] = $v;
			}
		}
		return $a;
	}

	/**
	 * Recursive array diff
	 *
	 * @copyright
	 * @author 		Amund, RolandD
	 * @todo
	 * @see 		http://www.php.net/manual/en/function.array-merge.php#91756
	 * @access 		private
	 * @param 		array	$aArray1	The array to update
	 * @param		array	$aArray2	The array with new values
	 * @return 		array	with all new values
	 * @since 		3.0
	 */
	public function recurseArrayDiff($aArray1, $aArray2) {
		$aReturn = array();
		if (is_array($aArray1) && is_array($aArray2)) {
			foreach ($aArray1 as $mKey => $mValue) {
				if (array_key_exists($mKey, $aArray2)) {
					if (is_array($mValue)) {
						$aRecursiveDiff = self::recurseArrayDiff($mValue, $aArray2[$mKey]);
						if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
					}
					else {
						if ($mValue != $aArray2[$mKey]) $aReturn[$mKey] = $mValue;
					}
				}
				else {
					$aReturn[$mKey] = $mValue;
				}
			}
		}
		return $aReturn;
	}

	/**
	 * Perform replacement on a value
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param 		int		$id		the id of the field to replace
	 * @param		string	$value	the text to replace
	 * @param		string	$type	whether to do and import or export replacement
	 * @return 		string	the replaced text
	 * @since 		3.0
	 */
	public function replaceValue($name, $value) {
		$template = JRequest::getVar('template');
		$fields = $template->getValue($name, 'replacement_fields', array());
		if (empty($fields)) return $value;
		else {
			// Perform the regular replacement
			if (array_key_exists('findtext', $fields)) {
				$fieldvalue = str_ireplace($fields['findtext'], $fields['replacetext'], $value);
			}
			else $fieldvalue = $value;

			// Peform the regex replacement
			if (array_key_exists('findregex', $fields)) {
				$fieldvalue = preg_replace($fields['findregex'], $fields['replaceregex'], $fieldvalue);
			}

			// All done return the value
			return $fieldvalue;
		}
	}

	/**
	 * Determine the shipping cost
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.5
	 */
	public function shippingCost($product_price) {
		$template = JRequest::getVar('template');
		$prices = $template->getValue('shopper_shipping_export_fields', '', array());
		$fee = null;
		if (!empty($prices)) {
			foreach ($prices['_price_from'] as $kfrom => $price_from) {
				// Check if we have an end price
				$price_from = str_replace(',', '.', $price_from);
				$price_to = str_replace(',', '.', $prices['_price_to'][$kfrom]);
				if (!empty($price_to)) {
					if ($product_price >= $price_from && $product_price < $price_to) {
						$fee = $kfrom;
						break;
					}
				}
				else {
					if ($product_price >= $price_from) {
						$fee = $kfrom;
						break;
					}
				}
			}

			if (!is_null($fee)) return $prices['_fee'][$fee];
			else return false;
		}
		else return false;
	}

	/**
	 * Get the list of custom tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return		array	list of order item product objects
	 * @since 		3.0
	 */
	public function getCustomTables() {
		$db = JFactory::getDBO();
		$q = "SELECT vm_table
			FROM #__csvivirtuemart_available_fields
			WHERE core = 0
			GROUP BY vm_table";
		$db->setQuery($q);
		return $db->loadResultArray();
	}

	/**
     * Check whether a file referenced by a URL exists
     *
     * Note: The time taken to check a valid format url:  0.10 secs, regardless of whether the file exists
     *
     * @copyright
     * @author 		doorknob, RolandD
     * @todo
     * @see
     * @access 		public
     * @param 		string	$file	The URL to be checked
     * @return 		boolean	true if file exists | false if file does not exist
     * @since 		2.17
     */
    public function fileExistsRemote($file) {
    	$csvilog = JRequest::getVar('csvilog');
        $url_parts = @parse_url($file);

        if (!isset($url_parts['host']) || empty($url_parts['host']))  {
            return false;
        }

        if (!isset($url_parts['path']) || empty($url_parts['path']))  {
            $documentpath = '/';
        }
        else {
            $documentpath = $url_parts['path'];
        }

        if (isset($url_parts['query']) && !empty($url_parts['query'])) {
            $documentpath .= '?'.$url_parts['query'];
        }

        $host = $url_parts['host'];

        if (!isset($url_parts['port']) || empty($url_parts['port']))  {
        	if ($url_parts['scheme'] == 'https') $port = '443';
            else $port = '80';
        }
        else {
            $port = $url_parts['port'];
        }
        
        if ($url_parts['scheme'] == 'https') {
        	$sslhost = 'ssl://'.$host;
        }
        else $sslhost = $host;
        $errno = null;
        $errstr = null;
        $documentpath = str_replace(' ', '%20', $documentpath);
        $socket = @fsockopen($sslhost, $port, $errno, $errstr, 30);
        if ($socket) {
        	$csvilog->addDebug('Documentpath: '.$documentpath);
        	$csvilog->addDebug('Host: '.$host);
            fwrite($socket, "HEAD $documentpath HTTP/1.0\r\nHost:  $host\r\n\r\n");
            $http_response = fgets($socket, 22);
            $csvilog->addDebug('HTTP response: '.$http_response);

            if (stripos($http_response, '200 OK') === false
            	&& stripos($http_response, '302 Found') === false) {
            	fclose($socket);
                return false;
            }
            else {
                fclose($socket);
                return true;
            }
        }
        return false;
    }

    /**
	 * Find the primary key of a given table
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param 		$table	string	the name of the table to find the primary key
	 * @return 		string	the fieldname that is the primary key
	 * @since 		3.0
	 */
	public function getPrimaryKey($tablename) {
		$db = JFactory::getDBO();

		// Get the Joomla config to find out the database being used
		$jconfig = new JConfig();
		$q = "SELECT COLUMN_NAME
			FROM INFORMATION_SCHEMA.STATISTICS
			WHERE INDEX_NAME = 'PRIMARY'
			AND INDEX_SCHEMA = ".$db->Quote($jconfig->db)."
			AND TABLE_NAME = ".$db->Quote($db->getPrefix().$tablename);
		$db->setQuery($q);
		return $db->loadResult();
	}

	/**
	 * Get the domainname
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return 		string	domain name
	 * @since 		3.4
	 */
	public function getDomainName() {
		$settings = JRequest::getVar('settings');

		// Get the domainname
		$domainname = $settings->getSetting('hostname');
		// Check for the trailing slash at the domain name
		if (substr($domainname, -1) == '/') $domainname = substr($domainname, 0, -1);
		// Assign the domainname
		return $domainname;
	}
}
?>
