Your IP : 216.73.216.55


Current Path : /home/giteleslfp/www/administrator/components/com_templateck/
Upload File :
Current File : /home/giteleslfp/www/administrator/components/com_templateck/controller.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;

jimport('joomla.application.component.controllerform');
jimport('joomla.application.component.controlleradmin');

class TemplateckController extends JControllerLegacy {

	/**
	 * Method to display a view.
	 *
	 * @param	boolean			$cachable	If true, the view output will be cached
	 * @param	array			$urlparams	An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return	JController		This object to support chaining.
	 * @since	1.5
	 */
	public function display($cachable = false, $urlparams = false) {
		$input = JFactory::getApplication()->input;

//		require_once JPATH_COMPONENT . '/helpers/templateck.php';

		// Load the left sidebar.
//		TemplateckHelper::addSubmenu($input->get('view', 'templates', 'cmd'));

		$input = new TCK_Input();
		$view = $input->get('view', 'templates');
		$input->set('view', $view);

		parent::display();

		return $this;
	}

	/**
	* Check updates for the component, module, or plugins
	*/
	public function check_update() {
		error_reporting(0); // to avoid errors to be triggered
		if ( version_compare(self::get_latest_version(), self::get_current_version() ) > 0 ) {
			$update_status = '<span class="ckbadgeupdate">' . TCK_Text::_('CK_UPDATE_NOTIFICATION') . '</span>';
		} else {
			$update_status = '';
		}

		echo $update_status;
		die;
	}

	/**
	 * Check if a new version is available
	 * 
	 * @return false, or the latest version
	 */
	public static function get_latest_version() {
		$release_notes = self::get_release_notes();
		$latest_version = false;
		if ($release_notes !== false) {
			$test_version = preg_match('/\*(.*?)\n/', $release_notes, $results);
			$latest_version = trim($results[1]);
//			$is_uptodate = version_compare($latest_version, self::get_current_version() ) > 0 ? false : true;
		}

		return $latest_version;
	}
	
	/*
	 * Get a variable from the manifest file (actually, from the manifest cache).
	 * 
	 * @return the current version
	 */
	public static function get_current_version() {
		$currentVersion = false;
		$file_url = TEMPLATECREATORCK_PATH .'/templateck.xml';
		if (! $xml_installed = JFactory::getXML($file_url)) {
			// die;
		} else {
			$currentVersion = (string)$xml_installed->version;
		}

		return $currentVersion;
	}

	/**
	 * Get the release notes content
	 * 
	 * @return false or the file content
	 */
	public static function get_release_notes() {
		$url = 'http://www.template-creator.com/tck_update.txt';
		return @file_get_contents($url);
	}
	
	/**
	 * Check if you have the latest version
	 * 
	 * @return boolean, true if outdated
	 */
	public static function is_outdated() {
		return version_compare(self::get_latest_version(), self::get_current_version() ) > 0;
	}

	/*
	 * Due to issues when uninstalling and reinstalling, we need to propose a manual way to create the tables
	 */
	public function fixSqlTable() {
		$sql = file_get_contents(TEMPLATECREATORCK_PATH . '/sql/install.mysql.utf8.sql');
		$queries = explode(';', $sql);
		$db = JFactory::getDbo();
		foreach ($queries as $q) {
			if (stristr($q, 'DROP') || ! $q) continue;
			try {
				$query = $db->getQuery(true);
				$db->setQuery(trim($q) . ';');
				$db->execute();
			}	catch (Exception $e) {
				echo '<div class="alert"><b>SQL ERROR FROM TEMPLATE CREATOR CK - FIXTABLE : </b>',  $e->getMessage(), "</div>\n";
				die;
			}
		}
		$this->setRedirect('index.php?option=com_templateck', false);
	}

	/**
	 * Get the file and store it on the server
	 * 
	 * @return mixed, the method return
	 */
	public function ajaxAddPicture() {
		require_once TEMPLATECREATORCK_PATH . '/helpers/ckbrowse.php';
		CKBrowse::ajaxAddPicture();
	}

	/**
	 * Load the backup file
	 * 
	 * @return string, the html content
	 */
	public function ajaxDoRestoration() {
		// security check
		TemplateckHelper::checkAjaxToken();

		$input = JFactory::getApplication()->input;
		$id = $input->get('id', 0, 'int');
		$name = $input->get('name','', 'string');
		$isLocked = $input->get('isLocked', 0, 'int');
		$filename = ($isLocked ? 'locked' : 'backup') . '_' . $id . '_' . $name . '.tck3';
		$path = TEMPLATECREATORCK_PATH . '/backup/' . $id . '_bak';
		$content = file_get_contents($path . '/' . $filename);
		$backup = str_replace('|URIROOT|', TEMPLATECREATORCK_URI_ROOT, $content);
//		$backup = json_decode($content);

		echo $backup;
		exit();
	}

	public function ajaxInstallWidget($url = '', $name = '') {
		require_once(TEMPLATECREATORCK_PATH . '/helpers/ckinstaller.php');

		$input = new TCK_Input();
		$url = $input->get('url', $url, 'string');
		$name = $input->get('name', $name, 'string');
//		$type = $input->get('type', $type, 'string');

		$installer = new CKInstaller();
		$result = $installer->install($url, $name);
		
		echo $result;
		exit();
	}

	public function ajaxEditWidget($name = '') {
		require_once(dirname(__FILE__) . '/helpers/ckwidgets.php');

		$input = JFactory::getApplication()->input;
		$name = $input->get('name', $name, 'string');

		$edition = CKWidgets::loadEdition($name);
		
		echo $edition;
		exit();
	}

	/*public function ajaxInstallPlugin($url = '', $name = '') {
		require_once(dirname(__FILE__) . '/helpers/ckinstaller.php');

		$input = JFactory::getApplication()->input;
		$url = $input->get('url', $url, 'string');
		$name = $input->get('name', $name, 'string');

		$installer = new CKInstaller();
		$installer->install($url, $name, 'plugin');
		
		echo $installer;
		exit();
	}*/
	
	public function ajaxCheckWidgetUpdate() {
		require_once(dirname(__FILE__) . '/helpers/ckwidgets.php');

		$widgets = CKWidgets::getWidgets();
		$widgetsVersions = Array();
		foreach ($widgets as $widget) {
			$widgetsVersions[$widget->name] = (int) CKWidgets::updateAvailable($widget->name);
		}
		
		echo json_encode($widgetsVersions);
		die;
	}
	
	public function ajaxCallWidgetAction() {
		$input = JFactory::getApplication()->input;
		$name = $input->get('name', '', 'string');
		$func = $input->get('func', '', 'string');

		// load the widget language
		require_once(dirname(__FILE__) . '/helpers/ckwidgets.php');
		CKWidgets::loadWidgetLanguage($name);

		require_once(dirname(__FILE__) . '/widgets/' . $name . '/' . $name . '.php');
		$widgetClassName = 'TCK_Widget' . ucfirst($name);
		$widgetClass = new $widgetClassName;
		echo $widgetClass->$func();
		exit();
	}

	public function ajaxAddWidgetManually() {
		// check why it does not work
		if (! JSession::checkToken('get')) {
			$msg = TCK_Text::_('JINVALID_TOKEN');
			echo '{"error" : "' . $msg . '"}';
			exit;
		}

		$app = JFactory::getApplication();
		$input = $app->input;
		// $file = $input->files->get('file', '', 'array');
		$fileInput = new TCK_Input($_FILES);
		$file = $fileInput->get('file', null, 'array');

		if (!is_array($file)) {
			$msg = TCK_Text::_('CK_NO_FILE_RECEIVED');
			echo '{"error" : "' . $msg . '"}';
			exit;
		}

		$filename = TCK_File::makeSafe($file['name']);

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

		// check if the file exists
		if (!$src || !TCK_File::exists($src)) {
			$msg = TCK_Text::_('CK_FILE_NOT_EXISTS');
			echo '{"error" : "' . $msg . '"}';
			exit;
		}

		require_once(dirname(__FILE__) . '/helpers/ckinstaller.php');
		$result = CKInstaller::extractWidgetPackage($src, TCK_File::stripExt($filename));

		// $this->ajaxInstallWidget($src, $filename);
		// write the file
		// if (! TCK_File::copy($src, JPATH_SITE . '/administrator/components/com_templateck/widgets/' . $filename)) {
			// $msg = TCK_Text::_('CK_UNABLE_WRITE_FILE');
			// echo '{"error" : "' . $msg . '"}';
			// exit;
		// }
		 echo '{"success" : "' . $result . '", "name" : "' . TCK_File::stripExt($filename) . '"}';
//		echo $result;
		exit;
	}
	
	public function ajaxInstallModule($url = '', $name = '') {
		$this->ajaxSecurityCheck(false);
		require_once(dirname(__FILE__) . '/helpers/ckinstaller.php');
		require_once(dirname(__FILE__) . '/helpers/ckmodules.php');

		$input = JFactory::getApplication()->input;
		$name = $input->get('name', $name, 'string');
		
//		$url = $input->get('url', $url, 'string');
		$url = CKModules::getInstance($name)->url;

		$installer = new CKInstaller();
		$result = $installer->install($url, $name, 'module');
		
		echo $result;
		exit();
}

	private function ajaxSecurityCheck($json = true) {
		if (! JSession::checkToken('get')) {
			$msg = TCK_Text::_('JINVALID_TOKEN');
			echo ($json ? '{"status" : 0, "message" : "' . $msg . '"}' : $msg);
			exit;
		}
	}

	public function ajaxPublishModule() {
		TemplateckHelper::checkAjaxToken();

		$input = JFactory::getApplication()->input;
		$type = $input->get('type', '', 'string');
		$position = $input->get('blockposition', '', 'string');
		$templateid = $input->get('templateid', '', 'int');

		// Import table
		JLoader::register('JTableModule', JPATH_PLATFORM . '/joomla/database/table/module.php');

		$module = str_replace('mod_', '', $type);

		$table = JTable::getInstance('Module', 'JTable');
		$table->position = $position;
		$table->module = $type; 
		$table->access = '1';
		$table->published = '1';
		$table->ordering = '1';
		$table->showtitle = '0';
		$table->client_id = '0';
		$table->language = '*';
		$table->title = ucfirst($module);
		$table->params = '';

		// Store the data.
		if (!$table->store())
		{
			$msg = $table->getError();
			echo '{"status" : 0, "message" : "'.$msg.'"}';
			exit;
		}
		
		// Now we need to handle the module assignments
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName('menuid'))
			->from($db->quoteName('#__modules_menu'))
			->where($db->quoteName('moduleid') . ' = ' . $table->id);
		$db->setQuery($query);
		$menus = $db->loadColumn();

		if (empty($menus)) {
			$menus[] = '0';
		}
		// Insert the new records into the table
		foreach ($menus as $menu)
		{
			$query->clear()
				->insert($db->quoteName('#__modules_menu'))
				->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid')))
				->values($table->id . ', ' . $menu);
			$db->setQuery($query);
			$db->execute();
		}

		// store the infos of the module for the template
		// $query->clear()
				// ->insert($db->quoteName('#__templateck_modules'))
				// ->columns(array($db->quoteName('module_id'), $db->quoteName('template_id')))
				// ->values($table->id . ', ' . $templateid);
			// $db->setQuery($query);
			// $db->execute();

		// success
		echo '{"status" : "1", "id" : "'.$table->id.'"}';
		exit;
	}

	public function ajaxSearchExistingModules() {
		// security check
		TemplateckHelper::checkAjaxToken();

		$input = JFactory::getApplication()->input;
		$type = $input->get('type', '', 'string');
		$position = $input->get('position', '', 'string');
		// $module = str_replace('module-', 'mod_', $type);

		$db = JFactory::getDbo();

		$q = "SELECT COUNT(*) FROM #__modules WHERE module='" . $type . "' AND published = 1 AND position='" . $position . "' AND client_id=0;";
		try {
			$query = $db->getQuery(true);
			$db->setQuery($q);
			$nbModules = $db->loadResult();
		}	catch (Exception $e) {
			echo '{"status" : "0", "message" : "<div class=alert><b>SQL ERROR FROM TEMPLATE CREATOR CK - LIST OF MODULES : </b>'. $e->getMessage().'</div>"}';
			exit;
		}

		echo '{"status" : "1", "count" : "' . $nbModules . '"}';
		exit;
	}

	public function ajaxSearchExistingModule() {
		TemplateckHelper::checkAjaxToken();

		$input = JFactory::getApplication()->input;
		$type = $input->get('type', '', 'string');
		$position = $input->get('position', '', 'string');
		$moduleid = $input->get('moduleid', 0, 'int');
		// $module = str_replace('module-', '', $type);
		// $module = 'mod_' . $type;

		$db = JFactory::getDbo();

		$q = "SELECT COUNT(*) FROM #__modules WHERE module='" . $type . "' AND published = 1 AND position='" . $position . "' AND id='" . (int)$moduleid . "' AND client_id=0;";
		try {
			$query = $db->getQuery(true);
			$db->setQuery($q);
			$nbModules = $db->loadResult();
		}	catch (Exception $e) {
			echo '{"status" : "0", "message" : "<div class=alert><b>SQL ERROR FROM TEMPLATE CREATOR CK - LIST OF MODULES : </b>'. $e->getMessage().'</div>"}';
			exit;
		}

		echo '{"status" : "1", "count" : "' . $nbModules . '"}';
		exit;
	}
	
	public function ajaxToggleModuleState() {
		TemplateckHelper::checkAjaxToken();

		$input = JFactory::getApplication()->input;
		$id = $input->get('moduleid', '', 'int');
		$state = $input->get('state', '', 'int');

		// Import table
		JLoader::register('JTableModule', JPATH_PLATFORM . '/joomla/database/table/module.php');

		$table = JTable::getInstance('Module', 'JTable');
		// Get the data.
		if (!$table->load($id))
		{
			$msg = $table->getError();
			echo '{"status" : 0, "message" : "'.$msg.'"}';
			exit;
		}
		$table->published = !(int)$state;

		// Store the data.
		if (!$table->store())
		{
			$msg = $table->getError();
			echo '{"status" : 0, "message" : "'.$msg.'"}';
			exit;
		}

		// success
		echo '{"status" : "1", "state" : "'.$table->published.'"}';
		exit;
	}
	
	/*public function ajaxAutoCreateThumbs() {
		TemplateckHelper::checkAjaxToken();

		$app = JFactory::getApplication();
		$input = $app->input;
		$data = $input->get('data', '', 'raw');
		$templatename = $input->get('templatename', '', 'string');
		$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
		$path = JPATH_SITE . '/templates/' . $templatename;
		if (file_exists($path)) {
			file_put_contents($path . '/template_preview.png', $data);
			file_put_contents($path . '/template_thumbnail.png', $data);
		}
		exit;
	}*/

	public function ajaxSetTemplateOptions() {
		TemplateckHelper::checkAjaxToken();

		$app = JFactory::getApplication();
		$input = $app->input;
		$templatename = $input->get('templatename', '', 'string');
		$blocid = $input->get('blocid', '', 'string');
		$logoalt = $input->get('logoalt', '', 'string');
		$logolink = $input->get('logolink', '', 'string');
		$uselogodesc = $input->get('uselogodesc', '', 'string');
		$logodesctext = $input->get('logodesctext', '', 'string');
		$logoimg = trim($input->get('logoimg', '', 'string'), '/');
		$logowidth = $input->get('logowidth', '', 'string');
		$logoheight = $input->get('logoheight', '', 'string');

		// get the template object
		$template = $this->getTemplateByName($templatename);

		if (! $template) exit;

		$logodesc = $uselogodesc == 'uselogodescyes' ? $logodesctext : '';
		// Store the template and its params to the config
		$template->params->set($blocid . '_logoimgsrc', $logoimg);
		$template->params->set($blocid . '_logoheight', $logoheight);
		$template->params->set($blocid . '_logowidth', $logowidth);
		$template->params->set($blocid . '_logolink', $logolink);
		$template->params->set($blocid . '_logotitle', $logoalt);
		$template->params->set($blocid . '_logodescription', $logodesc);

		$params = $template->params->toString();

		// store the template options
		$db = JFactory::getDbo();
		$query = 'UPDATE #__template_styles SET params = ' . $db->quote($params) . ' WHERE template = ' . $db->quote($templatename);
		$db->setQuery($query);
		$db->execute();

		exit;
	}
	
	public function getTemplateByName($name) {
		// Load styles
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('s.params')
			->from('#__template_styles as s')
			->where('s.client_id = 0')
			->where('s.template = ' . $db->quote($name));
//			->join('LEFT', '#__extensions as e ON e.element=s.template AND e.type=' . $db->quote('template') . ' AND e.client_id=s.client_id');

		$db->setQuery($query);
		$template = $db->loadObject();

		if (! $template) return false;

		$registry = new JRegistry;
		$registry->loadString($template->params);
		$template->params = $registry;

		return $template;
	}

	public function ajaxSaveElement() {
		TemplateckHelper::checkAjaxToken();

		$app = JFactory::getApplication();
		$input = $app->input;
		$name = $input->get('name', '', 'string');
		$html = json_encode($input->get('html', '', 'raw'));
		$success = file_put_contents(TEMPLATECREATORCK_PATH . '/elements/' . $name . '.tck', $html);
		echo '{"status" : "' . ($success == false ? '0' : '1') . '"}';
		exit;
	}
}