<?php



/**

  * Admin panel functions, functions.inc.php

  * @category admin

  *

  * @author PrestaShop <support@prestashop.com>

  * @copyright PrestaShop

  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0

  * @version 1.0

  *

  */



/**

  * Generate a cached thumbnail for object lists (eg. carrier, order states...etc)

  *

  * @param string $image Real image filename

  * @param string $cacheImage Cached filename

  * @param integer $size Desired size

  */

function cacheImage($image, $cacheImage, $size, $imageType = 'jpg')

{

	if (file_exists($image))

	{

		if (!file_exists(_PS_TMP_IMG_DIR_.$cacheImage))

		{

			$imageGd = ($imageType == 'gif' ? imagecreatefromgif($image) : imagecreatefromjpeg($image));

			$x = imagesx($imageGd);

			$y = imagesy($imageGd);

			

			/* Size is already ok */

			if ($x < $size) 

				copy($image, _PS_TMP_IMG_DIR_.$cacheImage);



			/* We need to resize */

			else

			{

				$ratioY = $y / ($x / $size);

				$newImage = ($imageType == 'gif' ? imagecreatetruecolor($size, $ratioY) : imagecreatetruecolor($size, $ratioY));

				

				/* Allow to keep nice look even if resized */

				$white = imagecolorallocate($newImage, 255, 255, 255);

				imagefill($newImage, 0, 0, $white);

				imagecopyresampled($newImage, $imageGd, 0, 0, 0, 0, $size, $ratioY, $x, $y);

				imagecolortransparent($newImage, $white);



				/* Quality alteration and image creation */

				if ($imageType == 'gif')

					imagegif($newImage, _PS_TMP_IMG_DIR_.$cacheImage);

				else

					imagejpeg($newImage, _PS_TMP_IMG_DIR_.$cacheImage, 86);

			}

		}

		return '<img src="../img/tmp/'.$cacheImage.'" alt="" class="imgm" />';

	}

	return '';

}



/**

  * Generate a new settings file, only transmitted parameters are updated

  *

  * @param string $baseUri Base URI

  * @param string $theme Theme name (eg. default)

  * @param array $arrayDB Parameters in order to connect to database

  */

function	rewriteSettingsFile($baseUri = NULL, $theme = NULL, $arrayDB = NULL)

{

 	$defines = array();

	$defines['__PS_BASE_URI__'] = !is_null($baseUri) ? $baseUri : __PS_BASE_URI__;

	$defines['_THEME_NAME_'] = $theme ? $theme : _THEME_NAME_;

	$defines['_DB_NAME_'] = (($arrayDB AND isset($arrayDB['_DB_NAME_'])) ? $arrayDB['_DB_NAME_'] : _DB_NAME_);

	$defines['_DB_SERVER_'] = (($arrayDB AND isset($arrayDB['_DB_SERVER_'])) ? $arrayDB['_DB_SERVER_'] : _DB_SERVER_);

	$defines['_DB_USER_'] = (($arrayDB AND isset($arrayDB['_DB_USER_'])) ? $arrayDB['_DB_USER_'] : _DB_USER_);

	$defines['_DB_PREFIX_'] = (($arrayDB AND isset($arrayDB['_DB_PREFIX_'])) ? $arrayDB['_DB_PREFIX_'] : _DB_PREFIX_);

	$defines['_DB_PASSWD_'] = (($arrayDB AND isset($arrayDB['_DB_PASSWD_'])) ? $arrayDB['_DB_PASSWD_'] : _DB_PASSWD_);

	$defines['_DB_TYPE_'] = (($arrayDB AND isset($arrayDB['_DB_TYPE_'])) ? $arrayDB['_DB_TYPE_'] : _DB_TYPE_);

	$defines['_COOKIE_KEY_'] = addslashes(_COOKIE_KEY_);

	$defines['_COOKIE_IV_'] = addslashes(_COOKIE_IV_);

	$defines['_PS_VERSION_'] = addslashes(_PS_VERSION_);

	$content = "<?php\n\n";

	foreach ($defines as $k => $value)

		$content .= 'define(\''.$k.'\', \''.addslashes($value).'\');'."\n";

	$content .= "\n?>";

	if ($fd = fopen(PS_ADMIN_DIR.'/../config/settings.inc.php', 'w'))

	{

		fwrite($fd, $content);

		fclose($fd);

	}

	else

		Tools::displayError('cannot access settings file');

}



/**

  * Display SQL date in friendly format

  *

  * @param string $sqlDate Date in SQL format (YYYY-MM-DD HH:mm:ss)

  * @param boolean $withTime Display both date and time

  * @todo Several formats (french : DD-MM-YYYY)

  */

function	displayDate($sqlDate, $withTime = false)

{

	return strftime('%Y-%m-%d'.($withTime ? ' %H:%M:%S' : ''), strtotime($sqlDate));

}



/**

  * Check image upload

  *

  * @param array $file Upload $_FILE value

  * @param integer $maxFileSize Maximum upload size

  */

function	checkImage($file, $maxFileSize)

{

	if ($file['size'] > $maxFileSize)

		return Tools::displayError('image is too large').' ('.($file['size'] / 1000).'ko). '.Tools::displayError('Maximum allowed:').' '.($maxFileSize / 1000).'ko';

	if (!isPicture($file))

		return Tools::displayError('image format not recognized, allowed formats are: .gif, .jpg, .png');

	if ($file['error'])

		return Tools::displayError('error while uploading image; change your server\'s settings');

	return false;

}



function isPicture($file)

{

    /* Detect mime content type */

    $mime_type = false;

    $types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');



    if (function_exists('finfo_open'))

    {

        $finfo = @finfo_open(FILEINFO_MIME);

        $mime_type = @finfo_file($finfo, $file['tmp_name']);

        @finfo_close($finfo);

    }

    elseif (function_exists('mime_content_type'))

        $mime_type = @mime_content_type($file['tmp_name']);

    elseif (function_exists('exec'))

        $mime_type = trim(@exec('file -bi '.escapeshellarg($file['tmp_name'])));

     if (empty($mime_type))

		$mime_type = $file['type'];



    // is it a picture ?

    return $mime_type && in_array($mime_type, $types);

}



/**

  * Check icon upload

  *

  * @param array $file Upload $_FILE value

  * @param integer $maxFileSize Maximum upload size

  */

function	checkIco($file, $maxFileSize)

{

	if ($file['size'] > $maxFileSize)

		return Tools::displayError('image is too large').' ('.($file['size'] / 1000).'ko). '.Tools::displayError('Maximum allowed:').' '.($maxFileSize / 1000).'ko';

	if (substr($file['name'], -4) != '.ico')

		return Tools::displayError('image format not recognized, allowed formats are: .ico');

	if ($file['error'])

		return Tools::displayError('error while uploading image; change your server\'s settings');

	return false;

}



/**

  * Resize, cut and optimize image

  *

  * @param array $sourceFile Image object from $_FILE

  * @param string $destFile Destination filename

  * @param integer $destWidth Desired width (optional)

  * @param integer $destHeight Desired height (optional)

  *

  * @return boolean Operation result

  */

function	imageResize($sourceFile, $destFile, $destWidth = NULL, $destHeight = NULL, $fileType = 'jpg')

{

	if (!isset($sourceFile['tmp_name']) OR !file_exists($sourceFile['tmp_name']))

		return false;



	list($sourceWidth, $sourceHeight, $type, $attr) = @getimagesize($sourceFile['tmp_name']);

	if ($destWidth == NULL) $destWidth = $sourceWidth;

	if ($destHeight == NULL) $destHeight = $sourceHeight;



	$sourceImage = createSrcImage($type, $sourceFile['tmp_name']);



	$widthDiff = $destWidth - $sourceWidth;

	$heightDiff = $destHeight - $sourceHeight;

	

	if ($widthDiff > 0 AND $heightDiff > 0)

	{

		$nextWidth = $sourceWidth;

		$nextHeight = $sourceHeight;

	}

	else

	{

		if (intval(Configuration::get('PS_IMAGE_GENERATION_METHOD')) == 2 OR (intval(Configuration::get('PS_IMAGE_GENERATION_METHOD')) == 0 AND $widthDiff > $heightDiff))

		{

			$nextHeight = $destHeight;

			$nextWidth = intval(($sourceWidth * $nextHeight) / $sourceHeight);

			$destWidth = (intval(Configuration::get('PS_IMAGE_GENERATION_METHOD')) == 0 ? $destWidth : $nextWidth);

		}

		else

		{

			$nextWidth = $destWidth;

			$nextHeight = intval($sourceHeight * $destWidth / $sourceWidth);

			$destHeight = (intval(Configuration::get('PS_IMAGE_GENERATION_METHOD')) == 0 ? $destHeight : $nextHeight);

		}

	}



	$borderWidth = intval(($destWidth - $nextWidth) / 2);

	$borderHeight = intval(($destHeight - $nextHeight) / 2);

	

	$destImage = @imagecreatetruecolor($destWidth, $destHeight);



	$white = imagecolorallocate($destImage, 255, 255, 255);

	imagefill($destImage, 0, 0, $white);



	imagecopyresampled($destImage, $sourceImage, $borderWidth, $borderHeight, 0, 0, $nextWidth, $nextHeight, $sourceWidth, $sourceHeight);

	imagecolortransparent($destImage, $white);

	return (returnDestImage($fileType, $destImage, $destFile));

}



/**

  * Cut image

  *

  * @param array $srcFile Image object from $_FILE

  * @param string $destFile Destination filename

  * @param integer $destWidth Desired width (optional)

  * @param integer $destHeight Desired height (optional)

  *

  * @return boolean Operation result

  */

function	imageCut($srcFile, $destFile, $destWidth = NULL, $destHeight = NULL, $fileType = 'jpg', $destX = 0, $destY = 0)

{

	if (!isset($srcFile['tmp_name']) OR !file_exists($srcFile['tmp_name']))

		return false;



	// Source infos

	$srcInfos = @getimagesize($srcFile['tmp_name']);

	$src['width'] = $srcInfos[0];

	$src['height'] = $srcInfos[1];

	$src['ressource'] = createSrcImage($srcInfos[2], $srcFile['tmp_name']);

	

	// Destination infos

	$dest['x'] = $destX;

	$dest['y'] = $destY;

	$dest['width'] = $destWidth != NULL ? $destWidth : $src['width'];

	$dest['height'] = $destHeight != NULL ? $destHeight : $src['height'];

	$dest['ressource'] = createDestImage($dest['width'], $dest['height']);

	

	imagecopyresampled($dest['ressource'], $src['ressource'], 0, 0, $dest['x'], $dest['y'], $dest['width'], $dest['height'], $dest['width'], $dest['height']);

	imagecolortransparent($dest['ressource'], $white);

	return	(returnDestImage($fileType, $dest['ressource'], $destFile));

}



function	createSrcImage($type, $filename)

{

	switch ($type)

	{

		case 1:

			return @imagecreatefromgif($filename);

			break;

		case 3:

			return @imagecreatefrompng($filename);

			break;

		case 2:

		default:

			return @imagecreatefromjpeg($filename);

			break;

	}

}



function	createDestImage($width, $height)

{

	$image = @imagecreatetruecolor($width, $height);

	$white = @imagecolorallocate($image, 255, 255, 255);

	@imagefill($image, 0, 0, $white);

	return $image;

}



function	returnDestImage($type, $ressource, $filename)

{

	switch ($type)

	{

		case 'gif':

			return @imagegif($ressource, $filename);

			break;

		case 'png':

			return @imagepng($ressource, $filename, 7);

			break;

		case 'jpeg':

		default:

			return @imagejpeg($ressource, $filename, 90);

			break;

	}

}



/**

  * Delete product or category image

  *

  * @param integer $id_item Product or category id

  * @param integer $id_image Image id

  */

function	deleteImage($id_item, $id_image = NULL)

{

	$path = ($id_image) ? _PS_PROD_IMG_DIR_ : _PS_CAT_IMG_DIR_;

	$table = ($id_image) ? 'product' : 'category';

	

	if (file_exists(_PS_TMP_IMG_DIR_.$table.'_'.$id_item.'.jpg'))

		unlink(_PS_TMP_IMG_DIR_.$table.'_'.$id_item.'.jpg');

	

	if ($id_image AND file_exists($path.$id_item.'-'.$id_image.'.jpg'))

		unlink($path.$id_item.'-'.$id_image.'.jpg');

	elseif (!$id_image AND file_exists($path.$id_item.'.jpg'))

		unlink($path.$id_item.'.jpg');

	

	$imagesTypes = ImageType::getImagesTypes();

	foreach ($imagesTypes AS $k => $imagesType)

		if ($id_image AND file_exists($path.$id_item.'-'.$id_image.'-'.$imagesType['name'].'.jpg'))

			unlink($path.$id_item.'-'.$id_image.'-'.$imagesType['name'].'.jpg');

		elseif (!$id_image AND file_exists($path.$id_item.'-'.$imagesType['name'].'.jpg'))

			unlink($path.$id_item.'-'.$imagesType['name'].'.jpg');

}



/**

  * Return path to a product category

  *

  * @param string $urlBase Start URL

  * @param integer $id_category Start category

  * @param string $path Current path

  * @param string $highlight String to highlight (in XHTML/CSS)

  */

function	getPath($urlBase, $id_category, $path = '', $highlight = '')

{

	global $cookie;

	

	$category = new Category($id_category, intval($cookie->id_lang));

	if (!$category->id)

		return $path;

	$name = ($highlight != NULL) ? str_ireplace($highlight, '<span class="highlight">'.$highlight.'</span>', 

	Category::hideCategoryPosition($category->name)) : Category::hideCategoryPosition($category->name);

	$edit = '<a href="'.$urlBase.'&id_category='.$category->id.'&addcategory&token=' . Tools::getAdminToken('AdminCatalog'.intval(Tab::getIdFromClassName('AdminCatalog')).intval($cookie->id_employee)).'"><img src="../img/admin/edit.gif" alt="Modify" /></a> ';

	if ($category->id == 1)

		$edit = '<a href="'.$urlBase.'&id_category='.$category->id.'&viewcategory&token=' . Tools::getAdminToken('AdminCatalog'.intval(Tab::getIdFromClassName('AdminCatalog')).intval($cookie->id_employee)).'"><img src="../img/admin/home.gif" alt="Home" /></a> ';

	$path = $edit.'<a href="'.$urlBase.'&id_category='.$category->id.'&viewcategory&token=' . Tools::getAdminToken('AdminCatalog'.intval(Tab::getIdFromClassName('AdminCatalog')).intval($cookie->id_employee)).'">'.$name.'</a> > '.$path;

	if ($category->id == 1)

		return substr($path, 0, strlen($path) - 3);

	return getPath($urlBase, $category->id_parent, $path);

}



function	getDirContent($path)

{

	$content = array();

	if (is_dir($path))

	{

		$d = dir($path);

		while (false !== ($entry = $d->read()))

			if ($entry{0} != '.')

				$content[] = $entry;

		$d->close();

	}

	return $content;

}



function createDir($path, $rights)

{

	if (file_exists($path))

		return true;

	return @mkdir($path, $rights);

}



function checkPSVersion()

{

	if ($feed = @simplexml_load_file('http://www.prestashop.com/xml/version.xml') AND _PS_VERSION_ < $feed->version->num)

		return array('name' => $feed->version->name, 'link' => $feed->download->link);

	return false;

}



?>