<?php
/**
 * SARU
 * organize your contacts
 *
 * Copyright (c) 2012-2014 Marie Kuntz - Lezard Rouge
 *
 * This file is part of SARU.
 * SARU is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * SARU 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 Affero General Public License for more details.

 * You should have received a copy of the GNU Affero General Public License
 * along with SARU. If not, see <http://www.gnu.org/licenses/>.
 * See LICENSE.TXT file for more information.
 *
 * Saru is released under dual license, AGPL and commercial license.
 * If you need a commercial license or if you don't know which licence you need,
 * please contact us at <info@saru.fr>
 *
 * @copyright  Copyright (c) 2012-2014 Marie Kuntz - Lezard Rouge (http://www.lezard-rouge.fr)
 * @license    GNU-AGPL v3 http://www.gnu.org/licenses/agpl.html
 * @version    1
 * @author     Marie Kuntz - Lezard Rouge SARL - www.lezard-rouge.fr - contact@lezard-rouge.fr
 */

/**
 * files manipulation functions
 *
 * @version $Id: Files.class.php 206 2014-04-04 13:16:16Z lezardro $
 * @author Marie Kuntz / Lézard Rouge
 */

class Files
{

	public $csv_sep = ';'; // csv separator
	public $csv_eol = "\n"; // csv end of line
	public $default_dir = 'files/'; // default directory for imported/exported files
	/* encoding supported and checked for csv import */
	public $supported_encoding = array(
		 "utf-8", "iso-8859-1", "iso-8859-15", "windows-1251", "windows-1252", "ASCII",
	);
	/* name of csv template for import */
	public $csv_template = 'modele_import_donnees.csv';


	public function __construct()
	{
	}


	/**
	 * open a file
	 *
	 * @param string $file, the file including path
	 * @param string $mode, the mode to use to open
	 *
	 * @return mixed boolean|resource
	 */
	public function openFile($file, $mode = 'w+b')
	{
		$handle = fopen($file, $mode);
		if($handle === false) {
			return false;
		}
		return $handle;
	}


	/**
	 * write in a file
	 *
	 * @param string $file, the filename with the path
	 * @param string $buffer, the text to write
	 *
	 * @return bool
	 */
	public function writeFile($file, $buffer, $mode = 'a+b')
	{
		$handle = $this->openFile($file, $mode);
		if($handle === false) {
			return false;
		}
		$res = fwrite($handle, $buffer);
		fclose($handle);
		if($res === false) {
			return false;
		}
		return true;
	}


	/**
	 * generate the csv template file for importing contacts
	 *
	 * @return bool $res
	 */
	public function generateCsvTemplate()
	{
		$buffer = $this->generateCsvHeader();
		// write file
		$res = $this->writeFile($this->default_dir . $this->csv_template, $buffer, 'wb');
		return $res;
	}


	/**
	 * generate the first line for a CSV export
	 *
	 * @param bool $include_type, if the type must be included
	 *
	 * @return string $buffer
	 */
	public function generateCsvHeader($include_type = false)
	{
		// fetch metas for companies
		$dao_company_metas = new DaoCompanyMetas();
		$company_metas = $dao_company_metas->getCompanyMetas(array('f_active' => 1), null, 0);
		// fetch metas for contacts
		$dao_contacts_metas = new DaoContactMetas();
		$contact_metas = $dao_contacts_metas->getContactMetas(array('f_active' => 1), null, 0);
		// create buffer
		$buffer = '';
		if($include_type) {
			$buffer .= '"Type"' . $this->csv_sep;
		}
		$buffer .= '"Entreprise"' . $this->csv_sep;
		foreach ($company_metas['results'] as $meta) {
			$buffer .= '"' . Utils::convertEncoding(Utils::displayEscapedString($meta->getName()), 'ISO-8859-15', 'UTF-8') . '"' . $this->csv_sep;
		}
		$buffer .= '"Notes entreprise"' . $this->csv_sep
				. '"Nom"' . $this->csv_sep . '"' . Utils::convertEncoding('Prénom', 'ISO-8859-15', 'UTF-8') . '"' . $this->csv_sep;
		foreach ($contact_metas['results'] as $meta) {
			$buffer .= '"' . Utils::convertEncoding(Utils::displayEscapedString($meta->getName()), 'ISO-8859-15', 'UTF-8') . '"' . $this->csv_sep;
		}
		$buffer .= '"Notes contact"'
				. $this->csv_eol;
		return $buffer;
	}


	/**
	 * general function to upload a file
	 *
	 * @param array $file, $_FILES array
	 * @param string $path, the destination path
	 * @param array $mimes, the mime types permitted
	 * @param str $new_name, the new name for the uploaded file
	 *
	 * @return bool
	 */
	public function upload($file, $path, $mimes, $new_name = '')
	{
		$result = array('filename' => '', 'success' => false);
		// check the file is ok & the mime type is correct & the path is set up
		if( ! empty($file["tmp_name"])
			&& $file["error"] == 0
			&& in_array($file["type"], $mimes)
			&&  ! empty($path))
		{
			if(! empty($new_name)) {
				// retrieve extension
				$ext = Utils::getExtension($file["name"]);
				$filename = Utils::escapeFilename($new_name . $ext);
			} else {
				$filename = Utils::escapeFilename($file["name"]);
			}
			if(move_uploaded_file($file["tmp_name"], $path . $filename)) {
				$result['success'] = true;
				$result['filename'] = $filename;
			}
		} else {
			Utils::log('file error: ' . $file["error"] . "\n"
					. 'mime: ' . $file["type"] . "\n"
					. 'file tmp name: ' . $file["tmp_name"] . "\n"
					. 'path: ' . $path);
		}
		return $result;
	}


	/**
	 * upload a csv file
	 *
	 * @param array $uploaded_file, $_FILES array
	 *
	 * @return bool
	 */
	public function uploadCsv($uploaded_file)
	{
		$path = LOCAL_PATH . $this->default_dir;
		$mimes = array("text/csv", "text/comma-separated-values", "application/vnd.ms-excel");
		$new_name = 'import_contacts_' . date('YmdHis');
		$result = $this->upload($uploaded_file, $path, $mimes, $new_name);
		return $result;
	}


	/**
	 * delete a file
	 *
	 * @param str $filename
	 */
	public function deleteFile($filename)
	{
		$res = false;
		if(file_exists($filename)) {
			$res = unlink($filename);
		}
		return $res;
	}


}

/* End of file Files.class.php */
/* Location: ./classes/Files.class.php */