<?php
/**
 * @package     VP Advanced User
 * @subpackage  System Plugin - 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;

// VP Advanced User Component not found
if(!(include_once(JPATH_SITE . '/components/com_vpadvanceduser/define.php')) || !defined('JPATH_ADVANCEDUSER_ADMIN'))
{
	return;
}

JLoader::import('joomla.filesystem.folder');
JLoader::import('joomla.filesystem.file');

use Joomla\Registry\Registry;

/**
* VP Advanced User System Plugin
* 
* @package   VP Advanced User
* @since     1.0
*/
class plgSystemVPAdvancedUser extends JPlugin
{
	protected $app;
	
	protected $_params;
	
	private $acceptanceForm;
	
	/**
	 * Constructor.
	 *
	 * @param   object  &$subject  The object to observe
	 * @param   array   $config    An optional associative array of configuration settings.
	 *
	 * @since   1.0.0
	 */
	public function __construct(&$subject, $config) 
	{
		parent::__construct($subject, $config);
		
		// Register route helper
		JLoader::register('VPAdvancedUserHelperRoute', JPATH_ADVANCEDUSER_SITE . '/helpers/route.php');
		
		// Register frontend helper
		JLoader::register('VPAdvancedUserFrontendHelper', JPATH_ADVANCEDUSER_SITE . '/helpers/vpadvanceduser.php');
		
		// Register utility helper
		JLoader::register('VPAdvancedUserHelperUtility', JPATH_ADVANCEDUSER_SITE . '/helpers/utility.php');
		
		// Register VPAUser class
		JLoader::register('VPAUser', JPATH_ADVANCEDUSER_SITE . '/helpers/user/user.php');
		
		// Get component parameters
		$this->_params = JComponentHelper::getParams('com_vpadvanceduser');
	}
	
	
	public function onAfterRoute()
	{
		$doc       = JFactory::getDocument();
		$input     = $this->app->input;
		$method    = $input->getMethod();
		$method    = empty($method) ? 'get' : $method;
		$option    = strtolower($input->getCmd('option', ''));
		$extension = strtolower($input->getCmd('extension', ''));
		$view      = strtolower($input->getCmd('view', ''));
		$task      = strtolower($input->getCmd('task',''));
		$layout    = strtolower($input->getCmd('layout', ''));
		$tmpl      = strtolower($input->getCmd('tmpl', ''));
		$id        = $input->getInt('id', 0);
		$type      = strtolower($doc->getType());
		$post      = JRequest::get('POST', 2);
		$redirect  = $this->_params->get('redirect_core_users');
		
		if($this->app->isSite())
		{
			// Get core users params
			$coreParams = JComponentHelper::getParams('com_users');

			// Clone core users captcha settings
			$this->_params->set('captcha', $coreParams->get('captcha'));
			
			if($this->_params->get('manage_core_login') && $option == 'com_users' && $task == 'user.login')
			{
				// Manage core login
				$username = $input->$method->get('username', null, 'USERNAME');
				
				if($username !== null)
				{
					if(!class_exists('VPAdvancedUserFrontendHelper'))
					{
						require(JPATH_ADVANCEDUSER_SITE . '/helpers/vpadvanceduser.php');
					}
					
					// Check if user has entered email instead of username
					$realUsername = VPAdvancedUserFrontendHelper::getUsernameByEmail($username);
					
					if($this->_params->get('email_as_username'))
					{
						if(empty($realUsername))
						{
							$redirect_to = VPAdvancedUserHelperRoute::getURL('login', 'login', true);
							
							$this->app->redirect(JRoute::_($redirect_to, false), JText::_('COM_VPADVANCEDUSER_MSG_EMAIL_DO_NOT_HAVE_ACCOUNT'));
							return false;
						}
						
						$username = $realUsername;
					}
					else
					{
						$username = !empty($realUsername) ? $realUsername : $username;
					}
					
					// Set correct username
					$input->$method->set('username', $username);
				}
			}
			
			if($option == 'com_virtuemart' && $view == 'user' && $task == 'saveuser' && $this->_params->get('email_as_username') && $this->_params->get('manage_virtuemart_username'))
			{
				$username = $input->$method->get('username', null, 'USERNAME');
				
				if(isset($post['email']) && isset($post['password']) && empty($username))
				{
					$email = $input->$method->get('email', '', 'EMAIL');

					// Set correct username
					$input->$method->set('username', $email);
					
					if(strtolower($method) == 'post')
					{
						$_POST['username'] = $email;
					}
					elseif(strtolower($method) == 'get')
					{
						$_GET['username'] = $email;
					}
					else
					{
						$_REQUEST['username'] = $email;
					}
				}
			}
			
			if($this->_params->get('override_language'))
			{
				$this->_overrideLanguage();
			}
		}
		
		// Redirect only valid requests
		if(!$redirect || $type != 'html' || !empty($post) || $option != 'com_users' || $layout == 'modal')
		{
			return false;
		}
		
		// Redirect core users admin
		if($this->app->isAdmin() && in_array($redirect, array(1, 3)))
		{
			if((empty($view) && empty($task)) || $view == 'users')
			{
				$this->app->redirect(JRoute::_('index.php?option=com_vpadvanceduser', false));
				return true;
			}
			
			if($view == 'user' || $task == 'user.edit')
			{
				$url = 'index.php?option=com_vpadvanceduser';
				
				if(!empty($view))
				{
					$url .= '&view=user';
				}
				
				if(!empty($task))
				{
					$url .= '&task=' . $task;
				}
				
				if(!empty($layout))
				{
					$url .= '&layout=' . $layout;
				}
				
				if($id)
				{
					$url .= '&id=' . $id;
				}

				$this->app->redirect(JRoute::_($url, false));
				return true;
			}
		}
		
		// Redirect core users site
		if($this->app->isSite() && in_array($redirect, array(2, 3)))
		{
			if((empty($view) && empty($task)) || $view == 'users')
			{
				$this->app->redirect(JRoute::_('index.php?option=com_vpadvanceduser', false));
				return true;
			}
			
			if($view == 'login' || $view == 'registration')
			{
				$redirect_to = VPAdvancedUserHelperRoute::getURL('login', $view, false);
				$return = $input->get('return', null, VPAdvancedUserHelperUtility::getEncodeFilter());
				
				if($return)
				{
					$redirect_to .= '&return=' . $return;
				}
				
				$this->app->redirect(JRoute::_($redirect_to, false));
				return true;
			}
			
			if(($view == 'profile' && $layout != 'edit') || $view == 'reset')
			{
				$redirect_to = VPAdvancedUserHelperRoute::getURL($view);
				
				$this->app->redirect(JRoute::_($redirect_to, false));
				return true;
			}
		}
	}
	
	public function onAfterDispatch()
	{
		if($this->app->isAdmin() || !$this->_isHTML())
		{
			return false;
		}
		
		$doc       = JFactory::getDocument();
		$input     = $this->app->input;
		$method    = $input->getMethod();
		$option    = strtolower($input->getCmd('option', ''));
		$extension = strtolower($input->getCmd('extension', ''));
		$view      = strtolower($input->getCmd('view', ''));
		$task      = strtolower($input->getCmd('task',''));
		$layout    = strtolower($input->getCmd('layout', ''));
		$tmpl      = strtolower($input->getCmd('tmpl', ''));
		$id        = $input->getInt('id', 0);
		$type      = strtolower($doc->getType());
		$tab       = $doc->_getTab();
		$end       = $doc->_getLineEnd();
		
		$profile_picture_width  = $this->_params->get('avatar_width', 90);
		$profile_picture_height = $this->_params->get('avatar_height', 90);
		
		$css = $tab . $tab . '.vp-profile-picture-cont,.vpau-avatar-image{width:' . $profile_picture_width . 'px;height:' . $profile_picture_height . 'px;}' . $end;
		$js = '';
		
		if($option == 'com_virtuemart' && $view == 'user')
		{
			if($this->_params->get('email_as_username') && $this->_params->get('manage_virtuemart_username'))
			{
				$css .= $tab . $tab . '#adminForm input#username_field,#adminForm label[for="username_field"]{display: none!important;}' . $end;
				
				$js .= "
				!(function($) {
				    $(function() {
				        var form;
				        $('input[name=\"task\"]:hidden').each(function() {
				            if ($(this).val() == 'saveUser') {
				                form = $(this).closest('form');
				                if (form && form.length) {
				                    var usernameField = form.find('input[name=\"username\"][type=\"text\"]');
				                    var usernameLabel;
				                    if (usernameField.length) {
				                        var id = usernameField.attr('id');
				                        var parentWrapper = usernameField.parent().parent();
				                        var parentWrapperTag = '';
				                        if (parentWrapper.length) {
				                            parentWrapperTag = parentWrapper.prop('tagName').toUpperCase();
				                        }
				                        if (parentWrapperTag == 'TR') {
				                            parentWrapper.remove();
				                            return false;
				                        }
				                        if (parentWrapperTag == 'DIV' && (parentWrapper.hasClass('form-group') || parentWrapper.hasClass('control-group'))) {
				                            parentWrapper.remove();
				                            return false;
				                        }
				                        if (id) {
				                            usernameLabel = form.find('label[for=\"' + id + '\"]');
				                        }
				                        if (usernameLabel && usernameLabel.length) {
				                            usernameLabel.remove();
				                        }
				                        usernameField.remove();
				                        return false;
				                    }
				                }
				                return false;
				            }
				        });
				    });
				})(jQuery);
				";
			}
		}
		
		if($this->_params->get('email_as_username') && $this->_params->get('remove_forgot_username'))
		{
			JFactory::getLanguage()->load('mod_login');
			$text = JText::_('MOD_LOGIN_FORGOT_YOUR_USERNAME', true);
			
			if($text && $text != 'MOD_LOGIN_FORGOT_YOUR_USERNAME')
			{
				$js .= "
				!(function($) {
				    $(function() {
				        $(\"a:contains('" . addslashes($text) . "')\").each(function() {
				            if ($(this).parent().prop('tagName').toUpperCase() == 'LI') {
				                $(this).parent().remove();
				            } else {
				                $(this).remove();
				            }
				        });
				    });
				})(jQuery);
				";
			}
		}
		
		if(!empty($js))
		{
			JHtml::_('jquery.framework');
			
			// Quick minification of JavaScript helps in faster rendering
			$js = $end . $tab . $tab . trim(preg_replace('/\s*(;|:|,|\{|\}|\[|\])\s*/', '$1', preg_replace('/\(\s*(.*)\s*\)/', '($1)', $js))) . $end;
			
			$doc->addScriptDeclaration($js);
		}
		
		$doc->addStyleDeclaration($css);
		
		// Load social button layout to load required JS and CSS.
		$this->_load('login', 'standard', $this->_getReturn());
		
		$this->acceptanceForm = $this->_loadAcceptanceForm();
	}

	public function onAfterRender()
	{
		$doc = JFactory::getDocument();
		
		if($this->app->isAdmin() || !$this->_isHTML())
		{
			return false;
		}
		
		list($prefix, $body, $suffix) = $this->_getBody();
		
		// Define the regular expression for the bot.
		$regex  = '/{loadvpausocial\s(.*?)}/i';
		$size   = 'standard';
		$return = $this->_getReturn();
		
		// Find all instances of plugin and put in $matches for loadvpausocial
		// $matches[0] is full pattern match, $matches[1] is the position
		preg_match_all($regex, $body, $matches, PREG_SET_ORDER);

		// No matches, skip this
		if ($matches)
		{
			foreach ($matches as $match)
			{
				$matcheslist = explode(',', $match[1]);
				
				// We may not have a return so fall back to the plugin default.
				if (!array_key_exists(1, $matcheslist))
				{
					$matcheslist[1] = $size;
				}
				
				// We may not have a return so fall back to the plugin default.
				if (!array_key_exists(2, $matcheslist))
				{
					$matcheslist[2] = $this->_getReturn($return);
				}

				$action = trim($matcheslist[0]);
				$size   = trim($matcheslist[1]);
				$return = trim($matcheslist[2]);
				
				// Get the output
				$output = $this->_load($action, $size, $return);

				// We should replace only first occurrence in order to allow positions with the same name to regenerate their content:
				$body = preg_replace("|$match[0]|", addcslashes($output, '\\$'), $body, 1);
			}
		}
		
		// Do we need to load modal module forms
		if(!JFactory::getConfig()->get('offline') && JFactory::getUser()->guest && $this->app->input->getCmd('tmpl') != 'component')
		{
			$forms = '';
			
			// Get all modules published in the page
			$modules = $this->_getModules();
			
			foreach($modules as $module)
			{
				if(is_object($module) && !empty($module->id))
				{
					// Prepare module params
					$module->params = new JRegistry($module->params);
					
					$layout = $module->params->get('layout');
					$layout = !empty($layout) ? str_replace('_:', '', $layout) : 'default';
					
					if($layout == 'modal')
					{
						// Get modal login and registration form
						list($login, $registration) = $this->_loadModalForms($module, $module->params);
						
						$forms .= $login . $registration;
					}
				}
			}
			
			$forms .= $this->acceptanceForm ? $this->acceptanceForm : '';
			
			if(trim($forms) != '')
			{
				// Add background element
				$forms = '<div class="vpau-modal-bg" aria-hidden="true"></div>' . $forms;
				
				$bodyEndTag = null;
				
				if(strpos($body, '</body>') !== false)
				{
					$bodyEndTag = '</body>';
				}
				elseif(strpos($body, '</ body>') !== false)
				{
					$bodyEndTag = '</ body>';
				}
				
				if($bodyEndTag)
				{
					$body = str_replace($bodyEndTag, ($forms . $bodyEndTag), $body);
				}
			}
		}
		
		// Rebuild body buffer
		$html = $prefix . $body . $suffix;
		
		// Set body buffer
		$this->app->setBody($html);
	}

	public function onAjaxVpadvanceduser()
	{
		$this->app = JFactory::getApplication();
		
		if($this->app->isSite())
		{
			return;
		}
		
		// Register dlk helper class
		JLoader::register('VPComDlkHelper', JPATH_ADVANCEDUSER_ADMIN . '/models/fields/vpcomdlk/helper.php');
		
		// Get an instance of dlk helper
		$dlkHelper = VPComDlkHelper::getInstance();
		
		if($this->app->input->getCmd('method') == 'validatedlk')
		{
			// Return validation result
			return $dlkHelper->validate();
		}
		elseif($this->app->input->getCmd('method') == 'revalidatedlk')
		{
			// Return validation result
			return $dlkHelper->revalidate();
		}
	}

	/**
	 * Called on live update installation.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function onInstallerBeforePackageDownload(&$url, &$headers)
	{
		// Register dlk helper class
		JLoader::register('VPComDlkHelper', JPATH_ADVANCEDUSER_ADMIN . '/models/fields/vpcomdlk/helper.php');
		
		return VPComDlkHelper::getInstance()->addDlk($url, $headers);
	}
	
	/**
	 * Replaces the matched tags.
	 *
	 * @param   array   An array of matches (see preg_match_all)
	 * @return  string
	 */
	private function _load($action, $size, $return)
	{
		$html = '';
		
		if(!JFactory::getUser()->guest)
		{
			return $html;
		}
		
		$action = (strtoupper($action) == 'REGISTRATION') ? 'REGISTER' : 'LOGIN';
		$size   = in_array(strtolower($size), array('small', 'standard')) ? strtolower($size) : 'standard';
		
		// Load com_users langauge
		JFactory::getLanguage()->load('com_users');
		
		// Load com_vpadvanceduser langauge
		JFactory::getLanguage()->load('com_vpadvanceduser');
		
		// Prepare display data
		$display_data = array('show' => true, 'size' => $size, 'params' => $this->_params, 'action' => $action, 'return' => $return);
		
		$output = JLayoutHelper::render('social_buttons', $display_data, null, array('client' => 'site', 'component' => 'com_vpadvanceduser'));
		
		if(!empty($output))
		{
			$html = '<div class="vp-wrapper vpau-loadsocial">' . $output . '</div>';
		}
		
		return $html;
	}
	
	private function _loadAcceptanceForm()
	{
		$html = '';
		
		if(!JFactory::getUser()->guest || !$this->_params->get('social_show_custom_fields', 0))
		{
			return $html;
		}
		
		// Load com_users langauge
		JFactory::getLanguage()->load('com_users');
		
		// Load com_vpadvanceduser langauge
		JFactory::getLanguage()->load('com_vpadvanceduser');
		
		// Add models path
		JModelLegacy::addIncludePath(JPATH_ADVANCEDUSER_SITE . '/models', 'VPAdvancedUserModel');
		
		// Try to get an instace of the model
		$model = JModelLegacy::getInstance('Registration', 'VPAdvancedUserModel', array('ignore_request' => true));
		
		if(!is_object($model))
		{
			// Throw exception if model not found
			throw new Exception(JText::sprintf('COM_VPADVANCEDUSER_MSG_ERROR_CLASS_NOT_FOUND', 'VPAdvancedUserModelRegistration'), 500);
		}
		
		$form = $model->getForm();
		
		if(empty($form))
		{
			return $html;
		}
		
		// Prepare display data
		$display_data = array(
			'form'          => clone($form),
			'params'        => $this->_params,
			'id_prefix'     => 'acceptanceform_',
			'ignoredFields' => array(
				'email1',
				'email2',
				'name',
				'username',
				'password1',
				'password2',
				'captcha',
				'spacer'
			)
		);
		
		$html = JLayoutHelper::render('social_acceptance', $display_data, null, array('client' => 'site', 'component' => 'com_vpadvanceduser'));
		
		return $html;
	}
	
	private function _loadModalForms($module, $params)
	{
		// Require module variables
		require(JPATH_SITE . '/modules/mod_vpadvanceduser/variables.php');
		
		$login        = '';
		$registration = '';
		
		if(in_array($display, array(1, 3)) && !$reg_inprocess)
		{
			// Prepare component's login form for the module
			$loginForm = ModVPAdvancedUserHelper::prepareForm($loginForm, $form_id_prefix);
			
			// Get Login Form
			ob_start();
			require JModuleHelper::getLayoutPath('mod_vpadvanceduser', 'modal_login');
			$login = ob_get_contents();
			ob_end_clean();
		}
		
		// Get Registration Form
		if(in_array($display, array(2, 3)))
		{
			// Prepare component's registration form for the module
			$regForm = ModVPAdvancedUserHelper::prepareForm($regForm, $form_id_prefix);
			
			ob_start();
			require JModuleHelper::getLayoutPath('mod_vpadvanceduser', 'modal_registration');
			$registration = ob_get_contents();
			ob_end_clean();
			$registration = (string) (!empty($registration) ? $registration : '');
		}
		
		return array($login, $registration);
	}
	
	
	private function _isHTML()
	{
		$doc   = JFactory::getDocument();
		$input = $this->app->input;
		
		$isFeed = ($doc->getType() == 'feed' || $input->getWord('format') == 'feed' || $input->getWord('type') == 'rss' || $input->getWord('type') == 'atom');
		$isHTML = ($doc->getType() == 'html' && !$isFeed);
		
		return $isHTML;
	}
	
	private function _getBody()
	{
		$html = $this->app->getBody();
		
		if (strpos($html, '<body') === false || strpos($html, '</body>') === false)
		{
			return array('', $html, '');
		}

		$html_split = explode('<body', $html, 2);
		$prefix     = $html_split['0'];
		$body       = '<body' . $html_split['1'];
		$body_split = explode('</body>', $body);
		$suffix     = array_pop($body_split);
		$body       = implode('</body>', $body_split) . '</body>';

		return array($prefix, $body, $suffix);
	}
	
	private function _getReturn($return = null)
	{
		// Register utility helper
		JLoader::register('VPAdvancedUserHelperUtility', JPATH_ADVANCEDUSER_SITE . '/helpers/utility.php');
		
		$url = !empty($return) ? VPAdvancedUserHelperUtility::decode($return) : null;
		
		if(empty($url) || JUri::isInternal($url))
		{
			$url = JUri::getInstance()->toString();
		}
		
		$base = JUri::base();
		
		if($base && strpos($url, $base) === 0)
		{
			$url = str_replace($base, '', $url);
			$url = JUri::base(true) . '/' . $url;
		}
		
		if(empty($url))
		{
			$url = JUri::base(true) . '/';
		}
		
		if(strpos($url, '/') === false && strpos($url, 'index.php?') === 0 && strpos($url, 'option=') !== false)
		{
			$url = JRoute::_($url, false);
		}
		
		return VPAdvancedUserHelperUtility::encode($url);
	}
	
	private function _getModules()
	{
		// Check for existance using standard Joomla module helper
		// This will avoid unnecessary query.
		$module = JModuleHelper::getModule('mod_vpadvanceduser');
		
		if(!is_object($module) || empty($module->id))
		{
			return array();
		}
		
		$Itemid   = $this->app->input->getInt('Itemid');
		$groups   = implode(',', JFactory::getUser()->getAuthorisedViewLevels());
		$lang     = JFactory::getLanguage()->getTag();
		$clientId = (int) $this->app->getClientId();

		$db = JFactory::getDbo();

		$query = $db->getQuery(true)
		    ->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params, mm.menuid')
		    ->from('#__modules AS m')
		    ->join('LEFT', '#__modules_menu AS mm ON mm.moduleid = m.id')
		    ->where('m.published = 1')
		    ->join('LEFT', '#__extensions AS e ON e.element = m.module AND e.client_id = m.client_id')
		    ->where('e.enabled = 1');

		$date     = JFactory::getDate();
		$now      = $date->toSql();
		$nullDate = $db->getNullDate();
		
		$query->where('(m.publish_up = ' . $db->quote($nullDate) . ' OR m.publish_up <= ' . $db->quote($now) . ')')
		      ->where('(m.publish_down = ' . $db->quote($nullDate) . ' OR m.publish_down >= ' . $db->quote($now) . ')')
		      ->where('m.access IN (' . $groups . ')')
		      ->where('m.client_id = ' . $clientId)
		      ->where('m.module = ' . $db->quote('mod_vpadvanceduser'))
		      ->where('(mm.menuid = ' . (int) $Itemid . ' OR mm.menuid <= 0)');

		// Filter by language
		if ($this->app->isSite() && $this->app->getLanguageFilter())
		{
			$query->where('m.language IN (' . $db->quote($lang) . ',' . $db->quote('*') . ')');
		}

		$query->order('m.position, m.ordering');

		// Set the query
		$db->setQuery($query);

		try
		{
			$modules = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			JLog::add(JText::sprintf('JLIB_APPLICATION_ERROR_MODULE_LOAD', $e->getMessage()), JLog::WARNING, 'jerror');
			return array();
		}
		
		return $modules;
	}
	
	private function _overrideLanguage()
	{
		$lang    = JFactory::getLanguage();
		$langTag = $lang->getTag();
		$strings = array();
		$changed = false;
		
		$filename = JPATH_SITE . '/language/overrides/' . $langTag . '.override.ini';
		
		if(is_file($filename))
		{
			$strings = $this->_parseLanguageFile($filename);
		}
		
		$oldCount = count($strings);
		$email_as_username = (int) $this->_params->get('email_as_username_login', 2);

		if($email_as_username == 1)
		{
			$usernameLabel = JText::_('JGLOBAL_EMAIL');
		}
		elseif($email_as_username == 2)
		{
			$usernameLabel = JText::_('JGLOBAL_USERNAME') . '/' . JText::_('JGLOBAL_EMAIL');
		}
		else
		{
			$usernameLabel = null;
		}

		if($usernameLabel && $this->_params->get('manage_virtuemart_username') && $email_as_username > 0)
		{
			if(!isset($strings['COM_VIRTUEMART_USERNAME']) || $strings['COM_VIRTUEMART_USERNAME'] != $usernameLabel)
			{
				$strings['COM_VIRTUEMART_USERNAME'] = $usernameLabel;
				$changed = true;
			}
		}
		else
		{
			unset($strings['COM_VIRTUEMART_USERNAME']);
		}

		if($this->_params->get('manage_core_login') && $email_as_username > 0)
		{
			if($usernameLabel && (!isset($strings['MOD_LOGIN_VALUE_USERNAME']) || $strings['MOD_LOGIN_VALUE_USERNAME'] != $usernameLabel))
			{
				$strings['MOD_LOGIN_VALUE_USERNAME'] = $usernameLabel;
				$changed = true;
			}
			
			if($changed)
			{
				$vpau_filename = JPATH_SITE . '/language/' . $langTag . '/' . $langTag . '.com_vpadvanceduser.ini';
				
				if(!is_file($vpau_filename))
				{
					$vpau_filename = JPATH_SITE . '/language/en-GB/en-GB.com_vpadvanceduser.ini';
				}
				
				if(is_file($vpau_filename))
				{
					$vpau_strings = $this->_parseLanguageFile($vpau_filename);
					
					if($email_as_username == 1)
					{
						$errorMessage = isset($vpau_strings['COM_VPADVANCEDUSER_MSG_EMAIL_DO_NOT_HAVE_ACCOUNT']) ?
						                $vpau_strings['COM_VPADVANCEDUSER_MSG_EMAIL_DO_NOT_HAVE_ACCOUNT'] : null;
					}
					elseif($email_as_username == 2)
					{
						$errorMessage = isset($vpau_strings['COM_VPADVANCEDUSER_JLIB_LOGIN_AUTHENTICATE']) ?
						                $vpau_strings['COM_VPADVANCEDUSER_JLIB_LOGIN_AUTHENTICATE'] : null;
					}
					
					if($errorMessage !== null)
					{
						if(!isset($strings['JLIB_LOGIN_AUTHENTICATE']) || $strings['JLIB_LOGIN_AUTHENTICATE'] != $errorMessage)
						{
							$strings['JLIB_LOGIN_AUTHENTICATE'] = $errorMessage;
						}
						
						if(!isset($strings['JGLOBAL_AUTH_INVALID_PASS']) || $strings['JGLOBAL_AUTH_INVALID_PASS'] != $errorMessage)
						{
							$strings['JGLOBAL_AUTH_INVALID_PASS'] = $errorMessage;
						}
						
						if(!isset($strings['JGLOBAL_AUTH_NO_USER']) || $strings['JGLOBAL_AUTH_NO_USER'] != $errorMessage)
						{
							$strings['JGLOBAL_AUTH_NO_USER'] = $errorMessage;
						}
					}
				}
			}
		}
		else
		{
			unset(
			    $strings['MOD_LOGIN_VALUE_USERNAME'], $strings['JLIB_LOGIN_AUTHENTICATE'],
			    $strings['JGLOBAL_AUTH_INVALID_PASS'], $strings['JGLOBAL_AUTH_NO_USER']
			);
		}
		
		$newCount = count($strings);
		
		if($changed || $newCount != $oldCount)
		{
			$registry = new Registry($strings);
			$reg = $registry->toString('INI');

			if (!JFile::write($filename, $reg))
			{
				return false;
			}
		}
	}
	
	private function _parseLanguageFile($filename)
	{
		$contents = file_get_contents($filename);
		$contents = str_replace('_QQ_', '"\""', $contents);
		$strings = @parse_ini_string($contents);

		if (!is_array($strings))
		{
			$strings = array();
		}
		
		return $strings;
	}
}