<?php
/**
 * @package    VP Advanced User
 * @author     Abhishek Das <info@virtueplanet.com>
 * @copyright  Copyright (C) 2012-2019 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

/**
 * VPAdvancedUser helper.
 *
 * @since  1.0
 */
class VPAdvancedUserHelper
{
	/**
	 * @var    JObject  A cache for the available actions.
	 * @since  1.0
	 */
	protected static $actions;
	
	protected static $extensions;

	/**
	 * Configure the Linkbar.
	 *
	 * @param   string  $vName  The name of the active view.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public static function addSubmenu($vName)
	{
		// Groups and Levels are restricted to core.admin
		$canDoAdvanced = JHelperContent::getActions('com_vpadvanceduser');
		$canDo         = JHelperContent::getActions('com_users');
		$extension     = JFactory::getApplication()->input->getString('extension');
		
		JHtmlSidebar::addEntry(JText::_('COM_USERS_SUBMENU_USERS'), 'index.php?option=com_vpadvanceduser&view=users', $vName == 'users');

		if($canDoAdvanced->get('core.admin'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_VPADVANCEDUSER_TITLE_CUSTOMFIELDS'), 'index.php?option=com_vpadvanceduser&view=customfields', $vName == 'customfields');
			JHtmlSidebar::addEntry(JText::_('COM_VPADVANCEDUSER_TITLE_EMAIL_TEMPLATES'), 'index.php?option=com_vpadvanceduser&view=emailtemplates', $vName == 'emailtemplates');
		}

		if ($canDo->get('core.admin'))
		{
			JHtmlSidebar::addEntry('<hr />', '', false);
			JHtmlSidebar::addEntry(JText::_('COM_USERS_SUBMENU_GROUPS'), 'index.php?option=com_users&view=groups', $vName == 'groups' );
			JHtmlSidebar::addEntry(JText::_('COM_USERS_SUBMENU_LEVELS'), 'index.php?option=com_users&view=levels', $vName == 'levels');
			JHtmlSidebar::addEntry(JText::_('COM_USERS_SUBMENU_NOTES'), 'index.php?option=com_users&view=notes', $vName == 'notes');
			JHtmlSidebar::addEntry(JText::_('COM_USERS_SUBMENU_NOTE_CATEGORIES'), 'index.php?option=com_categories&extension=com_users', $vName == 'categories' || $extension == 'com_users');
		}
	}
	
	public static function checkSystem()
	{
		$app = JFactory::getApplication();
		
		$systemPluginEnabled  = self::hasExtension('vpadvanceduser', 'plugin', 'system');
		$userPluginEnabled    = self::hasExtension('vpadvanceduser', 'plugin', 'user');
		$contentPluginEnabled = self::hasExtension('vpadvanceduser', 'plugin', 'content');

		if(!$systemPluginEnabled || !$userPluginEnabled || !$contentPluginEnabled)
		{
			$message = '<p>' . JText::_('COM_VPADVANCEDUSER_WARNING_REQUIRED_PLUGINS_MISSING') . '</p>';
			
			$url  = JRoute::_('index.php?option=com_plugins&view=plugins&filter_search=vp+advanced+user');
			$html = array();
			
			if(!$systemPluginEnabled)
			{
				$html[] = '<a href="' . $url . '" target="_blank">System - VP Advanced User</a>';
			}
			
			if(!$userPluginEnabled)
			{
				$html[] = '<a href="' . $url . '" target="_blank">User - VP Advanced User</a>';
			}
			
			if(!$contentPluginEnabled)
			{
				$html[] = '<a href="' . $url . '" target="_blank">Content - VP Advanced User</a>';
			}
			
			if(!empty($html))
			{
				$message .= '<ol><li>' . implode('</li><li>', $html) . '</li></ol>';
				
			}
			
			$app->enqueueMessage($message, 'warning');
		}
		
		if(self::hasExtension('pkg_vp_advanced_user', 'package'))
		{
			$params      = JComponentHelper::getParams('com_vpadvanceduser');
			$downloadKey = $params->get('download_key', '');
			$downloadKey = $downloadKey ? trim($downloadKey) : null;
			
			if(empty($downloadKey))
			{
				$app->enqueueMessage(JText::_('COM_VPADVANCEDUSER_WARNING_UPDATE_DOWNLOAD_KEY'), 'info');
			}
		}
	}
	
	/**
	* Method to check if an extension installed and enabled
	* 
	* @param  string  $element  Name of the extension
	* @param  string  $type     Type of the extension like component, module, plugins etc
	* 
	* @return boolean
	*/
	public static function hasExtension($element, $type = 'component', $folder = null)
	{
		if(!is_array(self::$extensions))
		{
			self::$extensions = array();
		}
		
		$hash = 'element:' . $element . '.type:' . $type;
		
		if(!empty($folder))
		{
			$hash .= '.folder:' . $folder;
		}
		
		if(!array_key_exists($hash, self::$extensions))
		{
			$type = strtolower($type);
			self::$extensions[$hash] = false;
			
			$db = JFactory::getDbo();
			$query = $db->getQuery(true)
			            ->select('extension_id, element, folder')
			            ->from('#__extensions')
			            ->where('type = ' . $db->quote($type))
			            ->where('element = ' . $db->quote($element))
			            ->where('enabled = 1');
			
			try
			{
				$db->setQuery($query);
				$results = $db->loadObjectList();
			}
			catch(Exception $e)
			{
				JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
				return false;
			}
			
			if(!empty($results))
			{
				foreach($results as $result)
				{
					if($type != 'package')
					{
						switch($type)
						{
							case 'module':
								$path = JPATH_SITE . '/modules/' . $result->element;
								break;
							case 'plugin':
								if(!empty($folder) && strtolower($folder) != $result->folder)
								{
									$path = null;
								}
								else
								{
									$path = JPATH_SITE . '/plugins/' . $result->folder . '/' . $result->element;
								}
								break;
							default:
							case 'component':
								$path = JPATH_ADMINISTRATOR . '/components/' . $result->element;
						}
						
						if($path && file_exists($path) && is_dir($path))
						{
							self::$extensions[$hash] = true;
							break;
						}
					}
					else
					{
						self::$extensions[$hash] = true;
						break;
					}
				}
			}
		}

		return self::$extensions[$hash];
	}

	/**
	 * Gets a list of the actions that can be performed.
	 *
	 * @return  JObject
	 *
	 * @deprecated  3.2  Use JHelperContent::getActions() instead
	 */
	public static function getActions()
	{
		// Log usage of deprecated function
		JLog::add(__METHOD__ . '() is deprecated, use JHelperContent::getActions() with new arguments order instead.', JLog::WARNING, 'deprecated');

		// Get list of actions
		return JHelperContent::getActions('com_vpadvanceduser');
	}

	/**
	 * Get a list of filter options for the blocked state of a user.
	 *
	 * @return  array  An array of JHtmlOption elements.
	 *
	 * @since   1.6
	 */
	public static function getStateOptions()
	{
		// Build the filter options.
		$options = array();
		$options[] = JHtml::_('select.option', '0', JText::_('JENABLED'));
		$options[] = JHtml::_('select.option', '1', JText::_('JDISABLED'));

		return $options;
	}

	/**
	 * Get a list of filter options for the activated state of a user.
	 *
	 * @return  array  An array of JHtmlOption elements.
	 *
	 * @since   1.6
	 */
	public static function getActiveOptions()
	{
		// Build the filter options.
		$options = array();
		$options[] = JHtml::_('select.option', '0', JText::_('COM_USERS_ACTIVATED'));
		$options[] = JHtml::_('select.option', '1', JText::_('COM_USERS_UNACTIVATED'));

		return $options;
	}

	/**
	 * Get a list of the user groups for filtering.
	 *
	 * @return  array  An array of JHtmlOption elements.
	 *
	 * @since   1.6
	 */
	public static function getGroups()
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('a.id AS value')
			->select('a.title AS text')
			->select('COUNT(DISTINCT b.id) AS level')
			->from('#__usergroups as a')
			->join('LEFT', '#__usergroups  AS b ON a.lft > b.lft AND a.rgt < b.rgt')
			->group('a.id, a.title, a.lft, a.rgt')
			->order('a.lft ASC');
		$db->setQuery($query);

		try
		{
			$options = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			JError::raiseNotice(500, $e->getMessage());

			return null;
		}

		foreach ($options as &$option)
		{
			$option->text = str_repeat('- ', $option->level) . $option->text;
		}

		return $options;
	}

	/**
	 * Creates a list of range options used in filter select list
	 * used in com_users on users view
	 *
	 * @return  array
	 *
	 * @since   2.5
	 */
	public static function getRangeOptions()
	{
		$options = array(
			JHtml::_('select.option', 'today', JText::_('COM_USERS_OPTION_RANGE_TODAY')),
			JHtml::_('select.option', 'past_week', JText::_('COM_USERS_OPTION_RANGE_PAST_WEEK')),
			JHtml::_('select.option', 'past_1month', JText::_('COM_USERS_OPTION_RANGE_PAST_1MONTH')),
			JHtml::_('select.option', 'past_3month', JText::_('COM_USERS_OPTION_RANGE_PAST_3MONTH')),
			JHtml::_('select.option', 'past_6month', JText::_('COM_USERS_OPTION_RANGE_PAST_6MONTH')),
			JHtml::_('select.option', 'past_year', JText::_('COM_USERS_OPTION_RANGE_PAST_YEAR')),
			JHtml::_('select.option', 'post_year', JText::_('COM_USERS_OPTION_RANGE_POST_YEAR')),
		);

		return $options;
	}

	/**
	 * Creates a list of two factor authentication methods used in com_users
	 * on user view
	 *
	 * @return  array
	 *
	 * @since   3.2.0
	 */
	public static function getTwoFactorMethods()
	{
		// Load the Joomla! RAD layer
		if (!defined('FOF_INCLUDED'))
		{
			include_once JPATH_LIBRARIES . '/fof/include.php';
		}

		FOFPlatform::getInstance()->importPlugin('twofactorauth');
		$identities = FOFPlatform::getInstance()->runPlugins('onUserTwofactorIdentify', array());

		$options = array(
			JHtml::_('select.option', 'none', JText::_('JGLOBAL_OTPMETHOD_NONE'), 'value', 'text'),
		);

		if (!empty($identities))
		{
			foreach ($identities as $identity)
			{
				if (!is_object($identity))
				{
					continue;
				}

				$options[] = JHtml::_('select.option', $identity->method, $identity->title, 'value', 'text');
			}
		}

		return $options;
	}
}
