<?php

/**

ver 1.0
libgods.php 대체용 uiltity php

@module utils.php

*/

//utf8유지용한글
//include_once('/lib/pdodb.php');
include_once('pdodb.php');

function modtest($expected, $result, $raise = true)
{
	if ($expected == $result) {
		echo "test ok\n";
		return;
	}
	echo "result-	<<<$expected>>>  \n\nexpected	-	<<<$result>>>";
	if ($raise)
		throw new Exception("test failed.");
}

/**
 * Create plain PHP associative array from XML.
 *
 * Example usage:
 *   $xmlNode = simplexml_load_file('example.xml');
 *   $arrayData = xmlToArray($xmlNode);
 *   echo json_encode($arrayData);
 *
 * @param SimpleXMLElement $xml The root node
 * @param array $options Associative array of options
 * @return array
 * @link http://outlandishideas.co.uk/blog/2012/08/xml-to-json/ More info
 * @author Tamlyn Rhodes <http://tamlyn.org>
 * @license http://creativecommons.org/publicdomain/mark/1.0/ Public Domain
 */
function xmlToArray($xml, $options = array()) {
    $defaults = array(
        'namespaceSeparator' => ':',//you may want this to be something other than a colon
        'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
        'alwaysArray' => array(),   //array of xml tag names which should always become arrays
        'autoArray' => true,        //only create arrays for tags which appear more than once
        'textContent' => '$',       //key used for the text content of elements
        'autoText' => true,         //skip textContent key if node has no attributes or child nodes
        'keySearch' => false,       //optional search and replace on tag and attribute names
        'keyReplace' => false       //replace values for above search values (as passed to str_replace())
    );
    $options = array_merge($defaults, $options);
    $namespaces = $xml->getDocNamespaces();
    $namespaces[''] = null; //add base (empty) namespace
 
    //get attributes from all namespaces
    $attributesArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
            //replace characters in attribute name
            if ($options['keySearch']) $attributeName =
                    str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
            $attributeKey = $options['attributePrefix']
                    . ($prefix ? $prefix . $options['namespaceSeparator'] : '')
                    . $attributeName;
            $attributesArray[$attributeKey] = (string)$attribute;
        }
    }
 
    //get child nodes from all namespaces
    $tagsArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->children($namespace) as $childXml) {
            //recurse into child nodes
            $childArray = xmlToArray($childXml, $options);
            list($childTagName, $childProperties) = each($childArray);
 
            //replace characters in tag name
            if ($options['keySearch']) $childTagName =
                    str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
            //add namespace prefix, if any
            if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
 
            if (!isset($tagsArray[$childTagName])) {
                //only entry with this key
                //test if tags of this type should always be arrays, no matter the element count
                $tagsArray[$childTagName] =
                        in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
                        ? array($childProperties) : $childProperties;
            } elseif (
                is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
                === range(0, count($tagsArray[$childTagName]) - 1)
            ) {
                //key already exists and is integer indexed array
                $tagsArray[$childTagName][] = $childProperties;
            } else {
                //key exists so convert to integer indexed array with previous value in position 0
                $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
            }
        }
    }
 
    //get text content of node
    $textContentArray = array();
    $plainText = trim((string)$xml);
    if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
 
    //stick it all together
    $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
            ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
 
    //return node as array
    return array(
        $xml->getName() => $propertiesArray
    );
}


function assert2($cond, $msg)
{
	if (!$cond)
		throw new Exception($msg);
}

function osfilename($fn)
{
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
		return euckr($fn);
	} 
	return $fn;
}

function urlfilename($fn)
{
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
		return utf8($fn);
	} 
	return $fn;
}

function euckr($fn)
{
	return iconv('utf-8', 'euc-kr', $fn);
}

function utf8($fn)
{
	return iconv('euc-kr', 'utf-8', $fn);
}

function json_encode2($s) // 한글 escaping 안하는 json
{
	if (version_compare(phpversion(), '5.4.0', '>='))
	{
		$encoded = json_encode($s, JSON_UNESCAPED_UNICODE); 
		return $encoded;
	}
	$encoded = json_encode($s); 
	$unescaped = preg_replace_callback('/(?<!\\\\)\\\\u(\w{4})/', function ($matches) {
		return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
	}, $encoded);
	return $unescaped;
}

function replyJSON($s)
{
	echo json_encode2($s);
}

function reply_json($s)
{
	replyJSON($s);
}
function json_reply($s)
{
	replyJSON($s);
}
function now($sec=0)
{
	return date('Y-m-d H:i:s', time() + $sec);
}

function redirect($url)
{
	Header( "HTTP/1.1 301 Moved Permanently" );
	Header( "Location: $url");
	die();
}

function cleanphoneno($val)
{
	return str_replace("-", "", $val);
}

function cleantel($val)
{
	return cleanphoneno($val);
}

function qrcode($url = 'http://google.com', $w=190, $h=190)
{
	return "<img src=http://chart.apis.google.com/chart?cht=qr&chs=$w"."x$h&chld=L|1&chl=$url>";	
}

function cookie_unset()
{
	if (isset($_SERVER['HTTP_COOKIE'])) {
		$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
		foreach($cookies as $cookie) {
			$parts = explode('=', $cookie);
			$name = trim($parts[0]);
			setcookie($name, '', time()-1000);
			setcookie($name, '', time()-1000, '/');
		}
	}
}

function setcookie2($key, $val, $expiry = null)
{
	$key = urlencode($key);
	
	if ($expiry == null)
		$expiry = time() + 60*60*24*365; // 기본 1년
		
	//echo $_SERVER[HTTP_HOST];
	$uri = substr($_SERVER[REQUEST_URI], 1);
	//echo $uri;
	$n = strpos($uri, '/');
	//echo $n;
	if ($n === false)
		$cookiepath = '/';
	else
		$cookiepath = '/'.strstr($uri, '/', true).'/'; 
		
//	echo $cookiepath;
		
	setcookie($key, $val, $expiry, $cookiepath);
}
/*
function setCookie($key, $val, $expiry = null) // goutils 의 setCookie와 동일하게 동작하도록 한다 => 대소문자 구별안하기 땜에 이름 이렇게 못지음, setcookie2 이용
{
	setcookie2($key, $val, $expiry);
}
*/
function get_url_no()
{
		$strip =  basename($_SERVER['REQUEST_URI']);
		$strip = explode( "?", $strip );

		if( count($strip) > 0 )
		{
			if ($strip[0]*1 == 0)
				return null;
			return $strip[0];
		}

		return NULL;
}
/**
	names 에 해당하는 값을 params에서 뽑아내서 sql 쿼리용 인자를 만듦
*/
function build_mysql_params($names, $params) {
	$r = "";
	foreach($names as $k) {
		if (isset($params[$k])) {
			$val = $params[$k];
			if ($val != 'null')
				$val = "'$val'";
			if ($r)
				$r .= ",";
			$r .= "`$k`=$val";
		}
	}
	return $r;		
}

/**
	names 에 해당하는 값을 params에서 뽑아내서 array를 만듦
*/
function build_array($names, $params) {
	$r = array();
	foreach($names as $k) {
		if (isset($params[$k])) {
			$val = $params[$k];
			if ($val != 'null')
				$val = "$val";
			$r[$k] = $val;
		}
	}
	return $r;		
}


?><?php  

  /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */  

//  - See more at: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/#sthash.f5crC08u.dpuf
  
class SimpleImage {
	var $image;
	var $image_type;
	function load($filename) {
		$image_info = getimagesize($filename);
		$this->image_type = $image_info[2];
		if($this->image_type==IMAGETYPE_JPEG) {
			$this->image = imagecreatefromjpeg($filename);
		}
		elseif($this->image_type==IMAGETYPE_GIF) {
			$this->image = imagecreatefromgif($filename);
		}
		elseif($this->image_type==IMAGETYPE_PNG) {
			$this->image = imagecreatefrompng($filename);
		}
	}
	function save($filename,$image_type = IMAGETYPE_JPEG,$compression = 75,$permissions = null) {
		if($image_type==IMAGETYPE_JPEG) {
			imagejpeg($this->image,$filename,$compression);
		}
		elseif($image_type==IMAGETYPE_GIF) {
			imagegif($this->image,$filename);
		}
		elseif($image_type==IMAGETYPE_PNG) {
			imagepng($this->image,$filename);
		}
		if($permissions!=null) {
			chmod($filename,$permissions);
		}
	}
	function output($image_type = IMAGETYPE_JPEG) {
		if($image_type==IMAGETYPE_JPEG) {
			imagejpeg($this->image);
		}
		elseif($image_type==IMAGETYPE_GIF) {
			imagegif($this->image);
		}
		elseif($image_type==IMAGETYPE_PNG) {
			imagepng($this->image);
		}
	}
	function getWidth() {
		return imagesx($this->image);
	}
	function getHeight() {
		return imagesy($this->image);
	}
	function resizeToHeight($height) {
		$ratio = $height/$this->getHeight();
		$width = $this->getWidth()*$ratio;
		$this->resize($width,$height);
	}
	function resizeToWidth($width) {
		$ratio = $width/$this->getWidth();
		$height = $this->getheight()*$ratio;
		$this->resize($width,$height);
	}
	function scale($scale) {
		$width = $this->getWidth()*$scale/100;
		$height = $this->getheight()*$scale/100;
		$this->resize($width,$height);
	}
	function resize($width,$height) {
		$new_image = imagecreatetruecolor($width,$height);
		imagecopyresampled($new_image,$this->image,0,0,0,0,$width,$height,$this->getWidth(),$this->getHeight());
		$this->image = $new_image;
	}
}?>
