Your IP : 216.73.216.55


Current Path : /home/g/i/t/giteleslfp/www/administrator/components/com_templateck/models/
Upload File :
Current File : /home/g/i/t/giteleslfp/www/administrator/components/com_templateck/models/template.php

<?php

/**
 * @name		Template Creator CK
 * @copyright	Copyright (C) since 2011. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 * @author		Cedric Keiflin - http://www.template-creator.com - http://www.joomlack.fr
 */
// No direct access.
defined('TCK_LOADED') or die;

use Templatecreatorck\CKFof;

jimport('joomla.application.component.modelform');
jimport('joomla.application.component.modeladmin');
jimport('joomla.event.dispatcher');
jimport('joomla.filesystem.folder');

/**
 * Templateck model.
 */
class TemplateckModelTemplate extends JModelAdmin {

	var $_item = null;

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
	protected function populateState() {
		$app = JFactory::getApplication('com_templateck');

		// Load state from the request userState on edit or from the passed variable on default
		if ($app->input->get('layout', '', 'cmd') == 'edit') {
			$id = JFactory::getApplication()->getUserState('com_templateck.edit.template.id');
		} else {
			$id = $app->input->get('id', 0, 'int');
			JFactory::getApplication()->setUserState('com_templateck.edit.template.id', $id);
		}
		$this->setState('template.id', $id);

		// Load the parameters.
		// $params = $app->getParams();
		// $this->setState('params', $params);
	}

	/**
	 * Method to get an ojbect.
	 *
	 * @param	integer	The id of the object to get.
	 *
	 * @return	mixed	Object on success, false on failure.
	 */
	public function &getData($id = null) {
		$app = JFactory::getApplication();
		if ($this->_item === null) {
			$this->_item = false;

			if (empty($id)) {
				$id = $app->input->get('id', '', 'int');
			}

			// Get a level row instance.
			$table = $this->getTable();

			// Attempt to load the row.
			if ($table->load($id)) {
				// Check published state.
				if ($published = $this->getState('filter.published')) {
					if ($table->state != $published) {
						return $this->_item;
					}
				}

				// Convert the JTable to a clean JObject.
				$properties = $table->getProperties(1);
				$this->_item = TemplateckHelper::toObject($properties);
				// fix for RSFirewall
				$this->_item->htmlcode = str_replace('<s-tyle>', '<style>', $this->_item->htmlcode);
			} elseif ($error = $table->getError()) {
				$this->setError($error);
			}
		}

		$this->_item->layouts = $this->getLayouts($id);

		return $this->_item;
	}

	public function getLayouts($id) {
		$l = $this->initLayouts();
		if (! $id) return $l;

		$db = JFactory::getDBO();
		$query = 'SELECT id,type,htmlcode FROM #__templateck_layouts WHERE template_id=' . (int) $id;
		$db->setQuery($query);
		$layouts = $db->loadObjectList('type');

		foreach($layouts as $layout) {
			$l[$layout->type] = new stdClass();
			$l[$layout->type]->id = $layout->id;
			$l[$layout->type]->htmlcode = $layout->htmlcode;
		}

		return $l;
	}

	private function initLayouts() {
		$l = array();
		$types = array('error404');

		foreach ($types as $type) {
			$l[$type] = new stdClass();
			$l[$type]->id = 0;
			$l[$type]->htmlcode = '';
		}
		return $l;
	}
	
	public function getTable($type = 'Template', $prefix = 'TemplateckTable', $config = array()) {
		$this->addTablePath(TEMPLATECREATORCK_PATH . '/tables');
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to check in an item.
	 *
	 * @param	integer		The id of the row to check out.
	 * @return	boolean		True on success, false on failure.
	 * @since	1.6
	 */
	public function checkin($id = null) {
		// Get the id.
		$id = (!empty($id)) ? $id : (int) $this->getState('template.id');

		if ($id) {

			// Initialise the table
			$table = $this->getTable();

			// Attempt to check the row in.
			if (method_exists($table, 'checkin')) {
				if (!$table->checkin($id)) {
					$this->setError($table->getError());
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Method to check out an item for editing.
	 *
	 * @param	integer		The id of the row to check out.
	 * @return	boolean		True on success, false on failure.
	 * @since	1.6
	 */
	public function checkout($id = null) {
		// Get the user id.
		$id = (!empty($id)) ? $id : (int) $this->getState('template.id');

		if ($id) {

			// Initialise the table
			$table = $this->getTable();

			// Get the current user object.
			$user = JFactory::getUser();

			// Attempt to check the row out.
			if (method_exists($table, 'checkout')) {
				if (!$table->checkout($user->get('id'), $id)) {
					$this->setError($table->getError());
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Method to get the profile form.
	 *
	 * The base form is loaded from XML
	 *
	 * @param	array	$data		An optional array of data for the form to interogate.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	JForm	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true) {
		// Get the form.
		$form = $this->loadForm('com_templateck.template', 'template', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData() {
		$data = $this->getData();

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param	array		The form data.
	 * @return	mixed		The user id on success, false on failure.
	 * @since	1.6
	 */
	public function save($data) {
		$app = JFactory::getApplication();
		$id = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('template.id');
		$user = JFactory::getUser();
//		$data['htmlcode'] = JRequest::getVar('htmlcode', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$data['htmlcode'] = $app->input->get('htmlcode', '', 'raw');
		$data['stylecode'] = $app->input->get('stylecode', '', 'raw');
		$htmlcode_responsive = $app->input->get('htmlcode_responsive', '', 'raw');
		if ($htmlcode_responsive) $data['htmlcode_responsive'] = $htmlcode_responsive;
		$modules = $app->input->get('modules', '', 'string');
		if ($modules) $data['modules'] = $modules;
		$data['widgets'] = $app->input->get('widgets', '', 'raw');
		$data['identifier'] = JUserHelper::genRandomPassword(10);

		if ($id) {
			//Check the user can edit this item
			$authorised = $user->authorise('core.edit', 'template.' . $id);
		} else {
			//Check the user can create new items in this section
			$authorised = $user->authorise('core.create', 'com_templateck');
		}

		if ($authorised !== true) {
			JError::raiseError(403, TCK_Text::_('JERROR_ALERTNOAUTHOR'));
			return false;
		}

		$table = $this->getTable();
		$table->load($data['id']);
		
		// make a backup before save
		$this->makeBackup();

		if ($data['id'] != 0 && $table->name !== $data['name']) {
			$this->changeTemplateName($table->name, $data['name']);
		}
		if ($table->save($data) === true) {
			$templateid = $table->id;
		} else {
			return false;
		}
	
		// save the layouts
		$table = $this->getTable('layouts');
		

		$layouts = $app->input->get('layouts', '', 'array');

		if ($layouts) {
			$layoutsid = $app->input->get('layoutsid', 0, 'array');
			foreach ($layouts as $name => $layout) {
				$layout_id = $layoutsid[$name] ? $layoutsid[$name] : 0;
				$table->load($layout_id);
				// $table->id = $layout_id;
				$table->template_id = $templateid;
				$table->type = $name;
				$table->htmlcode = trim($layout);
				$table->styles = '';
				$table->published = 1;

				if ($table->save($table) === true) {
					// return $table->id;
				} else {
					return false;
				}
			}
		}

		return $templateid;
	}

	public function changeTemplateName($oldname, $newname) {
		if (! $oldname) return;

		if (! TCK_Folder::exists(TEMPLATECREATORCK_PROJECTS_PATH . '/' . $oldname) && ! TCK_Folder::exists(TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $oldname)) {
			return;
		}
		if (TCK_Folder::exists(TEMPLATECREATORCK_PROJECTS_PATH . '/' . $oldname)) {
			$movefolder = TCK_Folder::move(TEMPLATECREATORCK_PROJECTS_PATH . '/' . $oldname, TEMPLATECREATORCK_PROJECTS_PATH . '/' . $newname);
			if ($movefolder !== true) {
				JFactory::getApplication()->enqueueMessage(TCK_Text::_('CK_UNABLE_TO_RENAME_FOLDER') . ' : ' . TEMPLATECREATORCK_PROJECTS_PATH . '/' . $newname, 'warning');
			}
		}

		if (TCK_Folder::exists(TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $oldname)) {
			$movefolder = TCK_Folder::move(TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $oldname, TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $newname);
			if ($movefolder !== true) {
				JFactory::getApplication()->enqueueMessage(TCK_Text::_('CK_UNABLE_TO_RENAME_FOLDER') . ' : ' . TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $newname, 'warning');
			}
		}
	}
	
	public function delete(&$pks) {
		$path = TEMPLATECREATORCK_PROJECTS_PATH;
		$table = $this->getTable();
		foreach ($pks as $i => $pk)
		{
			$table->load((int)$pk);
			if (TCK_Folder::exists($path . $table->name)) {
				TCK_Folder::delete($path . $table->name);
			}
		}

		parent::delete($pks);
	}
	
	private function makeBackup() {
//		jimport('joomla.filesystem.file');
//		jimport('joomla.filesystem.folder');
		$path = TEMPLATECREATORCK_PATH . '/backup';

		$item = $this->getData();
		$exportfiletext = json_encode($item);
		
		
		// create the folder
		if (! TCK_Folder::exists($path . '/' . $item->id . '_bak/')) {
			TCK_Folder::create($path . '/' . $item->id . '_bak/');
		}

		// check if we have more than 5 existing backups, delete the old one
		$existingBackups = TCK_Folder::files($path . '/' . $item->id . '_bak/', '^backup_' . $item->id);
		if (count($existingBackups) > 5) {
//			$this->deleteOldestBackup($path . '/' . $item->id . '_bak/');
			natsort($existingBackups);
			$oldest = $existingBackups[0];
			Jfile::delete($path . '/' . $item->id . '_bak/' . $oldest);
		}

		$exportfiledest = $path . '/' . $item->id . '_bak/backup_' . $item->id . '_' . date("d-m-Y-G-i-s") . '.tck3';
		TCK_File::write($exportfiledest, $exportfiletext);
		
	}
	
//	private function deleteOldestBackup($path) {
//		$files = TCK_Folder::files($path, '^backup_' . $item->id);
//
//		natsort($files);
//
//		$oldest = $files[0];
//		Jfile::delete($path . $oldest);
//	}

	/**
	 * Method to install a gabarit
	 *
	 * @access	public
	 * @return	true on success
	 */
	public function import() {
		$app = JFactory::getApplication();
		$fileInput = new TCK_Input($_FILES);
		$file = $fileInput->get('file', null, 'array');
		if (!is_array($file))
			return false;

		// include file and zip archive libraries
//		jimport('joomla.filesystem.file');

		// declare some variables
//		$file = JRequest::getVar('file', '', 'files', 'array');

		//Clean up filename to get rid of strange characters like spaces etc
		$filename = TCK_File::makeSafe($file['name']);

		// check if the file exists
		if (TCK_File::getExt($filename) != 'tck3' && TCK_File::getExt($filename) != 'tck3z') {
			$msg = TCK_Text::_('CK_NOT_TCK3_AND_NOT_TCK3Z_FILE');
			$app->redirect(TEMPLATECREATORCK_ADMIN_URL, $msg, 'error');
			return false;
		}
		if (TCK_File::getExt($filename) === 'tck3') {
			if (! $this->import_tck3_file($file) ) {
				return false;
			}
		} else if (TCK_File::getExt($filename) === 'tck3z') {
			if (! $this->import_tck3z_file($file) ) {
				return false;
			}
		}

		return true;
	}
	
	private function import_tck3_file($file) {
		$app = JFactory::getApplication();

		//Set up the source and destination of the file
		$src = $file['tmp_name'];

		// check if the file exists
		if (!$src || !file_exists($src)) {
			$msg = TCK_Text::_('CK_FILE_NOT_EXISTS');
			$app->redirect(TEMPLATECREATORCK_ADMIN_URL, $msg, 'error');
			return false;
		}

		// read the file
		if (!$filecontent = file_get_contents($src)) {
			$msg = TCK_Text::_('CK_UNABLE_READ_FILE');
			$app->redirect(TEMPLATECREATORCK_ADMIN_URL, $msg, 'error');
			return false;
		}

		// get the two parts, template and mobile data
		$filecontent = str_replace("|URIBASE|", TEMPLATECREATORCK_URI_ROOT, $filecontent);
		$filecontent = str_replace("|TCK_COMPONENT|", "components/com_templateck", $filecontent);
		$filecontent = str_replace("|TCK_ADMIN_COMPONENT|", "administrator/components/com_templateck", $filecontent);
		
		// |TCK_COMPONENT| = components/com_templateck - administrator/components/com_templateck
		$gabarittmp = explode("||TCK||", $filecontent);
		$gabarit = isset($gabarittmp[0]) ? json_decode($gabarittmp[0]) : json_decode($filecontent);
		if ($gabarit === null)
			return false;
		$gabaritmobile = isset($gabarittmp[1]) ? json_decode($gabarittmp[1]) : json_decode('{}');
		$gabarit->id = '0'; // set id to 0 to automatically increment value in database
		$gabarit->htmlcode = str_replace("|IMPORTFOLDER|", "images/" . $gabarit->name, $gabarit->htmlcode);
		$gabarit->htmlcode = stripslashes($gabarit->htmlcode);
		// do the replacement also for the stylecode
		if (isset($gabarit->stylecode)) {
			$gabarit->stylecode = str_replace("|IMPORTFOLDER|", "images/" . $gabarit->name, $gabarit->stylecode);
			$gabarit->stylecode = stripslashes($gabarit->stylecode);
		}

		$row = $this->getTable();

		// Bind the form fields to the table
		if (!$row->bind($gabarit)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Make sure the record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Store the table to the database
		if (!$row->store()) {
			$this->setError($row->getErrorMsg());
			return false;
		}

		// store the mobile data
		/*if (isset($gabaritmobile->id)) {
			// set id to 0 to automatically increment value in database
			$gabaritmobile->id = '0';
			// set the correct templateid
			$gabaritmobile->templateid = $row->id;
			if (!$this->save_item($gabaritmobile, 'mobile'))
				return false;
		}*/

		return $row->id;
	}
	
	private function extractFilesFromTck3z ($file) {
		$app = JFactory::getApplication();
		include_once TEMPLATECREATORCK_PATH . '/helpers/zip.php';

		// instanciate ZIP archiver
		$archiver = new CKArchiveZip();

		// extract archive
		$gabarit_folder_name = TCK_File::stripext($file['name']);
		$dest_extracted_zip_folder = TEMPLATECREATORCK_SITE_ROOT . '/tmp/' . $gabarit_folder_name;
		$isSuccess = $archiver->extract($file['tmp_name'], $dest_extracted_zip_folder, $options = array());

		if ($isSuccess === false) {
			return false;
}
		return $dest_extracted_zip_folder;
	}

	private function import_tck3z_file($file) {
		$dest_extracted_zip_folder = $this->extractFilesFromTck3z ($file);
		$files = TCK_Folder::files($dest_extracted_zip_folder, '.tck3');
		if (count($files) > 1) {
			// more than one file to import found
			$msg = TCK_Text::_('CK_MULTIPLE_TCK3_FILES_FOUND');
			$app->redirect("index.php?option=com_templateck&view=templateinfos&layout=install", $msg, 'error');
			return false;
		}
		$gabaritfilename = $files[0];
		$template_folder_name = str_replace('.tck3', '', $gabaritfilename);

		// import the tck3 gabarit file
		// $gabarit_file = array('tmp_name' => $dest_extracted_zip_folder . '/' . $template_folder_name . '.tck3');
		$gabarit_file = array('tmp_name' => $dest_extracted_zip_folder . '/' . $gabaritfilename);
		$id = $this->import_tck3_file($gabarit_file);
		if ($id === false) {
			return false;
		}

		// create the destination folder for images
		if (! TCK_Folder::exists( TEMPLATECREATORCK_SITE_ROOT . '/images/' . $template_folder_name ) ) {
			TCK_Folder::create( TEMPLATECREATORCK_SITE_ROOT . '/images/' . $template_folder_name );
		}
		// copy the images
		$exclude_files = array('tck3','css','php');
		$files = TCK_Folder::files($dest_extracted_zip_folder, false, true, true);
		foreach ($files as $file) {
			$filename = explode('/', $file);
			$filename = end($filename);
			if (! in_array(TCK_File::getExt($file), $exclude_files) ) {
				TCK_File::copy($file, TEMPLATECREATORCK_SITE_ROOT . '/images/' . $template_folder_name . '/' . $filename);
			}
		}

		$templatePath = TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $template_folder_name;
		// create the destination folder for css
		if (! TCK_Folder::exists( $templatePath . '/css' ) ) {
			TCK_Folder::create( $templatePath );
		}

		// copy the custom.css file
		if ( file_exists($dest_extracted_zip_folder . '/custom.css' ) ) {
			// create the destination folder for css
			if (! TCK_Folder::exists( $templatePath . '/css' ) ) {
				TCK_Folder::create( $templatePath . '/css' );
			}
			TCK_File::copy($dest_extracted_zip_folder . '/custom.css', $templatePath . '/css/custom.css' );
		}

		// copy the custom.css file
		if ( file_exists($dest_extracted_zip_folder . '/custom.js' ) ) {
			// create the destination folder for css
			if (! TCK_Folder::exists( $templatePath . '/js' ) ) {
				TCK_Folder::create( $templatePath . '/js' );
			}
			TCK_File::copy($dest_extracted_zip_folder . '/custom.js', $templatePath . '/css/custom.js' );
		}

		// copy the modules data file
		if ( file_exists($dest_extracted_zip_folder . '/modules.txt' ) ) {
			TCK_File::copy($dest_extracted_zip_folder . '/modules.txt', $templatePath . '/modules.qdtck' );
		}
		if ( file_exists($dest_extracted_zip_folder . '/modules.qdtck' ) ) {
			TCK_File::copy($dest_extracted_zip_folder . '/modules.qdtck', $templatePath . '/modules.qdtck' );
		}

		// copy the html folder
		if ( TCK_Folder::exists( $dest_extracted_zip_folder . '/html' ) ) {
			// create the destination folder for css
			if (! TCK_Folder::exists( $templatePath . '/html' ) ) {
				TCK_Folder::create( $templatePath . '/html' );
			}
			TCK_Folder::copy($dest_extracted_zip_folder . '/html', $templatePath . '/html', '', true);
		}

		// copy the customheader.php file
		if (file_exists($dest_extracted_zip_folder . '/customheader.php') ) {
			TCK_File::copy($dest_extracted_zip_folder . '/customheader.php', $templatePath . '/customheader.php' );
		}

		// copy the customheader.php file
		if (file_exists($dest_extracted_zip_folder . '/customendbody.php') ) {
			TCK_File::copy($dest_extracted_zip_folder . '/customendbody.php', $templatePath . '/customendbody.php' );
		}

		// install modules
		/*if ( file_exists($dest_extracted_zip_folder . '/modules.txt' ) ) {
			// create the destination folder for css
			$modulesdata = file_get_contents($dest_extracted_zip_folder . '/modules.txt');
			$this->getModulesList($modulesdata);
		}*/

		// remove the copy from the tmp folder
		TCK_Folder::delete($dest_extracted_zip_folder);

		return $id;
	}

	public function export() {
		$input = new TCK_Input();
		// path to store the file
		$path = TEMPLATECREATORCK_PATH . '/export';
		$id = $input->get('id', 0, 'int');

		// get the item data
		$item = $this->getData($id);
		$name = $input->get('name', $item->name, 'string');

		// get the item encoded to be saved
//		$exportfiletext = $model->getExportFile($item);
		$exportfiletext = TemplateckHelper::getExportFile($item);
		$exportfiledest = $path . '/' . $name . '.tck3';
		// delete the gabarit folder and recreate it, so it is empty
		if (TCK_Folder::exists($path . '/' . $name . '_gabarit/')) {
			TCK_Folder::delete($path . '/' . $name . '_gabarit/');
		}
		TCK_Folder::create($path . '/' . $name . '_gabarit/');

		// replace the path for imageurl data
		preg_match_all('/imageurl=\\\"(.*?)\\\"/i', $exportfiletext, $files);
		preg_match_all('/customimage.?=\\\"(.*?)\\\"/i', $exportfiletext, $files2);

		$allimgs = array_merge($files[1], $files2[1]);

		foreach ($allimgs as $i => $file) {
			if (! $file) continue;
			$filename = explode('/', $file);
			$filename = end($filename);

			$exportfiletext = str_replace('imageurl=\"' . $file, 'imageurl=\"|IMPORTFOLDER|\/' . $filename , $exportfiletext);
			$exportfiletext = str_replace('<img src=\"\/' . $file, '<img src=\"|URIBASE|\/|IMPORTFOLDER|\/' . $filename , $exportfiletext);
			$exportfiletext = str_replace("url('\/" . $file, "url('|URIBASE|\/|IMPORTFOLDER|\/" . $filename , $exportfiletext);
			if (TEMPLATECREATORCK_URI_ROOT && TEMPLATECREATORCK_URI_ROOT != '/') 
				$exportfiletext = str_replace(addcslashes(TEMPLATECREATORCK_URI_ROOT, '/'), '|URIBASE|', $exportfiletext);
			$file = str_replace('|URIBASE|\/', '', $file);
			$exportfiletext = str_replace($file, '|IMPORTFOLDER|\/' . $filename , $exportfiletext);

			// save the images
			$localfile = trim(stripslashes(str_replace('|URIBASE|', '', $file)), '/');
			if (! TCK_File::copy(TEMPLATECREATORCK_SITE_ROOT . '/' . $localfile, $path . '/' . $name . '_gabarit/' . $filename) ) {
				$msg = '<p class="errorck">' . TCK_Text::_('CK_ERROR_COPY_IMAGE') . ' : ' . TEMPLATECREATORCK_SITE_ROOT . '/' . $localfile . '</p>';
			} else {
				$msg = '<p class="successck">' . TCK_Text::_('CK_SUCCESS_COPY_IMAGE') . ' : ' . TEMPLATECREATORCK_SITE_ROOT . '/' . $localfile . '</p>';
			}
			echo $msg;
		}

		// replace the path for <img /> tags
		preg_match_all('/ <img src=\\\"(.*?)\\\"/i', $exportfiletext, $imgs);
		foreach ($imgs[1] as $i => $file) {
			$filename = explode('/', $file);
			$filename = end($filename);
			$exportfiletext = str_replace($file, '|URIBASE|\/|IMPORTFOLDER|\/' . $filename , $exportfiletext);
		}


		// create the file .tck3
		$exportfiletext = str_replace("administrator/components/com_templateck", "|TCK_ADMIN_COMPONENT|",  $exportfiletext);
		$exportfiletext = str_replace("components/com_templateck", "|TCK_COMPONENT|",  $exportfiletext);
		if (!TCK_File::write($exportfiledest, $exportfiletext)) {
			$msg = '<p class="errorck">' . TCK_Text::_('CK_ERROR_CREATE_GABARIT') . '</p>';
		} else {
			$msg = '<p class="successck">' . TCK_Text::_('CK_SUCCESS_CREATE_GABARIT') . '</p>';
		}
		echo $msg;

		// save the gabarit file
		if (! TCK_File::copy($exportfiledest, $path . '/' . $name . '_gabarit/' . $name . '.tck3' ) ) {
			$msg = '<p class="errorck">' . TCK_Text::_('CK_ERROR_COPY_GABARIT') . '</p>';
		} else {
			$msg = '<p class="successck">' . TCK_Text::_('CK_SUCCESS_COPY_GABARIT') . '</p>';
		}
		echo $msg;

		$templatePath = TEMPLATECREATORCK_TEMPLATES_PATH . '/' . $name;
		// save the html folder
		if (TCK_Folder::exists( $templatePath . '/html' ) ) {
			TCK_Folder::create($path . '/' . $name . '_gabarit/html');
			TCK_Folder::copy($templatePath . '/html', $path . '/' . $name . '_gabarit/html/', '', true);
		}

		// save the custom.css file
		if (TCK_File::exists($templatePath . '/css/custom.css') ) {
			TCK_File::copy($templatePath . '/css/custom.css', $path . '/' . $name . '_gabarit/custom.css' );
		}

		// save the customheader.php file
		if (TCK_File::exists($templatePath . '/customheader.php') ) {
			TCK_File::copy($templatePath . '/customheader.php', $path . '/' . $name . '_gabarit/customheader.php' );
		}

		// save the customheader.php file
		if (TCK_File::exists($templatePath . '/customendbody.php') ) {
			TCK_File::copy($templatePath . '/customendbody.php', $path . '/' . $name . '_gabarit/customendbody.php' );
		}

		// save the custom js file
		if (TCK_File::exists($templatePath . '/js/custom.js') ) {
			TCK_File::copy($templatePath . '/js/custom.js', $path . '/' . $name . '_gabarit/custom.js' );
		}


		//save the modules data
		if (! empty($item->modules)) {
			$modules = explode(',', $item->modules);
			$modulesdata = array();
			$db = JFactory::getDbo();
			foreach($modules as $module) {
				$query = "SELECT * FROM #__modules WHERE position='" . $module . "' AND published='1' AND client_id='0'";
				$db->setQuery($query);
				$moduleObj = $db->loadObjectList();

				if (!empty($moduleObj)) {
					$modulesdata = array_merge($moduleObj, $modulesdata);
				} else {
					// add the SQL field to the main table
		//			$db->setQuery('ALTER TABLE `#__templateck_fonts` ADD `alternatives` text NOT NULL;');
		//			if (!$db->query()) {
		//				echo '<p class="alert alert-danger">Error during export of module ID ' . $moduleObj->id .'</p>';
		//			} else {
		//				echo '<p class="alert alert-success">Table alternatives updated !</p>';
		//			}
				}
			}
			$modulesdata = serialize($modulesdata);
			$modulesdata = $this->replaceRoot($modulesdata);
			file_put_contents($path . '/' . $name . '_gabarit/modules.txt', $modulesdata);
		}

		// save the template into zip
		if (TCK_Folder::exists($templatePath)) {
			$files = TCK_Folder::files($templatePath, false, true, true);
			$exporter = new ZipArchiver();
			$isSuccess = $exporter->create($files, $templatePath . '.zip', $templatePath , true);

			TCK_File::copy(TEMPLATECREATORCK_SITE_ROOT . '/templates/' . $name . '.zip', $path . '/' . $name . '_gabarit/' . $name . '.zip');
			// return message after creating the zip archive
			if (!$isSuccess && $exporter->getError()) {
				$msg = '<p class="errorck">' . TCK_Text::_('CK_ERROR_CREATING_ARCHIVE') . '</p>';
			} else {
				$msg = '<p class="successck">' . TCK_Text::_('CK_SUCCESS_CREATING_ARCHIVE') . '</p>';
			}
		}

		echo $msg;

		$files = TCK_Folder::files($path . '/' . $name . '_gabarit/', false, true, true);
		$exporter = new ZipArchiver();
		$isSuccess = $exporter->create($files, $path . '/' . $name . '_gabarit.tck3z',$path . '/' . $name . '_gabarit', true);
		echo '<p style="padding: 15px;"><a class="ckdownload" style="background: #3D3D3D;border-radius: 3px;color: #E1E1E1;cursor: pointer;margin: 3px;padding: 2px 5px;text-decoration: none;" target="_blank" href="' . TEMPLATECREATORCK_MEDIA_URI . '/export/' . $name . '_gabarit.tck3z">' . TCK_Text::_('CK_DOWNLOAD_GABARIT') . '</a></p>';
//		TemplateckHelper::pushFileForDownload($name . '_gabarit.tck3z', );
//		header("Location: " . JURI::root() . "administrator/components/com_templateck/export/" . $name . "_gabarit.tck3z");
		// or however you get the path

		exit;
	}

	private function replaceRoot($text) {

		if (JUri::root(true)) {
			$text = str_replace("'\\" . JUri::root(true), "'\|URIBASE\|", $text);
		}
		return $text;
	}

	/**
	 * Method to install a gabarit
	 *
	 * @access	public
	 * @return	true on success
	 */
	public function ajaxInstallGabarit($url) {

		set_time_limit(0);
		try {
			$file = file_get_contents(urldecode($url));
		} catch (Exception $e) {
			echo 'Exception : ',  $e->getMessage(), "\n";
			exit;
		}
		if ($file === false) return false;

		$names = explode('/', $url);
		$filename = end($names);
		$name = JFile::stripExt($filename);

		$dest = TEMPLATECREATORCK_PATH . '/tmp/' . $name . '.zip';
		file_put_contents($dest, $file);

		// give the gabarit file to import
		$ffile = array('name' => $name, 'tmp_name' => $dest);
		$id = $this->import_tck3z_file($ffile);

		return $id;
	}
}