Your IP : 216.73.217.68


Current Path : /home/wuectly/www/03cbe/
Upload File :
Current File : /home/wuectly/www/03cbe/admin.zip

PK�L#]ex�sn=n=	theme.phpnu&1i�<?php
/**
 *------------------------------------------------------------------------------
 * @package       T3 Framework for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt, JoomlaBamboo, (contribute to this project at github
 *                & Google group to become co-author)
 * @Google group: https://groups.google.com/forum/#!forum/t3fw
 * @Link:         http://t3-framework.org
 *------------------------------------------------------------------------------
 */

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
// add new Less format class to work with joomla 3.3
if (version_compare(JVERSION, '3.3.0') >= 0) {
	T3::import('format/less3.3');
}

/**
 *
 * Admin helper module class
 * @author JoomlArt
 *
 */
class T3AdminTheme
{
	/**
	 *
	 * save Profile
	 */

	public static function response($data){
		die(json_encode($data));
	}

	public static function error($msg){
		return self::response(array('error' => $msg));
	}

	public static function save($path)
	{
		$result = array();

		if(empty($path)){
			return self::error(JText::_('T3_TM_UNKNOWN_THEME'));
		}

		$theme = JFactory::getApplication()->input->getCmd('theme');
		$from = JFactory::getApplication()->input->getCmd('from');
		if (!$theme) {
			return self::error(JText::_('T3_TM_INVALID_DATA_TO_SAVE'));
		}

		//incase empty from
		if(!$from){
			$from = 'base';
		}

		// $file = $path . '/less/themes/' . $theme . '/variables-custom.less';
		$file =T3Path::getLocalPath('less/themes/' . $theme . '/variables-custom.less');

		if(!class_exists('JRegistryFormatLESS')){
			T3::import('format/less');
		}
		$variables = new JRegistry();
		$variables->loadObject($_POST);

		$data = $variables->toString('LESS');
		$type = 'new';
		if (JFile::exists($file)) {
			$type = 'overwrite';
		} else {
			if($theme != $from && JFolder::exists($path . '/less/themes/' . $from)){
				$source = $path . '/less/themes/' . $from;
				if (!JFolder::exists($source)) {
					// try to find the source in local
					$source = T3Path::getPath('less/themes/' . $from);
					if (!$source) {
						return self::error(JText::sprintf('T3_TM_NOT_FOUND', $from));
					}
				}
				$desc = T3Path::getLocalPath('less/themes/' . $theme);
				if(@JFolder::copy($source, $desc) != true){
					return self::error(JText::_('T3_TM_NOT_FOUND'));
				}
				
				// detect & copy rtl
				$rtlsource = $path . '/less/rtl/' . $from;
				if (!JFolder::exists($rtlsource)) {
					// try to find the source in local
					$rtlsource = T3Path::getPath('less/rtl/' . $from);
				}
				
				if ($rtlsource) {
					$rtldest = T3Path::getLocalPath('less/rtl/' . $theme);
					// copy $from to $theme
					@JFolder::copy($rtlsource, $rtldest);
				}
			}
		}

		$return = @JFile::write($file, $data);

		if (!$return) {
			return self::error(JText::_('T3_TM_OPERATION_FAILED'));
		} else {
			$result['success'] = JText::sprintf('T3_TM_SAVE_SUCCESSFULLY', $theme);
			$result['theme'] = $theme;
			$result['type'] = $type;
		}

		//LessHelper::compileForTemplate(T3_TEMPLATE_PATH, $theme);
		T3::import ('core/less');
		T3Less::compileAll($theme);
		return self::response($result);
	}

	/**
	 *
	 * Clone Profile
	 */
	public static function duplicate($path)
	{
		$theme = JFactory::getApplication()->input->getCmd('theme');
		$from = JFactory::getApplication()->input->getCmd('from');
		$result = array();

		if (empty($theme) || empty($from)) {
			return self::error(JText::_('T3_TM_INVALID_DATA_TO_SAVE'));
		}

		$source = $path . '/less/themes/' . $from;
		if (!JFolder::exists($source)) {
			// try to find the source in local
			$source = T3Path::getPath('less/themes/' . $from);
			if (!$source) {
				return self::error(JText::sprintf('T3_TM_NOT_FOUND', $from));
			}
		}

		// $dest = $path . '/less/themes/' . $theme;
		// clone to local
		$dest = T3Path::getLocalPath('less/themes/' . $theme);
		if (JFolder::exists($dest)) {
			return self::error(JText::sprintf('T3_TM_EXISTED', $theme));
		}
		
		// copy $from to $theme
		$status = @JFolder::copy($source, $dest);
		
		$rtlsource = $path . '/less/rtl/' . $from;
		if (!JFolder::exists($rtlsource)) {
			// try to find the source in local
			$rtlsource = T3Path::getPath('less/rtl/' . $from);
		}
		
		if ($rtlsource) {
			$rtldest = T3Path::getLocalPath('less/rtl/' . $theme);
			// copy $from to $theme
			@JFolder::copy($rtlsource, $rtldest);
		}
		
		$result = array();
		if ($status) {
			$result['success'] = JText::_('T3_TM_CLONE_SUCCESSFULLY');
			$result['theme'] = $theme;
			$result['reset'] = true;
			$result['type'] = 'duplicate';
		} else {
			return self::error(JText::_('T3_TM_OPERATION_FAILED'));
		}

		//LessHelper::compileForTemplate(T3_TEMPLATE_PATH , $theme);
		T3::import ('core/less');
		T3Less::compileAll($theme);
		return self::response($result);
	}

	/**
	 *
	 * Delete a profile
	 */
	public static function delete($path)
	{
		// Initialize some variables
		$theme = JFactory::getApplication()->input->getCmd('theme');
		$result = array();

		if (!$theme) {
			return self::error(JText::_('T3_TM_UNKNOWN_THEME'));
		}

		// delete custom theme
		$paths = array();
		$paths = array_merge($paths, T3Path::getAllPath('less/themes/' . $theme));
		$paths = array_merge($paths, T3Path::getAllPath('css/themes/' . $theme));
		$paths = array_merge($paths, T3Path::getAllPath('less/rtl/' . $theme));
		$paths = array_merge($paths, T3Path::getAllPath('css/rtl/' . $theme));

		$errors = array();
		foreach ($paths as $path) {
			if (is_dir ($path) && !@JFolder::delete($path)) {
				$errors[] = $path;
			}
		}

		if (count($errors)) {
			return self::error(JText::sprintf('T3_TM_DELETE_FAIL', implode(' - ', $errors)));
		} else {
			$result['template'] = '0';
			$result['success'] = JText::sprintf('T3_TM_DELETE_SUCCESSFULLY', $theme);
			$result['theme'] = $theme;
			$result['type'] = 'delete';
		}

		return self::response($result);
	}

	/**
	 *
	 * Show thememagic form
	 */
	public static function thememagic($path)
	{
		$app       = JFactory::getApplication();
		$input     = $app->input;
		$isadmin   = T3::isAdmin();

		if($isadmin){
			$tplparams = T3::getTplParams();
		} else {
			$tplparams = $app->getTemplate(true)->params;
		}

		$url = $isadmin ? JUri::root(true).'/index.php' : JUri::current();
		$url .= (preg_match('/\?/', $url) ? '&' : '?') . 'themer=1';
		$url .= ($tplparams->get('theme', -1) != -1 ? ('&t3style=' . $tplparams->get('theme')) : '');
		if($isadmin){
			$url .= '&t3tmid=' . $input->getCmd('id');
		}

		$assetspath = T3_TEMPLATE_PATH;
		$themepath = $assetspath . '/less/themes';
		if(!class_exists('JRegistryFormatLESS')){
			include_once T3_ADMIN_PATH . '/includes/format/less.php';
		}

		$themes   = array();
		$jsondata = array();

		//push a default theme
		$tobj = new stdClass();
		$tobj->id    = 'base';
		$tobj->title = JText::_('JDEFAULT');

		$themes['base'] = $tobj;

		$varfile = $assetspath . '/less/variables.less';
		if(file_exists($varfile)){
			$params = new JRegistry;
			$params->loadString(file_get_contents($varfile), 'LESS');
			$jsondata['base'] = $params->toArray();
		}

		// if (JFolder::exists($themepath)) {
		foreach (T3Path::getAllPath('/less/themes') as $themepath) {
			$listthemes = JFolder::folders($themepath);
			if (count($listthemes)) {
				foreach ($listthemes as $theme) {
					//$varsfile = $themepath . '/' . $theme . '/variables-custom.less';
					//if(file_exists($varsfile)){

						$tobj = new stdClass();
						$tobj->id    = $theme;
						$tobj->title = $theme;

						//check for all less file in theme folder
						$params = false;
						$others = JFolder::files($themepath . '/' . $theme, '.less', false, true);
						foreach($others as $other){
							$otherrel = T3Path::relativePath('less/', str_replace (T3_TEMPLATE_PATH . '/', '', $other));

							//get those developer custom values
							if($other == 'variables.less'){
								$params = new JRegistry;
								$params->loadString(file_get_contents($themepath . '/' . $theme . '/variables.less'), 'LESS');
							}

							if($other != 'variables-custom.less'){
								$tobj->$other = $otherrel;
							}
						}

						$cparams = new JRegistry;
						$varsfile = $themepath . '/' . $theme . '/variables.less';
						if(file_exists($varsfile)) $cparams->loadString(file_get_contents($varsfile), 'LESS');
						$varsfile = $themepath . '/' . $theme . '/variables-custom.less';
						if(file_exists($varsfile)) $cparams->loadString(file_get_contents($varsfile), 'LESS');
						if($params){
							foreach ($cparams->toArray() as $key => $value) {
								$params->set($key, $value);
							}
						} else {
							$params = $cparams;
						}

						$themes[$theme] = $tobj;
						$jsondata[$theme] = $params->toArray();
					//}
				}
			}
		}

		// get active theme
		$active_theme = $tplparams->get('theme', 'base');
		if (!isset($themes[$active_theme])) $active_theme = 'base';

		$langs = array (
			'addTheme'       => JText::_('T3_TM_ASK_ADD_THEME'),
			'delTheme'       => JText::_('T3_TM_ASK_DEL_THEME'),
			'overwriteTheme' => JText::_('T3_TM_ASK_OVERWRITE_THEME'),
			'correctName'    => JText::_('T3_TM_ASK_CORRECT_NAME'),
			'themeExist'     => JText::_('T3_TM_EXISTED'),
			'saveChange'     => JText::_('T3_TM_ASK_SAVE_CHANGED'),
			'previewError'   => JText::_('T3_TM_PREVIEW_ERROR'),
			'unknownError'   => JText::_('T3_MSG_UNKNOWN_ERROR'),
			'lblCancel'      => JText::_('JCANCEL'),
			'lblOk'          => JText::_('T3_TM_LABEL_OK'),
			'lblNo'          => JText::_('JNO'),
			'lblYes'         => JText::_('JYES'),
			'lblDefault'     => JText::_('JDEFAULT')
		);

		//Keepalive
		$config      = JFactory::getConfig();
		$lifetime    = ($config->get('lifetime') * 60000);
		$refreshTime = ($lifetime <= 60000) ? 30000 : $lifetime - 60000;

		// Refresh time is 1 minute less than the liftime assined in the configuration.php file.
		// The longest refresh period is one hour to prevent integer overflow.
		if ($refreshTime > 3600000 || $refreshTime <= 0){
			$refreshTime = 3600000;
		}

		$backurl = JUri::getInstance();
		$backurl->delVar('t3action');
		$backurl->delVar('t3task');

		if(!$isadmin){
			$backurl->delVar('tm');
			$backurl->delVar('themer');
		}

		T3::import('depend/t3form');

		$form = new T3Form('thememagic.themer', array('control' => 't3form'));
		$form->load(file_get_contents(JFile::exists(T3_TEMPLATE_PATH . '/thememagic.xml') ? T3_TEMPLATE_PATH . '/thememagic.xml' : T3_PATH . '/params/thememagic.xml'));
		$form->loadFile(T3_TEMPLATE_PATH . '/templateDetails.xml', true, '//config');

		$tplform = new T3Form('thememagic.overwrite', array('control' => 't3form'));
		$tplform->loadFile(T3_TEMPLATE_PATH . '/templateDetails.xml', true, '//config');

		$fieldSets = $form->getFieldsets('thememagic');
		$tplFieldSets = $tplform->getFieldsets('thememagic');

		$disabledFieldSets = array();
		foreach ($tplFieldSets as $name => $fieldSet){
			if(isset($fieldSet->disabled)){
				$disabledFieldSets[] = $name;
			}
		}

		include T3_ADMIN_PATH.'/admin/thememagic/thememagic.tpl.php';

		exit();
	}

	public static function addAssets(){
		$japp = JFactory::getApplication();
		$user = JFactory::getUser();

		//do nothing when site is offline and user has not login (the offline page is only show login form)
		if ($japp->getCfg('offline') && !$user->authorise('core.login.offline')) {
			return;
		}

		$jdoc = JFactory::getDocument();
		$params = $japp->getTemplate(true)->params;
		$devmode = $params->get('devmode', 0);

		if(defined('T3_THEMER') && $params->get('themermode', 1)){

			$jdoc->addStyleSheet(T3_URL.'/css/thememagic.css');
			$jdoc->addScript(T3_URL.'/js/thememagic.js');

			$theme     = $params->get('theme');
			$params    = new JRegistry;
			$themeinfo = new stdClass;

			if($theme){
				foreach (T3Path::getAllPath('less/themes/' . $theme) as $themepath) {
					//$themepath = T3_TEMPLATE_PATH . '/less/themes/' . $theme;

					if(file_exists($themepath . '/variables-custom.less')){
						if(!class_exists('JRegistryFormatLESS')){
							include_once T3_ADMIN_PATH . '/includes/format/less.php';
						}

						//default variables
						$varfile = T3_TEMPLATE_PATH . '/less/variables.less';
						if(file_exists($varfile)){
							$params->loadString(file_get_contents($varfile), 'LESS');

							//get all less files in "theme" folder
							$others = JFolder::files($themepath, '.less');
							foreach($others as $other){
								//get those developer custom values
								if($other == 'variables.less'){
									$devparams = new JRegistry;
									$devparams->loadString(file_get_contents($themepath . '/variables.less'), 'LESS');

									//overwrite the default variables
									foreach ($devparams->toArray() as $key => $value) {
										$params->set($key, $value);
									}
								}

								//ok, we will import it later
								if($other != 'variables-custom.less' && $other != 'variables.less'){
									$themeinfo->$other = true;
								}
							}

							//load custom variables
							if (file_exists($themepath . '/variables-custom.less')) {
								$cparams = new JRegistry;
								$cparams->loadString(file_get_contents($themepath . '/variables-custom.less'), 'LESS');

								//and overwrite those defaults variables
								foreach ($cparams->toArray() as $key => $value) {
									$params->set($key, $value);
								}
							}
						}
					}
				}
			}

			$cache = array();

			// a little security
			if($user->authorise('core.manage', 'com_templates') || (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], JUri::base() . 'administrator') !== false)){
				T3::import('core/path');
				$baseurl = JUri::base();

				//should we provide a list of less path
				foreach (array(T3_TEMPLATE_PATH . '/less', T3_PATH . '/bootstrap/less', T3_PATH . '/less') as $lesspath) {
					if(is_dir($lesspath)){
						$lessfiles = JFolder::files($lesspath, '.less', true, true);
						if(is_array($lessfiles)){
							foreach ($lessfiles as $less) {
								$path            = ltrim(str_replace(array(JPATH_ROOT, '\\'), array('', '/'), $less), '/');
								$path            = T3Path::cleanPath($path);
								$fullurl         = $baseurl . preg_replace('@(\\+)|(/+)@', '/', $path);
								$cache[$fullurl] = file_get_contents($less);
							}
						}
					}
				}
			}

			//workaround for bootstrap icon path
			$sparams = new JRegistry;
			if(defined('T3_BASE_RSP_IN_CLASS') && T3_BASE_RSP_IN_CLASS){
				$sparams->set('icon-font-path', '"' . JUri::base() . 'plugins/system/t3/base-bs3/bootstrap/fonts/"');
			}

			// enable development mode for less.js
			if ($devmode) {
				$jdoc->addScriptDeclaration('
					var less = window.less || {};
					less.env = \'development\';
				');
			}

			$jdoc->addScriptDeclaration('
				var T3Theme = window.T3Theme || {};
				T3Theme.vars = ' . json_encode($params->toArray()) . ';
				T3Theme.svars = ' . json_encode($sparams->toArray()) . ';
				T3Theme.others = ' . json_encode($themeinfo) . ';
				T3Theme.theme = \'' . $theme . '\';
				T3Theme.template = \'' . T3_TEMPLATE . '\';
				T3Theme.base = \'' . JURI::base() . '\';
				T3Theme.cache = ' . json_encode($cache) . ';
				if(typeof less != \'undefined\'){
					
					//we need to build one - cause the js will have unexpected behavior
					try{
						if(window.parent != window && 
							window.parent.T3Theme && 
							window.parent.T3Theme.applyLess){
							
							window.parent.T3Theme.applyLess(true);
						} else {
							less.refresh();
						}
					} catch(e){

					}
				}'
			);
		}
	}
}PK�L#]�����7�7
layout.phpnu&1i�<?php
/** 
 *------------------------------------------------------------------------------
 * @package       T3 Framework for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt, JoomlaBamboo, (contribute to this project at github 
 *                & Google group to become co-author)
 * @Google group: https://groups.google.com/forum/#!forum/t3fw
 * @Link:         http://t3-framework.org 
 *------------------------------------------------------------------------------
 */

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');

/**
 * Layout helper module class
 */
class T3AdminLayout
{
	public static function response($result = array())
	{
		die(json_encode($result));
	}
	
	public static function error($msg = '')
	{
		return self::response(array(
			'error' => $msg
		));
	}
	
	public static function display()
	{
		
		$app   = JFactory::getApplication();
		$input = $app->input;
		
		if (!T3::isAdmin()) {
			
			$tpl = $app->getTemplate(true);
			
			// get template name
			if ($input->getCmd('t3action') && ($styleid = $input->getInt('styleid', '')) && $tpl->id != $styleid) {
				$db    = JFactory::getDbo();
				$query = $db->getQuery(true);
				$query->select('template, params');
				$query->from('#__template_styles');
				$query->where('client_id = 0');
				$query->where('id = ' . $styleid);
				
				$db->setQuery($query);
				$tpl = $db->loadObject();
				
				if ($tpl) {
					$registry = new JRegistry;
					$registry->loadString($tpl->params);
					$tpl->params = $registry;
				}
				
				if (!$tpl) {
					die(json_encode(array(
						'error' => JText::_('T3_MSG_UNKNOW_ACTION')
					)));
				}
			}
			
		} else {
			
			$tplid = $input->getCmd('view') == 'style' ? $input->getCmd('id', 0) : false;
			if (!$tplid) {
				die(json_encode(array(
					'error' => JText::_('T3_MSG_UNKNOW_ACTION')
				)));
			}
			
			$cache = JFactory::getCache('com_templates', '');
			if (!$templates = $cache->get('t3tpl')) {
				// Load styles
				$db    = JFactory::getDbo();
				$query = $db->getQuery(true);
				$query->select('id, home, template, s.params');
				$query->from('#__template_styles as s');
				$query->where('s.client_id = 0');
				$query->where('e.enabled = 1');
				$query->leftJoin('#__extensions as e ON e.element=s.template AND e.type=' . $db->quote('template') . ' AND e.client_id=s.client_id');
				
				$db->setQuery($query);
				$templates = $db->loadObjectList('id');
				foreach ($templates as &$template) {
					$registry = new JRegistry;
					$registry->loadString($template->params);
					$template->params = $registry;
				}
				$cache->store($templates, 't3tpl');
			}
			
			if (isset($templates[$tplid])) {
				$tpl = $templates[$tplid];
			} else {
				$tpl = $templates[0];
			}
		}
		
		//load language for template
		JFactory::getLanguage()->load('tpl_' . T3_TEMPLATE, JPATH_SITE);
		
		//clean all unnecessary datas
		if(ob_get_length()){
			@ob_end_clean();
		}
		$t3app  = T3::getSite($tpl);
		$layout = $t3app->getLayout();
		$t3app->loadLayout($layout);
		$lbuffer = ob_get_clean();
		die($lbuffer);
	}
	
	public static function save()
	{
		// Initialize some variables
		$input    = JFactory::getApplication()->input;
		$template = $input->getCmd('template');
		$layout   = $input->getCmd('layout');
		if (!$template || !$layout) {
			return self::error(JText::_('T3_LAYOUT_INVALID_DATA_TO_SAVE'));
		}

		// store layout configuration into custom directory
    $file = T3Path::getLocalPath ('etc/layout/' . $layout . '.ini');

		if (!is_dir(dirname($file))) {
			JFolder::create(dirname($file));
		}
		
		$params = new JRegistry();
		$params->loadObject($_POST);
		
		$data = $params->toString('INI');
		if (!@JFile::write($file, $data)) {
			return self::error(JText::_('T3_LAYOUT_OPERATION_FAILED'));
		}
		
		return self::response(array(
			'successful' => JText::sprintf('T3_LAYOUT_SAVE_SUCCESSFULLY', $layout),
			'layout' => $layout,
			'type' => 'new'
		));
	}
	
	public static function copy()
	{
		// Initialize some variables
		$input    = JFactory::getApplication()->input;
		$template = $input->getCmd('template');
		$original = $input->getCmd('original');
		$layout   = $input->getCmd('layout');
		
		//safe name
		$layout = JApplicationHelper::stringURLSafe($layout);
		
		if (!$template || !$original || !$layout) {
			return self::error(JText::_('T3_LAYOUT_INVALID_DATA_TO_SAVE'));
		}


		// clone to CUSTOM dir
		$source = T3Path::getPath('tpls/' . $original . '.php');
    $dest   = T3Path::getLocalPath('tpls/' . $layout . '.php');
		$confsource = T3Path::getPath('etc/layout/'. $layout . '.ini');
    $confdest   = T3Path::getLocalPath('etc/layout/'. $layout . '.ini');

		$params = new JRegistry();
		$params->loadObject($_POST);
		
		$data = $params->toString('INI');
		
		if (!is_dir(dirname($confdest))) {
			JFolder::create(dirname($confdest));
		}

		if (!is_dir(dirname($dest))) {
			JFolder::create(dirname($dest));
		}
		
		if ($data && !@JFile::write($confdest, $data)) {
			return self::error(JText::_('T3_LAYOUT_OPERATION_FAILED'));
		}
		
		// Check if original file exists
		if (JFile::exists($source)) {
			// Check if the desired file already exists
			if (!JFile::exists($dest)) {
				if (!JFile::copy($source, $dest)) {
					return self::error(JText::_('T3_LAYOUT_OPERATION_FAILED'));
				}
				//clone configuration file, we only copy if the target file does not exist
				if (!JFile::exists($confdest) && JFile::exists($confsource)) {
					JFile::copy($confsource, $confdest);
				}
			} else {
				return self::error(JText::_('T3_LAYOUT_EXISTED'));
			}
		} else {
			return self::error(JText::_('T3_LAYOUT_NOT_FOUND'));
		}
		
		return self::response(array(
			'successful' => JText::_('T3_LAYOUT_SAVE_SUCCESSFULLY'),
			'original' => $original,
			'layout' => $layout,
			'type' => 'clone'
		));
	}
	
	public static function delete()
	{
		// Initialize some variables
		$input    = JFactory::getApplication()->input;
		$layout   = $input->getCmd('layout');
		$template = $input->getCmd('template');
		
		if (!$layout) {
			return self::error(JText::_('T3_LAYOUT_UNKNOW_ACTION'));
		}
		
		// delete custom layout    
		$layoutfile = T3Path::getLocalPath('tpls/' . $layout . '.php');
		$initfile   = T3Path::getLocalPath('etc/layout/' . $layout . '.ini');

		if (!@JFile::delete($layoutfile) || !@JFile::delete($initfile)) {
			return self::error(JText::_('T3_LAYOUT_DELETE_FAIL'));
		} else {
			return self::response(array(
				'successful' => JText::_('T3_LAYOUT_DELETE_SUCCESSFULLY'),
				'layout' => $layout,
				'type' => 'delete'
			));
		}
	}

	public static function purge()
	{
		// Initialize some variables
		$input    = JFactory::getApplication()->input;
		$layout   = $input->getCmd('layout');
		$template = $input->getCmd('template');

		if (!$layout) {
			return self::error(JText::_('T3_LAYOUT_UNKNOW_ACTION'));
		}

		// delete custom layout
		$layoutfile = T3Path::getLocalPath('tpls/' . $layout . '.php');
		$initfile   = T3Path::getLocalPath('etc/layout/' . $layout . '.ini');

		// delete default layout
		$defaultlayoutfile = T3_TEMPLATE_PATH . '/tpls/' . $layout . '.php';
		$defaultinitfile   = T3_TEMPLATE_PATH . '/etc/layout/' . $layout . '.ini';

		if (!@JFile::delete($layoutfile) || !@JFile::delete($defaultlayoutfile)
        || !@JFile::delete($initfile) || !@JFile::delete($defaultinitfile)
      ) {
			return self::error(JText::_('T3_LAYOUT_DELETE_FAIL'));
		} else {
			return self::response(array(
				'successful' => JText::_('T3_LAYOUT_DELETE_SUCCESSFULLY'),
				'layout' => $layout,
				'type' => 'delete'
			));
		}
	}
	
	public static function getTplPositions($clientId = 0, $template = '')
	{
		$positions = array();
		
		$templateBaseDir = $clientId ? JPATH_ADMINISTRATOR : JPATH_SITE;
		$filePath        = JPath::clean($templateBaseDir . '/templates/' . $template . '/templateDetails.xml');
		
		if (is_file($filePath)) {
			// Read the file to see if it's a valid component XML file
			$xml = simplexml_load_file($filePath);
			if (!$xml) {
				return false;
			}
			
			// Check for a valid XML root tag.
			
			// Extensions use 'extension' as the root tag.  Languages use 'metafile' instead
			
			if ($xml->getName() != 'extension' && $xml->getName() != 'metafile') {
				unset($xml);
				return false;
			}
			
			$positions = (array) $xml->positions;
			
			if (isset($positions['position'])) {
				$positions = $positions['position'];
			} else {
				$positions = array();
			}
		}
		
		return $positions;
	}
	
	public static function getPositions()
	{
		
		$template = T3_TEMPLATE;
		$path     = JPATH_SITE;
		$lang     = JFactory::getLanguage();
		
		$clientId = 0;
		$state    = 1;
		
		$templates      = array_keys(self::getTemplates($clientId, $state));
		$templateGroups = array();
		
		// Add positions from templates
		foreach ($templates as $template) {
			$options = array();
			
			$positions = self::getTplPositions($clientId, $template);
			if (is_array($positions))
				foreach ($positions as $position) {
					$text      = self::getTranslatedModulePosition($clientId, $template, $position) . ' [' . $position . ']';
					$options[] = self::createOption($position, $text);
				}
			
			$templateGroups[$template] = self::createOptionGroup(ucfirst($template), $options);
		}
		
		// Add custom position to options
		$customGroupText                  = JText::_('T3_LAYOUT_CUSTOM_POSITION');
		$customPositions                  = self::getDbPositions($clientId);
		$templateGroups[$customGroupText] = self::createOptionGroup($customGroupText, $customPositions);
		
		return JHtml::_('select.groupedlist', $templateGroups, '', array(
			'id' => 'tpl-positions-list',
			'list.select' => ''
		));
		
	}
	
	public static function getDbPositions($clientId)
	{
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('DISTINCT(position)')
			->from('#__modules')
			->where($db->quoteName('client_id') . ' = ' . (int) $clientId)->order('position');
		
		$db->setQuery($query);
		
		try {
			$positions = $db->loadColumn();
			$positions = is_array($positions) ? $positions : array();
		}
		catch (RuntimeException $e) {
			JError::raiseWarning(500, $e->getMessage());
			return;
		}
		
		// Build the list
		$options = array();
		foreach ($positions as $position) {
			if ($position) {
				$options[] = JHtml::_('select.option', $position, $position);
			}
		}
		return $options;
	}
	
	/**
	 * Create and return a new Option
	 *
	 * @param   string  $value  The option value [optional]
	 * @param   string  $text   The option text [optional]
	 *
	 * @return  object  The option as an object (stdClass instance)
	 *
	 * @since   3.0
	 */
	public static function createOption($value = '', $text = '')
	{
		if (empty($text)) {
			$text = $value;
		}
		
		$option        = new stdClass;
		$option->value = $value;
		$option->text  = $text;
		
		return $option;
	}
	
	/**
	 * Create and return a new Option Group
	 *
	 * @param   string  $label    Value and label for group [optional]
	 * @param   array   $options  Array of options to insert into group [optional]
	 *
	 * @return  array  Return the new group as an array
	 *
	 * @since   3.0
	 */
	public static function createOptionGroup($label = '', $options = array())
	{
		$group          = array();
		$group['value'] = $label;
		$group['text']  = $label;
		$group['items'] = $options;
		
		return $group;
	}
	
	/**
	 * Check if the string was translated
	 *
	 * @param   string  $langKey  Language file text key
	 * @param   string  $text     The "translated" text to be checked
	 *
	 * @return  boolean  Return true for translated text
	 *
	 * @since   3.0
	 */
	public static function isTranslatedText($langKey, $text)
	{
		return $text !== $langKey;
	}
	
	/**
	 * Return a translated module position name
	 *
	 * @param   string  $template  Template name
	 * @param   string  $position  Position name
	 *
	 * @return  string  Return a translated position name
	 *
	 * @since   3.0
	 */
	public static function getTranslatedModulePosition($clientId, $template, $position)
	{
		// Template translation
		$lang = JFactory::getLanguage();
		$path = $clientId ? JPATH_ADMINISTRATOR : JPATH_SITE;
		
		$lang->load('tpl_' . $template . '.sys', $path, null, false, false) 
			|| $lang->load('tpl_' . $template . '.sys', $path . '/templates/' . $template, null, false, false) 
			|| $lang->load('tpl_' . $template . '.sys', $path, $lang->getDefault(), false, false) 
			|| $lang->load('tpl_' . $template . '.sys', $path . '/templates/' . $template, $lang->getDefault(), false, false);
		
		$langKey = strtoupper('TPL_' . $template . '_POSITION_' . $position);
		$text    = JText::_($langKey);
		
		// Avoid untranslated strings
		if (!self::isTranslatedText($langKey, $text)) {
			// Modules component translation
			$langKey = strtoupper('COM_MODULES_POSITION_' . $position);
			$text    = JText::_($langKey);
			
			// Avoid untranslated strings
			if (!self::isTranslatedText($langKey, $text)) {
				// Try to humanize the position name
				$text = ucfirst(preg_replace('/^' . $template . '\-/', '', $position));
				$text = ucwords(str_replace(array(
					'-',
					'_'
				), ' ', $text));
			}
		}
		
		return $text;
	}
	
	/**
	 * Return a list of templates
	 *
	 * @param   integer  $clientId  Client ID
	 * @param   string   $state     State
	 * @param   string   $template  Template name
	 *
	 * @return  array  List of templates
	 */
	public static function getTemplates($clientId = 0, $state = '', $template = '')
	{
		$db = JFactory::getDbo();
		
		// Get the database object and a new query object.
		$query = $db->getQuery(true);
		
		// Build the query.
		$query
			->select('element, name, enabled')
			->from('#__extensions')
			->where('client_id = ' . (int) $clientId)
			->where('type = ' . $db->quote('template'));

		if ($state != '') {
			$query->where('enabled = ' . $db->quote($state));
		}
		
		if ($template != '') {
			$query->where('element = ' . $db->quote($template));
		}
		
		// Set the query and load the templates.
		$db->setQuery($query);
		$templates = $db->loadObjectList('element');
		return $templates;
	}
}PK�L#]O�(�(megamenu.phpnu&1i�<?php

use Joomla\Registry\Registry;

/** 
 *------------------------------------------------------------------------------
 * @package       T3 Framework for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt, JoomlaBamboo, (contribute to this project at github 
 *                & Google group to become co-author)
 * @Google group: https://groups.google.com/forum/#!forum/t3fw
 * @Link:         http://t3-framework.org 
 *------------------------------------------------------------------------------
 */

class T3AdminMegamenu
{
	public static function display()
	{
		T3::import('menu/megamenu');
		$input = JFactory::getApplication()->input;
		
		//params
		$tplparams = T3::getTplParams();
		
		//menu type
		$menutype = $input->get('t3menu', 'mainmenu');
		
		//accessLevel
		$t3acl       = (int) $input->get('t3acl', 1);
		$accessLevel = array(1, $t3acl);
		if(in_array(3, $accessLevel)){
			$accessLevel[] = 2;
		}
		$accessLevel = array_unique($accessLevel);
		sort($accessLevel);
		
		//languages
		$languages = array(trim($input->get('t3lang', '*')));
		if($languages[0] != '*'){
			$languages[] = '*';
		}

		//check config
		$currentconfig = $tplparams instanceof Registry ? json_decode($tplparams->get('mm_config', ''), true) : null;
		$mmkey         = $menutype . (($t3acl == 1) ? '' : '-' . $t3acl);
		$mmconfig      = array();

		if($currentconfig){
			for ($i = $t3acl; $i >= 1; $i--) {
				$tmmkey = $menutype . (($i == 1) ? '' : '-' . $i);
				if(isset($currentconfig[$tmmkey])){
					$mmconfig = $currentconfig[$tmmkey];
					break;
				}
			}
		}

		if(!is_array($mmconfig)){
			$mmconfig = array();
		}

		$mmconfig['editmode'] = true;
		$mmconfig['access']   = $accessLevel;
		$mmconfig['language'] = $languages;

		//build the menu
		$menu   = new T3MenuMegamenu($menutype, $mmconfig);
		$buffer = $menu->render(true);
		
		// replace image path
		$base      = JURI::base(true) . '/';
		$protocols = '[a-zA-Z0-9]+:'; //To check for all unknown protocals (a protocol must contain at least one alpahnumeric fillowed by :
		$regex     = '#(src)="(?!/|' . $protocols . '|\#|\')([^"]*)"#m';
		$buffer    = preg_replace($regex, "$1=\"$base\$2\"", $buffer);
		
		//remove invisibile content	
		$buffer = preg_replace(array(
			'@<style[^>]*?>.*?</style>@siu',
			'@<script[^>]*?.*?</script>@siu'
		), array(
			'',
			''
		), $buffer);

		//output the megamenu key to save
		echo $buffer . '<input id="megamenu-key" type="hidden" name="mmkey" value="' . $mmkey . '"/>';
	}

	public static function delete(){
		$input         = JFactory::getApplication()->input;
		$template      = $input->get('template');
		$mmkey         = $input->get('mmkey', $input->get('menutype', 'mainmenu'));
		$tplparams     = T3::getTplParams();
		
		$currentconfig = $tplparams instanceof Registry ? json_decode($tplparams->get('mm_config', ''), true) : null;

		if (!is_array($currentconfig)) {
			$currentconfig = array();
		}

		//delete it
		if(isset($currentconfig[$mmkey])){
			unset($currentconfig[$mmkey]);
		}
		$currentconfig = json_encode($currentconfig, JSON_UNESCAPED_UNICODE);
		
		//get all other styles that have the same template
		$db    = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query
			->select('*')
			->from('#__template_styles')
			->where('template=' . $db->quote($template));

		$db->setQuery($query);
		$themes = $db->loadObjectList();
		$return = true;
		
		foreach($themes as $theme){
			$registry = new Registry;
			$registry->loadString($theme->params);

			//overwrite with new value
			$registry->set('mm_config', $currentconfig);

			$query = $db->getQuery(true);
			$query
				->update('#__template_styles')
				->set('params =' . $db->quote($registry->toString()))
				->where('id =' . (int)$theme->id);

			$db->setQuery($query);
			$return = $db->execute() && $return;
		}

		die(json_encode(array(
					'status' => $return,
					'message' => JText::_($return ? 'T3_NAVIGATION_DELETE_SUCCESSFULLY' : 'T3_NAVIGATION_DELETE_FAILED')
				)
			)
		);
	}
	
	public static function save()
	{
		$input         = JFactory::getApplication()->input;
		$template      = $input->get('template');
		$mmconfig      = $input->getString('config');
		$mmkey         = $input->get('mmkey', $input->get('menutype', 'mainmenu'));
		$tplparams     = T3::getTplParams();

		if(!is_null($mmconfig)){
			$mmconfig  = stripslashes($mmconfig);
		} 
		
		$currentconfig = $tplparams instanceof Registry ? $tplparams->get('mm_config', '') : null;
		$_reg = new Registry;
		if(getType(json_decode($currentconfig, true)) == "array"){
			$_reg->loadArray(json_decode($currentconfig, true));
		}
		$_reg->set($mmkey, json_decode($mmconfig, true));

		$mm_config = $_reg->toString();

		//get all other styles that have the same template
		$db    = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query
			->select('*')
			->from('#__template_styles')
			->where('template=' . $db->quote($template));

		$db->setQuery($query);
		$themes = $db->loadObjectList();
		$return = true;
		
		foreach($themes as $theme){
			$registry = new Registry;
			$registry->loadString($theme->params);

			//overwrite with new value
			$registry->set('mm_config', $mm_config);

			$query = $db->getQuery(true);
			$query
				->update('#__template_styles')
				->set('params =' . $db->quote($registry->toString()))
				->where('id =' . (int)$theme->id);

			$db->setQuery($query);
			$return = $db->execute() && $return;
		}

		die(json_encode(array(
					'status' => $return,
					'message' => JText::_($return ? 'T3_NAVIGATION_SAVE_SUCCESSFULLY' : 'T3_NAVIGATION_SAVE_FAILED')
				)
			)
		);
	}

	/**
	 *
	 * Ge all available modules
	 */
	public static function menus()
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('menutype AS value, title AS text')
			->from($db->quoteName('#__menu_types'))
			->order('title');
		$db->setQuery($query);
		$menus = $db->loadObjectList();

		$query = $db->getQuery(true)
			->select('menutype, language')
			->from($db->quoteName('#__menu'))
			->where('published = 1')
			->group('menutype');
		$db->setQuery($query);
		$menulangs = $db->loadAssocList('menutype');

		$query = $db->getQuery(true)
			->select('menutype, language')
			->from($db->quoteName('#__menu'))
			->where('home = 1 and published = 1');
		$db->setQuery($query);
		$homelangs = $db->loadAssocList('menutype');

		if(is_array($menulangs) && is_array($homelangs)){
			$menulangs = array_merge($menulangs, $homelangs);
		}

		if(is_array($menus) && is_array($menulangs)){
			foreach ($menus as $menu) {
				$menu->text = $menu->text . ' [' . $menu->value . ']';
				$menu->language = isset($menulangs[$menu->value]) ? $menulangs[$menu->value]['language'] : '*';
			}
		}
		
		return is_array($menus) ? $menus : array();
	}

	/**
	 *
	 * Ge all support access levels
	 */
	public static function access()
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		$query->select('a.id AS value, a.title AS text');
		$query->from('#__viewlevels AS a');
		$query->group('a.id, a.title, a.ordering');
		$query->order('a.ordering ASC');
		$query->order($query->qn('title') . ' ASC');
		$query->where('a.id in (1,2,3) or a.title = ' . $db->quote('Guest')); //we only support Public, Registered, Special, Guest
		
		// Get the options.
		$db->setQuery($query);
		$options = $db->loadObjectList();
		
		return is_array($options) ? $options : array();
	}

	/**
	 *
	 * Ge all available modules
	 */
	public static function modules()
	{
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query
			->select('id, title, module, position')
			->from('#__modules')
			->where('published = 1')
			->where('client_id = 0')
			->order('title');
		$db->setQuery($query);
		$modules = $db->loadObjectList();
		
		return is_array($modules) ? $modules : array();
	}
	
	/**
	 *
	 * Show thememagic form
	 */
	public static function megamenu()
	{
		$tplparams = T3::getTplParams();
		
		//$url = JFactory::getURI();
		$url = JUri::getInstance();
		$url->delVar('t3action');
		$url->delVar('t3task');
		$referer  = $url->toString();
		$template = T3_TEMPLATE;
		$styleid  = JFactory::getApplication()->input->getCmd('id');

		$mm_type  = ($tplparams && $tplparams instanceof Registry) ? $tplparams->get('mm_type', '') : null;

		//Keepalive
		$config      = JFactory::getConfig();
		$lifetime    = ($config->get('lifetime') * 60000);
		$refreshTime = ($lifetime <= 60000) ? 30000 : $lifetime - 60000;
		
		// Refresh time is 1 minute less than the liftime assined in the configuration.php file.
		// The longest refresh period is one hour to prevent integer overflow.
		if ($refreshTime > 3600000 || $refreshTime <= 0) {
			$refreshTime = 3600000;
		}

		//check config
		$currentconfig = ($tplparams && $tplparams instanceof Registry) ? $tplparams->get('mm_config', '') : null;
		if(!$currentconfig){
			$currentconfig = '"{}"';
		}
		
		include T3_ADMIN_PATH . '/admin/megamenu/megamenu.tpl.php';
		
		exit;
	}

	/**
	 * Copy from Joomla 3.x
	 */
	public static function tooltipText($title = '', $content = '', $translate = 1, $escape = 1)
	{
	  // Return empty in no title or content is given.
	  if ($title == '' && $content == '')
	  {
	    return '';
	  }

	  // Split title into title and content if the title contains '::' (old Mootools format).
	  if ($content == '' && !(strpos($title, '::') === false))
	  {
	    list($title, $content) = explode('::', $title, 2);
	  }

	  // Pass texts through the JText.
	  if ($translate)
	  {
	    $title = JText::_($title);
	    $content = JText::_($content);
	  }

	  // Escape the texts.
	  if ($escape)
	  {
	    $title = str_replace('"', '&quot;', $title);
	    $content = str_replace('"', '&quot;', $content);
	  }

	  // Return only the content if no title is given.
	  if ($title == '')
	  {
	    return $content;
	  }

	  // Return only the title if title and text are the same.
	  if ($title == $content)
	  {
	    return '<strong>' . $title . '</strong>';
	  }

	  // Return the formated sting combining the title and  content.
	  if ($content != '')
	  {
	    return '<strong>' . $title . '</strong><br />' . $content;
	  }

	  // Return only the title.
	  return $title;
	}
}
PK�L#]ex�sn=n=	theme.phpnu&1i�PK�L#]�����7�7
�=layout.phpnu&1i�PK�L#]O�(�(�umegamenu.phpnu&1i�PK���