<?php
/**
 * FW Food menu 5.1.1
 * @copyright (C) 2020 Fastw3b
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * @link http://www.fastw3b.net/ Official website
 **/

defined( '_JEXEC' ) or die( 'Restricted access' );

define('FWA_UPDATE_NAME', 'com_fwfoodmenu');
define('FWA_UPDATE_SERVER', 'https://fastw3b.com');

/* WP integration */
if (!defined('FWFM_LANGUAGE_SITE')) {
	define('FWFM_LANGUAGE_SITE', JPATH_SITE);
}
if (!defined('FWFM_LANGUAGE_ADMINISTRATOR')) {
	define('FWFM_LANGUAGE_ADMINISTRATOR', JPATH_ADMINISTRATOR);
}
if (!defined('FWFM_COMPONENT_SITE')) {
	define('FWFM_COMPONENT_SITE', JPATH_SITE.'/components/com_fwfoodmenu');
}
if (!defined('FWFM_COMPONENT_ADMINISTRATOR')) {
	define('FWFM_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR.'/components/com_fwfoodmenu');
}
if (!defined('FWFM_ASSETS_URI')) {
	define('FWFM_ASSETS_URI', JURI::root(true).'/components/com_fwfoodmenu/assets/');
}
if (!defined('FWFM_ADMIN_ASSETS_URI')) {
	define('FWFM_ADMIN_ASSETS_URI', JURI::root(true).'/administrator/components/com_fwfoodmenu/assets/');
}

define('FWFM_ASSETS_PATH', FWFM_COMPONENT_SITE.'/assets/');

JPluginHelper::importPlugin('fwfoodmenu');
JPluginHelper::importPlugin('fwfoodmenutmpl');

if (!class_exists('fwfmGlobalParams')) {
	class fwfmGlobalParams {
		var $data = null;
		static function getInstance() {
			static $params = null;
			if (is_null($params)) {
				$params = new fwfmGlobalParams();
			}
			return $params;
		}
		function __construct() {
//			$app = JFactory::getApplication();
//			if ($app->isClient('site') and $app->input->getCmd('option') == 'com_fwfoodmenu') {
//				$this->data = $app->getParams();
//			} else {
				$this->data = JComponentHelper::getParams('com_fwfoodmenu');
				JFactory::getApplication()->triggerEvent('onLoadParams', array('com_fwfoodmenu', &$this->data));
//			}
		}
		function loadArray($array) {
			$this->data->loadArray($array);
		}
		function merge($params) {
			$this->data->merge($params);
		}
		function set($key, $val) {
			$this->data->set($key, $val);
		}
		function get($key, $def=null) {
			return $this->data->get($key, $def);
		}
		function toString() {
			return $this->data->toString();
		}
	}
}

if (!class_exists('JFParams')) {
	class JFParams {
		var $params = null;
		var $parent_categories = null;
		function __construct($params, $parent_categories=null) {
			$this->params = clone($params);
			if ($parent_categories) {
				$this->parent_categories = $parent_categories;
			}
		}
		function set($key, $val) {
			$this->params->set($key, $val);
		}
		function get($key, $def=null) {
			$val = $this->params->get($key, 'def');
			$is_size = in_array($key, array('image_size_x', 'image_size_y'));
			if ($is_size and !$val) {
				$val = 'def';
			}
			if ($val == 'def') {
				if ($this->parent_categories) {
					foreach ($this->parent_categories as $category) {
						$val = $category->params->get($key, 'def');
						if ($is_size and !$val) {
							$val = 'def';
						}
						if ($val != 'def') {
							return $val;
						}
					}
				}
				$app = JFactory::getApplication();
				if ($app->isClient('site') and $app->input->getCmd('option') == 'com_fwfoodmenu') {
					$val = $app->getParams()->get($key, $def);
					if ($val == 'def') {
						$val = fwfmGlobalParams::getInstance()->get($key, $def);
					}
				} else {
					$val = fwfmGlobalParams::getInstance()->get($key, $def);
				}
			}
			return $val;
		}
	}
}

if (!class_exists('fwfmView')) {
	class fwfmView {
		var $layout = 'default';
		function getLayout() {
			return $this->layout;
		}
		function setLayout($layout) {
			$this->layout = $layout;
		}
		function loadTemplate($tmpl='') {
			$app = JFactory::getApplication();
			if ($tmpl) $tmpl = '_'.$tmpl;
			$path = JPATH_SITE.'/templates/'.$app->getTemplate().'/html/com_fwfoodmenu/menu/'.$this->layout.$tmpl.'.php';
			ob_start();
			if (file_exists($path)) {
				include($path);
			} else {
				$path = JPATH_SITE.'/components/com_fwfoodmenu/views/menu/tmpl/'.$this->layout.$tmpl.'.php';
				include($path);
			}
			return ob_get_clean();
		}
		function display() {
			echo $this->loadTemplate();
		}
		function escape($text) {
			return htmlspecialchars($text);
		}
	}
}

jimport('joomla.plugin.plugin');

class fwfmJPlugin extends JPlugin {
	var $errors = array();
	function setError($msg) {
		$this->errors[] = $msg;
	}
	function getError($i = NULL, $toString = true) {
		if ($this->errors) {
			return $this->errors[count($this->errors) - 1];
		}
	}
	function getErrors() {
		return $this->errors;
	}
}

class fwfmMessages {
	static function getInstance() {
		static $instance = null;
		if (is_null($instance)) {
			$instance = new fwfmMessages();
		}
		return $instance;
	}
	function add($msg, $status='warning') {
		$messages = $this->getAll();
		$messages[] = (object)array(
			'msg' => $msg,
			'status' => $status
		);
		$this->set($messages);
	}
	function getLast() {
		if ($messages = $this->getAll()) {
			return $messages[count($messages)-1];
		}
	}
	function clearAll() {
		$this->set(array());
	}
	function set($messages) {
		JFactory::getApplication()->setUserState('com_fwfoodmenu.messages', $messages);
	}
	function getAll() {
		return JFactory::getApplication()->getUserState('com_fwfoodmenu.messages', array());
	}
}

class fwfmButtons {
	var $buttons = array();
	static function getInstance() {
		static $btns;
		if (!is_object($btns)) {
			$btns = new fwfmButtons;
		}
		return $btns;
	}
	function addButton($icon, $color, $alt, $task, $listSelect) {
		$btn = (object)array(
			'icon' => $icon,
			'color' => $color,
			'alt' => JText::_($alt),
			'task' => $task,
			'listSelect' => $listSelect
		);
		$this->buttons[] = $btn;
	}
	function getButtons() {
		return $this->buttons;
	}
}
class fwfmButtonsHelper {
	static function addNew($task='add', $alt="JTOOLBAR_APPLY") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='plus', $color='green', $alt, $task, $listSelect=false);
	}
	static function custom($icon, $color, $alt, $task, $listSelect) {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon, $color, $alt, $task, $listSelect);
	}
	static function editList($task='edit', $alt="JTOOLBAR_EDIT") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='file-edit', $color='', $alt, $task, $listSelect=true);
	}
	static function deleteList($listSelect='', $task='remove', $alt="JTOOLBAR_DELETE") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='trash', $color='red', $alt, $task, $listSelect);
	}
	static function publish($task='publish', $alt="JTOOLBAR_PUBLISH", $listSelect=true) {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='check', $color='', $alt, $task, $listSelect);
	}
	static function unpublish($task='unpublish', $alt="JTOOLBAR_UNPUBLISH", $listSelect=true) {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='close', $color='', $alt, $task, $listSelect);
	}
	static function apply($task='apply', $alt="JTOOLBAR_APPLY") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='file-edit', $color='green', $alt, $task, $listSelect=false);
	}
	static function save($task='save', $alt="JTOOLBAR_SAVE") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='save', $color='', $alt, $task, $listSelect=false);
	}
	static function save2New($task='save2new', $alt="JTOOLBAR_SAVE_NEW") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='save', $color='', $alt, $task, $listSelect=false);
	}
	static function save2Copy($task='save2copy', $alt="JTOOLBAR_SAVE_COPY") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='save', $color='', $alt, $task, $listSelect=false);
	}
	static function cancel($task='cancel', $alt="JTOOLBAR_CANCEL") {
		$btns = fwfmButtons::getInstance();
		$btns->addButton($icon='close', $color='', $alt, $task, $listSelect=false);
	}
}

class fwFoodMenuHelper {
	static function numeral($num) {
		$lang = fwFoodMenuHelper::getLanguage();
		$suffix = '';
		$last_num = $num%10;
		switch ($lang) {
			case 'ru-RU' :
				if ($last_num == 3) {
					$suffix = 'ий';
				} elseif (in_array($last_num, array(2, 6, 7, 8))) {
					$suffix = 'ой';
				} else {
					$suffix = 'ый';
				}
			break;
			case 'uk-UA' :
				if ($last_num == 3) {
					$suffix = 'iй';
				} else {
					$suffix = 'ий';
				}
			break;
			default:
				if ($num == '11' or $last_num > 3) {
					$suffix = 'th';
				} elseif ($last_num == 1) {
					$suffix = 'st';
				} elseif ($last_num == 2) {
					$suffix = 'nd';
				} else {
					$suffix = 'rd';
				}
		}
		return $num.$suffix;
	}
	static function getAppVersion() {
		$buff = file_get_contents(FWFM_COMPONENT_ADMINISTRATOR.'/fwfoodmenu.xml');
		if (preg_match('#<version>(.*?)</version>#msi', $buff, $match)) {
			return $match[1];
		}
	}
	static function jtext($const) {
		static $buff = null;
		if (is_null($buff)) {
			$lang = fwFoodMenuHelper::getLanguage();
			$admin_override = JPATH_ADMINISTRATOR.'/language/overrides/'.$lang.'.override.ini';
			if (file_exists($admin_override)) {
				$admin_buff = explode("\n", file_get_contents($admin_override));
				foreach ($admin_buff as $tmp) {
					$row = explode('=', $tmp, 2);
					if (!empty($row[1])) {
						$buff[$row[0]] = trim($row[1], '"');
					}
				}
			}
			$site_override = JPATH_SITE.'/language/overrides/'.$lang.'.override.ini';
			if (file_exists($site_override)) {
				$site_buff = explode("\n", file_get_contents($site_override));
				foreach ($site_buff as $tmp) {
					$row = explode('=', $tmp, 2);
					if (!empty($row[1])) {
						$buff[$row[0]] = trim($row[1], '"');
					}
				}
			}
		}
		return empty($buff[$const])?JText::_($const):$buff[$const];
	}
	static function route($url, $b1=true, $b2=0) {
		static $j4r = null;
		if (is_null($j4r)) {
			$inp = JFactory::getApplication()->input;
			if ($inp->getCmd('option') == 'com_fwfoodmenu' and class_exists('JVersion')) {
				$ver = new JVersion;
				$j4r = $ver->isCompatible('4.0');
			}
			if (is_null($j4r)) $j4r = false;
		}
		if ($j4r) {
			$url = str_replace(array('option=com_fwfoodmenu&amp;', 'option=com_fwfoodmenu&'), '', $url);
		}
		return JRoute::_($url, $b1, $b2);
	}
	static function getModificatorsById($mids) {
		$result = array();
		static $mods = null;
		if (!is_array($mods)) {
			$db = JFactory::getDBO();
			$db->setQuery('SELECT * FROM `#__fwfoodmenu_menu_modificator`');
			$mods = (array)$db->loadObjectList();
		}
		if ($mods and $mids) {
			foreach ($mods as $mod) {
				if (in_array($mod->id, $mids)) {
					$result[] = $mod;
				}
			}
		}
		return $result;
	}
	static function relativeDate($date, $start=null) {
		$result = '';

		if (!empty($start) and !is_numeric($start)) {
			$start = strtotime($start);
		}
		if (is_null($start)) {
			$start = strtotime(JHTML::date('now', 'Y-m-d H:i:s'));
		}

		$time = is_numeric($date)?$date:strtotime($date);
		if (!$time) {
			return JText::_('FWFM_PERIOD_UNKNOWN');
		}

		$time = $start - $time;

		$years = (int)($time/31104000);
		if ($years) $time -= $years * 31104000;

		$months = (int)($time/2592000);
		if ($months) $time -= $months * 2592000;


		$weeks = (int)($time/604800);
		if ($weeks) $time -= $weeks * 604800;
		$days = (int)($time/86400);
		if ($days) $time -= $days * 86400;
		$hours = (int)($time/3600);
		if ($hours) $time -= $hours * 3600;
		$minutes = (int)($time/60);
		if ($minutes) $time -= $minutes * 60;
		$seconds = $time;
		if ($years) {
			$result .= $years.' ';
			if ($years == 1) $result .= JText::_('FWFM_YEAR');
			else $result .= JText::_('FWFM_YEARS');

			if ($months) {
				$result .= ($result?' ':'').$months.' ';
				if ($months == 1) $result .= JText::_('FWFM_MONTH');
				else $result .= JText::_('FWFM_MONTHS');
			}
		} elseif ($months) {
			$result .= $months.' ';
			if ($months == 1) $result .= JText::_('FWFM_MONTH');
			else $result .= JText::_('FWFM_MONTHS');

			if ($weeks) {
				$result .= ($result?' ':'').$weeks.' ';
				if ($weeks == 1) $result .= JText::_('FWFM_WEEK');
				else $result .= JText::_('FWFM_WEEKS');
			}
		} elseif ($weeks) {
			$result .= $weeks.' ';
			if ($weeks == 1) $result .= JText::_('FWFM_WEEK');
			else $result .= JText::_('FWFM_WEEKS');

			if ($days) {
				$result .= ($result?' ':'').$days.' ';
				if ($days == 1) $result .= JText::_('FWFM_DAY');
				else $result .= JText::_('FWFM_DAYS');
			}
		} elseif ($days) {
			$result .= $days.' ';
			if ($days == 1) $result .= JText::_('FWFM_DAY');
			else $result .= JText::_('FWFM_DAYS');

			if ($hours) {
				$result .= ($result?' ':'').$hours.' ';
				if ($hours == 1) $result .= JText::_('FWFM_HOUR');
				else $result .= JText::_('FWFM_HOURS');
			}
		} elseif ($hours) {
			$result .= $hours.' ';
			if ($hours == 1) $result .= JText::_('FWFM_HOUR');
			else $result .= JText::_('FWFM_HOURS');

			if ($minutes) {
				$result .= ($result?' ':'').$minutes.' ';
				if ($minutes == 1) $result .= JText::_('FWFM_MINUTE');
				else $result .= JText::_('FWFM_MINUTES');
			}
		} elseif ($minutes or $seconds) {
			if ($minutes) {
				$result .= $minutes.' ';
				if ($minutes == 1) $result .= JText::_('FWFM_MINUTE');
				else $result .= JText::_('FWFM_MINUTES');
			} elseif ($seconds) {
				$result .= JText::_('FWFM_LESS_MINUTE');
			}
		}

		return $result;
	}
	static function triggerEvent($event, $params) {
		$data = JFactory::getApplication()->triggerEvent($event, $params);
		static $modals = array();
		$plugins = array(
			'plg_fwfoodmenu_cart',
			'plg_fwfoodmenu_cascading',
			'plg_fwfoodmenu_categorypdf',
			'plg_fwfoodmenu_color',
			'plg_fwfoodmenu_columns',
			'plg_fwfoodmenu_image',
			'plg_fwfoodmenu_mealbadges',
			'plg_fwfoodmenu_multilingual',
			'plg_fwfoodmenu_prices',
			'plg_fwfoodmenu_seobooster',
		);
		$path = FWFM_COMPONENT_ADMINISTRATOR.'/layouts/addons/';
		foreach ($plugins as $plugin) {
			$buff = explode('_', $plugin);
			if (!fwFoodMenuHelper::pluginEnabled($buff[count($buff) - 1]) and file_exists($path.$plugin.'/'.strtolower($event).'.php')) {
				if (!isset($modals[$plugin])) {
					if (file_exists($path.$plugin.'/modal_advert.php')) {
?>
<div id="fwfm-modal-advert-<?php echo esc_attr($plugin); ?>" uk-modal>
  <div class="uk-modal-dialog">
      <div class="uk-modal-header">
        <h5 class="uk-modal-title" id="exampleModalLabel"><?php echo JText::_('FWFM_ADDON_'.$plugin); ?></h5>
        <button class="uk-modal-close-default" type="button" uk-close></button>
      </div>
      <div class="uk-modal-body">
        <?php include($path.$plugin.'/modal_advert.php'); ?>
      </div>
  </div>
</div>
<?php
					}
					$modals[$plugin] = true;
				}
?>
<div class="fwa-modal-advert" uk-toggle="target: #fwfm-modal-advert-<?php echo esc_attr($plugin); ?>"><?php include($path.$plugin.'/'.strtolower($event).'.php'); ?></div>
<?php
			}
		}
		return $data;
	}
	static function stripTags($text, $limit=null, $show_counter=false) {
		if (!$limit) return;
		$text = strip_tags(preg_replace(array('#\{[^\}]+\}#', '#^<p>|</p>$#', '#\r\n\r\n#', '#\n\n#', '#\&nbsp;#'), array('', '', "\n", "\n", ' '), trim($text)));
		if (is_numeric($limit) and $limit > 0 and mb_strlen($text) > $limit) {
			$text = rtrim(mb_substr($text, 0, $limit), '.').'&hellip;'.($show_counter?(' ['.mb_strlen($text).']'):'');
		}
		return nl2br($text);
	}
	static function messageEscape($text) {
		return addcslashes(str_replace(array("\r\n", "\n", "\r"), '<br/>', $text), "'");
	}
	static function addMessage($msg, $status='warning') {
		$messages = fwfmMessages::getInstance();
		$messages->add($msg, $status);
	}
	static function getMessage() {
		$messages = fwfmMessages::getInstance();
		return $messages->getLast();
	}
	static function getMessages() {
		$messages = fwfmMessages::getInstance();
		return $messages->getAll();
	}
	static function clearMessages() {
		$messages = fwfmMessages::getInstance();
		return $messages->clearAll();
	}
	static function encodeDate($date) {
		if (!$date) return;
		$params = fwfmGlobalParams::getInstance();
		$buff = explode(' ', $date, 2);
		$encoded_date = '';
		switch ($params->get('date_format')) {
			case 'd/m/Y' :
				$parts = explode('/', $buff[0]);
				if (count($parts) == 3) {
					$encoded_date = $parts[2].'-'.$parts[1].'-'.$parts[0];
				}
			break;
			case 'd.m.Y' :
				$parts = explode('.', $buff[0]);
				if (count($parts) == 3) {
					$encoded_date = $parts[2].'-'.$parts[1].'-'.$parts[0];
				}
			break;
			case 'Y-m-d' :
				$parts = explode('-', $buff[0]);
				if (count($parts) == 3) {
					$encoded_date = $parts[0].'-'.$parts[1].'-'.$parts[2];
				}
			break;
			default :
				$parts = explode('/', $buff[0]);
				if (count($parts) == 3) {
					$encoded_date = $parts[2].'-'.$parts[0].'-'.$parts[1];
				}
		}
		return $encoded_date.(empty($buff[1])?'':(' '.$buff[1]));
	}
	static function colorpicker() {
		JHTML::_('jquery.framework');
		JHTML::stylesheet('components/com_fwfoodmenu/assets/css/jquery.minicolors.css', array('version'=>'v=100'));
		JHTML::script('components/com_fwfoodmenu/assets/js/jquery.minicolors.min.js');
		JFactory::getDocument()->addScriptDeclaration('
		document.addEventListener(\'DOMContentLoaded\', function() {
			(function($) {
			$(\'.minicolors\').each(function() {
				$(this).minicolors({
					control: $(this).attr(\'data-control\') || \'hue\',
					format: $(this).attr(\'data-validate\') === \'color\'
						? \'hex\'
						: ($(this).attr(\'data-format\') === \'rgba\'
							? \'rgb\'
							: $(this).attr(\'data-format\'))
						|| \'hex\',
					keywords: $(this).attr(\'data-keywords\') || \'\',
					opacity: $(this).attr(\'data-format\') === \'rgba\' ? true : false || false,
					position: $(this).attr(\'data-position\') || \'default\',
					theme: \'bootstrap\'
				});
			});
			})(jQuery);
		});');
	}
	static function getEditor() {
		$editor = JFactory::getConfig()->get('editor');
		return JEditor::getInstance($editor);
	}
	static function splitSql($sql) {
		$start = 0;
		$open = false;
		$char = '';
		$end = strlen($sql);
		$queries = array();

		for ($i = 0; $i < $end; $i++)
		{
			$current = substr($sql, $i, 1);

			if (($current == '"' || $current == '\''))
			{
				$n = 2;

				while (substr($sql, $i - $n + 1, 1) == '\\' && $n < $i)
				{
					$n++;
				}

				if ($n % 2 == 0)
				{
					if ($open)
					{
						if ($current == $char)
						{
							$open = false;
							$char = '';
						}
					}
					else
					{
						$open = true;
						$char = $current;
					}
				}
			}

			if (($current == ';' && !$open) || $i == $end - 1)
			{
				$queries[] = substr($sql, $start, ($i - $start + 1));
				$start = $i + 1;
			}
		}

		return $queries;
	}
	static function getCategory($cid) {
		$cats = fwFoodMenuHelper::loadCategories();
		foreach ($cats as $cat) {
			if ($cat->id == $cid) {
				return $cat;
			}
		}
	}
	static function getCategoryParams($cid) {
		static $data = array();
		if (!isset($data[$cid])) {
			$cats = fwFoodMenuHelper::loadCategories();
			$params = null;
			if ($cid) {
				foreach ($cats as $cat) {
					if ($cat->id == $cid) {
						$data[$cid] = new JFParams($cat->params, fwFoodMenuHelper::getParentCategories($cat->parent));
						break;
					}
				}
			}
			if (!isset($data[$cid])) {
				$data[$cid] = new JFParams(new JRegistry);
			}
		}
		return $data[$cid];
	}
	static function getParentCategories($id) {
		$categories = fwFoodMenuHelper::loadCategories();
		$data = array();
		if ($id) {
			foreach ($categories as $category) {
				if ($category->id == $id) {
					$data[$category->parent] = $category;
				}
			}
			do {
				$found = false;
				$ids = array_keys($data);
				foreach ($categories as $category) {
					if (!isset($data[$category->parent]) and in_array($category->id, $ids)) {
						$data[$category->parent] = $category;
						$found = true;
					}
				}
			} while($found);
		}
		return $data;
	}
	static function getInstalledLanguages() {
		static $languages;
		if (!is_array($languages)) {
			$buff = JLanguageHelper::getKnownLanguages();
			foreach ($buff as $row) {
				$lang = new stdclass;
				$lang->id = $row['tag'];
				$lang->tag = $row['tag'];
				$lang->name = $row['name'];
				$languages[$row['tag']] = $lang;
			}
		}
		return $languages;
	}
	static function getLanguage() {
		static $lang = null;
		if (!$lang) {
			$db = JFactory::getDBO();
			$app = JFactory::getApplication();
			$lang = $app->getUserStateFromRequest('com_fwfoodmenu.language', 'lang');
			if ($lang and strlen($lang) == 2) {
				$db->setQuery('SELECT `lang_code` FROM `#__languages` WHERE `sef` = '.$db->quote($lang));
				$lang = $db->loadResult();
			}
			if (!$lang) {
				$lang  = JFactory::getLanguage()->getTag();
			}
			if (!$lang or ($lang and !in_array($lang, array_keys(fwFoodMenuHelper::getInstalledLanguages())))) {
				$db->setQuery('SELECT `lang_code` FROM `#__languages` WHERE `published` = 1 AND `ordering` = 1');
				$lang = $db->loadResult();
				if (!$lang) {
					$lang = 'en-GB';
				}
			}
		}
		return $lang;
	}
	static function getJoomlaLanguage() {
		$lang = fwFoodMenuHelper::getLanguage();
		return JLanguage::getInstance($lang);
	}
	static function storeConfig($params) {
		$cache = JFactory::getCache('_system', 'callback');
    	$cache->clean();

    	$db = JFactory::getDBO();
    	$db->setQuery('UPDATE `#__extensions` SET params = '.$db->quote($params->toString()).' WHERE `element` = \'com_fwfoodmenu\' AND `type` = \'component\'');
    	return $db->execute();
	}
    static function loadPlugins() {
        static $plugins;
        if (!is_array($plugins)) {
			$plugins = array();

            $db = JFactory::getDBO();
            $db->setQuery('
SELECT
    `element`,
    `enabled`,
	`folder`
FROM
    `#__extensions`
WHERE
    `type` = \'plugin\'
    AND
    `folder` IN (\'fwfoodmenu\', \'fwfoodmenutmpl\')');
            if ($data = $db->loadObjectList()) {
				foreach ($data as $row) {
					if (!isset($plugins[$row->folder])) {
						$plugins[$row->folder] = array();
					}
					$plugins[$row->folder][$row->element] = $row;
				}
			}
        }
        return $plugins;
    }
    static function pluginInstalled($name, $type = 'fwfoodmenu') {
        $plugins = fwFoodMenuHelper::loadPlugins();
        return isset($plugins[$type][$name]);
    }
    static function pluginEnabled($name, $type = 'fwfoodmenu') {
        $plugins = fwFoodMenuHelper::loadPlugins();
        if (!empty($plugins[$type][$name])) {
            return $plugins[$type][$name]->enabled;
        }
	}
	static function pluginDisabledViaMenu($plugin) {
		$app = JFactory::getApplication();
		if ($app->isClient('administrator')) return;
		$params = $app->getParams();
		if ($params->get('show_addons_menu_settings')) {
			$disabled_addons = $params->get('plugins', array($plugin=>1));
			return empty($disabled_addons[$plugin]);
		}
	}
	static function getThemesList() {
		$themes = array(
			JHTML::_('select.option', 'common', JText::_('FWFM_THEME_DEFAULT'), 'id', 'name')
		);
		$db = JFactory::getDBO();
		$db->setQuery("SELECT name, `element` FROM `#__extensions` WHERE `type` = 'plugin' AND `folder` = 'fwfoodmenutmpl' AND `enabled` = 1");
		if ($list = $db->loadObjectList()) {
			$lang = JFactory::getLanguage();
			foreach ($list as $row) {
				$lang->load('plg_fwfoodmenutmpl_'.$row->element);
				$themes[] = JHTML::_('select.option', $row->element, JText::_($row->name), 'id', 'name');
			}
		}
		return $themes;
	}
	static function escPluginsOutput($plugins_output) {
		static $tags = null;
		/** @note - plugin output escaped already and complicated to filter, this filter broke scripts */
		if (false and function_exists('wp_kses')) {
			if (is_null($tags)) {
				$tags = wp_kses_allowed_html();
				$tags['h1'] = array('class'=>1, 'id'=>1, 'data-title'=>1, 'data-toggle'=>1, 'itemprop'=>1);
				$tags['form'] = array('class'=>1, 'id'=>1, 'name'=>1, 'action'=>1);
				$tags['input'] = array('id'=>1, 'class'=>1, 'type'=>1, 'name'=>1, 'value'=>1);
				$tags['textarea'] = array('id'=>1, 'class'=>1, 'cols'=>1, 'rows'=>1, 'style'=>1, 'name'=>1, 'value'=>1);
				$tags['select'] = array('id'=>1, 'class'=>1, 'type'=>1, 'name'=>1, 'data-toggle'=>1, 'data-title'=>1);
				$tags['button'] = array('id'=>1, 'class'=>1, 'type'=>1, 'name'=>1, 'data-toggle'=>1, 'data-title'=>1, 'data-dismiss'=>1, 'data-bs-dismiss'=>1, 'data-filter'=>1, 'data-value'=>1, 'data-active-class'=>1);
				$tags['iframe'] = array('id'=>1, 'class'=>1, 'src'=>1, 'name'=>1, 'frameborder'=>1, 'allow'=>1, 'webkitallowfullscreen'=>1, 'mozallowfullscreen'=>1, 'allowfullscreen'=>1, 'allowautoplay'=>1);
				$tags['i'] = array('class'=>1, 'id'=>1);
				$tags['span'] = array('class'=>1, 'id'=>1);
				$tags['div'] = array('id'=>1, 'class'=>1, 'data-toggle'=>1, 'data-target'=>1);
				$tags['p'] = array('id'=>1, 'class'=>1);
				$tags['label'] = array('id'=>1, 'class'=>1);
				$tags['style'] = array();
				$tags['script'] = array();
				$tags['option'] = array('value'=>1);
				$tags['video'] = array('poster'=>1, 'preload'=>1, 'controls'=>1, 'height'=>1, 'width'=>1, 'class'=>1, 'id'=>1, 'data-setup'=>1);
				$tags['source'] = array('src'=>1, 'type'=>1);

				$tags['a'] = array('class'=>1, 'id'=>1, 'href'=>1, 'data-layout'=>1, 'data-target'=>1, 'data-selector'=>1, 'data-items-per-page'=>1, 'data-total'=>1, 'data-order'=>1, 'data-tmpl'=>1);
			}
			return str_replace(array('&amp;&amp;', ' &gt;', '&lt; ', '&#039;'), array('&&', ' >', '< ', "'"), wp_kses($plugins_output, $tags));
		} else return $plugins_output;
	}
	static function loadAdminStyles() {
		if (JFactory::getLanguage()->isRtl()) {
			JHTML::stylesheet('components/com_fwfoodmenu/assets/css/uikit-rtl.min.css', array('version'=>'v=100'));
		} else {
			JHTML::stylesheet('components/com_fwfoodmenu/assets/css/uikit.min.css', array('version'=>'v=100'));
		}
		JHTML::stylesheet('administrator/components/com_fwfoodmenu/assets/css/fw-back-end.css', array('version'=>'v=108'));
		JHTML::stylesheet('administrator/components/com_fwfoodmenu/assets/css/fwfm-admin.css', array('version'=>'v=111'));
		JHTML::_('jquery.framework');
		JHTML::script('components/com_fwfoodmenu/assets/js/uikit.min.js');
		JHTML::script('components/com_fwfoodmenu/assets/js/uikit-icons.min.js');
		JHTML::script('components/com_fwfoodmenu/assets/js/custom-icons.js', array('version'=>'v=103'));
	}
	static function loadSiteStyles() {
		if (!defined('FWFM_STYLES_LOADED')) {
			define('FWFM_STYLES_LOADED', true);
			$com_params = fwfmGlobalParams::getInstance();
			if (!$com_params->get('do_not_load_uikit')) {
				if (JFactory::getLanguage()->isRtl()) {
					JHTML::stylesheet('components/com_fwfoodmenu/assets/css/uikit-rtl.min.css', array('version'=>'v=100'));
				} else {
					JHTML::stylesheet('components/com_fwfoodmenu/assets/css/uikit.min.css', array('version'=>'v=100'));
				}
				JHTML::script('components/com_fwfoodmenu/assets/js/uikit.min.js');
				JHTML::script('components/com_fwfoodmenu/assets/js/uikit-icons.min.js');
			}
			JHTML::stylesheet('components/com_fwfoodmenu/assets/css/fwfm-design-styles.css', array('version'=>'v=109'));
			JHTML::script('components/com_fwfoodmenu/assets/js/custom-icons.js', array('version'=>'v=102'));
			$buff = $com_params->get('additional_css');
			$font_size = (int)$com_params->get('font_size', 16);
			if (!$font_size) $font_size = 16;
			$buff = 'html {font-size: '.$font_size.'px;}'.$buff;

			if (JFactory::getApplication()->input->getCmd('format', 'html') == 'html') {
				$main_color = $com_params->get('main_color');
				$bgmain_color = $com_params->get('bgmain_color');
				$secondary_color = $com_params->get('secondary_color');
				$bgsecondary_color = $com_params->get('bgsecondary_color');
				$link_color = $com_params->get('link_color');
				if ($main_color or $bgmain_color or $secondary_color or $bgsecondary_color or $link_color) {
					?><style type="text/css">:root{<?php
					if ($main_color) {
						?>--main-color: <?php echo $main_color; ?>;<?php
					}
					if ($bgmain_color) {
						?>--main-background: <?php echo $bgmain_color; ?>;<?php
					}
					if ($secondary_color) {
						?>--secondary-color: <?php echo $secondary_color; ?>;<?php
					}
					if ($bgsecondary_color) {
						?>--secondary-background: <?php echo $bgsecondary_color; ?>;<?php
					}
					if ($link_color) {
						?>--link-color: <?php echo $link_color; ?>;<?php
					}
					?>}</style><?php
				}
			}
			if ($google_font = $com_params->get('google_font')) {
				JHTML::stylesheet('https://fonts.googleapis.com/css?family='.str_replace(' ', '+', $google_font));
				$buff .= '.fwcss * {font-family: '.str_replace('+', ' ', $google_font).', sans-serif}';
			}
			if ($header_font = $com_params->get('google_font_head') and $header_font != $header_font) {
				JHTML::stylesheet('https://fonts.googleapis.com/css?family='.str_replace(' ', '+', $header_font));
				$buff .= '.fwcss h1, .fwcss h2, .fwcss h3, .fwcss h4, .fwcss h5, .fwcss h6, .fwcss .h1, .fwcss .h2, .fwcss .h3, .fwcss .h4, .fwcss .h5, .fwcss .h6 {font-family: '.str_replace('+', ' ', $header_font).', sans-serif}';
			}
			$doc = JFactory::getDocument();
			$doc->addStyleDeclaration($buff);
			$doc->addScriptDeclaration('
document.addEventListener(\'DOMContentLoaded\', function() {
    (function($) {
        window.fwfm_alert = function (msg, title = \''.JText::_('FWFM_NOTIFICATION', true).'\', status = \'info\') {
            var $el = $(\'<div class="toast show toast-\' +
                status + \'" style="opacity:0">\
    <div class="toast-header">\
        <i uk-icon="bell"></i>\
        <strong>\' + title + \'</strong>\
    </div>\
    <div class="toast-body">\' + msg + \'</div>\
</div>\');
			var $wrp = $(\'#fwa-toast-stack\');
			if (!$wrp.length) {
				$wrp = $(\'<div />\', {
					id: \'fwa-toast-stack\'
				});
				$(\'body\').append($wrp);
				$wrp.wrap(\'<div class="fwcss"></div>\');
			}
			$wrp.append($el);
            $el.animate({
                \'opacity\': 1
            }, 500);
            setTimeout(function () {
                $el.animate({
                    \'opacity\': 0
                }, 500, function () {
                    $el.remove();
                });
            }, 5000);
        }
		$(document).on(\'click\', \'a.fwfm-modal\', function(ev) {
			ev.preventDefault();
			var $link = $(this);
			var $popup = $(\'#fwa-modal\');
			if (!$popup.length) {
				$popup = $(\'<div id="fwa-modal" class="uk-modal-container" uk-modal>\
	<div class="uk-modal-dialog">\
		<div class="uk-modal-header">\
			<h5 class="uk-modal-title"></h5>\
			<button class="uk-modal-close-default" type="button" uk-close></button>\
		</div>\
		<div class="uk-modal-body"></div>\
	</div>\
</div>\');
				$(\'body\').append($popup);
			}
			$popup.find(\'.uk-modal-title\').html($link.html());
			$popup.find(\'.uk-modal-body\').html(\'\').load($link.attr(\'href\'), {format: \'raw\'});
			UIkit.modal($popup[0]).show();
		});
    })(jQuery);
});
');
		}
	}
    static function loadTemplate($view, $displayData, $path=null) {
        $app = JFactory::getApplication();

        $tmpl = '';
		$com_path = FWFM_COMPONENT_SITE.'/layouts/';
		if (is_null($path)) {
			$path = JPATH_SITE.'/plugins/fwfoodmenutmpl/';
			$tmpl = $app->input->getCmd('t', $displayData['view']->params->get('template'));
/*echo $tmpl.' '.$view;*/
			if (!$tmpl or ($tmpl and !is_dir($path.$tmpl))) {
				$tmpl = 'common';
				$path = $com_path;
			}
			fwFoodMenuHelper::loadSiteStyles();
			if (file_exists($path.$tmpl.'/assets/css/fwfm-design-styles.css')) {
				JHTML::stylesheet('plugins/fwfoodmenutmpl/'.$tmpl.'/assets/css/fwfm-design-styles.css');
			}
		}

        $buff = explode('.', $view);
        $filename = array_pop($buff).'.php';
        $view_path = implode('/', $buff);

        $full_path = $path.$tmpl.'/'.$view_path.'/'.$filename;
        $tmpl_found = file_exists($full_path);
        if (!$tmpl_found and $tmpl != 'common') {
            $full_path = $com_path.'common/'.$view_path.'/'.$filename;
            $tmpl_found = file_exists($full_path);
        }
        if ($tmpl_found) {
            ob_start();
            include($full_path);
            return ob_get_clean();
        } else {
            return 'template '.$tmpl.', view '.$view.' not found';
        }
    }
	static function fixDescriptionImagesLinks($text) {
		if (preg_match_all('#(src\=")(images/)#', $text, $matches, PREG_SET_ORDER)) {
			$base = JURI::root(true).'/';
			foreach ($matches as $match) {
				$text = str_replace($match[0], $match[1].$base.$match[2], $text);
			}
		}
		return $text;
	}
	static function escape($text) {
		return htmlspecialchars($text);
	}
	static function straightenTree($cat, $level = 1) {
		$result = array();

		$header_added = false;

		if (!empty($cat->_children)) {
			foreach ($cat->_children as $child) {
				if (!$child->published) {
					continue;
				}
				if ($buff = fwFoodMenuHelper::straightenTree($child, $level + 1)) {
					if (!$header_added and $level > 1) {
						$header_added = true;
						$result[] = (object)array(
							'id' => $cat->id,
							'parent' => $cat->parent,
							'image' => $cat->image,
							'type' => 'category',
							'level' => min($level, 4),
							'name' => $cat->name,
							'alias' => $cat->alias,
							'_menu_qty' => $cat->_menu_qty,
							'pdf_menu' => $cat->pdf_menu,
							'published' => $cat->published,
							'description' => $cat->description,
							'short_description' =>$cat->short_description,
							'params' => $cat->params
						);
					}
					$result = array_merge($result, $buff);
				}
			}
		}

		if (!$header_added and $level > 1) {
			$result[] = (object)array(
				'id' => $cat->id,
				'parent' => $cat->parent,
				'image' => $cat->image,
				'type' => 'category',
				'level' => min($level, 4),
				'name' => $cat->name,
				'alias' => $cat->alias,
				'_menu_qty' => $cat->_menu_qty,
				'pdf_menu' => $cat->pdf_menu,
				'published' => $cat->published,
				'description' => $cat->description,
				'short_description' =>$cat->short_description,
				'params' => $cat->params
			);
		}
		if (!empty($cat->_items)) {
			foreach ($cat->_items as $item) {
				$result[] = $item;
			}
		}
		return $result;
	}
	static function loadCategoriesTree($sel_cats) {
		static $cats;
		if (!is_array($cats)) {
			if ($items = fwFoodMenuHelper::loadCategories()) {
				$children = array();
				foreach($items as $i=>$item) {
	//				$items[$i]->params = new JRegistry($item->params);
					$children[$item->parent][] = $item;
				}
				foreach($items as $item) {
					if (isset($children[$item->id])) {
						$item->_children = $children[$item->id];
					}
				}
				$cats = $children[0];
			} else {
				$cats = array();
			}
		}
		if ($cats and $sel_cats and !in_array(0, $sel_cats)) {
			return fwFoodMenuHelper::getSelectedCategories($cats, $sel_cats);
		} else {
			return $cats;
		}
	}
	static function getCategoriesIdBelow($cats, $ids) {
		foreach ($cats as $cat) {
			if (!in_array($cat->id, $ids)) {
				$ids[] = $cat->id;
			}
			if (!empty($cat->_children) and $buff = fwFoodMenuHelper::getCategoriesIdBelow($cat->_children, array())) {
				$ids = array_merge($ids, $buff);
			}
		}
		return $ids;
	}
	static function getSelectedCategories($cats, $sel_cats) {
		$data = array();
		if ($cats) {
			foreach ($cats as $cat) {
				if (in_array($cat->id, $sel_cats)) {
					$data[] = $cat;
				} elseif (!empty($cat->_children) and $buff = fwFoodMenuHelper::getSelectedCategories($cat->_children, $sel_cats)) {
					$data = array_merge($data, $buff);
				}
			}
		}
		return $data;
	}
	static function loadCategories() {
		static $cats;
		if (!is_array($cats)) {
			$db = JFactory::getDBO();
			$app = JFactory::getApplication();
			$where = array();
			$app->triggerEvent('onGetCategoriesListWhere', array('com_fwfoodmenu', &$where));
			$db->setQuery('
SELECT
    c.*,
	(SELECT COUNT(*) FROM #__fwfoodmenu_category AS cc WHERE cc.parent = c.id) AS _cats_qty,
	(SELECT COUNT(*) FROM #__fwfoodmenu_menu AS m WHERE m.category_id = c.id) AS _menu_qty
FROM
    #__fwfoodmenu_category AS c
'.($where?('WHERE '.implode(' AND ', $where)):'').'
ORDER BY
	`parent`,
	ordering');
			if ($cats = $db->loadObjectList('id')) {
				$ids = array();
				foreach ($cats as $i=>$row) {
					$ids[$row->id] = $row->id;
					$cats[$i]->params = new JRegistry($row->params);
				}
				JFactory::getApplication()->triggerEvent('onCalculateCategoryListExtraFields', array('com_fwfoodmenu', &$cats, $ids));
			}
		}
		return $cats;
	}
	static function countCategoriesQty($cid) {
		$cats = fwFoodMenuHelper::loadCategories();
		$qty = 0;
		foreach ($cats as $cat) {
			if ($cat->id == $cid) {
				$qty += $cat->_cats_qty;
			}
			if ($cat->parent == $cid) {
				$qty += fwFoodMenuHelper::countCategoriesQty($cat->id);
			}
		}
		return $qty;
	}
	static function countMealsQty($cid) {
		$cats = fwFoodMenuHelper::loadCategories();
		$qty = 0;
		foreach ($cats as $cat) {
			if ($cat->id == $cid) {
				$qty += $cat->_menu_qty;
			}
			if ($cat->parent == $cid) {
				$qty += fwFoodMenuHelper::countMealsQty($cat->id);
			}
		}
		return $qty;
	}
	static function checkPrevCategory($c) {
		$items = fwFoodMenuHelper::loadCategories();
		$cats = array();
		foreach ($items as $item) {
			if ($item->parent == $c->parent) {
				$cats[$item->id] = $item;
			}
		}

		$prev_id = 0;
		foreach ($cats as $cat) {
			if ($cat->id == $c->id) {
				return !(!$prev_id or ($prev_id and $cats[$prev_id]->parent != $cat->parent));
			}
			$prev_id = $cat->id;
		}
	}
	static function checkNextCategory($c) {
		$items = fwFoodMenuHelper::loadCategories();
		$cats = array();
		foreach ($items as $item) {
			if ($item->parent == $c->parent) {
				$cats[$item->id] = $item;
			}
		}

		$ids = array_keys($cats);
		$next_id = 0;
		for ($i = count($ids) - 1; $i >= 0; $i--) {
			if ($cats[$ids[$i]]->id == $c->id) {
				return !(!$next_id or ($next_id and $cats[$next_id]->parent != $cats[$ids[$i]]->parent));
			}
			$next_id = $cats[$ids[$i]]->id;
		}
	}
	static function findUnicFilename($path, $ext) {
		$filename = '';
		do {
			$filename = md5(microtime().rand()).'.'.$ext;
		} while(file_exists($path.$filename));
		return $filename;
	}
	static function humanFileSize($val) {
		if ($val > 1073741824) return round($val / 1073741824, 2).' Gb';
		if ($val > 1048576) return round($val / 1048576, 2).' Mb';
		elseif ($val > 1024) return round($val / 1024, 2).' Kb';
		elseif ($val and is_numeric($val)) return $val.' b';
		else return $val;
	}
	static function getIniSize($name) {
		$val = ini_get($name);
		if (preg_match('/^(\d+)([MK])$/', $val, $matches)) {
			if ($matches[2] == 'M') $val = $matches[1] * 1024 * 1024;
			elseif ($matches[2] == 'K') $val = $matches[1] * 1024;
		}
		return $val;
	}
	static function formatPrice($price, $use_letters_curr = false) {
		if (!is_numeric($price)) return $price;
		$params = fwfmGlobalParams::getInstance();
    	$lang = fwFoodMenuHelper::getLanguage();
    	$th = ',';
    	$dec = '.';
    	switch ($params->get('currency_delimeter_'.$lang)) {
    		case 'prime' :
		    	$th = "'";
		    	$dec = '.';
    		break;
    		case 'point' :
		    	$th = '.';
		    	$dec = ',';
    		break;
    		case 'space' :
		    	$th = ' ';
		    	$dec = ',';
    		break;
    	}
		$currency = $params->get($use_letters_curr?'currency_code':'currency');
		if (!$currency) return number_format($price, 2, $dec, $th);
		if ($params->get('currency_after')) {
			if ($params->get('hide_ending_ziro')) {
				return rtrim(rtrim(number_format($price, 2, $dec, $th), '0'), '.,').' '.$currency;
			} else {
				return number_format($price, 2, $dec, $th).' '.$currency;
			}
		} else {
			if ($use_letters_curr) {
				$currency .= ' ';
			}
			if ($params->get('hide_ending_ziro')) {
				return $currency.rtrim(rtrim(number_format($price, 2, $dec, $th), '0'), '.,');
			} else {
				return $currency.number_format($price, 2, $dec, $th);
			}
		}
	}
	static function checkImage($menu) {
		return ($menu->image and file_exists(JPATH_SITE.'/media/com_fwfoodmenu/menu/'.$menu->image));
	}
	static function getImageUrl($menu, $direct_link=false) {
		if (fwFoodMenuHelper::checkImage($menu)) {
			return ($direct_link?JURI::root(false):(JURI::root(true).'/')).'media/com_fwfoodmenu/menu/'.$menu->image;
		}
		return 'data:image/svg+xml;charset=UTF-8,%3C%3Fxml-stylesheet%20rel%3D%22stylesheet%22%20href%3D%22http%3A%2F%2Fnetdna.bootstrapcdn.com%2Ffont-awesome%2F4.1.0%2Fcss%2Ffont-awesome.min.css%22%3F%3E%0A%3C%3Fxml-stylesheet%20rel%3D%22stylesheet%22%20href%3D%22http%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DPacifico%22%3F%3E%3Csvg%20width%3D%22400%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1690f886afe%20text%20%7B%20fill%3A%23AAAAAA%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A20pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1690f886afe%22%3E%3Crect%20width%3D%22400%22%20height%3D%22400%22%20fill%3D%22%23EEEEEE%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22148.0234375%22%20y%3D%22209%22%3E400x400%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E';
	}
	static function checkMenuImage($menu) {
		return (!empty($menu->_images) and file_exists(JPATH_SITE.'/media/com_fwfoodmenu/menu/'.$menu->_images[0]->image));
	}
	static function getMenuImageUrl($menu, $direct_link=false) {
		if (fwFoodMenuHelper::checkMenuImage($menu)) {
			return ($direct_link?JURI::root(false):(JURI::root(true).'/')).'media/com_fwfoodmenu/menu/'.$menu->_images[0]->image;
		}
		return 'data:image/svg+xml;charset=UTF-8,%3C%3Fxml-stylesheet%20rel%3D%22stylesheet%22%20href%3D%22http%3A%2F%2Fnetdna.bootstrapcdn.com%2Ffont-awesome%2F4.1.0%2Fcss%2Ffont-awesome.min.css%22%3F%3E%0A%3C%3Fxml-stylesheet%20rel%3D%22stylesheet%22%20href%3D%22http%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DPacifico%22%3F%3E%3Csvg%20width%3D%22400%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1690f886afe%20text%20%7B%20fill%3A%23AAAAAA%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A20pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1690f886afe%22%3E%3Crect%20width%3D%22400%22%20height%3D%22400%22%20fill%3D%22%23EEEEEE%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22148.0234375%22%20y%3D%22209%22%3E400x400%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E';
	}
	static function getItemid($view='menu', $id=null) {
		$menu = JMenu::getInstance('site');
		$item = null;
		if ($items = $menu->getItems('link', 'index.php?option=com_fwfoodmenu&view='.$view)) {
			if (!is_null($id)) {
				foreach ($items as $menuItem) {
					if (in_array($id, (array)$menuItem->getParams()->get('category_id'))) {
						$item = $menuItem;
						break;
					}
				}
			}
			if (!$item) $item = $items[0];
		}

		if ($item) return $item->id;
	}
	static function request($url, $method='get', $data=null, $headers=array(), $timeout=5) {
		$method = strtolower($method);
		if (!in_array($method, array('get', 'post', 'put', 'delete'))) {
			$method = 'get';
		}
		if ($data and in_array($method, array('get', 'delete'))) {
			$buff = http_build_query($data);
			$url .= (strpos($url, '?')===false?'?':'&').$buff;
		}

		$result = '';
		try {
			$http = JHttpFactory::getHttp();
			switch ($method) {
				case 'get' :
					$result = $http->get($url, $headers, $timeout);
				break;
				case 'post' :
					$result = $http->post($url, $data, $headers, $timeout);
				break;
				case 'put' :
					$result = $http->put($url, $data);
				break;
				case 'delete' :
					$result = $http->delete($url);
				break;
			}
		} catch(Exception $e) {
			fwFoodMenuHelper::addMessage($e->getMessage());
		}
		return $result?$result->body:'';
	}
	static function getCategoryAlias($id, $name) {
		$lang = fwFoodMenuHelper::getJoomlaLanguage();
		$name = JFilterOutput::stringURLSafe($lang?$lang->transliterate($name):$name);
		if (!$name) return '';
		$db = JFactory::getDBO();
		$index = 0;
		$alias = '';
		do {
			$alias = $name.($index?('-'.$index):'');
			$db->setQuery('SELECT COUNT(*) FROM `#__fwfoodmenu_category` WHERE alias = '.$db->quote($alias).' AND id <> '.(int)$id);
			$index++;
		} while ($db->loadResult());
		return $alias;
	}
}
if (!class_exists('StringHelper')) {
	class StringHelper {
		public static function strcasecmp($str1, $str2, $locale = false)
		{
			if ($locale)
			{
				// Get current locale
				$locale0 = setlocale(LC_COLLATE, 0);
	
				if (!$locale = setlocale(LC_COLLATE, $locale))
				{
					$locale = $locale0;
				}
	
				// See if we have successfully set locale to UTF-8
				if (!stristr($locale, 'UTF-8') && stristr($locale, '_') && preg_match('~\.(\d+)$~', $locale, $m))
				{
					$encoding = 'CP' . $m[1];
				}
				elseif (stristr($locale, 'UTF-8') || stristr($locale, 'utf8'))
				{
					$encoding = 'UTF-8';
				}
				else
				{
					$encoding = 'nonrecodable';
				}
	
				// If we successfully set encoding it to utf-8 or encoding is sth weird don't recode
				if ($encoding == 'UTF-8' || $encoding == 'nonrecodable')
				{
					return strcoll(utf8_strtolower($str1), utf8_strtolower($str2));
				}
	
				return strcoll(
					static::transcode(utf8_strtolower($str1), 'UTF-8', $encoding),
					static::transcode(utf8_strtolower($str2), 'UTF-8', $encoding)
				);
			}
	
			return utf8_strcasecmp($str1, $str2);
		}
		public static function strcmp($str1, $str2, $locale = false)
		{
			if ($locale)
			{
				// Get current locale
				$locale0 = setlocale(LC_COLLATE, 0);
	
				if (!$locale = setlocale(LC_COLLATE, $locale))
				{
					$locale = $locale0;
				}
	
				// See if we have successfully set locale to UTF-8
				if (!stristr($locale, 'UTF-8') && stristr($locale, '_') && preg_match('~\.(\d+)$~', $locale, $m))
				{
					$encoding = 'CP' . $m[1];
				}
				elseif (stristr($locale, 'UTF-8') || stristr($locale, 'utf8'))
				{
					$encoding = 'UTF-8';
				}
				else
				{
					$encoding = 'nonrecodable';
				}
	
				// If we successfully set encoding it to utf-8 or encoding is sth weird don't recode
				if ($encoding == 'UTF-8' || $encoding == 'nonrecodable')
				{
					return strcoll($str1, $str2);
				}
	
				return strcoll(static::transcode($str1, 'UTF-8', $encoding), static::transcode($str2, 'UTF-8', $encoding));
			}
	
			return strcmp($str1, $str2);
		}
		public static function transcode($source, $fromEncoding, $toEncoding)
		{
			if (\is_string($source))
			{
				switch (ICONV_IMPL)
				{
					case 'glibc':
						return @iconv($fromEncoding, $toEncoding . '//TRANSLIT,IGNORE', $source);
	
					case 'libiconv':
					default:
						return iconv($fromEncoding, $toEncoding . '//IGNORE//TRANSLIT', $source);
				}
			}
		}
	}
}
if (!class_exists('JArrayHelper')) {
	class JArrayHelper {
		protected static $sortCase;
		protected static $sortDirection;
		protected static $sortKey;
		protected static $sortLocale;
		static function toInteger(&$data, $default=0) {
			foreach ($data as $i=>$val) {
				$data[$i] = is_numeric($val)?(int)$val:$default;
			}
		}
		static function toString($data) {
			return implode(' ', (array)$data);
		}
		static function getValue($data, $name, $default='') {
			if (isset($data[$name])) return $data[$name];
			else return $default;
		}
		public static function sortObjects(&$a, $k, $direction = 1, $caseSensitive = true, $locale = false) {
			if (!is_array($locale) || !is_array($locale[0]))
			{
				$locale = array($locale);
			}
	
			self::$sortCase = (array) $caseSensitive;
			self::$sortDirection = (array) $direction;
			self::$sortKey = (array) $k;
			self::$sortLocale = $locale;
	
			usort($a, array(__CLASS__, '_sortObjects'));
	
			self::$sortCase = null;
			self::$sortDirection = null;
			self::$sortKey = null;
			self::$sortLocale = null;
	
			return $a;
		}
		protected static function _sortObjects($a, $b)
		{
			$key = self::$sortKey;
	
			for ($i = 0, $count = count($key); $i < $count; $i++)
			{
				if (isset(self::$sortDirection[$i]))
				{
					$direction = self::$sortDirection[$i];
				}
	
				if (isset(self::$sortCase[$i]))
				{
					$caseSensitive = self::$sortCase[$i];
				}
	
				if (isset(self::$sortLocale[$i]))
				{
					$locale = self::$sortLocale[$i];
				}
	
				$va = $a->{$key[$i]};
				$vb = $b->{$key[$i]};
	
				if ((is_bool($va) || is_numeric($va)) && (is_bool($vb) || is_numeric($vb)))
				{
					$cmp = $va - $vb;
				}
				elseif ($caseSensitive)
				{
					$cmp = StringHelper::strcmp($va, $vb, $locale);
				}
				else
				{
					$cmp = StringHelper::strcasecmp($va, $vb, $locale);
				}
	
				if ($cmp > 0)
				{
					return $direction;
				}
	
				if ($cmp < 0)
				{
					return -$direction;
				}
			}
	
			return 0;
		}
	}
}
if (!function_exists('esc_attr')) {
	function esc_attr($text) {
		return htmlspecialchars((string)$text);
	}
}
if (!function_exists('esc_html')) {
	function esc_html($text) {
		return $text;
	}
}
if (!function_exists('esc_js')) {
	function esc_js($text) {
		return addcslashes($text, "'");
	}
}
if (!function_exists('esc_textarea')) {
	function esc_textarea($text) {
		return htmlspecialchars($text, ENT_QUOTES);
	}
}
if (!function_exists('esc_url')) {
	function esc_url($text) {
		return urlencode($text);
	}
}
if (!function_exists('esc_url_raw')) {
	function esc_url_raw($text) {
		return rawurlencode($text);
	}
}
