<?php
/*----------------------------------------------------------------------------------|  www.vdm.io  |----/
				Lmskaran 
/-------------------------------------------------------------------------------------------------------/

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		user_maps.php
	@author			Lmskaran <http://Lmskaran.com>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____  _____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \(  _  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/ )(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__)  (_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;

/**
 * User_maps Controller
 */
class MoojlaControllerUser_maps extends JControllerAdmin
{
	/**
	 * The prefix to use with controller messages.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_MOOJLA_USER_MAPS';

	/**
	 * Method to get a model object, loading it if required.
	 *
	 * @param   string  $name    The model name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JModelLegacy  The model.
	 *
	 * @since   1.6
	 */
	public function getModel($name = 'User_map', $prefix = 'MoojlaModel', $config = array('ignore_request' => true))
	{
		return parent::getModel($name, $prefix, $config);
	}

	public function exportData()
	{
		// Check for request forgeries
		JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
		// check if export is allowed for this user.
		$user = JFactory::getUser();
		if ($user->authorise('user_map.export', 'com_moojla') && $user->authorise('core.export', 'com_moojla'))
		{
			// Get the input
			$input = JFactory::getApplication()->input;
			$pks = $input->post->get('cid', array(), 'array');
			// Sanitize the input
			$pks = ArrayHelper::toInteger($pks);
			// Get the model
			$model = $this->getModel('User_maps');
			// get the data to export
			$data = $model->getExportData($pks);
			if (MoojlaHelper::checkArray($data))
			{
				// now set the data to the spreadsheet
				$date = JFactory::getDate();
				MoojlaHelper::xls($data,'User_maps_'.$date->format('jS_F_Y'),'User maps exported ('.$date->format('jS F, Y').')','user maps');
			}
		}
		// Redirect to the list screen with error.
		$message = JText::_('COM_MOOJLA_EXPORT_FAILED');
		$this->setRedirect(JRoute::_('index.php?option=com_moojla&view=user_maps', false), $message, 'error');
		return;
	}


	public function importData()
	{
		// Check for request forgeries
		JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
		// check if import is allowed for this user.
		$user = JFactory::getUser();
		if ($user->authorise('user_map.import', 'com_moojla') && $user->authorise('core.import', 'com_moojla'))
		{
			// Get the import model
			$model = $this->getModel('User_maps');
			// get the headers to import
			$headers = $model->getExImPortHeaders();
			if (MoojlaHelper::checkObject($headers))
			{
				// Load headers to session.
				$session = JFactory::getSession();
				$headers = json_encode($headers);
				$session->set('user_map_VDM_IMPORTHEADERS', $headers);
				$session->set('backto_VDM_IMPORT', 'user_maps');
				$session->set('dataType_VDM_IMPORTINTO', 'user_map');
				// Redirect to import view.
				$message = JText::_('COM_MOOJLA_IMPORT_SELECT_FILE_FOR_USER_MAPS');
				$this->setRedirect(JRoute::_('index.php?option=com_moojla&view=import', false), $message);
				return;
			}
		}
		// Redirect to the list screen with error.
		$message = JText::_('COM_MOOJLA_IMPORT_FAILED');
		$this->setRedirect(JRoute::_('index.php?option=com_moojla&view=user_maps', false), $message, 'error');
		return;
	}


/***[JCBGUI.admin_view.php_controller_list.130.$$$$]***/
  function getUsersFromMoodle()
  {
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    require_once JPATH_ADMINISTRATOR . "/components/com_moojla/models/user_map.php";
    $data = array(
      "wsfunction"          => "moojla_get_users_minimal",
      "moodlewsrestformat"  => "json"
    );
    $usersResult = json_decode(MoojlaHelper::sendRequestToMoodle($data)->response);
    
    $params = JComponentHelper::getParams('com_moojla');
    $create_user_on_fetch = trim($params->get('create_user_on_fetch'));
    $log = "";
    $logArraySynced = array();
    $logArrayAdded = array();
    foreach($usersResult as $user)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select($db->quoteName(array('id', 'jid')));
      $query->from($db->quoteName('#__moojla_user_map'));
      $query->where($db->quoteName('mid') . ' = ' . $db->quote($user->id));
      $db->setQuery($query);
      $searchResults = $db->loadRow();
      
      if($user->username != 'admin' && $user->username != 'guest')
      {
        $logArraySynced[] = 'JUser with id ' . $res . " Synced!";
        
        if(!$searchResults)
        {
          $query = $db->getQuery(true);
          $query->select($db->quoteName(array('id')));
          $query->from($db->quoteName('#__users'));
          $query->where($db->quoteName('username') . ' = ' . $db->quote($user->username));
          $db->setQuery($query);
          $res = $db->loadResult();
          
          if($res)
          {
            $data = array(
              'mid'	=>	$user->id,
              'jid'	=>	$res
            );
            $usermap = new MoojlaModelUser_map();
            $usermap->save($data);
            
          }
          else if($create_user_on_fetch)
          {
            $data = array(
              "name"			=>	$user->firstname . ' ' . $user->lastname,
              "username"		=>	$user->username,
              "password"		=>	$user->password,
              "password2"		=>	$user->password,
              "email"			=>	$user->email,
              "block"			=>	0,
            );
            $newUser = MoojlaHelper::addJoomlaUser($data);
            if($newUser->status == "ok")
            {
              $data = array(
                'mid'	=>	$user->id,
                'jid'	=>	$newUser->id
              );
              $usermap = new MoojlaModelUser_map();
              $usermap->save($data);
              $logArrayAdded[] = 'JUser with id ' . $newUser->id . " Added!";
            }
          }
        }
      }
    }
    
    $query = $db->getQuery(true);
    $query->select('*');
    $query->from($db->quoteName('#__moojla_user_map'));
    $db->setQuery($query);
    $results = $db->loadAssocList('mid');

    $data = array(
      "wsfunction"          => "moojla_get_teachers",
      "moodlewsrestformat"  => "json"
    );

    $teacherRes = json_decode(MoojlaHelper::sendRequestToMoodle($data)->response);
    $coursesTeacherMap = array();
    foreach($teacherRes as $index => $teacher)
    {
      if(!array_key_exists($teacher->userid, $coursesTeacherMap)){
        $coursesTeacherMap[$teacher->userid] = array();
      }
      $coursesTeacherMap[$teacher->userid][] = $teacher->courseid;

    }
    foreach($coursesTeacherMap as $index => $ctm)
    {
      if(array_key_exists($index, $results))
      {
        $data = array(
          'id'		  =>	intval($results[$index]['id']),
          'mid'     =>	intval($results[$index]['mid']),
          'jid'     =>	intval($results[$index]['jid']),
          'courses' => implode(',', $ctm)
        );
        $usermap = new MoojlaModelUser_map();
        $usermap->save($data);
      }
    }
    
    $log .= count($logArraySynced) . " User Synced and " . count($logArrayAdded) . " User Added!<br/>";
    $log .= implode('<br/>', $logArraySynced) . "<br/>";
    $log .= implode('<br/>', $logArrayAdded) . "<br/>";
    $app = JFactory::getApplication();
    $message = $log . JText::_('COM_MOOJLA_COMPLETELY_FETCHED');// translate_need
    $app->redirect(JRoute::_("index.php?option=com_moojla&view=user_maps", false), $message, 'message');
    return true;
  }

  function syncToMoodle()
  {
    $cid = $this->input->get('cid', array(), 'array');
    $cid = ArrayHelper::toInteger($cid);

    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName('jid'));
    $query->from($db->quoteName('#__moojla_user_map'));
    $query->where($db->quoteName('id') . ' IN (' . implode(',', $cid) . ')');
    $query->where($db->quoteName('jid') .' <> ""');
    $query->where($db->quoteName('jid') .' <> 0');
    $db->setQuery($query);
    $joomlausermaps = $db->loadColumn();
    foreach($joomlausermaps as $jusermap)
    {
      $params = JComponentHelper::getParams('com_moojla');
      $ads = trim($params->get('additional_data_source'));
      if($ads == "jf")
      {
        $juser = JFactory::getUser($jusermap);
        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');

        $data = array(
          "wsfunction"          => "moojla_user_get_users_by_field",
          "moodlewsrestformat"  => "json",
          "field"		=> "username",
          "values"	=>
          array(
            $juser->username
          )
        );
        $usernameExist = json_decode(MoojlaHelper::sendRequestToMoodle($data)->response);

        $data = array(
          "wsfunction"          => "moojla_user_get_users_by_field",
          "moodlewsrestformat"  => "json",
          "field"		=> "email",
          "values"	=>
          array(
            $juser->email
          )
        );
        $emailExist = json_decode(MoojlaHelper::sendRequestToMoodle($data)->response);
        $isNew = false;
        if(!$emailExist && !$usernameExist)
          $isNew = true;
        
        jimport('joomla.user.helper');
        $user = new JUser;
        $user->load($jusermap);
        JPluginHelper::importPlugin("user");
        $dispatcher = JEventDispatcher::getInstance();
        $user->from_joomla = 1;
        $dispatcher->trigger("onUserAfterSave", array((array)$user, $isNew, (array)$user, null));
      }
      else if($ads == "cb")
      {
        $user = JFactory::getUser($jusermap);
        if ( ( ! file_exists( JPATH_SITE . '/libraries/CBLib/CBLib/Core/CBLib.php' ) ) || ( ! file_exists( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' ) ) ) {
          echo 'CB not installed';
          return;
        }
        include_once( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' );
        cbimport( 'cb.html' );
        global $_CB_framework, $_PLUGINS, $ueConfig;
        global $cbUser;
        $cbUser =& CBuser::getInstance( $jusermap, false);
        // $cbUser =& CBuser::getUserDataInstance( $searchResults[1]);
        $cuser =& $cbUser->getUserData();
        $oldUserComplete		=	new \CB\Database\Table\UserTable();
        $_PLUGINS->loadPluginGroup($user->username); // for using cb trigering
        $_PLUGINS->loadPluginGroup( 'user' );
        foreach ( array_keys( get_object_vars( $cuser ) ) as $k ) {
          if ( substr( $k, 0, 1 ) != '_' ) {
            $oldUserComplete->set( $k, $cuser->get( $k ) );
          }
        }

        // $user->set( 'name', $name );

        $_PLUGINS->trigger( 'onBeforeUserUpdate', array( &$cuser, &$cuser, &$oldUserComplete, &$oldUserComplete ) );
        $cuser->set( 'params', array() ); 
        // if ( ! $cuser->store() ) {
          // return false;
        //}
        $_PLUGINS->trigger( 'onAfterUserUpdate', array( &$cuser, &$cuser, $oldUserComplete ) );
        // $_PLUGINS->trigger( 'onAfterUserRegistration', array( &$cuser, &$cuser, $oldUserComplete ) );
      }
      
    
    }

    $app = JFactory::getApplication();
    $message = $log . JText::_('COM_MOOJLA_COMPLETELY_SYNCED'); // translate_need
    $app->redirect(JRoute::_("index.php?option=com_moojla&view=user_maps", false), $message, 'message');
    return true;
  }
  
    function fetchMoodleUsers()
    {
        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR . '/components/com_moojla/helpers/moojla.php');
        require_once JPATH_ADMINISTRATOR . "/components/com_moojla/models/user_map.php";
        $data = array(
            "wsfunction" => "moojla_get_users_minimal",
            "moodlewsrestformat" => "json"
        );
        $musers = json_decode(MoojlaHelper::sendRequestToMoodle($data)->response);
        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__users'));
        $db->setQuery($query);
        $usermaps = $db->loadAssocList('username');
        $params = JComponentHelper::getParams('com_moojla');
        $create_user_on_fetch = trim($params->get('create_user_on_fetch'));
        $total_fetch_moodle_users = $params->get('total_fetch_moodle_users', 1000);
        $number_per_request_fetch_moodle_users = $params->get('number_per_request_fetch_moodle_users', 50);



        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__moojla_user_map'));
        $db->setQuery($query);
        $user_maps = $db->loadAssocList('mid');

        $musers = array_filter($musers, function ($v) use ($user_maps) {
            return !isset($user_maps[$v->id]);
        });

        if (isset($_GET['c'])) {
            $c = $_GET['c'];
        } else {
            $c = 0;
        }

        $progress_percent = (($c / $total_fetch_moodle_users) * 100);
        echo '<div class="progress">
                    <div class="progress-bar" role="progressbar" aria-valuenow="70"
                         aria-valuemin="0" aria-valuemax="100" style="
                         width:' . $progress_percent . '%;
                        float: left;
                        height: 100%;
                        font-size: 12px;
                        line-height: 20px;
                        color: #fff;
                        text-align: center;
                        background-color: #337ab7;
                        -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
                        box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
                        -webkit-transition: width .6s ease;
                        -o-transition: width .6s ease;
                        transition: width .6s ease;">
                        ' . floor($progress_percent) . '%
                    </div>
                </div>';

        foreach ($musers as $muser) {
            if (!in_array($muser->username, ['admin', 'guest', 'superuser', 'moojla'])) {
                if (array_key_exists($muser->username, $usermaps)) {
                    $mapArray = array(
                        "mid" => intval($muser->id),
                        "jid" => intval($usermaps[$muser->username]['id'])
                    );
                    MoojlaHelper::addToUserMap($mapArray);
                } else {
                    if (1) {
                        $data = array(
                            "name" => $muser->firstname . ' ' . $muser->lastname,
                            "username" => $muser->username,
                            "password" => $muser->password,
                            "password2" => $muser->password,
                            "email" => $muser->email,
                            "block" => 0,
                        );
                        $newUser = MoojlaHelper::addJoomlaUser($data);
                        if ($newUser->status == "ok") {
                            $data = array(
                                'mid' => $muser->id,
                                'jid' => $newUser->id
                            );
                            $usermap = new MoojlaModelUser_map();
                            $usermap->save($data);
                        }
                    }
                    $db = JFactory::getDbo();
                    $query = $db->getQuery(true);
                    $query->select($db->quoteName(array('id')));
                    $query->from($db->quoteName('#__moojla_user_map'));
                    $query->where($db->quoteName('mid') . ' = ' . $db->quote($muser->id));
                    $db->setQuery($query);
                    $muser_exist = $db->loadResult();
                    if (!$muser_exist) {
                        $mapArray = array(
                            "mid" => intval($muser->id),
                            "jid" => ''
                        );
                        MoojlaHelper::addToUserMap($mapArray);
                    }
                }

                $c++;
                if ($c == $total_fetch_moodle_users) {
                    break;
                }
                 if ($number_per_request_fetch_moodle_users != -1 && $number_per_request_fetch_moodle_users != 0)
                {
                    if ($c % $number_per_request_fetch_moodle_users == 0) {
                        echo "<script>window.location = '/administrator/index.php?option=com_moojla&view=user_maps&task=user_maps.fetchMoodleUsers&c=$c'</script>";
                        return 0;
                    }
                }

            }
        }

        $message = ($c) . ' ' . JText::_('COM_MOOJLA_COMPLETELY_FETCHED');// translate_need
        $app->redirect(JRoute::_("index.php?option=com_moojla&view=user_maps", false), $message, 'message');
        return true;
    }

  function syncToJoomla()
  {
    $app = JFactory::getApplication();
    $cid = $this->input->get('cid', array(), 'array');
    $cid = ArrayHelper::toInteger($cid);
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName('mid'));
    $query->from($db->quoteName('#__moojla_user_map'));
    $query->where($db->quoteName('id') . ' IN (' . implode(',', $cid) . ')');
    $query->where($db->quoteName('mid') .' <> ""');
    $query->where($db->quoteName('mid') .' <> 0');
    $db->setQuery($query);
    $musers = $db->loadColumn(); 
    $data = array(
      "wsfunction"          => "moojla_trigger_create_users",
      "moodlewsrestformat"  => "json",
      "userids"	=> array()
    );
    foreach($musers as $muser)
    {
      $data['userids'][] = array('id' => intval($muser));
    }
    // dump($data, "data");
    $triggeringResult = json_decode(MoojlaHelper::sendRequestToMoodle($data, array("from_joomla" => 0))->response);
    // dump($triggeringResult, "triggeringResult");
    foreach($triggeringResult as $newuser)
    {
      $userId    = JUserHelper::getUserId($newuser->username);
      $mapdata = array(
        "mid"   => $newuser->id,
        "jid"   => $userId
      );
      MoojlaHelper::addToUserMap($mapdata);
    }
    $message = JText::_('COM_MOOJLA_COMPLETELY_FETCHED');// translate_need
    $app->redirect(JRoute::_("index.php?option=com_moojla&view=user_maps", false), $message, 'message');
    return true;
  }

  function fetchJoomlaUsers() 
  {
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    require_once JPATH_ADMINISTRATOR . "/components/com_moojla/models/user_map.php";
    $app = JFactory::getApplication();
    
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select('*');
    $query->from($db->quoteName('#__moojla_user_map'));
    $db->setQuery($query);
    $usermaps = $db->loadAssocList('jid');

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select('*');
    $query->from($db->quoteName('#__users'));
    $db->setQuery($query);
    $jusers = $db->loadAssocList('username');

    
    // dump($jusers, "jusers");
    foreach($jusers as $juser)
    {
      if(!in_array($juser['username'], ['admin', 'guest', 'superuser', 'moojla']))
      {
        if(!array_key_exists($juser['id'], $usermaps))
        {
          $mapArray = array(
            "jid"	=>	intval($juser['id'])
          );
          // dump($mapArray, "mapArray");
          MoojlaHelper::addToUserMap($mapArray);
        }
      }
    }
    
    $params = JComponentHelper::getParams('com_moojla');
    $create_user_on_fetch = trim($params->get('create_user_on_fetch'));
    
    $message = $log . JText::_('COM_MOOJLA_COMPLETELY_FETCHED');// translate_need
    $app->redirect(JRoute::_("index.php?option=com_moojla&view=user_maps", false), $message, 'message');
    return true;
  }

  function checkMoodleUser()
  {
    $cid = $this->input->get('cid', array(), 'array');
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    $data = array(
      "wsfunction"          => "moojla_user_is_fully_setted",
      "moodlewsrestformat"  => "json",
      "id"	=> $cid[0]
    );
    $triggeringResult = MoojlaHelper::sendRequestToMoodle($data)->response;
    print_r($triggeringResult);
    // print_r($data);
    die();
    

  }
/***[/JCBGUI$$$$]***/

}
