Spade

Mini Shell

Directory:~$ /proc/self/root/home/lmsyaran/public_html/administrator/components/com_moojla/helpers/
Upload File

[Home] [System Details] [Kill Me]
Current File:~$ //proc/self/root/home/lmsyaran/public_html/administrator/components/com_moojla/helpers/moojla.php

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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		moojla.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\CMS\Filesystem\File;
use Joomla\CMS\Language\Language;
use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * Moojla component helper.
 */
abstract class MoojlaHelper
{
	/**
	 * Composer Switch
	 * 
	 * @var      array
	 */
	protected static $composer = array();

	/**
	 * The Main Active Language
	 * 
	 * @var      string
	 */
	public static $langTag;

/***[JCBGUI.joomla_component.php_helper_both.29.$$$$]***/
	public static function get_role_by_remoteid($remoteid, $role)
    {

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('mc.id as id, shortname, remoteid, cat_name,
catid, cost, summary_files, summary, fullname, e.jid, e.role');
        $query->from($db->quoteName('#__moojla_enrolment',
'e'));
       
$query->join('inner',$db->quoteName('#__moojla_enrolment','ee').'
on
'.$db->quoteName('e.jid').'='.$db->quoteName('ee.jid'));
       
$query->join('inner',$db->quoteName('#__moojla_course','mc').'
on
'.$db->quoteName('mc.remoteid').'='.$db->quoteName('ee.moojlacourse'));
       
$query->where($db->quoteName('ee.moojlacourse').'!='.$remoteid);
       
$query->where($db->quoteName('e.moojlacourse').'='.$remoteid);
       
$query->where($db->quoteName('ee.role').'='.
$role);

        $db->setQuery($query);
        $result = $db->loadObjectList('remoteid');
        return $result;
	} 

public static function addJoomlaUser($data) {
    // $file_name = __DIR__. "/addJoomlaUser.txt";
    // file_put_contents($file_name, print_r($data, true)."\n",
FILE_APPEND);
    $result = new stdClass();
    $result->id = 0;
    // $app		= JFactory::getApplication();
    jimport('joomla.user.helper');
    $userdata = array(
      "name"=>trim(strval($data['name'])),
      "username"=>trim(strval($data['username'])),
      "password"=>trim(strval($data['password'])),
      "password2"=>trim(strval($data['password'])),
      "email"=>trim(strval($data['email'])),
      "block"=>0,
    );
    foreach($userdata as $d)
    {
      if(trim(strval($d)) == "" || !$d)
        unset($d);
    }

    $userdata["groups"] = array("2");
    $user = new JUser;
    //Write to database
    if(!$user->bind($userdata)) {
      $result->status = $user->getError();
      return $result;
      // $app->enqueueMessage($user->getError(), 'error');
      // $app->redirect(JRoute::_($_SERVER['HTTP_REFERER'],
false));
    }

    //before save
    $user->from_moodle = true;
    if (!$user->save()) {
      $result->status = $user->getError();
      return $result;
      // $app->enqueueMessage($user->getError(), 'error');
      // $app->redirect(JRoute::_($_SERVER['HTTP_REFERER'],
false));
    }
    if(isset($data["moodle"]))
    {
      JPluginHelper::importPlugin("moojlaaditionalfields");
      $dispatcher = JEventDispatcher::getInstance();
      $dispatch_res	= $dispatcher->trigger("addUserToJoomla",
array($data["moodle"], $user->id));

    }
    $userdata['userid'] = $user->id;
    $result->status = "ok";
    $result->id = $user->id;
    return $result;
  }

  public static function updateJoomlaUser($data, $id) {
    $result = new stdClass();
    $result->id = $id;
    jimport('joomla.user.helper');
    $userdata = array(
      "name"=>trim(strval($data['name'])),
      "username"=>trim(strval($data['username'])),
      "password"=>trim(strval($data['password'])),
      "password2"=>trim(strval($data['password'])),
      "email"=>trim(strval($data['email'])),
      "block"=>0,
    );
    foreach($userdata as $d)
    {
      if(trim(strval($d)) == "" || !$d)
        unset($d);
    }

    $userdata["groups"] = array("2");
    $user = new JUser;
    $user->load($id);
    //Write to database
    if(!$user->bind($userdata)) {
      $result->status = $user->getError();
      return $result;

    }
    $user->from_moodle = true;
    if (!$user->save()) {
      $result->status = $user->getError();
      return $result;

    }

    $params = JComponentHelper::getParams('com_moojla');
    $ads = trim($params->get('additional_data_source'));
    if(isset($data["post"]))
    {
      $newdata = isset($data["moodle"]) ?
$data["moodle"] : $data["post"];
      // if($ads == "jf")
      // {
      JPluginHelper::importPlugin("moojlaaditionalfields");
      $dispatcher = JEventDispatcher::getInstance();
      $dispatch_res	= $dispatcher->trigger("addUserToJoomla",
array($newdata, $id));
      // }
      // else if($ads == "cb")
      // {
      // $file_name = __DIR__. "/updateJoomlaUser111111111.txt";
      // file_put_contents($file_name, 'dispatch_res = ' .
print_r($dispatch_res, true)."\n", FILE_APPEND);
      // }
    }
    $result->status = "ok";

    return $result;
  }
  public static function deleteJoomlaUser($id) {
    $result = new stdClass();

    jimport('joomla.user.helper');

    $user = new JUser;
    $user->load($id);

    if (!$user->delete()) {
      $result->status = $user->getError();
      return $result;

    }

    $result->status = "ok";
    return $result;
  }


  /**
    * 
    *
    *
    *	$data and body are array with keys and values
    */
  public static function sendRequestToMoodle($data, $body=array())
  {
    /*
      $curl = curl_init();

      curl_setopt_array($curl, array(
        CURLOPT_URL =>
"http://atwh.ir/lms/webservice/rest/server.php?wsfunction=moojla_trigger_create_users&moodlewsrestformat=json&wstoken=1b7d4d04a7bff9cd676ae5e20cba6260&userids%5B0%5D%5Bid%5D=428",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS =>"{}",
        CURLOPT_HTTPHEADER => array(
          "Content-Type: application/json"
        ),
      ));

      $response = curl_exec($curl);

      curl_close($curl);
      echo $response;
      */
    /*
      */
    $postField = new stdClass();
    $postField->from_joomla = 1;
    foreach($body as $key => $value)
    {
      $postField->$key = $value;
      if(!$value)
        unset($postField->$key);
    }
    $postField = json_encode($postField);

    $params = JComponentHelper::getParams('com_moojla');
    $moodle_url= trim($params->get('moodle_url'));
    $moodle_token = trim($params->get('moodle_token'));
    $data["wstoken"] = $moodle_token;

    $url = $moodle_url . "webservice/rest/server.php?" .
http_build_query($data);
    //$url = urldecode($url);
    // dump($url, "url");
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_SSL_VERIFYHOST  => 0,
      CURLOPT_SSL_VERIFYPEER  => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $postField,
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json"
      ),
    ));

    $response = curl_exec($curl);
    $error    = curl_error($curl);
    curl_close($curl);
    $output = new stdClass();
    $output->response   = $response;
    $output->error      = $error;
    return $output;
  }

  public static function addToUserMap($data){
    if(!$data['jid'])
      $data['jid'] = 0;
    if(!$data['mid'])
      $data['mid'] = 0;
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/user_map.php";
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query = "SELECT * FROM `#__moojla_user_map` WHERE ((jid > 0
AND jid = '{$data['jid']}') OR (mid > 0 AND mid =
'{$data['mid']}')) AND published = 1";
    $db->setQuery($query);
    $usermapres = $db->loadAssocList()[0];
    if(isset($usermapres['id']))
      $id = $usermapres['id'];
    else
      $id = '';
    if($data['jid'] || $data['mid'])
    {
      if($id)
        $data['id'] = $id;
      $usermap = new MoojlaModelUser_map();
      $usermap->save($data);
    }
    if($data['jid'] != 0 && $data['mid'] != 0)
    {
      require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/user_map.php";
      $query = $db->getQuery(true);
      $query->select('id');
      $query->from($db->quoteName('#__moojla_user_map'));
      $query->where($db->quoteName('jid') .' = '
. $db->quote($data['jid']));
      $query->where($db->quoteName('mid') .' =
0');
      $db->setQuery($query);
      $rowToDel = $db->loadResult(); 
      if($rowToDel)
      {
        $usermap = new MoojlaModelUser_map();
        $usermap->myDelete($rowToDel);
      }

      $query = $db->getQuery(true);
      $query->select('id');
      $query->from($db->quoteName('#__moojla_user_map'));
      $query->where($db->quoteName('mid') .' = '
. $db->quote($data['mid']));
      $query->where($db->quoteName('jid') .' =
0');
      $db->setQuery($query);
      $rowToDel = $db->loadResult(); 
      if($rowToDel)
      {
        $usermap = new MoojlaModelUser_map();
        $usermap->myDelete($rowToDel);
      }
    }
  }	

  public static function deleteFromUserMap($id){
    /*
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $conditions = array($db->quoteName('jid') . ' =
' . $db->quote($id));
     
$query->delete($db->quoteName('#__moojla_user_map'));
      $query->where($conditions);
      $db->setQuery($query);
      $result = $db->execute();
      */
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/user_map.php";
    $usermap = new MoojlaModelUser_map();
    $usermap->myDelete($id);

  }

  public static function joomlaToMoodleID($id){
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('mid')));
    $query->from($db->quoteName('#__moojla_user_map'));
    $query->where($db->quoteName('jid') . ' = ' .
$db->quote($id));
    $db->setQuery($query);
    $mid = $db->loadResult();
    return $mid;
  }

  public static function loginToJoomla($username, $password,
$from_moodle=0){
    $mainframe = JFactory::getApplication('site');
    $user_id = JUserHelper::getUserId($username);
    $user = JFactory::getUser($user_id);

    if (!$user)
      return false;

    if ($user->block)
      return false;

    $options = array ( 'remember' => '1',
'silent' => 1);
    $credentials = array ( 'username' => $username,
'password' => $password, "from_moodle" =>
$from_moodle);
    if ($mainframe->login( $credentials, $options ))
      return true;

    return false;
  }

  public static function logoutFromJoomla($username, $from_moodle=0){
    $mainframe	= JFactory::getApplication('site');
    $id			= JUserHelper::getUserId($username);
    $error		= $mainframe->logout($id, array ('clientid' =>
0, "from_moodle" => $from_moodle));
    $session	= JFactory::getSession();
    $sessid		= $session->getId();
    return $sessid;
  }

  public static function loginToMoodle($username, $token)
  {
    $params		= JComponentHelper::getParams('com_moojla');
    $moodle_url	= trim($params->get('moodle_url'));
    $moodle_cookie_path	=
trim($params->get('moodle_cookie_path'));
    $config		= JFactory::getConfig();
    $temppath	= $config->get('tmp_path');
    $file		= $temppath . "/" . JUserHelper::genRandomPassword() .
".txt";
    $postField = array ( 'username' => $username,
'token' => $token, "from_joomla" => 1);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL				=> $moodle_url .
"auth/moojla/loginHandler.php",
      CURLOPT_RETURNTRANSFER	=> true,
      CURLOPT_COOKIEJAR			=> $file,
      CURLOPT_HEADER			=> true,
      CURLOPT_SSL_VERIFYPEER	=> false,
      CURLOPT_SSL_VERIFYHOST	=> false,
      CURLOPT_CUSTOMREQUEST		=> "POST",
      CURLOPT_POSTFIELDS => $postField,

    ));

    $response			= curl_exec($curl);
    $error				= curl_error($curl);
    curl_close($curl);
    $output				= new stdClass();
    $output->response   = $response;
    $output->error      = $error;
    preg_match_all('/^Set-Cookie: (.*?); path=(.*)/m', $response,
$match);
          $cookie_options = array (
//          'path' => $moodle_url,
          'path' => $moodle_cookie_path,
//          'secure' => true,
          'secure' => false,
          'httponly' => false,
//          'samesite' => 'None'

      );
    foreach($match[1] as $key => $m)
    {
      $cookie = explode('=', $m);
      setcookie($cookie[0], $cookie[1], $cookie_options);
    }

    if (file_exists($file)) 
      unlink ($file);
    return $output;

  }

  public static function logoutFromMoodle($username){
    $app = JFactory::getApplication('site');
    $cookieName  = 'joomla_remember_me_' .
JUserHelper::getShortHashedUserAgent();
    if (!$app->input->cookie->get($cookieName))
    {
      $cookieName = JUserHelper::getShortHashedUserAgent();
    }
    $cookieValue = $app->input->cookie->get($cookieName);
    if ($cookieValue)
    {
      $cookieArray = explode('.', $cookieValue);
      $filter = new JFilterInput;
      $series = $filter->clean($cookieArray[1], 'ALNUM');
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query
        ->delete('#__user_keys')
        ->where($db->quoteName('series') . ' = '
. $db->quote($series));
      $app->input->cookie->set(
        $cookieName,
        false,
        time() - 42000,
        $app->get('cookie_path', '/'),
        $app->get('cookie_domain')
      );
    }
    $params = JComponentHelper::getParams('com_moojla');
    $moodle_url	= trim($params->get('moodle_url'));
    $moodle_cookie_path=
trim($params->get('moodle_cookie_path'));
    //session_get_cookie_params
    unset($_SESSION['USER']);
    unset($_SESSION['SESSION']);
    $cookie_options = array (
          //'path' => $moodle_url,
          'path' => $moodle_cookie_path,
          //'secure' => true,
          'httponly' => false,
          //'samesite' => 'None',
          'expires'=> time() - 3600
      );
    setcookie('MoodleSession', '',$cookie_options);
    unset($_SESSION);
  }


  public static function changeObjectKey($object, $oldkey, $newkey)
  {
    if(isset($object->$oldkey))
    {
      $object->$newkey = $object->$oldkey;
      unset($object->$oldkey);
    }
    else{
      $object->$newkey = false;
    }

  }

  public static function getLoginUrl($return)
  {
    $loginUrl = 'index.php?option=com_users&view=login' .
($return ? ('&return=' . base64_encode($return)) :
'');
    return $loginUrl;
  }

  public static function updateCourseContents($sections, $courseid)
  {
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/section.php";
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/module.php";
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/content.php";
    require_once JPATH_ADMINISTRATOR .
"/components/com_moojla/models/module.php";
    foreach($sections as $section)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select($db->quoteName(array('id')))
        ->from($db->quoteName('#__moojla_section'))
        ->where($db->quoteName('section_id') . ' =
' . $db->quote($section->id));
      $db->setQuery($query);
      $sectionResult = $db->loadResult();
      $sectionData = array(
        "courseid"	=> $courseid,
        "name"		=> $section->name,
        "section_id"	=> $section->id,
        "summary"		=> $section->summary,
        "visible"		=> $section->visible,
        "published"	=> $section->visible,
        "uservisible"	=> $section->uservisible
      );
      if($sectionResult)
      {
        $sectionData["id"] = $sectionResult; //for update
      }
      $sectionModel = new MoojlaModelsection;
      $sectionModel->save($sectionData);
      foreach($section->modules as $module)
      {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($db->quoteName(array('id')))
          ->from($db->quoteName('#__moojla_module'))
          ->where($db->quoteName('module_id') . ' =
' . $db->quote($module->id));
        $db->setQuery($query);
        $moduleResult = $db->loadResult();

        $moduleData = array(
          "module_section_id"	=> $section->id,
          "name"				=> $module->name,
          "module_id"			=> $module->id,
          "description"			=> isset($module->description) ?
$module->description : "",
          "visible"				=> $module->visible,
          "published"			=> $module->visible,
          "uservisible"			=> $module->uservisible,
          "modname"				=> $module->modname,
          "url"					=> $module->url,
          "modicon"				=> $module->modicon,
        );
        if($moduleResult)
        {
          $moduleData["id"] = $moduleResult;
        }
        $moduleModel = new MoojlaModelmodule;
        $moduleModel->save($moduleData);

        if(isset($module->contents))
        {
          $contents = current($module->contents);
          $db = JFactory::getDbo();
          $query = $db->getQuery(true);
          $query->select($db->quoteName(array('id')))
            ->from($db->quoteName('#__moojla_content'))
            ->where($db->quoteName('contents_module_id') .
' = ' . $db->quote($module->id));
          $db->setQuery($query);
          $contentResult = $db->loadResult();

          $contentData = array(
            "contents_module_id"	=> $module->id,
            "type"				=> $contents->type,
            "filename"			=> isset($contents->filename) ?
$contents->filename : "",
            "filesize"			=> isset($contents->filesize) ?
$contents->filesize : 0,
            "fileurl"				=> isset($contents->fileurl) ?
$contents->fileurl : "",
            "mimetype"			=> isset($contents->mimetype) ?
$contents->mimetype : "",
          );
          if($contentResult)
          {
            $contentData["id"] = $contentResult;
          }
          $contentModel = new MoojlaModelcontent;
          $contentModel->save($contentData);

        }

      }
    }
  }

  public static function createButton($label, $id, $loginurl,
$registrationurl)
  {
    return "<input type='button'
class='moojla-login-button' id='moojla-start-modal'
value='".$label."'>
      <div id='moojla-modal'
class='moojla-login-modal'>
        <div class='moojla-login-modal-content animate'>
          <span id='logintabbtn'
class='modal_tab_button_login_registration
active_tab_login_registration'>
            ورود
          </span>
          <span id='regtabbtn'
class='modal_tab_button_login_registration'>
            ثبت نام
          </span>
          <div id='moojla-login-modal-content'
class='display_content_log_reg show_content'>
            <img
src='/components/com_moojla/assets/images/loading-modal.gif'
id='loadinggif'>
          </div>
          <div id='moojla-reg-modal-content'
class='display_content_log_reg'>
            <img
src='/components/com_moojla/assets/images/loading-modal.gif'
id='loadinggif'>
          </div>
        </div>
      </div>


      <script>
        loginbtn = jQuery('#logintabbtn');
        regbtn = jQuery('#regtabbtn');
        l = jQuery('#moojla-login-modal-content');
        r = jQuery('#moojla-reg-modal-content');
        var moojla_login_modal =
document.getElementById('moojla-modal');






        loginbtn.click(function(e){
          // l.show();
          // r.hide();
        });


        regbtn.click(function(e){
          // r.show();
          // l.hide();
          jQuery('#member-registration > div > div >
a').click(function(e) {
            moojla_login_modal.style.display = 'none';
            return false;
          });
        });

        window.onclick = function(event) {
          if (event.target == moojla_login_modal) {
            moojla_login_modal.style.display = 'none';
          }
        }

        document.getElementById('moojla-start-modal').onclick =
function() {
          moojla_login_modal.style.display ='block';
          l = jQuery('#moojla-login-modal-content');
         
l.load('".$loginurl."&return=".base64_encode('index.php?option=com_moojla&view=coursedetail&id='.$id)."',
function(){
            loadinggif = jQuery('#loadinggif');

            loadinggif.hide();
          });
          r = jQuery('#moojla-reg-modal-content');
         
r.load('".$registrationurl."&return=".base64_encode('index.php?option=com_moojla&view=coursedetail&id='.$id)."',
function(){
            loadinggif = jQuery('#loadinggif');
            loadinggif.hide();
            regform = jQuery('#member-registration');
            oldaction = regform[0].getAttribute('action')

            regform[0].setAttribute('action', oldaction +
'&return=' +
'".base64_encode('index.php?option=com_moojla&view=coursedetail&id='.$id)."')
          });


          // r.hide();
        }

        jQuery('#member-registration > div > div >
a').click(function(e) {
          moojla_login_modal.style.display = 'none';
          return false;
        });

      </script>";
  }
  public static function pageModal($btntitle, $courseid, $modid,
$pageheader, $content, $pagefooter)
  {
    $jid = JFactory::getUser()->id;
    $mid = MoojlaHelper::joomlaToMoodleID($jid);
    return "<style>
            /* The Modal (background) */
            .pageModal-$modid {
              display: none; /* Hidden by default */
              position: fixed; /* Stay in place */
              z-index: 10000; /* Sit on top */
              padding-top: 100px; /* Location of the box */
              left: 0;
              top: 0;
              width: 100%; /* Full width */
              height: 100%; /* Full height */
              overflow: auto; /* Enable scroll if needed */
              background-color: rgb(0,0,0); /* Fallback color */
              background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
            }

            /* Modal Content */
            .pageModal-content-$modid {
              position: relative;
              background-color: #fefefe;
              margin: auto;
              padding: 0 20px;
              border: 1px solid #888;
              width: 80%;
              box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0
rgba(0,0,0,0.19);
              -webkit-animation-name: animatetop;
              -webkit-animation-duration: 0.4s;
              animation-name: animatetop;
              animation-duration: 0.4s
            }

            /* Add Animation */
            @-webkit-keyframes animatetop {
              from {top:-300px; opacity:0} 
              to {top:0; opacity:1}
            }

            @keyframes animatetop {
              from {top:-300px; opacity:0}
              to {top:0; opacity:1}
            }

            /* The Close Button */
            .close {
              color: gray;
              float: right;
              font-size: 28px;
              font-weight: bold;
            }

            .close:hover,
            .close:focus {
              color: #000;
              text-decoration: none;
              cursor: pointer;
            }
			
			.lmskaran-closeModal {
				display: inline-flex;
				margin-top: 10px;
				cursor: pointer;
			}
			
			.lmskaran-closeModal > i {
				color: red;
				font-size: 30px;
			}

      </style>
      <!-- Trigger/Open The Modal -->
      <button id='page-$modid'>$btntitle</button>
      <!-- The Modal -->
      <div id='pageModal-$modid'
class='pageModal-$modid'>
        <!-- Modal content -->
        <div class='pageModal-content-$modid'>
          <div class='pageModal-header-$modid'>
            <div class='lmskaran-closeModal'><i
class='fas fa-times'></i></div>
            <h2>$pageheader</h2>
          </div>
          <div id='pageModal-body-$modid'
class='pageModal-body-$modid'>
            $content
          </div>
          <div class='pageModal-footer-$modid'>
            <h3>$pagefooter</h3>
          </div>
        </div>
      </div>
      <script>
      var span = document.getElementsByClassName('close')[0];
      document.getElementById('page-$modid').onclick = function()
{
        var content =
document.getElementById('pageModal-body-$modid');
        jQuery.ajax({
          url:
'/?option=com_moojla&view=coursedetail&task=coursedetail.getPageContent&pageid=$modid&courseid=$courseid',
        }).done(function(e){
			modal = document.getElementById('pageModal-$modid');
			content.innerHTML  = e;
			viewActivity($mid, $modid)
			modal.style.display = 'block';
        });
  
      }
      window.onclick = function(event) {
        if (event.target == modal) {
          modal.style.display = 'none';
        }
      }
						
      jQuery(document).ready(function($) {
				$('.lmskaran-closeModal').click(function() {
					modal.style.display = 'none';
				});
			});
      </script>";
  }

  public static function getCurrentPriceByProductCode($product_code) {
   
require_once(JPATH_ADMINISTRATOR.'/components/com_hikashop/helpers/helper.php'
);

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName('product_id'));
    $query->from($db->quoteName('#__hikashop_product'));
    $query->where($db->quoteName('product_code') . ' =
' . $db->quote($product_code));
    $query->where($db->quoteName('product_published') .
' = 1');
    $db->setQuery($query);
    $productid = $db->loadResult();
    // dump($query->__toString());

    if(!$productid)
      return 0;
    $user = JFactory::getUser();
    $productClass = hikashop_get('class.product');
    $product=$productClass->get($productid);
    $currencyClass = hikashop_get('class.currency');
    $config = hikashop_config();
    if(is_object($product))
    {
      $parent = $productClass->get($product->product_parent_id);
      if(!is_object($parent))
      {
        $parent = new stdClass;
        $parent->product_id = $product->product_parent_id;
      }
      $ids = array($product->product_id, $parent->product_id);
      $parent->variants = array($product);
      $p = $currencyClass->getPrices($product, $ids,
hikashop_getCurrency(), $config->get('main_currency'),
hikashop_getZone(), $config->get('discount_before_tax'));
      if(property_exists($product, 'prices'))
      {
        $prices = $product->prices;
        if(is_array($prices))
        {
          $price = current($prices);
          return $currencyClass->format($price->price_value_with_tax,
$price->price_currency_id);
        }
      }
      else
        return 0;
    }
    return 0;
  }
public static function newActionButton($course, $is_enrolled, $module=null,
$returnurl='', $moodleurl='')
  {
    $params = JComponentHelper::getParams('com_moojla');
    $sp = '-'; 
    $jsp = '_'; 
    $btn_index = $course->id.($module ? $sp.$module->id :
"");
    $elm_index = $course->id.($module ? $jsp.$module->id :
"");
    $moodle_url= $moodleurl ? $moodleurl :
trim($params->get('moodle_url'));

    $loginurl = trim($course->loginurl);
    if($loginurl == '')
    {
      $loginurl = trim($params->get('loginurl',
'index.php?option=com_users&task=login&tmpl=component'));
    }
    $loginurl = JRoute::_($loginurl, false);
    
    $showlogintab = $course->showlogintab;
    if($showlogintab == '' || $showlogintab == 2)
    {
      $showlogintab = $params->get('showlogintab', 1);
    }
    
    $showregtab = $course->showregtab;
    if($showregtab == '' || $showregtab == 2)
    {
      $showregtab = $params->get('showregtab', 1);
    }
    
    
    $registrationurl = trim($course->registrationurl);
    if($registrationurl == '')
    {
      $registrationurl = trim($params->get('registrationurl',
'index.php?option=com_users&view=registration&tmpl=component'));
    }
    $registrationurl = JRoute::_($registrationurl, false);

    $uri = JUri::getInstance(); 
    $returnurl = ($returnurl == '' ? $uri->toString() :
$returnurl);

    $returnurl = base64_encode($returnurl);
    if(trim($course->loginlbl) == '')
      $btnlbl = trim($params->get('loginlbl'));
    else
      $btnlbl = trim($course->loginlbl);

    $user = JFactory::getUser();     
    $is_enrolled = property_exists($course, "is_enrolled") ?
$course->is_enrolled : $is_enrolled;
    $self_enrolment = $course->self_enrolment;
    $guest = $course->guest;
    $cost = $course->cost;
    $remoteid = $course->remoteid;
    $courseid = $course->id;
    $btnclass = 'loginbtn';
    $html =
"<style>.moojla-login-modal{display:none;position:fixed;z-index:1000;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:rgb(0,0,0);background-color:rgba(0,0,0,.4);padding-top:60px}.moojla-login-modal-content{background-color:#fefefe;margin:0
auto 15% auto;border:1px solid
#888;width:40%;border-radius:20px;padding-top:20px}.close{position:absolute;right:25px;top:0;color:#000;font-size:35px;font-weight:700}.close:hover,.close:focus{color:red;cursor:pointer}.animate{-webkit-animation:animatezoom
0.8s;animation:animatezoom 0.8s}@-webkit-keyframes
animatezoom{from{-webkit-transform:scale(0)}to{-webkit-transform:scale(1)}}@keyframes
animatezoom{from{transform:scale(0)}to{transform:scale(1)}}@media screen
and
(max-width:300px){span.psw{display:block;float:none}.cancelbtn{width:100%}}.moojla-login-modal-content{background-color:transparent;border:unset;width:40%}.moojla-login-modal{background-color:rgb(0
0 0 / 69%)}ul.nav.nav-tabs.nav-stacked li
a{color:#000;padding:20px}form.form-validate.form-horizontal.well{border-bottom:unset;background:#fff}.form-horizontal
.control-label{width:100%!important}.form-horizontal
.controls{margin-right:unset!important}</style>";
    if(!$user->id && $guest == 0)
    {
      $flag=true;
      $html .= "
            <a id='moojla-start-modal-$btn_index'
class='moojla-login-button $btnclass'><span
class='actionbtn-$btn_index' >$btnlbl</span></a>
            <div id='moojla-modal-$btn_index'
class='moojla-login-modal' >
              <div class='moojla-login-modal-content
animate'>".($showlogintab == 0 ? "" : 
                "<span id='logintabbtn-$btn_index'
class='active'>
                  ورود
                </span>
                <div
id='moojla-login-modal-content-$btn_index'>
                  <img
src='/components/com_moojla/assets/images/loading-modal.svg'
id='loadinggif-$btn_index'>
                </div>").($showregtab == 0 ? "" : 
                "<span id='regtabbtn-$btn_index'>
                  ثبت نام
                </span>
                <div id='moojla-reg-modal-content-$btn_index'
class='active'>
                  <img
src='/components/com_moojla/assets/images/loading-modal.svg'
id='loadinggif-$btn_index'>
                </div>").
              "</div>
            </div>
            <script>
              loginbtn$elm_index =
jQuery('#logintabbtn-$btn_index');
              regbtn$elm_index =
jQuery('#regtabbtn-$btn_index');
              l$elm_index =
jQuery('#moojla-login-modal-content-$btn_index');
              r$elm_index =
jQuery('#moojla-reg-modal-content-$btn_index');
              var moojla_login_modal$elm_index =
document.getElementById('moojla-modal-$btn_index');
              loginbtn$elm_index.click(function(e){
                l$elm_index.show();
                r$elm_index.hide();
              });
              regbtn$elm_index.click(function(e){
                r$elm_index.show();
                l$elm_index.hide();
                jQuery('#member-registration-$btn_index > div >
div > a').click(function(e) {
                  moojla_login_modal$elm_index.style.display =
'none';
                  return false;
                });
              });
             
document.getElementById('moojla-start-modal-$btn_index').onclick
= function() {
                moojla_login_modal$elm_index.style.display
='block';
                if(r$elm_index.hasClass('loaded')) {
                  r$elm_index.css('display', 'block');
                }
               
l$elm_index.load('$loginurl&return=$returnurl', function(){
                  loadinggif$elm_index =
jQuery('#loadinggif-$btn_index');
                  if(loadinggif$elm_index) {
                    loadinggif$elm_index.hide();
                    l$elm_index.addClass('loaded');
                  }
                });
               
r$elm_index.load('$registrationurl&return=$returnurl',
function(){
                  loadinggif$elm_index =
jQuery('#loadinggif-$btn_index');
                  if(loadinggif$elm_index) {
                    loadinggif$elm_index.hide();
                    r$elm_index.addClass('loaded');
                  }
                  regform$elm_index =
jQuery('#member-registration-$btn_index');
                  regf = regform$elm_index;
                  if(regf[0]) {
                    oldaction$elm_index =
regf[0].getAttribute('action')
                    regf[0].setAttribute('action',
oldaction$elm_index + '&return=' + '$returnurl')
                  }
                });
                // r$elm_index.hide();
                // l$elm_index.hide();
                ".($showlogintab == 0 ?
"l$elm_index.hide();" : "r$elm_index.hide();").
              "}
              jQuery('#member-registration-$btn_index > div >
div > a').click(function(e) {
                moojla_login_modal$elm_index.style.display =
'none';
                return false;
              });

              window.addEventListener('click', function(e){
                if(e.target == moojla_login_modal$elm_index) {
                  moojla_login_modal$elm_index.style.display =
'none';
                  l$elm_index.removeClass('hidden');
                  r$elm_index.removeClass('hidden');
                }
              });
            </script>

           
<style>/*div#moojla-login-modal-content-$btn_index{display:flex;justify-content:center;align-items:center;background:#fff;padding:10px}input#modlgn-passwd-$btn_index,input#modlgn-username-$btn_index{margin:unset!important}span#logintabbtn-$btn_index{background:#fff;padding:15px
20px;display:inline-flex;margin-left:10px;border-radius:10px 10px 0
0;cursor:pointer}span#regtabbtn-$btn_index{background:#fff;padding:15px
20px;border-radius:10px 10px 0
0;cursor:pointer}div#moojla-reg-modal-content-$btn_index{display:block;background:#fff}
*/</style>";

    }
    else
    {
      $flag = false;
      if($course->cangotomoodle == 2)
        $cangotomoodle = $params->get('cangotomoodle', 0);
      else
        $cangotomoodle = $course->cangotomoodle;

      if($is_enrolled)
      {
        if($cangotomoodle == 1)
        {
          $redirect_url = $moodle_url . 'course/view.php?id=' .
$remoteid;
          $flag = true;
        }
        else
        {
          $redirect_url = '#';
          $flag = false;
        }

        if(trim($course->enterlbl) == '')
          $label = trim($params->get('enterlbl'));
        else
          $label = trim($course->enterlbl);

        $btnclass = 'enterbtn';
        $html .= "<a id='moojla-start-modal-$btn_index'
class='moojla-login-button $btnclass'
href='$redirect_url'> <span class='actionbtn'
> $label </span> </a>";
      }
      elseif($guest == 1)
      {
        if($cangotomoodle == 1)
        {
          $redirect_url = $moodle_url . 'course/view.php?id=' .
$remoteid;
          $flag = true;
        }
        else
        {
          $redirect_url = '#';
          $flag = false;
        }

        if(trim($course->freeenterlbl) == '')
          $label = trim($params->get('freeenterlbl'));
        else
          $label = trim($course->freeenterlbl);

        $btnclass = 'freebtn';
        
        $html .= "<a id='moojla-start-modal-$btn_index'
class='moojla-login-button $btnclass'
href='$redirect_url'> <span class='actionbtn'
> $label </span> </a>";
      }
      else if($cost != 0)
      {
        if(trim($course->buylbl) == '')
          $label = trim($params->get('buylbl'));
        else
          $label = trim($course->buylbl);
        $btnclass = 'buybtn';
        $flag = true;
        $shop_integration =
trim($params->get('shop_integration'));
        if($shop_integration == '0')
        {
          $redirect_url =
JRoute::_('index.php?option=com_moojla&view=coursedetail&id='.$tcourse->id,
false);
          $app = JFactory::getApplication();
         
$app->enqueueMessage(JText::_('MOOJLA_NO_SHOP_INTEGRATION_SELECTED'));
// translate need
        }
        else if($shop_integration == 'hk') // hikashop
        {
          $db = JFactory::getDbo();
          $query = $db->getQuery(true);
          $query->select($db->quoteName('product_id'));
         
$query->from($db->quoteName('#__hikashop_product'));
          $query->where($db->quoteName('product_code') .
' = ' . $db->quote($remoteid));
          $db->setQuery($query);
          $product_id = $db->loadResult();
          $redirect_url =
JRoute::_('index.php?option=com_hikashop&ctrl=product&task=show&cid='
. $product_id, false); 
          // $html .= "<a
id='moojla-start-modal-$btn_index'
class='moojla-login-button $btnclass'
href='$redirect_url'> <span class='actionbtn'
> $label </span> </a>";
          $html .= "<a class='hikabtn hikacart'
rel='nofollow'
href='/index.php?option=com_hikashop&ctrl=product&task=updatecart&add=1&product_id=$product_id'
onclick='if(window.hikashop.addToCart){return
window.hikashop.addToCart(this);}'data-addtocart='$product_id'data-addto-class='add_in_progress'><span>$label</span></a>";
        }


      }
      elseif($self_enrolment)
      {
        $redirect_url =
JRoute::_('index.php?option=com_moojla&task=coursedetail.enrol&itemid='
. $courseid . '&type=self', false);
        if(trim($course->enrollbl) == '')
          $label = trim($params->get('enrollbl'));
        else
          $label = trim($course->enrollbl);
        $btnclass = 'enrolbtn';
        $flag = true;

        $html .= "<a id='moojla-start-modal-$btn_index'
class='moojla-login-button $btnclass'
href='$redirect_url'> <span class='actionbtn'
> $label </span> </a>";
      }

    }
    $css = "
          <style>

            /*login tab */
            #logintabbtn-$btn_index {
              position: absolute;
              right: 0px;
              top: -36px;
            }

            #regtabbtn-$btn_index {
              position: absolute;
              right: 70px;
              top: -36px;
            }

            #logintabbtn-$btn_index,#regtabbtn-$btn_index {
              background: #fff;
              padding: 15px 20px;
              border-radius: 10px 10px 0 0;
              cursor: pointer;
              font-size: 16px;
              font-weight:100;
              color: black;
            }

            .moojla-login-modal-content{
              position:relative;
            }



            /* preloader */
           
div#moojla-login-modal-content-$btn_index,div#moojla-reg-modal-content-$btn_index
{
              background: white;
              border-radius: 10px 0 10px 10px;
            }

             div#moojla-login-modal-content-$btn_index{
               display:flex;
               justify-content:center;
             }

            .customizedbyMJT {
              padding:10px 50px;
            }


            .moojla-login-modal-content{
              background-color: transparent;
              border: unset;
              width:40%;
            }

            .moojla-login-modal{
              background-color: rgb(0 0 0 / 69%);
            }

            input#modlgn-username,input#modlgn-passwd {
              margin: unset !important;
              width: 100%;
            }

            .input-prepend {
              width: 100%;
              display: flex !important;
            }

            .add-on [class^='icon-'], .add-on [class*='
icon-']{
              margin-left:unset !Important;
            }

            /*ul in tab login*/

            ul.nav.nav-tabs.nav-stacked li a {
              color: black;
              padding: 20px;
            }

            /* margin unset input */

            .form-horizontal .controls{
              margin-right:unset !important;
            }

            div#form-login-submit .controls {
              display: flex;
              justify-content: center;
              align-items: center;
            }

            div#form-login-submit .controls button{
              width: 30%;
              padding: 10px;
              font-size: 1rem;
              font-weight: 100;
              background: #3ea2e2;
            }

            #moojla-reg-modal-content #cbcheckedadminForm
#registrationTable{
              color:black;
            }

            ul#form-login-links {
              font-size: 15px;
              font-weight: 100;
              margin-bottom: unset;
            }

            ul#form-login-links li {
              text-align: right;
            }

            ul#form-login-links li a {
              color: black;
            }

            ul#form-login-links li a:hover {
              color: black;
            }

            #moojla-login-modal-content .image_head_modal_login {
              width: 100%;
            }

            div#form-login-remember {
              display: flex;
              align-items: center;
              flex-direction: row-reverse;
              justify-content: flex-end;
            }

            div#form-login-remember label {
              color: black;
              font-size: 15px;
              font-weight: 100;
              margin-right: 5px;
            }


            /*moojla modal*/
            #moojla-modal{
              cursor: auto;
            }

            @media screen and (max-width: 1200px) and (min-width: 768px){

              .moojla-login-modal-content{
                width:60%;
              }
            }

            @media screen and (max-width: 768px) and (min-width: 500px){

              .moojla-login-modal-content{
                width:80%;
              }
            }

            @media only screen and (max-width: 500px){

              .moojla-login-modal-content{
                width:99%;
              }

            }

            .lmskaran_reg_download > input{
                background-color: #4ece3d;
                border: unset;
             }
          </style>
        ";
    $html .=$css;
    return array($flag, $html); 
  }


  public static function fileActionButton(array $options, int $type)
  {
    /*
        type {
          1	-> Modal
          2	-> Embed
          3	-> Scrol to top
        */
    $src = $options["src"];
    $id = $options["id"];
    $name = $options["name"];
    $course = $options["course"];
    $mimetype = $options["mimetype"];
    $onclick = isset($options["onclick"]) ?
$options["onclick"] :
"location.href='$src'";
    $onclick = htmlspecialchars_decode($onclick);
    $tagname = "";
    $endigtag = "";
    $jid = JFactory::getUser()->id;
    $mid = MoojlaHelper::joomlaToMoodleID($jid);
    $params	= JComponentHelper::getParams('com_moojla');
    if($course->useglobalvideo == 1)
    {
      $preventdownload = $params->get('preventdownload', 0);
      $addcontrols = $params->get('addcontrols', 1);
      $preloadvideo = $params->get('preloadvideo', 0);
      $autoplay = $params->get('autoplay', 0);
      $muted = $params->get('muted', 0);
    }
    else
    {
      $preventdownload = $course->preventdownload ?
$course->preventdownload : 0;
      $addcontrols = $course->addcontrols ? $course->addcontrols :
1;
      $preloadvideo = $course->preloadvideo ? $course->preloadvideo :
0;
      $autoplay = $course->autoplay ? $course->autoplay : 0;
      $muted = $course->muted ? $course->muted : 0;
      $type = $course->videotype ? $course->videotype : $type;
    }


    switch($mimetype)
    {
      case 'video':
        $tagname = 'video';
        $endigtag = "</video>";
        break;
      case 'image':
        $tagname = 'img';
        break;
      case 'audio':
        $tagname = 'audio';      
        $endigtag = "</audio>";
        break;
    }
    if($tagname == "")
    {
      $src = $onclick ? "#" : $src;
      return "<a href='$src'
onclick='onClickFunction$id()' class='btn btn-primary
file-btn' id='file-btn-$id' >$name</a>
                <script>
                function onClickFunction$id(){
                    viewActivity($mid, $id);
                    $onclick;
                }
                </script>
                ";
    }
    if($tagname == 'audio')
    {
      $type = '2';
      $addcontrols = 1;

      if($course->useglobalaudio == 1)
      {
        $preventdownload =
$params->get('preventdownloadaudio', 0);
        $preloadvideo = $params->get('preloadaudio', 0);
        $autoplay = $params->get('autoplayaudio', 0);
      }
      else
      {
        $preventdownload = $course->preventdownloadaudio ?
$course->preventdownloadaudio : 0;
        $preloadvideo = $course->preloadaudio ? $course->preloadaudio
: 0;
        $autoplay = $course->autoplayaudio ? $course->autoplayaudio :
0;
      }
    }
    switch($type)
    {
      case 1:
        $html = "<button type='button' class='btn
btn-primary file-btn' id='file-btn-$id'
data-toggle='modal' data-src='$src'
data-target='#myModal-$id'>
            $name
            </button>
            <!-- Modal -->
            <div class='modal fade' id='myModal-$id'
tabindex='-1' role='dialog'
aria-labelledby='exampleModalLabel'
aria-hidden='true'>
              <div class='modal-dialog'
role='document'>
                <div class='modal-content'>
                  <div class='modal-body'>
                    <button type='button'
class='close' data-dismiss='modal'
aria-label='Close'>
                      <span
aria-hidden='true'>&times;</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class='embed-responsive
embed-responsive-16by9'>
                      <$tagname class='embed-responsive-item'
src='' 
                      id='modalfile-$id'
allowscriptaccess='always' allow='autoplay'
                      " . ($addcontrols ? 'controls' :
'') . 
                      " preload='" . ($preloadvideo ?
'true' : 'none') . 
                      "' " . ($muted ? 'muted' :
''). " " 
                      . ($preventdownload ?
'controlsList="nodownload"' : '') . 
                      " " 
                      . ($autoplay ? 'autoplay' : '') .
" >$endigtag
                    </div>
                  </div>
                </div>
              </div>
            </div>

          <script>
          jQuery(document).ready(function($) {
            // Gets the file src from the data-src on each button
            var fileSrc;
            $('#file-btn-$id').click(function() {
              fileSrc = $(this).data('src');
            });

            // when the modal is opened autoplay it  
            $('#myModal-$id').on('shown.bs.modal',
function(e) {
              // set the file src to autoplay and not to show related file.
Youtube related file is like a box of chocolates... you never know what
you're gonna get
              $('#modalfile-$id').attr('src',
fileSrc);
              viewActivity($mid, $id);
            })

            // stop playing the youtube file when I close the modal
            $('#myModal-$id').on('hide.bs.modal',
function(e) {
              $('#modalfile-$id').attr('src',
fileSrc);
              body = $('body');
              body.removeClass('modal-open');
              modalback =
document.getElementsByClassName('modal-backdrop');
              try
              {
              	document.getElementById('modalfile-$id').pause();
              }
              catch
              {
              
              }
              
              for (let item of modalback) {
               item.remove();
              }
            })
          });
         
".($preventdownload?'noRightClicks=document.getElementsByTagName(`'.$tagname.'`);for(i
= 0; i < noRightClicks.length;
i++){noRightClicks[i].addEventListener(`contextmenu`, e =>
e.preventDefault());}':'')."
          </script>
          <style>
          .modal-dialog {
            max-width: 800px;
            margin: 30px auto;
          }
          .modal-body {
            position: relative;
            padding: 0px;
          }
          .close {
            position: absolute;
            right: 5px;
            top: 5px;
            z-index: 999;
            font-size: 2rem;
            font-weight: normal;
            color: #fff;
            opacity: 1;
            text-shadow: 0 0 5px #ff0000;
          }
          </style>";
        break;
      case 2:
        $html = "<button type='button' class='btn
btn-primary file-btn' onclick='show$mimetype(this, $id,
\"$src \")'>$name</button>
          <script>
          function show$mimetype(elm, id, src){
            par = elm.parentElement;
            elementExist =
par.querySelector('$tagname.resource-$mimetype');
            if(!elementExist){
              fileElement = document.createElement('$tagname');
              fileElement.setAttribute('src', src);
              if($addcontrols)
                fileElement.setAttribute('controls',
'');
              fileElement.setAttribute('class',
'resource-$mimetype')
              if($preloadvideo == 0)
                fileElement.setAttribute('preload',
'none');
              if($muted)
                fileElement.setAttribute('muted', '');
              if($autoplay)
                fileElement.setAttribute('autoplay',
'');
              if($preventdownload)
                fileElement.setAttribute('controlsList',
'nodownload');
              par.append(fileElement);
              viewActivity($mid, $id);
            }
          }
         
".($preventdownload?'noRightClicks=document.getElementsByTagName(`'.$tagname.'`);for(i
= 0; i < noRightClicks.length;
i++){noRightClicks[i].addEventListener(`contextmenu`, e =>
e.preventDefault());}':'')."
          </script>";
        break;
      case 3:
        $html = "<button type='button' class='btn
btn-primary file-btn' onclick='show$mimetype(this, $id,
\"$src \")'>$name</button>
          <script>
          function show$mimetype(elm, id, src){
            par =
document.getElementById('lmskaran_course_image');
						console.log(par);
            elementExist =
par.querySelector('$tagname.resource-$mimetype');
            // if(!elementExist){
              fileElement = document.createElement('$tagname');
              fileElement.setAttribute('src', src);
              if($addcontrols)
                fileElement.setAttribute('controls',
'');
              fileElement.setAttribute('class',
'resource-$mimetype')
              if($preloadvideo == 0)
                fileElement.setAttribute('preload',
'none');
              if($muted)
                fileElement.setAttribute('muted', '');
              if($autoplay)
                fileElement.setAttribute('autoplay',
'');
              if($preventdownload)
                fileElement.setAttribute('controlsList',
'nodownload');

							par.innerHTML = ''
              par.append(fileElement);
							jQuery('html, body').animate({
									scrollTop: jQuery('#lmskaran_course_image').offset().top
- 100
							}, 700);
              viewActivity($mid, $id);
            // }
          }
         
".($preventdownload?'noRightClicks=document.getElementsByTagName(`'.$tagname.'`);for(i
= 0; i < noRightClicks.length;
i++){noRightClicks[i].addEventListener(`contextmenu`, e =>
e.preventDefault());}':'')."
          </script>";
        break;
    }
    $videowidth = trim($params->get('videowidth',
'100%'));
    $videoheight = trim($params->get('videoheight',
'100%'));
    $css = "
    <style>
    	#lmskaran_course_image video.resource-video {
            width: $videowidth;
            height: $videoheight;
        }
    </style>
    ";
    return $html . $css;
  }

  public static function getHierarchialTemplate($params, $templateField,
$default='default')
  {
    $param = $params->get($templateField);
    if (!$param) {
      $tmpl =
JComponentHelper::getParams('com_moojla')->get($templateField,
$default);
    } else {
      $tmpl = $param;
    }
    $tmpl = preg_replace('/\.php$/', '', $tmpl);
    return $tmpl;
  }
/***[/JCBGUI$$$$]***/


	/**
	 * Load the Composer Vendors
	 */
	public static function composerAutoload($target)
	{
		// insure we load the composer vendor only once
		if (!isset(self::$composer[$target]))
		{
			// get the function name
			$functionName = self::safeString('compose' . $target);
			// check if method exist
			if (method_exists(__CLASS__, $functionName))
			{
				return self::{$functionName}();
			}
			return false;
		}
		return self::$composer[$target];
	}

	/**
	 * Load the Component xml manifest.
	 */
	public static function manifest()
	{
		$manifestUrl =
JPATH_ADMINISTRATOR."/components/com_moojla/moojla.xml";
		return simplexml_load_file($manifestUrl);
	}

	/**
	 * Joomla version object
	 */	
	protected static $JVersion;

	/**
	 * set/get Joomla version
	 */
	public static function jVersion()
	{
		// check if set
		if (!self::checkObject(self::$JVersion))
		{
			self::$JVersion = new JVersion();
		}
		return self::$JVersion;
	}

	/**
	 * Load the Contributors details.
	 */
	public static function getContributors()
	{
		// get params
		$params	= JComponentHelper::getParams('com_moojla');
		// start contributors array
		$contributors = array();
		// get all Contributors (max 20)
		$searchArray = range('0','20');
		foreach($searchArray as $nr)
 		{
			if ((NULL !== $params->get("showContributor".$nr))
&& ($params->get("showContributor".$nr) == 1 ||
$params->get("showContributor".$nr) == 3))
			{
				// set link based of selected option
				if($params->get("useContributor".$nr) == 1)
         		{
					$link_front = '<a
href="mailto:'.$params->get("emailContributor".$nr).'"
target="_blank">';
					$link_back = '</a>';
				}
				elseif($params->get("useContributor".$nr) == 2)
				{
					$link_front = '<a
href="'.$params->get("linkContributor".$nr).'"
target="_blank">';
					$link_back = '</a>';
				}
				else
				{
					$link_front = '';
					$link_back = '';
				}
				$contributors[$nr]['title']	=
self::htmlEscape($params->get("titleContributor".$nr));
				$contributors[$nr]['name']	=
$link_front.self::htmlEscape($params->get("nameContributor".$nr)).$link_back;
			}
		}
		return $contributors;
	}

	/**
	 *	Can be used to build help urls.
	 **/
	public static function getHelpUrl($view)
	{
		return false;
	}

	/**
	 * Configure the Linkbar.
	 */
	public static function addSubmenu($submenu)
	{
		// load user for access menus
		$user = JFactory::getUser();
		// load the submenus to sidebar
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_DASHBOARD'),
'index.php?option=com_moojla&view=moojla', $submenu ===
'moojla');
		if ($user->authorise('course.access',
'com_moojla') &&
$user->authorise('course.submenu', 'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COURSES'),
'index.php?option=com_moojla&view=courses', $submenu ===
'courses');
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_COURSE_COURSES_CATEGORIES'),
'index.php?option=com_categories&view=categories&extension=com_moojla.course',
$submenu === 'categories.course');
		}
		if (JComponentHelper::isEnabled('com_fields'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COURSES_FIELDS'),
'index.php?option=com_fields&context=com_moojla.course',
$submenu === 'fields.fields');
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COURSES_FIELDS_GROUPS'),
'index.php?option=com_fields&view=groups&context=com_moojla.course',
$submenu === 'fields.groups');
		}
		if ($user->authorise('course_field_mapper.access',
'com_moojla') &&
$user->authorise('course_field_mapper.submenu',
'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COURSE_FIELDS_MAPPER'),
'index.php?option=com_moojla&view=course_fields_mapper',
$submenu === 'course_fields_mapper');
		}
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_USER_MAPS'),
'index.php?option=com_moojla&view=user_maps', $submenu ===
'user_maps');
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_USER_FIELDS_MAP'),
'index.php?option=com_moojla&view=user_fields_map', $submenu
=== 'user_fields_map');
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COURSE_GROUP_MAPS'),
'index.php?option=com_moojla&view=course_group_maps',
$submenu === 'course_group_maps');
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_ENROLMENTS'),
'index.php?option=com_moojla&view=enrolments', $submenu ===
'enrolments');
		if ($user->authorise('tag.access', 'com_moojla')
&& $user->authorise('tag.submenu',
'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_TAGS'),
'index.php?option=com_moojla&view=tags', $submenu ===
'tags');
		}
		if ($user->authorise('tag_instance.access',
'com_moojla') &&
$user->authorise('tag_instance.submenu',
'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_TAG_INSTANCES'),
'index.php?option=com_moojla&view=tag_instances', $submenu
=== 'tag_instances');
		}
		// Access control (healthcheck.submenu).
		if ($user->authorise('healthcheck.submenu',
'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_HEALTHCHECK'),
'index.php?option=com_moojla&view=healthcheck', $submenu ===
'healthcheck');
		}
		JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_COHORTS'),
'index.php?option=com_moojla&view=cohorts', $submenu ===
'cohorts');
		if ($user->authorise('language_translation.submenu',
'com_moojla'))
		{
			JHtmlSidebar::addEntry(JText::_('COM_MOOJLA_SUBMENU_LANGUAGETRANSLATION'),
'index.php?option=com_moojla&view=languagetranslation',
$submenu === 'languagetranslation');
		}
	}

	/**
	* Prepares the xml document
	*/
	public static function xls($rows, $fileName = null, $title = null,
$subjectTab = null, $creator = 'Lmskaran', $description = null,
$category = null,$keywords = null, $modified = null)
	{
		// set the user
		$user = JFactory::getUser();
		// set fileName if not set
		if (!$fileName)
		{
			$fileName =
'exported_'.JFactory::getDate()->format('jS_F_Y');
		}
		// set modified if not set
		if (!$modified)
		{
			$modified = $user->name;
		}
		// set title if not set
		if (!$title)
		{
			$title = 'Book1';
		}
		// set tab name if not set
		if (!$subjectTab)
		{
			$subjectTab = 'Sheet1';
		}

		// make sure we have the composer classes loaded
		self::composerAutoload('phpspreadsheet');

		// Create new Spreadsheet object
		$spreadsheet = new Spreadsheet();

		// Set document properties
		$spreadsheet->getProperties()
			->setCreator($creator)
			->setCompany('Lmskaran')
			->setLastModifiedBy($modified)
			->setTitle($title)
			->setSubject($subjectTab);
		// The file type
		$file_type = 'Xls';
		// set description
		if ($description)
		{
			$spreadsheet->getProperties()->setDescription($description);
		}
		// set keywords
		if ($keywords)
		{
			$spreadsheet->getProperties()->setKeywords($keywords);
		}
		// set category
		if ($category)
		{
			$spreadsheet->getProperties()->setCategory($category);
		}

		// Some styles
		$headerStyles = array(
			'font'  => array(
				'bold'  => true,
				'color' => array('rgb' =>
'1171A3'),
				'size'  => 12,
				'name'  => 'Verdana'
		));
		$sideStyles = array(
			'font'  => array(
				'bold'  => true,
				'color' => array('rgb' =>
'444444'),
				'size'  => 11,
				'name'  => 'Verdana'
		));
		$normalStyles = array(
			'font'  => array(
				'color' => array('rgb' =>
'444444'),
				'size'  => 11,
				'name'  => 'Verdana'
		));

		// Add some data
		if (($size = self::checkArray($rows)) !== false)
		{
			$i = 1;

			// Based on data size we adapt the behaviour.
			$xls_mode = 1;
			if ($size > 3000)
			{
				$xls_mode = 3;
				$file_type = 'Csv';
			}
			elseif ($size > 2000)
			{
				$xls_mode = 2;
			}

			// Set active sheet and get it.
			$active_sheet = $spreadsheet->setActiveSheetIndex(0);
			foreach ($rows as $array)
			{
				$a = 'A';
				foreach ($array as $value)
				{
					$active_sheet->setCellValue($a.$i, $value);
					if ($xls_mode != 3)
					{
						if ($i == 1)
						{
							$active_sheet->getColumnDimension($a)->setAutoSize(true);
							$active_sheet->getStyle($a.$i)->applyFromArray($headerStyles);
							$active_sheet->getStyle($a.$i)->getAlignment()->setHorizontal(PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
						}
						elseif ($a === 'A')
						{
							$active_sheet->getStyle($a.$i)->applyFromArray($sideStyles);
						}
						elseif ($xls_mode == 1)
						{
							$active_sheet->getStyle($a.$i)->applyFromArray($normalStyles);
						}
					}
					$a++;
				}
				$i++;
			}
		}
		else
		{
			return false;
		}

		// Rename worksheet
		$spreadsheet->getActiveSheet()->setTitle($subjectTab);

		// Set active sheet index to the first sheet, so Excel opens this as the
first sheet
		$spreadsheet->setActiveSheetIndex(0);

		// Redirect output to a client's web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="' .
$fileName . '.' . strtolower($file_type) .'"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be
needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in
the past
		header ('Last-Modified: '.gmdate('D, d M Y
H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$writer = IOFactory::createWriter($spreadsheet, $file_type);
		$writer->save('php://output');
		jexit();
	}

	/**
	* Get CSV Headers
	*/
	public static function getFileHeaders($dataType)
	{
		// make sure we have the composer classes loaded
		self::composerAutoload('phpspreadsheet');
		// get session object
		$session = JFactory::getSession();
		$package = $session->get('package', null);
		$package = json_decode($package, true);
		// set the headers
		if(isset($package['dir']))
		{
			// only load first three rows
			$chunkFilter = new PhpOffice\PhpSpreadsheet\Reader\chunkReadFilter(2,1);
			// identify the file type
			$inputFileType = IOFactory::identify($package['dir']);
			// create the reader for this file type
			$excelReader = IOFactory::createReader($inputFileType);
			// load the limiting filter
			$excelReader->setReadFilter($chunkFilter);
			$excelReader->setReadDataOnly(true);
			// load the rows (only first three)
			$excelObj = $excelReader->load($package['dir']);
			$headers = array();
			foreach ($excelObj->getActiveSheet()->getRowIterator() as $row)
			{
				if($row->getRowIndex() == 1)
				{
					$cellIterator = $row->getCellIterator();
					$cellIterator->setIterateOnlyExistingCells(false);
					foreach ($cellIterator as $cell)
					{
						if (!is_null($cell))
						{
							$headers[$cell->getColumn()] = $cell->getValue();
						}
					}
					$excelObj->disconnectWorksheets();
					unset($excelObj);
					break;
				}
			}
			return $headers;
		}
		return false;
	}

	/**
	* Load the Composer Vendor phpspreadsheet
	*/
	protected static function composephpspreadsheet()
	{
		// load the autoloader for phpspreadsheet
		require_once JPATH_SITE .
'/libraries/phpspreadsheet/vendor/autoload.php';
		// do not load again
		self::$composer['phpspreadsheet'] = true;

		return  true;
	}

	/**
	 * Get a Variable 
	 *
	 * @param   string   $table        The table from which to get the
variable
	 * @param   string   $where        The value where
	 * @param   string   $whereString  The target/field string where/name
	 * @param   string   $what         The return field
	 * @param   string   $operator     The operator between $whereString/field
and $where/value
	 * @param   string   $main         The component in which the table is
found
	 *
	 * @return  mix string/int/float
	 *
	 */
	public static function getVar($table, $where = null, $whereString =
'user', $what = 'id', $operator = '=', $main
= 'moojla')
	{
		if(!$where)
		{
			$where = JFactory::getUser()->id;
		}
		// Get a db connection.
		$db = JFactory::getDbo();
		// Create a new query object.
		$query = $db->getQuery(true);
		$query->select($db->quoteName(array($what)));
		if (empty($table))
		{
			$query->from($db->quoteName('#__'.$main));
		}
		else
		{
			$query->from($db->quoteName('#__'.$main.'_'.$table));
		}
		if (is_numeric($where))
		{
			$query->where($db->quoteName($whereString) . '
'.$operator.' '.(int) $where);
		}
		elseif (is_string($where))
		{
			$query->where($db->quoteName($whereString) . '
'.$operator.' '. $db->quote((string)$where));
		}
		else
		{
			return false;
		}
		$db->setQuery($query);
		$db->execute();
		if ($db->getNumRows())
		{
			return $db->loadResult();
		}
		return false;
	}

	/**
	 * Get array of variables
	 *
	 * @param   string   $table        The table from which to get the
variables
	 * @param   string   $where        The value where
	 * @param   string   $whereString  The target/field string where/name
	 * @param   string   $what         The return field
	 * @param   string   $operator     The operator between $whereString/field
and $where/value
	 * @param   string   $main         The component in which the table is
found
	 * @param   bool     $unique       The switch to return a unique array
	 *
	 * @return  array
	 *
	 */
	public static function getVars($table, $where = null, $whereString =
'user', $what = 'id', $operator = 'IN', $main
= 'moojla', $unique = true)
	{
		if(!$where)
		{
			$where = JFactory::getUser()->id;
		}

		if (!self::checkArray($where) && $where > 0)
		{
			$where = array($where);
		}

		if (self::checkArray($where))
		{
			// prep main <-- why? well if $main='' is empty then $table
can be categories or users
			if (self::checkString($main))
			{
				$main = '_'.ltrim($main, '_');
			}
			// Get a db connection.
			$db = JFactory::getDbo();
			// Create a new query object.
			$query = $db->getQuery(true);

			$query->select($db->quoteName(array($what)));
			if (empty($table))
			{
				$query->from($db->quoteName('#__'.$main));
			}
			else
			{
				$query->from($db->quoteName('#_'.$main.'_'.$table));
			}
			// add strings to array search
			if ('IN_STRINGS' === $operator || 'NOT IN_STRINGS'
=== $operator)
			{
				$query->where($db->quoteName($whereString) . ' ' .
str_replace('_STRINGS', '', $operator) . '
("' . implode('","',$where) .
'")');
			}
			else
			{
				$query->where($db->quoteName($whereString) . ' ' .
$operator . ' (' . implode(',',$where) .
')');
			}
			$db->setQuery($query);
			$db->execute();
			if ($db->getNumRows())
			{
				if ($unique)
				{
					return array_unique($db->loadColumn());
				}
				return $db->loadColumn();
			}
		}
		return false;
	}

	public static function jsonToString($value, $sperator = ", ",
$table = null, $id = 'id', $name = 'name')
	{
		// do some table foot work
		$external = false;
		if (strpos($table, '#__') !== false)
		{
			$external = true;
			$table = str_replace('#__', '', $table);
		}
		// check if string is JSON
		$result = json_decode($value, true);
		if (json_last_error() === JSON_ERROR_NONE)
		{
			// is JSON
			if (self::checkArray($result))
			{
				if (self::checkString($table))
				{
					$names = array();
					foreach ($result as $val)
					{
						if ($external)
						{
							if ($_name = self::getVar(null, $val, $id, $name, '=',
$table))
							{
								$names[] = $_name;
							}
						}
						else
						{
							if ($_name = self::getVar($table, $val, $id, $name))
							{
								$names[] = $_name;
							}
						}
					}
					if (self::checkArray($names))
					{
						return (string) implode($sperator,$names);
					}	
				}
				return (string) implode($sperator,$result);
			}
			return (string) json_decode($value);
		}
		return $value;
	}

	public static function isPublished($id,$type)
	{
		if ($type == 'raw')
		{
			$type = 'item';
		}
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select(array('a.published'));
		$query->from('#__moojla_'.$type.' AS a');
		$query->where('a.id = '. (int) $id);
		$query->where('a.published = 1');
		$db->setQuery($query);
		$db->execute();
		$found = $db->getNumRows();
		if($found)
		{
			return true;
		}
		return false;
	}

	public static function getGroupName($id)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select(array('a.title'));
		$query->from('#__usergroups AS a');
		$query->where('a.id = '. (int) $id);
		$db->setQuery($query);
		$db->execute();
		$found = $db->getNumRows();
		if($found)
  		{
			return $db->loadResult();
		}
		return $id;
	}

	/**
	 * Get the action permissions
	 *
	 * @param  string   $view        The related view name
	 * @param  int      $record      The item to act upon
	 * @param  string   $views       The related list view name
	 * @param  mixed    $target      Only get this permission (like edit,
create, delete)
	 * @param  string   $component   The target component
	 * @param  object   $user        The user whose permissions we are loading
	 *
	 * @return  object   The JObject of permission/authorised actions
	 * 
	 */
	public static function getActions($view, &$record = null, $views =
null, $target = null, $component = 'moojla', $user =
'null')
	{
		// load the user if not given
		if (!self::checkObject($user))
		{
			// get the user object
			$user = JFactory::getUser();
		}
		// load the JObject
		$result = new JObject;
		// make view name safe (just incase)
		$view = self::safeString($view);
		if (self::checkString($views))
		{
			$views = self::safeString($views);
 		}
		// get all actions from component
		$actions = JAccess::getActionsFromFile(
			JPATH_ADMINISTRATOR . '/components/com_' . $component .
'/access.xml',
			"/access/section[@name='component']/"
		);
		// if non found then return empty JObject
		if (empty($actions))
		{
			return $result;
		}
		// get created by if not found
		if (self::checkObject($record) && !isset($record->created_by)
&& isset($record->id))
		{
			$record->created_by = self::getVar($view, $record->id,
'id', 'created_by', '=', $component);
		}
		// set actions only set in component settings
		$componentActions = array('core.admin',
'core.manage', 'core.options',
'core.export');
		// check if we have a target
		$checkTarget = false;
		if ($target)
		{
			// convert to an array
			if (self::checkString($target))
			{
				$target = array($target);
			}
			// check if we are good to go
			if (self::checkArray($target))
			{
				$checkTarget = true;
			}
		}
		// loop the actions and set the permissions
		foreach ($actions as $action)
		{
			// check target action filter
			if ($checkTarget && self::filterActions($view, $action->name,
$target))
			{
				continue;
			}
			// set to use component default
			$fallback = true;
			// reset permission per/action
			$permission = false;
			$catpermission = false;
			// set area
			$area = 'comp';
			// check if the record has an ID and the action is item related (not a
component action)
			if (self::checkObject($record) && isset($record->id)
&& $record->id > 0 && !in_array($action->name,
$componentActions) &&
				(strpos($action->name, 'core.') !== false ||
strpos($action->name, $view . '.') !== false))
			{
				// we are in item
				$area = 'item';
				// The record has been set. Check the record permissions.
				$permission = $user->authorise($action->name, 'com_' .
$component . '.' . $view . '.' . (int) $record->id);
				// if no permission found, check edit own
				if (!$permission)
				{
					// With edit, if the created_by matches current user then dig deeper.
					if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
					{
						// the correct target
						$coreCheck = (array) explode('.', $action->name);
						// check that we have both local and global access
						if ($user->authorise($coreCheck[0] . '.edit.own',
'com_' . $component . '.' . $view . '.' .
(int) $record->id) &&
							$user->authorise($coreCheck[0]  . '.edit.own',
'com_' . $component))
						{
							// allow edit
							$result->set($action->name, true);
							// set not to use global default
							// because we already validated it
							$fallback = false;
						}
						else
						{
							// do not allow edit
							$result->set($action->name, false);
							$fallback = false;
						}
					}
				}
				elseif (self::checkString($views) && isset($record->catid)
&& $record->catid > 0)
				{
					// we are in item
					$area = 'category';
					// set the core check
					$coreCheck = explode('.', $action->name);
					$core = $coreCheck[0];
					// make sure we use the core. action check for the categories
					if (strpos($action->name, $view) !== false &&
strpos($action->name, 'core.') === false )
					{
						$coreCheck[0] = 'core';
						$categoryCheck = implode('.', $coreCheck);
					}
					else
					{
						$categoryCheck = $action->name;
					}
					// The record has a category. Check the category permissions.
					$catpermission = $user->authorise($categoryCheck, 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid);
					if (!$catpermission && !is_null($catpermission))
					{
						// With edit, if the created_by matches current user then dig deeper.
						if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
						{
							// check that we have both local and global access
							if ($user->authorise('core.edit.own', 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid) &&
								$user->authorise($core . '.edit.own', 'com_'
. $component))
							{
								// allow edit
								$result->set($action->name, true);
								// set not to use global default
								// because we already validated it
								$fallback = false;
							}
							else
							{
								// do not allow edit
								$result->set($action->name, false);
								$fallback = false;
							}
						}
					}
				}
			}
			// if allowed then fallback on component global settings
			if ($fallback)
			{
				// if item/category blocks access then don't fall back on global
				if ((($area === 'item') && !$permission) || (($area
=== 'category') && !$catpermission))
				{
					// do not allow
					$result->set($action->name, false);
				}
				// Finally remember the global settings have the final say. (even if
item allow)
				// The local item permissions can block, but it can't open and
override of global permissions.
				// Since items are created by users and global permissions is set by
system admin.
				else
				{
					$result->set($action->name,
$user->authorise($action->name, 'com_' . $component));
				}
			}
		}
		return $result;
	}

	/**
	 * Filter the action permissions
	 *
	 * @param  string   $action   The action to check
	 * @param  array    $targets  The array of target actions
	 *
	 * @return  boolean   true if action should be filtered out
	 * 
	 */
	protected static function filterActions(&$view, &$action,
&$targets)
	{
		foreach ($targets as $target)
		{
			if (strpos($action, $view . '.' . $target) !== false ||
				strpos($action, 'core.' . $target) !== false)
			{
				return false;
				break;
			}
		}
		return true;
	}

	/**
	 * Get any component's model
	 */
	public static function getModel($name, $path =
JPATH_COMPONENT_ADMINISTRATOR, $Component = 'Moojla', $config =
array())
	{
		// fix the name
		$name = self::safeString($name);
		// full path to models
		$fullPathModels = $path . '/models';
		// load the model file
		JModelLegacy::addIncludePath($fullPathModels, $Component .
'Model');
		// make sure the table path is loaded
		if (!isset($config['table_path']) ||
!self::checkString($config['table_path']))
		{
			// This is the JCB default path to tables in Joomla 3.x
			$config['table_path'] = JPATH_ADMINISTRATOR .
'/components/com_' . strtolower($Component) .
'/tables';
		}
		// get instance
		$model = JModelLegacy::getInstance($name, $Component . 'Model',
$config);
		// if model not found (strange)
		if ($model == false)
		{
			jimport('joomla.filesystem.file');
			// get file path
			$filePath = $path . '/' . $name . '.php';
			$fullPathModel = $fullPathModels . '/' . $name .
'.php';
			// check if it exists
			if (File::exists($filePath))
			{
				// get the file
				require_once $filePath;
			}
			elseif (File::exists($fullPathModel))
			{
				// get the file
				require_once $fullPathModel;
			}
			// build class names
			$modelClass = $Component . 'Model' . $name;
			if (class_exists($modelClass))
			{
				// initialize the model
				return new $modelClass($config);
			}
		}
		return $model;
	}

	/**
	 * Add to asset Table
	 */
	public static function setAsset($id, $table, $inherit = true)
	{
		$parent = JTable::getInstance('Asset');
		$parent->loadByName('com_moojla');
		
		$parentId = $parent->id;
		$name     = 'com_moojla.'.$table.'.'.$id;
		$title    = '';

		$asset = JTable::getInstance('Asset');
		$asset->loadByName($name);

		// Check for an error.
		$error = $asset->getError();

		if ($error)
		{
			return false;
		}
		else
		{
			// Specify how a new or moved node asset is inserted into the tree.
			if ($asset->parent_id != $parentId)
			{
				$asset->setLocation($parentId, 'last-child');
			}

			// Prepare the asset to be stored.
			$asset->parent_id = $parentId;
			$asset->name      = $name;
			$asset->title     = $title;
			// get the default asset rules
			$rules = self::getDefaultAssetRules('com_moojla', $table,
$inherit);
			if ($rules instanceof JAccessRules)
			{
				$asset->rules = (string) $rules;
			}

			if (!$asset->check() || !$asset->store())
			{
				JFactory::getApplication()->enqueueMessage($asset->getError(),
'warning');
				return false;
			}
			else
			{
				// Create an asset_id or heal one that is corrupted.
				$object = new stdClass();

				// Must be a valid primary key value.
				$object->id = $id;
				$object->asset_id = (int) $asset->id;

				// Update their asset_id to link to the asset table.
				return
JFactory::getDbo()->updateObject('#__moojla_'.$table, $object,
'id');
			}
		}
		return false;
	}

	/**
	 * Gets the default asset Rules for a component/view.
	 */
	protected static function getDefaultAssetRules($component, $view, $inherit
= true)
	{
		// if new or inherited
		$assetId = 0;
		// Only get the actual item rules if not inheriting
		if (!$inherit)
		{
			// Need to find the asset id by the name of the component.
			$db = JFactory::getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('id'))
				->from($db->quoteName('#__assets'))
				->where($db->quoteName('name') . ' = ' .
$db->quote($component));
			$db->setQuery($query);
			$db->execute();
			// check that there is a value
			if ($db->getNumRows())
			{
				// asset already set so use saved rules
				$assetId = (int) $db->loadResult();
			}
		}
		// get asset rules
		$result =  JAccess::getAssetRules($assetId);
		if ($result instanceof JAccessRules)
		{
			$_result = (string) $result;
			$_result = json_decode($_result);
			foreach ($_result as $name => &$rule)
			{
				$v = explode('.', $name);
				if ($view !== $v[0])
				{
					// remove since it is not part of this view
					unset($_result->$name);
				}
				elseif ($inherit)
				{
					// clear the value since we inherit
					$rule = array();
				}
			}
			// check if there are any view values remaining
			if (count((array) $_result))
			{
				$_result = json_encode($_result);
				$_result = array($_result);
				// Instantiate and return the JAccessRules object for the asset rules.
				$rules = new JAccessRules($_result);
				// return filtered rules
				return $rules;
			}
		}
		return $result;
	}

	/**
	 * xmlAppend
	 *
	 * @param   SimpleXMLElement   $xml      The XML element reference in
which to inject a comment
	 * @param   mixed              $node     A SimpleXMLElement node to append
to the XML element reference, or a stdClass object containing a comment
attribute to be injected before the XML node and a fieldXML attribute
containing a SimpleXMLElement
	 *
	 * @return  null
	 *
	 */
	public static function xmlAppend(&$xml, $node)
	{
		if (!$node)
		{
			// element was not returned
			return;
		}
		switch (get_class($node))
		{
			case 'stdClass':
				if (property_exists($node, 'comment'))
				{
					self::xmlComment($xml, $node->comment);
				}
				if (property_exists($node, 'fieldXML'))
				{
					self::xmlAppend($xml, $node->fieldXML);
				}
				break;
			case 'SimpleXMLElement':
				$domXML = dom_import_simplexml($xml);
				$domNode = dom_import_simplexml($node);
				$domXML->appendChild($domXML->ownerDocument->importNode($domNode,
true));
				$xml = simplexml_import_dom($domXML);
				break;
		}
	}

	/**
	 * xmlComment
	 *
	 * @param   SimpleXMLElement   $xml        The XML element reference in
which to inject a comment
	 * @param   string             $comment    The comment to inject
	 *
	 * @return  null
	 *
	 */
	public static function xmlComment(&$xml, $comment)
	{
		$domXML = dom_import_simplexml($xml);
		$domComment = new DOMComment($comment);
		$nodeTarget = $domXML->ownerDocument->importNode($domComment,
true);
		$domXML->appendChild($nodeTarget);
		$xml = simplexml_import_dom($domXML);
	}

	/**
	 * xmlAddAttributes
	 *
	 * @param   SimpleXMLElement   $xml          The XML element reference in
which to inject a comment
	 * @param   array              $attributes   The attributes to apply to
the XML element
	 *
	 * @return  null
	 *
	 */
	public static function xmlAddAttributes(&$xml, $attributes = array())
	{
		foreach ($attributes as $key => $value)
		{
			$xml->addAttribute($key, $value);
		}
	}

	/**
	 * xmlAddOptions
	 *
	 * @param   SimpleXMLElement   $xml          The XML element reference in
which to inject a comment
	 * @param   array              $options      The options to apply to the
XML element
	 *
	 * @return  void
	 *
	 */
	public static function xmlAddOptions(&$xml, $options = array())
	{
		foreach ($options as $key => $value)
		{
			$addOption = $xml->addChild('option');
			$addOption->addAttribute('value', $key);
			$addOption[] = $value;
		}
	}

	/**
	 * get the field object
	 *
	 * @param   array      $attributes   The array of attributes
	 * @param   string     $default      The default of the field
	 * @param   array      $options      The options to apply to the XML
element
	 *
	 * @return  object
	 *
	 */
	public static function getFieldObject(&$attributes, $default =
'', $options = null)
	{
		// make sure we have attributes and a type value
		if (self::checkArray($attributes) &&
isset($attributes['type']))
		{
			// make sure the form helper class is loaded
			if (!method_exists('JFormHelper', 'loadFieldType'))
			{
				jimport('joomla.form.form');
			}
			// get field type
			$field = JFormHelper::loadFieldType($attributes['type'],
true);
			// get field xml
			$XML = self::getFieldXML($attributes, $options);
			// setup the field
			$field->setup($XML, $default);
			// return the field object
			return $field;
		}
		return false;
	}

	/**
	 * get the field xml
	 *
	 * @param   array      $attributes   The array of attributes
	 * @param   array      $options      The options to apply to the XML
element
	 *
	 * @return  object
	 *
	 */
	public static function getFieldXML(&$attributes, $options = null)
	{
		// make sure we have attributes and a type value
		if (self::checkArray($attributes))
		{
			// start field xml
			$XML = new SimpleXMLElement('<field/>');
			// load the attributes
			self::xmlAddAttributes($XML, $attributes);
			// check if we have options
			if (self::checkArray($options))
			{
				// load the options
				self::xmlAddOptions($XML, $options);
			}
			// return the field xml
			return $XML;
		}
		return false;
	}

	/**
	 * Render Bool Button
	 *
	 * @param   array   $args   All the args for the button
	 *                             0) name
	 *                             1) additional (options class) // not used
at this time
	 *                             2) default
	 *                             3) yes (name)
	 *                             4) no (name)
	 *
	 * @return  string    The input html of the button
	 *
	 */
	public static function renderBoolButton()
	{
		$args = func_get_args();
		// check if there is additional button class
		$additional = isset($args[1]) ? (string) $args[1] : ''; // not
used at this time
		// button attributes
		$buttonAttributes = array(
			'type' => 'radio',
			'name' => isset($args[0]) ? self::htmlEscape($args[0]) :
'bool_button',
			'label' => isset($args[0]) ?
self::safeString(self::htmlEscape($args[0]), 'Ww') : 'Bool
Button', // not seen anyway
			'class' => 'btn-group',
			'filter' => 'INT',
			'default' => isset($args[2]) ? (int) $args[2] : 0);
		// set the button options
		$buttonOptions = array(
			'1' => isset($args[3]) ? self::htmlEscape($args[3]) :
'JYES',
			'0' => isset($args[4]) ? self::htmlEscape($args[4]) :
'JNO');
		// return the input
		return self::getFieldObject($buttonAttributes,
$buttonAttributes['default'], $buttonOptions)->input;
	}

	/**
	 * Check if have an json string
	 *
	 * @input	string   The json string to check
	 *
	 * @returns bool true on success
	 */
	public static function checkJson($string)
	{
		if (self::checkString($string))
		{
			json_decode($string);
			return (json_last_error() === JSON_ERROR_NONE);
		}
		return false;
	}

	/**
	 * Check if have an object with a length
	 *
	 * @input	object   The object to check
	 *
	 * @returns bool true on success
	 */
	public static function checkObject($object)
	{
		if (isset($object) && is_object($object))
		{
			return count((array)$object) > 0;
		}
		return false;
	}

	/**
	 * Check if have an array with a length
	 *
	 * @input	array   The array to check
	 *
	 * @returns bool/int  number of items in array on success
	 */
	public static function checkArray($array, $removeEmptyString = false)
	{
		if (isset($array) && is_array($array) && ($nr =
count((array)$array)) > 0)
		{
			// also make sure the empty strings are removed
			if ($removeEmptyString)
			{
				foreach ($array as $key => $string)
				{
					if (empty($string))
					{
						unset($array[$key]);
					}
				}
				return self::checkArray($array, false);
			}
			return $nr;
		}
		return false;
	}

	/**
	 * Check if have a string with a length
	 *
	 * @input	string   The string to check
	 *
	 * @returns bool true on success
	 */
	public static function checkString($string)
	{
		if (isset($string) && is_string($string) &&
strlen($string) > 0)
		{
			return true;
		}
		return false;
	}

	/**
	 * Check if we are connected
	 * Thanks https://stackoverflow.com/a/4860432/1429677
	 *
	 * @returns bool true on success
	 */
	public static function isConnected()
	{
		// If example.com is down, then probably the whole internet is down,
since IANA maintains the domain. Right?
		$connected = @fsockopen("www.example.com", 80); 
                // website, port  (try 80 or 443)
		if ($connected)
		{
			//action when connected
			$is_conn = true;
			fclose($connected);
		}
		else
		{
			//action in connection failure
			$is_conn = false;
		}
		return $is_conn;
	}

	/**
	 * Merge an array of array's
	 *
	 * @input	array   The arrays you would like to merge
	 *
	 * @returns array on success
	 */
	public static function mergeArrays($arrays)
	{
		if(self::checkArray($arrays))
		{
			$arrayBuket = array();
			foreach ($arrays as $array)
			{
				if (self::checkArray($array))
				{
					$arrayBuket = array_merge($arrayBuket, $array);
				}
			}
			return $arrayBuket;
		}
		return false;
	}

	// typo sorry!
	public static function sorten($string, $length = 40, $addTip = true)
	{
		return self::shorten($string, $length, $addTip);
	}

	/**
	 * Shorten a string
	 *
	 * @input	string   The you would like to shorten
	 *
	 * @returns string on success
	 */
	public static function shorten($string, $length = 40, $addTip = true)
	{
		if (self::checkString($string))
		{
			$initial = strlen($string);
			$words = preg_split('/([\s\n\r]+)/', $string, null,
PREG_SPLIT_DELIM_CAPTURE);
			$words_count = count((array)$words);

			$word_length = 0;
			$last_word = 0;
			for (; $last_word < $words_count; ++$last_word)
			{
				$word_length += strlen($words[$last_word]);
				if ($word_length > $length)
				{
					break;
				}
			}

			$newString	= implode(array_slice($words, 0, $last_word));
			$final	= strlen($newString);
			if ($initial != $final && $addTip)
			{
				$title = self::shorten($string, 400 , false);
				return '<span class="hasTip"
title="'.$title.'"
style="cursor:help">'.trim($newString).'...</span>';
			}
			elseif ($initial != $final && !$addTip)
			{
				return trim($newString).'...';
			}
		}
		return $string;
	}

	/**
	 * Making strings safe (various ways)
	 *
	 * @input	string   The you would like to make safe
	 *
	 * @returns string on success
	 */
	public static function safeString($string, $type = 'L', $spacer
= '_', $replaceNumbers = true, $keepOnlyCharacters = true)
	{
		if ($replaceNumbers === true)
		{
			// remove all numbers and replace with english text version (works well
only up to millions)
			$string = self::replaceNumbers($string);
		}
		// 0nly continue if we have a string
		if (self::checkString($string))
		{
			// create file name without the extention that is safe
			if ($type === 'filename')
			{
				// make sure VDM is not in the string
				$string = str_replace('VDM', 'vDm', $string);
				// Remove anything which isn't a word, whitespace, number
				// or any of the following caracters -_()
				// If you don't need to handle multi-byte characters
				// you can use preg_replace rather than mb_ereg_replace
				// Thanks @Łukasz Rysiak!
				// $string = mb_ereg_replace("([^\w\s\d\-_\(\)])",
'', $string);
				$string = preg_replace("([^\w\s\d\-_\(\)])", '',
$string);
				// http://stackoverflow.com/a/2021729/1429677
				return preg_replace('/\s+/', ' ', $string);
			}
			// remove all other characters
			$string = trim($string);
			$string = preg_replace('/'.$spacer.'+/', '
', $string);
			$string = preg_replace('/\s+/', ' ', $string);
			// Transliterate string
			$string = self::transliterate($string);
			// remove all and keep only characters
			if ($keepOnlyCharacters)
			{
				$string = preg_replace("/[^A-Za-z ]/", '',
$string);
			}
			// keep both numbers and characters
			else
			{
				$string = preg_replace("/[^A-Za-z0-9 ]/", '',
$string);
			}
			// select final adaptations
			if ($type === 'L' || $type === 'strtolower')
			{
				// replace white space with underscore
				$string = preg_replace('/\s+/', $spacer, $string);
				// default is to return lower
				return strtolower($string);
			}
			elseif ($type === 'W')
			{
				// return a string with all first letter of each word uppercase(no
undersocre)
				return ucwords(strtolower($string));
			}
			elseif ($type === 'w' || $type === 'word')
			{
				// return a string with all lowercase(no undersocre)
				return strtolower($string);
			}
			elseif ($type === 'Ww' || $type === 'Word')
			{
				// return a string with first letter of the first word uppercase and
all the rest lowercase(no undersocre)
				return ucfirst(strtolower($string));
			}
			elseif ($type === 'WW' || $type === 'WORD')
			{
				// return a string with all the uppercase(no undersocre)
				return strtoupper($string);
			}
			elseif ($type === 'U' || $type === 'strtoupper')
			{
					// replace white space with underscore
					$string = preg_replace('/\s+/', $spacer, $string);
					// return all upper
					return strtoupper($string);
			}
			elseif ($type === 'F' || $type === 'ucfirst')
			{
					// replace white space with underscore
					$string = preg_replace('/\s+/', $spacer, $string);
					// return with first caracter to upper
					return ucfirst(strtolower($string));
			}
			elseif ($type === 'cA' || $type === 'cAmel' || $type
=== 'camelcase')
			{
				// convert all words to first letter uppercase
				$string = ucwords(strtolower($string));
				// remove white space
				$string = preg_replace('/\s+/', '', $string);
				// now return first letter lowercase
				return lcfirst($string);
			}
			// return string
			return $string;
		}
		// not a string
		return '';
	}

	public static function transliterate($string)
	{
		// set tag only once
		if (!self::checkString(self::$langTag))
		{
			// get global value
			self::$langTag =
JComponentHelper::getParams('com_moojla')->get('language',
'en-GB');
		}
		// Transliterate on the language requested
		$lang = Language::getInstance(self::$langTag);
		return $lang->transliterate($string);
	}

	public static function htmlEscape($var, $charset = 'UTF-8',
$shorten = false, $length = 40)
	{
		if (self::checkString($var))
		{
			$filter = new JFilterInput();
			$string = $filter->clean(html_entity_decode(htmlentities($var,
ENT_COMPAT, $charset)), 'HTML');
			if ($shorten)
			{
                                return self::shorten($string,$length);
			}
			return $string;
		}
		else
		{
			return '';
		}
	}

	public static function replaceNumbers($string)
	{
		// set numbers array
		$numbers = array();
		// first get all numbers
		preg_match_all('!\d+!', $string, $numbers);
		// check if we have any numbers
		if (isset($numbers[0]) && self::checkArray($numbers[0]))
		{
			foreach ($numbers[0] as $number)
			{
				$searchReplace[$number] = self::numberToString((int)$number);
			}
			// now replace numbers in string
			$string = str_replace(array_keys($searchReplace),
array_values($searchReplace),$string);
			// check if we missed any, strange if we did.
			return self::replaceNumbers($string);
		}
		// return the string with no numbers remaining.
		return $string;
	}

	/**
	 * Convert an integer into an English word string
	 * Thanks to Tom Nicholson
<http://php.net/manual/en/function.strval.php#41988>
	 *
	 * @input	an int
	 * @returns a string
	 */
	public static function numberToString($x)
	{
		$nwords = array( "zero", "one", "two",
"three", "four", "five", "six",
"seven",
			"eight", "nine", "ten",
"eleven", "twelve", "thirteen",
			"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen",
			"nineteen", "twenty", 30 => "thirty",
40 => "forty",
			50 => "fifty", 60 => "sixty", 70 =>
"seventy", 80 => "eighty",
			90 => "ninety" );

		if(!is_numeric($x))
		{
			$w = $x;
		}
		elseif(fmod($x, 1) != 0)
		{
			$w = $x;
		}
		else
		{
			if($x < 0)
			{
				$w = 'minus ';
				$x = -$x;
			}
			else
			{
				$w = '';
				// ... now $x is a non-negative integer.
			}

			if($x < 21)   // 0 to 20
			{
				$w .= $nwords[$x];
			}
			elseif($x < 100)  // 21 to 99
			{ 
				$w .= $nwords[10 * floor($x/10)];
				$r = fmod($x, 10);
				if($r > 0)
				{
					$w .= ' '. $nwords[$r];
				}
			}
			elseif($x < 1000)  // 100 to 999
			{
				$w .= $nwords[floor($x/100)] .' hundred';
				$r = fmod($x, 100);
				if($r > 0)
				{
					$w .= ' and '. self::numberToString($r);
				}
			}
			elseif($x < 1000000)  // 1000 to 999999
			{
				$w .= self::numberToString(floor($x/1000)) .' thousand';
				$r = fmod($x, 1000);
				if($r > 0)
				{
					$w .= ' ';
					if($r < 100)
					{
						$w .= 'and ';
					}
					$w .= self::numberToString($r);
				}
			} 
			else //  millions
			{    
				$w .= self::numberToString(floor($x/1000000)) .' million';
				$r = fmod($x, 1000000);
				if($r > 0)
				{
					$w .= ' ';
					if($r < 100)
					{
						$w .= 'and ';
					}
					$w .= self::numberToString($r);
				}
			}
		}
		return $w;
	}

	/**
	 * Random Key
	 *
	 * @returns a string
	 */
	public static function randomkey($size)
	{
		$bag =
"abcefghijknopqrstuwxyzABCDDEFGHIJKLLMMNOPQRSTUVVWXYZabcddefghijkllmmnopqrstuvvwxyzABCEFGHIJKNOPQRSTUWXYZ";
		$key = array();
		$bagsize = strlen($bag) - 1;
		for ($i = 0; $i < $size; $i++)
		{
			$get = rand(0, $bagsize);
			$key[] = $bag[$get];
		}
		return implode($key);
	}
}