<?php
if (!defined('_VALID_MOS') && !defined('_JEXEC')) die('Direct Access to ' . basename(__FILE__) 
        . ' is not allowed.');
/**
 *
 * @package  MediaLibrary
 * @copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com);
 * Homepage: https://ordasoft.com
 * @version: 4.6 Free
 * @license GNU General Public license version 2 or later; see LICENSE.txt
 *
 */
if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;
global $mosConfig_lang, $user_configuration; // for 1.6
$mainframe = JFactory::getApplication(); // for 1.6
$GLOBALS['mainframe'] = $mainframe;

require_once ($mosConfig_absolute_path . "/components/com_medialibrary/compat.joomla1.5.php");
if (version_compare(JVERSION, "3.0.0", "lt")) include_once ($mosConfig_absolute_path 
    . '/libraries/joomla/application/pathway.php'); // for 1.6
jimport('joomla.html.pagination');
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.main.categories.class.php"); 
    //for 1.6
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/functions.php"); //for 1.6
require_once $mosConfig_absolute_path . "/administrator/components/com_medialibrary/language.php";
// load language

/** load the html drawing class */
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.html.php"); // for 1.6
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.php"); // for 1.6
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_game.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_music.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_book.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary_video.class.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.lend_request.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.lend.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.review.php");
require_once ($mosConfig_absolute_path 
        . "/administrator/components/com_medialibrary/admin.medialibrary.class.others.php");
require_once ($mosConfig_absolute_path 
        . "/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php");
require_once ($mosConfig_absolute_path 
        . "/administrator/components/com_medialibrary/admin.medialibrary.class.ws.php");
require_once ($mosConfig_absolute_path . "/components/com_medialibrary/medialibrary.class.people.php");

jimport('joomla.html.pagination');
if (version_compare(JVERSION, "3.0.0", "lt")) include_once ($mosConfig_absolute_path 
    . '/libraries/joomla/application/pathway.php'); // for 1.6

$doc->addStyleSheet($mosConfig_live_site . '/components/com_medialibrary/includes/medialibrary-grid.css');
//$doc->addScript($mosConfig_live_site . '/components/com_medialibrary/includes/jquery.min.js');

require_once ($mosConfig_absolute_path . "/components/com_medialibrary/functions.php");
if (!array_key_exists('medialibrary_configuration', $GLOBALS))
{
    require_once ($mosConfig_absolute_path 
            . "/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php");
    $GLOBALS['medialibrary_configuration'] = $medialibrary_configuration;
} else
    global $medialibrary_configuration;
if (!isset($option)) $GLOBALS['option'] = $option = mosGetParam($_REQUEST, 'option', 'com_medialibrary');
else $GLOBALS['option'] = $option ;
$GLOBALS['music_order_type'] = $medialibrary_configuration['music_order_type']['show'];
$GLOBALS['page_items_author'] = $medialibrary_configuration['people']['items'];
$GLOBALS['page_items_media'] = $medialibrary_configuration['page']['items'];
$GLOBALS['high_author'] = $medialibrary_configuration['foto']['high_author'];
$GLOBALS['width_author'] = $medialibrary_configuration['foto']['width_author'];
$GLOBALS['author_photo_show'] = $medialibrary_configuration['author_photo']['show'];
$GLOBALS['book_order_type'] = $medialibrary_configuration['book_order_type']['show'];
$GLOBALS['video_order_type'] = $medialibrary_configuration['video_order_type']['show'];
$GLOBALS['game_order_type'] = $medialibrary_configuration['game_order_type']['show'];
$GLOBALS['all_order_type'] = $medialibrary_configuration['all_order_type']['show'];
$GLOBALS['task'] = $task = mosGetParam($_REQUEST, 'task', '');
$GLOBALS['option'] = $option = mosGetParam($_REQUEST, 'option', 'com_medialibrary');
$GLOBALS['add_media_button_registrationlevel'] = $medialibrary_configuration['add']['registrationlevel'];
$doc = JFactory::getDocument(); // for 1.6
$GLOBALS['doc'] = $doc; // for 1.6
$GLOBALS['op'] = $doc; // for 1.6

$doc->setTitle(_MEDIALIBRARY_TITLE); // for 1.6
if (!isset($GLOBALS['Itemid'])) $GLOBALS['Itemid'] = $Itemid = JRequest::getInt('Itemid',0);
if ($option == "com_medialibrary") {
    if (!array_key_exists('user_configuration', $GLOBALS)) {
        require_once (JPATH_SITE . DS . 'administrator' . DS . 'components' . DS . 'com_medialibrary' . DS 
                . 'admin.medialibrary.class.conf.php');
        $GLOBALS['user_configuration'] = $user_configuration;
    } else {
        global $user_configuration;
    }
} else  if ($option == "com_simplemembership"){
    $task = $_GLOBALS['task'];
}
$id = intval(mosGetParam($_REQUEST, 'id', 0));
$pid = intval(mosGetParam($_REQUEST, 'pid', 0));
$other_uid = intval(mosGetParam($_REQUEST, 'other_uid', 0));
$GLOBALS['other_uid'] = $other_uid;
$catid = intval(mosGetParam($_REQUEST, 'catid', 0));
$efileid = intval(mosGetParam($_REQUEST, 'efileid', 0));
//$mid = mosGetParam($_REQUEST, 'mid', array());
$mid = protectInjectionWithoutQuote('mid', array(),"ARRAY");
// Get Current User for J 1.6
$user = JFactory::getUser();
$uid = $user->get('id');
$current_user = new JUser($uid);
$GLOBALS['current_user'] = $current_user; //for 1.6
$printItem = trim(mosGetParam($_REQUEST, 'printItem', ""));
// paginations
$intro = $medialibrary_configuration['page']['items']; // page length


if ($intro) {
    $paginations = 1;
    $limit = intval(mosGetParam($_REQUEST, 'limit', $intro));
    $GLOBALS['limit'] = $limit;
    $limitstart = intval(mosGetParam($_REQUEST, 'limitstart', 0));
    $GLOBALS['limitstart'] = $limitstart;
    $total = 0;
    $LIMIT = 'LIMIT ' . $limitstart . ',' . $limit;
} else {
    $paginations = 0;
    $LIMIT = '';
}
$session = JFactory::getSession();
$session->set("array", $paginations);
if ($medialibrary_configuration['debug'] == '1') {
    echo "Task: " . $task . "<br />";
    print_r($_POST);
    echo "<hr /><br />";
}
// for 1.6
if (isset($_REQUEST['view'])) $view = mosGetParam($_REQUEST, 'view','');
if ((!isset($task) OR $task == '') AND isset($view)) $task = $view;
//if ($task == 'showUsersProfile') $task = $GLOBALS['task'];
//if (isset($GLOBALS) && isset($task) OR $task == '')  $task = $GLOBALS['task'];
// if ((isset($_GLOBALS)) && ($_GLOBALS['task'] != "")) {
//     $task = $_GLOBALS['task'];
// }

//  var_dump($task);
//  echo "<br>";
//  echo "<br>";
//  var_dump($_REQUEST);
//  exit();

// print_r($_REQUEST);exit;

// print_r($task);exit;

switch ($task) {
    case 'view_people':
    case 'view_author':
        if (!$pid) {
            if (version_compare(JVERSION, '3.0', 'ge')) {
                $menu = new JTableMenu($database);
                $menu->load($Itemid);
                $params = new JRegistry;
                $params->loadString($menu->params);
            } else {
                $menu = new mosMenu($database);
                $menu->load($GLOBALS['Itemid']);
                $params = new mosParameters($menu->params);
            }
            if (version_compare(JVERSION, "1.6.0", "lt")) {
                $pid = $params->get('people');
            } else if (version_compare(JVERSION, "1.6.0", "ge")) {
                $view_people_id = ''; // for 1.6
                $view_people_id = $params->get('people');
                if ($view_people_id > 0) {
                    $pid = $view_people_id;
                } else {
                    $pid = intval($_REQUEST['id']);
                    /*$query = "SELECT id FROM #__medialibrary_people";
                    $database->setQuery($query);
                    $author = $database->loadObjectList();
                    $pid = $author[0]->id;*/
                }
            }
        }
        showPeople($pid, $printItem);
        //print_r('ok');exit;
        break;
    case 'all_authors':
    case 'all_peoples':
    case 'allpeople':
        showAllPeoples($id, $printItem, $langContent);
        break;

    case 'show_search':
    case 'show_search_media':
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($GLOBALS['Itemid']);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($GLOBALS['Itemid']);
            $params = new mosParameters($menu->params);
        }
        $layout = $params->get('showsearchmedialayout', '');
        if ($layout == '') $layout = 'default';
        showSearchMedias($option, $catid, $option, $layout);
    break;
    case 'search':
        searchMedias($option, $catid, $option);
    break;
    case 'view':
        showItemML($id, $catid, $printItem);
    break;
    case 'displaybook':
    case 'displaygame':
    case 'displaymusic':
    case 'displayvideo':
    
        $layout = "default" ;
        if (!$id) {
            if (version_compare(JVERSION, '3.0', 'ge')) {
                $menu = new JTableMenu($database);
                $menu->load($GLOBALS['Itemid']);
                $params = new JRegistry;
                $params->loadString($menu->params);
                $id = $params->def('media');
                if($task == "displaybook" ) $layout = $params->def('displaybook');
                if($task == "displaygame" ) $layout = $params->def('displaygame');
                if($task == "displaymusic" ) $layout = $params->def('displaymusic');
                if($task == "displayvideo" ) $layout = $params->def('displayvideo');
            } else {
                $menu = new mosMenu($database); //for 1.6
                $menu->load($GLOBALS['Itemid']);
                $params = new mosParameters($menu->params);
                $id = $params->def('media');
                if($task == "displaybook" ) $layout = $params->def('displaybook');
                if($task == "displaygame" ) $layout = $params->def('displaygame');
                if($task == "displaymusic" ) $layout = $params->def('displaymusic');
                if($task == "displayvideo" ) $layout = $params->def('displayvideo');
            }
        }
        showItemML($id, $catid, $printItem, $layout);
        
    break;
    case 'review':
        reviewMedia($option);
    break;

    case 'new_url':
        new_direct_url($id);
    break;
    case "randNumber":
        randNumber();
    break;



    case 'lend_request':
        showLendRequest($option, $mid);
    break;

    case 'save_lend_request':
        saveLendRequest($option, $mid);
    break;

    case 'lend':
        if (protectInjection('save') == "'1'") {
            saveLend($option, $mid);
        } else { 
            lend($option, $mid);
        }
    break;
    case 'lend_return':
        if (protectInjection('save') == 1) {
            saveLend_return($option, $mid);
        } else {
            lend_return($option, $mid);
        }
    break;



    //=================================================================================
    // do not change names of tasks that are below, because these files are associated
    // with mvc model and need for compatibility versions of Joomla!

    case 'alonecategory':
      if (version_compare(JVERSION, '3.0', 'ge')) {
                $menu = new JTableMenu($database);
                $menu->load($GLOBALS['Itemid']);
                // $menu->load($GLOBALS['start']);
                $params = new JRegistry;
                $params->loadString($menu->params);
                if (!$catid ) $catid = $params->def('category_id');
                $layout = $params->get('alonecategory');
      } else {
                $menu = new mosMenu($database); //for 1.6
                $menu->load($GLOBALS['Itemid']);
                $params = new mosParameters($menu->params);
                if (!$catid ) $catid = $params->def('category_id');
                $layout = $params->get('alonecategory');
      }
      showCategory($catid, $printItem, $layout);
    break;
    case 'allcategories':
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($GLOBALS['Itemid']);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($GLOBALS['Itemid']);
            $params = new mosParameters($menu->params);
        }

        $database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_medialibrary&view=allcategories' AND `published`=1");
        $menuId = $database->loadResult();
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($menuId);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($menuId);
            $params = new mosParameters($menu->params);
        }
        $layout = $params->get('allcategory', '');
        if ($layout == '') {
            $layout = $params->get('allcategories', '');
        } else if ($layout == '') {
            $layout = $medialibrary_configuration['view_media'];
        }

        listCategories($option, $catid, $layout, $langContent);
        break;

    case 'allmedia':
        if (!$catid) {
            if (version_compare(JVERSION, '3.0', 'ge')) {
                $menu = new JTableMenu($database);
                $menu->load($GLOBALS['Itemid']);
                $params = new JRegistry;
                $params->loadString($menu->params);
                $catid = $params->def('category_id');
            } else {
                $menu = new mosMenu($database); //for 1.6
                $menu->load($GLOBALS['Itemid']);
                $params = new mosParameters($menu->params);
                $catid = $params->def('category_id');
            }
        }
        $catid = intval(mosGetParam($_REQUEST, 'catid', 0));
        //var_dump($catid);die();
        if (version_compare(JVERSION, '1.5.0', 'ge')) {
            $layout = $params->get('allmedia', '');
            if ($layout == '') $layout = $medialibrary_configuration['view_type_game'];
        } else {
            $layout = $j15;
            if ($layout == '') $layout = $medialibrary_configuration['view_type_game'];
        }

        
        showAllMedia($catid, $printItem, $layout, $langContent);
        break;


    case 'ownerslist':
        ownersList($option, $printItem);
        break;
        //=================================================================================

    default:
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($GLOBALS['Itemid']);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($GLOBALS['Itemid']);
            $params = new mosParameters($menu->params);
        }
        $layout = $params->get('allcategory', '');
        if ($layout == '') $layout = $medialibrary_configuration['view_type_all'];
        if ($layout == '') $layout = 'default';
        listCategories($option, $catid, $layout);
    break;
}

function mylenStr($str, $lenght) {
    if (strlen($str) > $lenght) {
        $str = substr($str, 0, $lenght);
        $str = substr($str, 0, strrpos($str, " "));
    }
    return $str;
}

function randNumber() {
    $path = protectInjectionWithoutQuote('path', '');
    $filename = basename(protectInjectionWithoutQuote('file', ''));
    $file = $path . $filename;
    if (file_exists($file)) {
        echo "The file with such name already is!";
    } else {
        echo "";
    }
}
function get_author_description($people_name, &$authors, &$books_titles, &$rows){
    global $database, $langContent, $Itemid;
    
    if (isset($langContent)) {
        $lang = $langContent;
        // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
        // $database->setQuery($query);
        // $lang = $database->loadResult();
        $lang = "AND ( other_table.langDescription='$lang' or other_table.langDescription='*' 
            or other_table.langDescription is null or other_table.langDescription='')";
        } else {
        $lang = "";
        }
    if (!empty($people_name)) {
      $selectstring = "SELECT other_table.id, p.people_name ,library.id, pc.fk_media_id, 
        c.catid, other_table.title FROM #__medialibrary AS library"  
        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = library.id"
        ."\n LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
        ."\n LEFT JOIN #__medialibrary_categories AS c ON c.mediaid = library.id".
         " LEFT JOIN (SELECT g.id, g.title AS title, g.langDescription, 'game' as type, g.comment " .
         " FROM #__medialibrary_game AS g ".
         " UNION all SELECT m.id, m.title AS title, m.langDescription, 'music' as type, m.comment " .
         " FROM #__medialibrary_music AS m  ".
         "UNION all SELECT b.id, b.title AS title, b.langDescription, 'book' as type, b.comment " .
         " FROM #__medialibrary_book AS b " .
         " UNION all SELECT v.id, v.title AS title, v.langDescription, 'video' as type, v.comment " .
         " FROM #__medialibrary_video AS v)".
         " AS other_table ON other_table.id =library.media_id AND other_table.type = library.media_type "
        ."\n WHERE people_name LIKE '%" .   trim($people_name) . "%' $lang"
        ."\n GROUP BY other_table.title";
      $database->setQuery($selectstring);
      $rows = $database->loadObjectList();
      //print_r($rows);exit;

      $database->setQuery("SELECT id FROM #__menu WHERE link LIKE
          'index.php?option=com_medialibrary&view=allcategories%'
            or link LIKE 'index.php?option=com_medialibrary&task=allcategories%' ");
      $ItemId_tmp_from_db = $database->loadResult();
      foreach($rows as $row2) {
          $link1 = "index.php?option=com_medialibrary&amp;task=view&amp;id=" . $row2->id .
        "&amp;catid=" . $row2->catid . "&amp;Itemid=" . $ItemId_tmp_from_db;
          $books_titles.= '<br/><a href="' . sefRelToAbs($link1) .
            '" target="_self">' . $row2->title . '</a>';
           // print_r($link1);exit;
      }
      $message = $authors->description;
      if ($message == ''){
        $message = $authors->auto_gener_description;
      }
      if ($message == ''){
        $message = $authors->auto_gener_description;
        switch ($authors->type) {
            case 'actor':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_ACTOR_DESCTIPTION;
                break;
            case 'artist':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_ARTIST_DESCTIPTION;
                break;
            case 'author':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_AUTHOR_DESCTIPTION;
                break;
            case 'director':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_DIRECTOR_DESCTIPTION;
                break;
            case 'game_studio':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_GAME_STUDIO_DESCTIPTION;
                break;
            case 'producer':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_PRODUCER_DESCTIPTION;
                break;
            case 'video_studio':
                $message = _MEDIALIBRARY_ADMIN_CONFIG_VIDEO_STUDIO_DESCTIPTION;
                break;
        };

      }
      $message = str_replace("{person_name}", $people_name, $message);
      $message = str_replace("{media_titles}", $books_titles, $message);
      return $message;
    }else {
      return 0;
    }
}
function showPeople($id, $printItem) {
        global $mainframe, $database, $my, $acl, $option;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $langContent; 
            //print_r($printItem);exit;
        //for 1.6
        $mosConfig_live_site = JURI::root(true);
        $doc = JFactory::getDocument();
        $doc->addStyleSheet($mosConfig_live_site 
                . '/components/com_medialibrary/includes/custom.css');
        $path_way = $mainframe->getPathway(); // variant 2
        // --
      //  PHP_booklibrary::addTitleAndMetaTags($id);
        
        $sql = "UPDATE #__medialibrary_people SET hits = hits + 1 WHERE id = " . $id . "";
        $database->setQuery($sql);
        $database->query();
        $authors = new mosMediaLibrary_people($database);
        $authors->load($id);
        if ($authors->id == ''){
            $query = "SELECT id FROM #__medialibrary_people";
            $database->setQuery($query);
            $author = $database->loadObjectList();
            $id = $author[0]->id;
        
            $sql = "UPDATE #__medialibrary_people SET hits = hits + 1 WHERE id = " . $id . "";
            $database->setQuery($sql);
            $database->query();
            $authors = new mosMediaLibrary_people($database);
            $authors->load($id);
        }
        
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database);
            $menu->load($GLOBALS['Itemid']);
            $params = new mosParameters($menu->params);
        }
        $menu_name = set_header_name_ml($menu, $Itemid);
        $params->def('header', $menu_name); //for 1.6
        $params->def('pageclass_sfx', '');
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        $params->def('pageclass_sfx', '');
        $params->def('item_description', 1);
        $database->setQuery("SELECT username FROM #__users WHERE id ='$authors->owner_id'");
        $authors->ownername = $database->loadResult();
        if (!empty($authors)) {
            $selectstring = "SELECT p.id as id, p.people_name as people_name, p.type as type, 
                p.hits as hits,  p.published as published,
            p.checked_out as checked_out, p.langshow as langshow, 
            GROUP_CONCAT(DISTINCT other_table.title SEPARATOR ',') AS title       
            FROM #__medialibrary AS library " .
               " LEFT JOIN #__medialibrary_people_connect AS pc ON library.id = pc.fk_media_id" .
            " RIGHT JOIN #__medialibrary_people AS p ON   pc.fk_people_id = p.id ".
                   " LEFT JOIN #__medialibrary_lend AS l on library.id = l.fk_mediaid and 
                   l.lend_return is null  " .
             " LEFT JOIN #__users AS u on u.id = library.owner_ID ".
             " LEFT JOIN (SELECT g.id, g.title AS title, g.langDescription, 'game' as type, g.comment " .
             " FROM #__medialibrary_game AS g ".
             " UNION all SELECT m.id, m.title AS title, m.langDescription, 'music' as type, m.comment " .
             " FROM #__medialibrary_music AS m  ".
             "UNION all SELECT b.id, b.title AS title, b.langDescription, 'book' as type, b.comment " .
             " FROM #__medialibrary_book AS b " .
             " UNION all SELECT v.id, v.title AS title, v.langDescription, 'video' as type, v.comment " .
             " FROM #__medialibrary_video AS v)".
             " AS other_table ON other_table.id =library.media_id AND other_table.
                type = library.media_type "
            ."\n WHERE p.people_name LIKE '%" . $authors->people_name . "%' AND p.id = " . $authors->id;

            $database->setQuery($selectstring);
            $rows = $database->loadObjectList();
            //print_r($rows);exit;
        }
         if ($authors->owner_id != 0 && $medialibrary_configuration['owner']['show'] != '0') {
            $query = "SELECT name, email FROM #__users WHERE id = " . $authors->owner_id . "";
            $database->setQuery($query);
            $user_b = $database->loadObject();
            $authors->user_b = $user_b;
        }

        $zapros = "SELECT people_name FROM #__medialibrary_people WHERE id = '" . $authors->id . "';";
        $database->setQuery($zapros);
        $people_name = $database->loadResult(); //print_r($authors_name);exit;

        $books_titles = '';
        $author_description = get_author_description($people_name, $authors, $books_titles, $rows);

        
        $category = new stdClass();
        //getting the current category informations
        $category->title = $category->name = _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL . " " 
            . _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME;
        $category->description = "";
        $category->image = "";
        if (isset($medias[0])){
            $category->catid = $medias[0]->catid;
        } else {
            $category->catid = 0;
        }

        $currentcat = NULL;
        $currentcat = new stdClass();
        $currentcat->descrip = $category->description;
        // page image
        $currentcat->img = null;
        $path = $mosConfig_live_site . '/images/stories/';
        if ($category->image != null && count($category->image) > 0) {
            $currentcat->img = $path . $category->image;
            $currentcat->align = $category->image_position;
        }
        $currentcat->header = '';
        if ($category->name <> '') {
            $currentcat->header = $category->name;
        } else {
            $currentcat->header = $params->get('header');
        }
        $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header 
            . ": ") : ("")) . $category->title;


        $params->def('view01', "{loadposition com_madialibrary_view_people_01}");
        $params->def('view02', "{loadposition com_madialibrary_view_people_02}");
        $params->def('view03', "{loadposition com_madialibrary_view_people_03}");
        // $params->def('viewdescription', "{loadposition com_booklibrary_view_book_description}");
        $params->def('view04', "{loadposition com_madialibrary_view_people_04}");
        $params->def('view05', "{loadposition com_madialibrary_view_people_05}");
    //--------------------
        //ebook urls
        //             $query = "select * " . " from  #__booklibrary_files AS s " 
        //          . " where s.fk_book_id=" . $book->id . " ORDER BY s.id ";
        //             $database->setQuery($query);
        //             $row = $databa
        $params->def('printItem', $printItem);
        switch ($printItem) {
            default:
                HTML_medialibrary::displayPeople($authors, $params, $rows, $author_description, 
                    $books_titles, $currentcat);
                
            break;
        }
    }

    
function showAllPeoples($id, $printItem, $langContent) {
        global $mainframe, $database, $acl, $my;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $option, $limit, $total, $limitstart;
        //PHP_booklibrary::addTitleAndMetaTags();

        $typeshow_filter = protectInjectionWithoutQuote('typeshow_filter', '');
        if ($typeshow_filter){
            $_SESSION['typeshow_filter'] = $typeshow_filter;
        } else{
            if (isset($_SESSION['typeshow_filter']) && $_SESSION['typeshow_filter'] != ''){
                $typeshow_filter = $_SESSION['typeshow_filter'];
            } else {
                $typeshow_filter = 0;
            }
        }
        // $typeshow_filter = $mainframe->getUserStateFromRequest("typeshow_filter{$option}", 
        //         'typeshow_filter', '0');
        $authors_one_page = $medialibrary_configuration['people']['items']; // page length
        $search = '';
        if (array_key_exists("letindex", $_REQUEST)) {
            $search = mb_substr(protectInjectionWithoutQuote('letindex'), 0, 1, 'UTF-8');
        }
        if ($authors_one_page) {
            $limit = $authors_one_page;
        } else {
            $limit = 0;
        }
        $sp = null;
        if (array_key_exists("sp", $_REQUEST)) {
            $sp = protectInjectionWithoutQuote('sp', 0);
        }
        if (version_compare(JVERSION, '3.0', 'lt')) {
            $menu = new JTableMenu($database); // for 1.6
            $menu->load($Itemid);
            $params = new mosParameters($menu->params);
        } else {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
        }

        $typeuages_row = ['All types', 'author', 'game_studio', 'artist', 'video_studio', 'director', 
            'producer', 'actor'];
        $people_type = $params->get('people_type');
        $add_str = "";
        if ($people_type != '0' && $people_type != ''){
            $add_str .= " AND p.type='".$typeuages_row[$people_type]."'";
        } else {
            if ($typeshow_filter != '*' and $typeshow_filter != '0') {
               $add_str .= " AND p.type='".$typeuages_row[$typeshow_filter]."'";
            }
        }

        if ($people_type == '0'){
            $typeshow_filter = mosHTML::selectList($typeuages_row, 'typeshow_filter', 
                    'class="inputbox inputboxutype" onchange="document.orderForm.submit();" size="1"', 
                    'value', 'text', $typeshow_filter);
        } else {
            $typeshow_filter = '';
        }
        if ($sp == 'one') {
            $add_str .= " AND (LOWER(p.people_name) LIKE '$search%' )";
        }
        $layout = $params->get('all_peoples', '');
        $query = "SELECT COUNT(DISTINCT p.id)
          \nFROM #__medialibrary_people AS p" .
         "\nWHERE (p.langshow LIKE '" . $langContent 
         . "' OR p.langshow='*') AND p.approved='1' and p.published='1'" . $add_str;
        $database->setQuery($query);
        $total = $database->loadResult();
        $pageNav = new JPagination($total, $limitstart, $limit);
        
        $query = "SELECT p.id, p.people_name,p.imageURL,p.description,p.owneremail,p.date" . "
            FROM #__medialibrary_people as p" . "
            WHERE (p.langshow LIKE '" . $langContent 
            . "' OR p.langshow='*') AND p.approved='1' and p.published='1'" . $add_str . "
            ORDER BY p.people_name, p.date desc" . " LIMIT $pageNav->limitstart,$pageNav->limit";
        $database->setQuery($query);
        $all_authors = $database->loadObjectList();
        $list_str = array();
        if ($medialibrary_configuration['litpage_author']['show'] &&
            checkAccess_ML($medialibrary_configuration['litpage_author']['registrationlevel'], 
                'RECURSE', userGID_ML($my->id), $acl)) {
            $query = 'SELECT DISTINCT UPPER(SUBSTRING(p.people_name, 1,1)) AS symb
                  FROM #__medialibrary_people as p
                  WHERE  p.published=\'1\' AND p.approved=\'1\' '.$add_str.'
                  ORDER BY symb';
            $database->setQuery($query);
            $tmp_array = $database->loadObjectList();
            $symb_list_str = '<ul>';
            if (count($tmp_array) > 0) {
                foreach($tmp_array as $symbol) {
                    $symb_list_str.= '<li>' . '<a href="index.php?option=' . $option 
                    . '&view=all_peoples&letindex=' . $symbol->symb .
                    '&sp=one&Itemid=' . $Itemid . '">' . $symbol->symb . '</a></li>';
                }
                $symb_list_str.= "</ul>";
                $list_str['symbol_list'] = $symb_list_str;
            }
        }

        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database);
            $menu->load($Itemid);
            $params = new mosParameters($menu->params);
        }

        $category = new stdClass();
        //getting the current category informations
        $category->title = $category->name = _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL . " " 
            . _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME;
        $category->description = "";
        $category->image = "";
        if (isset($medias[0])){
            $category->catid = $medias[0]->catid;
        } else {
            $category->catid = 0;
        }

        $currentcat = NULL;
        $currentcat = new stdClass();
        $currentcat->descrip = $category->description;
        // page image
        $currentcat->img = null;
        $path = $mosConfig_live_site . '/images/stories/';
        if ($category->image != null && count($category->image) > 0) {
            $currentcat->img = $path . $category->image;
            $currentcat->align = $category->image_position;
        }
        $currentcat->header = '';
        if ($category->name <> '') {
            $currentcat->header = $category->name;
        } else {
            $currentcat->header = $params->get('header');
        }
        $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header 
                . ": ") : ("")) . $category->title;
        $menu_name = set_header_name_ml($menu, $Itemid);

        $params->def('header', $menu_name);
        $params->def('pageclass_sfx', '');
        $params->def('show_search', '1');
        $params->def('back_button', $mainframe->getCfg('back_button'));
        $params->def('printItem', $printItem);
        

        switch ($printItem) {
            default:
                HTML_medialibrary::displayPeoples($all_authors, $pageNav, $params, $layout, $list_str, 
                    $typeshow_filter, $currentcat, $category);
                
            break;
        }

    }

function addTitleAndMetaTags() {

    global $database, $doc, $mainframe;
    $view = JREQUEST::getCmd('view', null);
    $catid = JREQUEST::getInt('catid', null);
    $id = JREQUEST::getInt('id', null);
    $lang = protectInjection('lang');
    $title = array();
    $sitename = htmlspecialchars($mainframe->getCfg('sitename'));
    if (isset($view)) {
        $view = str_replace("_", " ", $view);
        $view = ucfirst($view);
        $title[] = $view;
    }
    //To get name of category
    if (isset($catid)) {
        $query = "SELECT cc.id, cc.name, mc.catid,cc.parent_id 
            FROM #__medialibrary_main_categories AS cc" 
            . " LEFT JOIN #__medialibrary_categories AS mc ON mc.catid=cc.id " 
            . " LEFT JOIN #__medialibrary AS a ON mc.mediaid = a.id " 
            . " WHERE cc.section= 'com_medialibrary' AND cc.id = " . intval($catid);
        $database->setQuery($query);
        $row = null;
        $row = $database->loadObject();
        if (isset($row)) {
            $cattitle = array();
            $cattitle[] = $row->name;
            while (isset($row) && $row->parent_id > 0) {
                $query = "SELECT  name, id, parent_id FROM #__medialibrary_main_categories AS cc" 
                    . " where  cc.id = " . intval($row->parent_id);
                $database->setQuery($query);
                $row = $database->loadObject();
                if (isset($row) && $row->name != '') {
                    $cattitle[] = $row->name;
                }
            }
            $title = array_merge($title, array_reverse($cattitle));
        }
    }
    if (isset($id)) {
        $query = "SELECT mc.catid, other_table.title as title, other_table.comment as comment 
                  FROM #__medialibrary AS m" 
                . "\n LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid=m.id" 
                . "\n LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id=mc.catid" 
                . "\n JOIN (SELECT id, title, comment, 'game' as type FROM #__medialibrary_game " 
                . "\n UNION all SELECT id, title, comment, 'video' as type FROM #__medialibrary_video" 
                . "\n UNION all SELECT id, title, comment, 'music' as type FROM #__medialibrary_music" 
                . "\n UNION all SELECT id, title, comment, 'book' as type 
                        FROM #__medialibrary_book) AS other_table" 
                . "\n WHERE m.id=" . intval($id) . " AND  m.media_type = other_table.type AND 
                        m.media_id = other_table.id";
        $database->setQuery($query);
        $row = null;
        $row = $database->loadObject();
        if (isset($row)) {
            $idtitle = array();
            $idtitle[] = $row->title;
            $desctitle = array();
            $desctitle[] = $row->comment;
            $desctitle = strip_tags($desctitle[0]);
            $title = array_merge($title, $idtitle);
        }
    }
    if (!isset($desctitle)) {
        $desctitle = "";
    }
    $tagtitle = "";
    for ($i = 0;$i < count($title);$i++) {
        $tagtitle = trim($tagtitle) . " | " . trim($title[$i]);
    }
    $rem = "Media Library ";
    //To set Title
    $title_tag = mylenStr($sitename . " | " . $rem . $tagtitle, 75);
    //To set meta Description
    $metadata_description_tag = mylenStr($rem . $tagtitle . " | " . $desctitle, 200);
    //To set meta KeywordsTag
    $metadata_keywords_tag = mylenStr($rem . $tagtitle, 250);
    $doc->setTitle($title_tag);
    $doc->setMetaData('description', 'm'.$metadata_description_tag);
    $doc->setMetaData('keywords', 'm'.$metadata_keywords_tag);
}


    function saveLendRequest($option, $mids) {
        global $mainframe, $database, $my, $Itemid, $acl;
        global $medialibrary_configuration, $mosConfig_mailfrom, $mosConfig_live_site, $doc;
        addTitleAndMetaTags();
        $GLOBALS['id_media'] = $mids[0];
        //*********************   begin compare to key   ***************************
        $user = JFactory::getUser();

        //**********************   end compare to key   *****************************
        if (!($medialibrary_configuration['lendstatus']['show']) || 
            !checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
            echo _MEDIALIBRARY_NOT_AUTHORIZED;
            return;
        }
        $help = array();
        $lend_request = new mosMediaLibrary_lend_request($database);
        $lend_request->user_email = trim($_REQUEST["user_email"]);
        $lend_request->user_mailing = trim($_REQUEST["user_mailing"]);
        $lend_request->user_name = trim($_REQUEST["user_name"]);

        //-----------------
        if (phpversion() >= '5.3.0') {
             $d_format = str_replace("%", '', $medialibrary_configuration["date_format"]);
             $from = DateTime::createFromFormat($d_format, trim($_REQUEST["lend_from"]));
             $until = DateTime::createFromFormat($d_format, trim($_REQUEST["lend_until"]));
             if ($from === FALSE or $until === FALSE) {
                   echo "<script> alert('Bad date format'); window.history.go(-1); </script>\n";
                   exit;
             }
             $lend_request->lend_from = $from->format('Y-m-d');
             $lend_request->lend_until = $until->format('Y-m-d');;
         } else {
             $lend_request->lend_from = data_transformer_med(trim($_REQUEST["lend_from"]),'to');
           $lend_request->lend_until = data_transformer_med(trim($_REQUEST["lend_until"]),'to');
         }
        //-----------------

        $lend_request->lend_request = date("Y-m-d H:i:s");
        $lend_request->fk_mediaid = intval($_REQUEST["mediaid"]);
        $lend_request->user_email = $database->Quote($lend_request->user_email);
        $query = "SELECT * FROM #__medialibrary_lend where fk_mediaid = " . $lend_request->fk_mediaid 
            . " AND lend_return is NULL ";
        $database->setQuery($query);
        $lendTerm = $database->loadObjectList();
        $lend_from = substr($lend_request->lend_from, 0, 10);
        $lend_until = substr($lend_request->lend_until, 0, 10);
        if (isset($lendTerm[0])) {
            for ($e = 0, $m = count($lendTerm);$e < $m;$e++) {
                $lendTerm[$e]->lend_from = substr($lendTerm[$e]->lend_from, 0, 10);
                $lendTerm[$e]->lend_until = substr($lendTerm[$e]->lend_until, 0, 10);
  
                if (($lend_from >= $lendTerm[$e]->lend_from && 
                            $lend_from <= $lendTerm[$e]->lend_until) || 
                        ($lend_from <= $lendTerm[$e]->lend_from && 
                            $lend_until >= $lendTerm[$e]->lend_until) || 
                        ($lend_until >= $lendTerm[$e]->lend_from && 
                            $lend_until <= $lendTerm[$e]->lend_until)) {
                    echo "<script> alert('Sorry lend out from " . $lendTerm[$e]->lend_from . " until " 
                        . $lendTerm[$e]->lend_until . "'); window.history.go(-1); </script>\n";
                    exit();
                }
            }
        } //if end
        if ($my->id != 0)
            $lend_request->fk_userid = $my->id;

        if (!$lend_request->check()) {
            echo "<script> alert('" . addslashes($lend_request->getError()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (!$lend_request->store()) {
            echo "<script> alert('" . addslashes($lend_request->getError()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        $lend_request->checkin();
        $currentcat = new stdClass();
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
            //$params->def( 'header', $menu_name );//for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', $menu_name); //for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        }
        //
        $currentcat->descrip = _MEDIALIBRARY_LABEL_LEND_REQUEST_THANKS;
        // page image
        $currentcat->img = $mosConfig_live_site 
            . "/components/com_medialibrary/images/medialibrary_logo.png";
        $currentcat->header = $params->get('header');
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        //********************   begin add send mail for admin   ********
        //    mosMail( $mosConfig_mailfrom, $mosConfig_fromname, $row->email, $subject, $message, 
        //      $mode );
        if (($medialibrary_configuration['lendrequest_email']['show']) && 
             trim($medialibrary_configuration['lendrequest_email']['address']) != "") {
            $params->def('show_email', 1);
            if (checkAccess_ML($medialibrary_configuration['lendrequest_email']['registrationlevel'], 
                'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_input_email', 1);
            }
        }
        if ($params->get('show_input_email')) {
            $mail_to = explode(",", $medialibrary_configuration['lendrequest_email']['address']);
            $userid = $my->id;
            //select user (added lend request)
            $zapros = "SELECT name, email FROM #__users WHERE id=" . $userid . ";";
            $database->setQuery($zapros);
            $item_user = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
            $mides = implode(',', $mids);
            $query = "SELECT library.id, library.media_type, library.media_id," 
            . " library.hits, library.checked_out, mc.catid, " 
            . " library.fk_lendid,library.date," 
            . " other_table.id as media_type_id, other_table.title as title, " 
            . " other_table.media_class_id as media_class_id " 
            . " FROM #__medialibrary AS library " 
            . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid=library.id " 
            . " LEFT JOIN (SELECT id,title, game_id AS media_class_id,'game' AS type 
                FROM #__medialibrary_game " 
            . " UNION ALL SELECT id,title,music_id AS media_class_id,'music' AS type 
                FROM #__medialibrary_music " 
            . " UNION ALL SELECT id,title,book_id AS media_class_id,'book' AS type 
                FROM #__medialibrary_book " 
            . " UNION ALL SELECT id,title,video_id AS media_class_id,'video' AS type 
                FROM #__medialibrary_video) " 
            . " AS other_table ON other_table.id = library.media_id and 
                other_table.type = library.media_type" 
            . " WHERE library.id IN (" . $mides . ") AND mc.mediaid IN (" . $mides 
                . ") AND fk_lendid = 0" . " ORDER BY mc.catid, ordering";
            $database->setQuery($query);
            $medias = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
            for ($i = 0;$i < count($medias);$i++) {
                $mediaid = "";
                switch ($medias[$i]->media_type) {
                    case 'book':
                        $mediaid = _MEDIALIBRARY_LABEL_BOOKID;
                    break;
                    case 'video':
                        $mediaid = _MEDIALIBRARY_LABEL_VIDEOID;
                    break;
                    case 'music':
                        $mediaid = _MEDIALIBRARY_LABEL_MUSICID;
                    break;
                    case 'game':
                        $mediaid = _MEDIALIBRARY_LABEL_GAMEID;
                    break;
                }
                $media_type = _MEDIALIBRARY_LABEL_MEDIA_TYPE;
                if ($userid == 0) {
                    mosMail($mosConfig_mailfrom, 'anonymous', $mail_to, 'New lend request added!', 
                        'User anonymous has submitted a Lend Request for:<br /><br /> ' . $mediaid 
                        . ': ' . $medias[$i]->media_class_id . '<br />' . $media_type . ': ' 
                        . $medias[$i]->media_type . '<br />' . $medias[$i]->title . '<br /><br /> ' 
                        . 'Please log on and approve or deny this Lend Request', true);
                } else {
                    mosMail($mosConfig_mailfrom, $item_user[0]->name,$mail_to,'New lend request added!',
                         'User '.$item_user[0]->name.' has submitted a Lend Request for:<br /><br /> ' 
                         . $mediaid . ': ' . $medias[$i]->media_class_id . '<br />' . $media_type 
                         . ': ' . $medias[$i]->media_type . '<br />' . $medias[$i]->title 
                         . '<br /><br /> ' . 'Please log on and approve or deny this Lend Request', 
                         true);
                }
            }
        }
        //********************   end add send mail for admin   ****************
        $doc->addStyleSheet($mosConfig_live_site 
            . '/components/com_medialibrary/includes/medialibrary.css');
        HTML_medialibrary::showLendRequestThanks($params, $currentcat);
    }


    function showLendRequest($option, $mid) {
        global $mainframe, $database, $my, $Itemid, $acl;
        global $medialibrary_configuration, $mosConfig_live_site, $doc;
        $doc->addStyleSheet($mosConfig_live_site 
            . '/components/com_medialibrary/includes/medialibrary.css');
        addTitleAndMetaTags();
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        if (!($medialibrary_configuration['lendstatus']['show']) || 
            !checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 
                'RECURSE', userGID_ML($my->id), $acl)) {
            echo _MEDIALIBRARY_NOT_AUTHORIZED;
            return;
        }
        $mids = implode(',', $mid);
        // getting all medias for this category
        $query = "SELECT library.id, library.media_type, library.media_id,"
                . " library.hits, library.checked_out, mc.catid, "
                . " library.fk_lendid,library.date,"
                . " other_table.id as media_type_id, other_table.title as title, 
                    other_table.rating as rating, "
                . " other_table.URL as URL, other_table.imageURL as imageURL " 
                    . " FROM #__medialibrary AS library "
                . " left join #__medialibrary_categories as mc on mc.mediaid=library.id "
                . " LEFT JOIN (SELECT id,title,rating,URL,imageURL,'game' as type 
                    FROM #__medialibrary_game "
                . " UNION all SELECT id,title,rating,URL,imageURL,'music' as type 
                    FROM #__medialibrary_music "
                . " UNION all SELECT id,title,rating,URL,imageURL,'book' as type 
                    FROM #__medialibrary_book "
                . " UNION all SELECT id,title,rating,URL,imageURL,'video' as type 
                    FROM #__medialibrary_video) "
                . " AS other_table ON other_table.id = library.media_id and 
                    other_table.type = library.media_type"
                . " WHERE library.id IN (" . $mids . ") AND mc.mediaid IN (" . $mids . ") "
                . " ORDER BY mc.catid, ordering";
               // print_r($query);exit;
        $database->setQuery($query);
        $medias = $database->loadObjectList();

		$query = " SELECT people_name, type, id FROM `#__medialibrary_people` b 
                    WHERE EXISTS ( SELECT fk_people_id, fk_media_id FROM `#__medialibrary_people_connect` a 
                    WHERE a.fk_people_id = b.id AND a.fk_media_id = " .$mid[0] ." ) ";
           
        $database->setQuery($query);
        $authors = $database->loadObjectlist();
            
        $medias[0]->authors = $authors[0]->people_name;

        $currentcat = new stdClass();

        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
            $params->def('header', _MEDIALIBRARY_DESC_TITLE);
            //$params->def( 'header', $menu_name ); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_lendstatus', 1);
            $params->def('show_lendrequest', 1);
            $params->def('lend_save', 1);
            $params->def('back_button', $mainframe->getCfg('back_button'));
        } else {
            $menu = new mosMenu($database); // for 1.6 - JTableMenu
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', _MEDIALIBRARY_DESC_TITLE);
            $params->def('header', $menu_name); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_lendstatus', 1);
            $params->def('show_lendrequest', 1);
            $params->def('lend_save', 1);
            $params->def('back_button', $mainframe->getCfg('back_button'));
        }
        // page description
        $currentcat->descrip = _MEDIALIBRARY_DESC_LEND;
        // page image
        $currentcat->img = "" . $mosConfig_live_site 
            . "/components/com_medialibrary/images/medialibrary_logo.png";
        $currentcat->align = 'right';
        $currentcat->header = $params->get('header');
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        HTML_medialibrary::showLendRequest($medias, $currentcat, $params, $tabclass, $catid, 
                $sub_categories, false, $category = []);
    }
    /**
     * comments for registered users
     */
    function reviewMedia() {
        global $mainframe, $database, $my, $Itemid, $acl, $medialibrary_configuration, 
            $mosConfig_absolute_path, $catid;
        global $mosConfig_mailfrom, $session, $option;
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        if (!($medialibrary_configuration['reviews']['show']) || !checkAccess_ML(
                $medialibrary_configuration['reviews']['registrationlevel'], 'RECURSE', 
                userGID_ML($my->id), $acl)) {
            echo _MEDIALIBRARY_NOT_AUTHORIZED;
            return;
        }
        $review = new mosMediaLibrary_review($database);
        $review->date = @date("Y-m-d H:i:s");
        $review->fk_userid = $my->id;
        $review->published = 1;
        //*********************   begin compare to key   ***************************
        $session = JFactory::getSession();

        //**********************   end compare to key   *****************************
        if (!$review->bind($_POST)) {
            echo "<script> alert('" . addslashes($review->getError()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (!$review->check()) {
            echo "<script> alert('" . addslashes($review->getError()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        if (!$review->store()) {
            echo "<script> alert('" . addslashes($review->getError()) 
                . "'); window.history.go(-1); </script>\n";
            exit();
        }
        //***************   begin add send mail for admin   ******************
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database);
            $menu->load($Itemid);
            $params = new mosParameters($menu->params);
        }
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        if (($medialibrary_configuration['review_added_email']['show']) && 
                trim($medialibrary_configuration['review_email']['address']) != "") {
            $params->def('show_email', 1);
            if (checkAccess_ML($medialibrary_configuration['review_added_email']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_input_email', 1);
            }
        }
        if ($params->get('show_input_email')) {
            $mail_to = explode(",", $medialibrary_configuration['review_email']['address']);
            $query = "SELECT library.id, library.media_type, library.media_id," 
                . " library.hits, library.checked_out, mc.catid, " 
                . " library.fk_lendid,library.date," 
                . " other_table.id as media_type_id, other_table.title as title, " 
                . " other_table.media_class_id as media_class_id " 
                . " FROM #__medialibrary AS library " 
                . " left join #__medialibrary_categories as mc on mc.mediaid=library.id " 
                . " LEFT JOIN (SELECT id,title, game_id as media_class_id,'game' as type 
                    FROM #__medialibrary_game " 
                . " UNION all SELECT id,title,music_id as media_class_id,'music' as type 
                    FROM #__medialibrary_music " 
                . " UNION all SELECT id,title,book_id as media_class_id,'book' as type 
                    FROM #__medialibrary_book " 
                . " UNION all SELECT id,title,video_id as media_class_id,'video' as type 
                    FROM #__medialibrary_video) " 
                . " AS other_table ON other_table.id = library.media_id and 
                    other_table.type = library.media_type" 
                . " WHERE library.id = " . JRequest::getVar('fk_mediaid') 
                . " AND  mc.mediaid = " . JRequest::getVar('fk_mediaid');
            $database->setQuery($query);
            $media = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
            $mediaid = "";
            switch ($media[0]->media_type) {
                case 'book':
                    $mediaid = _MEDIALIBRARY_LABEL_BOOKID;
                break;
                case 'video':
                    $mediaid = _MEDIALIBRARY_LABEL_VIDEOID;
                break;
                case 'music':
                    $mediaid = _MEDIALIBRARY_LABEL_MUSICID;
                break;
                case 'game':
                    $mediaid = _MEDIALIBRARY_LABEL_GAMEID;
                break;
            }
            $media_type = _MEDIALIBRARY_LABEL_MEDIA_TYPE;
            //select new review
            $zapros = "SELECT * FROM #__medialibrary_review WHERE date = '" . $review->date . "';";
            $database->setQuery($zapros);
            $item_review = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
            //select user (add new review)
            $zapros = "SELECT name, email FROM #__users WHERE id=" . $item_review[0]->fk_userid . ";";
            $database->setQuery($zapros);
            $item_user = $database->loadObjectList();
            if ($database->getErrorNum()) {
                echo $database->stderr();
            }
            $t = _MEDIALIBRARY_LABEL_TITLE_COMMENT; //Review title
            $c = _MEDIALIBRARY_LABEL_TITLE_REVIEW_COMMENT; //Review comment
            $r = _MEDIALIBRARY_LABEL_RATING; //Rating
            $rating = (($item_review[0]->rating) / 2);
            if ($item_review[0]->fk_userid == 0) {
                mosMail($mosConfig_mailfrom, 'anonymous', $mail_to, 'New media review added', 
                    'User Anonymous has added a Review to media:<br />' . $media[0]->title . '<br />' 
                    . $mediaid . ': ' . $media[0]->media_class_id . '<br />' . $media_type . ': ' 
                    . $media[0]->media_type . '<br /><br />' . $t . ': "' . $item_review[0]->title 
                    . '"<br /><br /> ' . $r . ': [' . $rating . ']<br /><br /> ' . $c . ':<br /> ' 
                    . $item_review[0]->comment . '<br /><br /> ' 
                    . 'Please log on and edit this review where necessary.', true);
            } else if ($item_review[0]->fk_userid != 0) {
                mosMail($mosConfig_mailfrom, $item_user[0]->name, $mail_to, 'New media review added', 
                    'User ' . $item_user[0]->name . ' has added a Review to media:<br />' 
                    . $media[0]->title . '<br />' . $mediaid . ': ' . $media[0]->media_class_id 
                    . '<br />' . $media_type . ': ' . $media[0]->media_type . '<br /><br />' . $t 
                    . ': "' . $item_review[0]->title . '"<br /><br />  ' . $r . ': [' . $rating 
                    . ']<br /><br / ' . $c . ':<br /> ' . $item_review[0]->comment . '<br /><br /> ' 
                    . 'Please log on and edit this review where necessary.', true);
            }
        }
        //********************   end add send mail for admin ************
        //showing the original entries
         mosRedirect("index.php?option=" . $option . "&task=view&tab=getmymediasTab&catid=" 
            . JRequest::getVar('catid') . "&id=" . $review->fk_mediaid . "&Itemid=" . $Itemid 
            ."#tabs-2");
    }
    
    //this function check - is exist books in this folder and folders under this category
    function is_exist_curr_and_subcategory_medias($catid) {
        global $database, $my, $langContent;

        $s = getWhereUsergroupsString("c");

        if (isset($langContent)) {
            $lang = $langContent;

            $lang = "AND ( c.langDescription='$lang' or c.langDescription='*' 
                        or c.langDescription is null or c.langDescription='')"
                    . "AND ( m.langDescription='$lang' or m.langDescription='*' or m.langDescription='\'*\'' 
                                            or m.langDescription is null or m.langDescription='')";
        } else {
            $lang = "";
        }

        $query = "SELECT c.id FROM #__medialibrary_main_categories AS c
        \n JOIN #__medialibrary_categories as mc ON c.id = mc.catid" 
        . "\n LEFT JOIN #__medialibrary AS m ON m.id = mc.mediaid" 
        . "\n WHERE m.published='1' AND m.approved='1' AND section='com_medialibrary' 
            AND c.id='$catid' AND c.published='1'  $lang  and ($s) " 
        . "\n GROUP BY c.id";
        $database->setQuery($query);
        $categories = $database->loadObjectList();
        if (count($categories) != 0) return true;
        $query = "SELECT id " . "FROM #__medialibrary_main_categories AS cc " 
            . " WHERE section='com_medialibrary' AND parent_id='$catid' AND published='1'";
        $database->setQuery($query);
        $categories = $database->loadObjectList();
        if (count($categories) == 0) return false;
        foreach($categories as $k) {
            if (is_exist_curr_and_subcategory_medias($k->id)) return true;
        }
        return false;
    } //end function
    //*****************************************************************************
    //this function check - is exist folders under this category
    function is_exist_subcategory_books($catid) {
        global $database, $my, $langContent;

        $s = getWhereUsergroupsString("c");


        if (isset($langContent)) {
            $lang = $langContent;

            $lang = "AND ( c.langDescription='$lang' or c.langDescription='*' 
                        or c.langDescription is null or c.langDescription='')"
                    . "AND ( m.langDescription='$lang' or m.langDescription='*' or m.langDescription='\'*\'' 
                                            or m.langDescription is null or m.langDescription='')";
        } else {
            $lang = "";
        }


        $query = "SELECT m.*, COUNT(m.id) AS numlinks FROM #__medialibrary_main_categories AS c" 
            . " join #__medialibrary_categories as mc on mc.catid=c.id " 
            . "\n  JOIN #__medialibrary AS m ON m.id = mc.mediaid" 
            . "\n WHERE mc.catid=c.id AND m.published='1' AND m.approved='1' AND 
                section='com_medialibrary' AND parent_id='$catid' AND c.published='1' $lang AND ($s) " 
            . "\n GROUP BY c.id" 
            . "\n ORDER BY c.ordering";
        $database->setQuery($query);
        $categories = $database->loadObjectList();
        if (count($categories) != 0) return true;
        $query = "SELECT id " . "FROM #__medialibrary_main_categories AS cc " 
            . " WHERE section='com_medialibrary' AND parent_id='$catid' AND published='1'";
        $database->setQuery($query);
        $categories = $database->loadObjectList();
        if (count($categories) == 0) return false;
        foreach($categories as $k) {
            if (is_exist_subcategory_books($k->id)) return true;
        }
        return false;
    } //end function

    /**
     * This function is used to show a list of all books
     */
    function listCategories($option, $catid, $layout) {

        global $mainframe, $database, $my, $acl, $langContent;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration;
        addTitleAndMetaTags();

       

        if (isset($langContent)) {
            $lang = $langContent;

            // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
            // $database->setQuery($query);
            // $lang = $database->loadResult();
            $lang = "AND ( c.langDescription='$lang' or c.langDescription='*' 
                        or c.langDescription is null or c.langDescription='')"
                    . "AND ( m.langDescription='$lang' or m.langDescription='*' or m.langDescription='\'*\'' 
                                            or m.langDescription is null or m.langDescription='')";
        } else {
            $lang = "";
        }

        

        $s = getWhereUsergroupsString("c");
        $query = "select m.*, c.id,c.parent_id, COUNT(DISTINCT m.id) AS medias, c.title, c.image, 
            '1' AS display, c.params2"
        . " FROM  #__medialibrary_main_categories as c
        LEFT JOIN #__medialibrary_categories AS mc ON c.id=mc.catid \n
        LEFT JOIN #__medialibrary AS m ON m.id=mc.mediaid AND m.published=1 AND m.approved=1
        WHERE  c.section='com_medialibrary'
          AND c.published=1 $lang AND ({$s})
        GROUP BY c.id \n
        ORDER BY parent_id DESC, c.ordering ";
        $database->setQuery($query);
        $cat_all = $database->loadObjectList();

        foreach ($cat_all as $k1 => $cat_item1) {
           $cat_all[$k1]->display = is_exist_curr_and_subcategory_medias($cat_all[$k1]->id);
          }

        $currentcat = new stdClass();
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params->loadString($menu->params);
            $params->def('header', $menu_name); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        } else {
            $menu = new mosMenu($database); // for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', $menu_name); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        }
        // page header
        $currentcat->header = $params->get('header');
        //add for show in category picture
        if (($medialibrary_configuration['cat_pic']['show'])) $params->def('show_cat_pic', 1);
        // page description
        $currentcat->descrip = _MEDIALIBRARY_DESC;
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        if (checkAccess_ML($medialibrary_configuration['search_field']['registrationlevel'], 
                'RECURSE', userGID_ML($my->id), $acl) && 
                $medialibrary_configuration['search_field']['show']) {
            $params->def('search_fieldshow', 1);
        }
        if (checkAccess_ML($medialibrary_configuration['advsearch']['registrationlevel'], 'RECURSE', 
                userGID_ML($my->id), $acl) && $medialibrary_configuration['advsearch']['show']) {
            $params->def('advsearch_show', 1);
        }

        $params->def('allcategories01', "{loadposition com_medialibrary_all_categories_01,xhtml}");
        $params->def('allcategories02', "{loadposition com_medialibrary_all_categories_02,xhtml}");
        $params->def('allcategories03', "{loadposition com_medialibrary_all_categories_03,xhtml}");
        $params->def('allcategories04', "{loadposition com_medialibrary_all_categories_04,xhtml}");
        $params->def('allcategories05', "{loadposition com_medialibrary_all_categories_05,xhtml}");
        $params->def('allcategories06', "{loadposition com_medialibrary_all_categories_06,xhtml}");
        $params->def('allcategories07', "{loadposition com_medialibrary_all_categories_07,xhtml}");
        $params->def('allcategories08', "{loadposition com_medialibrary_all_categories_08,xhtml}");
        $params->def('allcategories09', "{loadposition com_medialibrary_all_categories_09,xhtml}");
        $params->def('allcategories10', "{loadposition com_medialibrary_all_categories_10,xhtml}");

        HTML_medialibrary::showCategories($params, $cat_all, $catid, $tabclass, $currentcat, $layout);
    }

    function constructMediaPathway($cat) {
        global $mainframe, $database, $option, $Itemid, $mosConfig_absolute_path;
        $path_way = $mainframe->getPathway();
        $query = "SELECT * FROM #__medialibrary_main_categories WHERE section = 'com_medialibrary' AND 
            published = 1";
        $database->setQuery($query);
        $rows = $database->loadObjectlist('id');
        $pid = $cat->id;
        $pathway = array();
        $pathway_name = array();
        while ($pid != 0) {
            $cat = $rows[$pid];
            $pathway[] = JRoute::_("index.php?option=" . $option . "&task=alonecategory&catid=" 
                . $cat->id . "&Itemid=" . $Itemid);
            //$pathway[] = JRoute::_("index.php?option=".$option."&task=alonecategory&Itemid=".$Itemid);
            $pathway_name[] = $cat->name;
            $pid = $cat->parent_id;
        }
        $pathway = array_reverse($pathway);
        $pathway_name = array_reverse($pathway_name);
        for ($i = 0, $n = count($pathway);$i < $n;$i++) {
            $path_way->addItem($pathway_name[$i], $pathway[$i]);
        }
    }
    
    /*************************Show all media******************************/
    function showAllMedia($option, $printItem, $layout) {

      

        global $mainframe, $database, $acl, $my, $params, $limit, $total, $limitstart, $langContent;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $doc;
        $doc->addStyleSheet($mosConfig_live_site 
                . '/components/com_medialibrary/includes/medialibrary.css');
        $query = "SELECT params FROM #__menu WHERE id =" . $Itemid;
        $database->setQuery($query);
        $params2 = $database->loadResult();
        $object_params = json_decode($params2);
        if (isset($object_params->allgame) && $object_params && $object_params->allgame != '') 
            $layout = $object_params->allgame;
        if (!$layout) $layout = $medialibrary_configuration['view_type_game'];
        addTitleAndMetaTags();
        $item_session = JFactory::getSession();
        $sort_arr = $item_session->get('ml_game_mediasort', '');
        if (is_array($sort_arr)) {
            $tmp1 = protectInjectionWithoutQuote('order_direction');
            if ($tmp1 != '') {
                $sort_arr['order_direction'] = $tmp1;
            }
            $tmp1 = protectInjectionWithoutQuote( 'order_field');
            if ($tmp1 != '') {
                $sort_arr['order_field'] = $tmp1;
            }
            $item_session->set('ml_game_mediasort', $sort_arr);
        } else {
            $sort_arr = array();
            $ordertype = $GLOBALS['all_order_type'];
            if ($ordertype == 0) {
                $sort_arr['order_field'] = 'title';
                $sort_arr['order_direction'] = 'asc';
            } else if ($ordertype == 1) {
                $sort_arr['order_field'] = 'title';
                $sort_arr['order_direction'] = 'desc';
            } else if ($ordertype == 2) {
                $sort_arr['order_field'] = 'people_name';
                $sort_arr['order_direction'] = 'asc';
            } else if ($ordertype == 3) {
                $sort_arr['order_field'] = 'people_name';
                $sort_arr['order_direction'] = 'desc';
            }
            $item_session->set('ml_game_mediasort', $sort_arr);
        }
        if ($sort_arr['order_field'] == "price") {
            $sort_string = "CAST( " . $sort_arr['order_field'] . " AS DECIMAL(15,2))" . " " 
                . $sort_arr['order_direction'];
        } else if ($sort_arr['order_field'] == "title") {
            $sort_string = 'other_table.'.$sort_arr['order_field'] . " " . $sort_arr['order_direction'];
        } else {
            $sort_string = 'p.'.$sort_arr['order_field'] . " " . $sort_arr['order_direction'];
        }
        //getting groups of user
        $s = getWhereUsergroupsString("c");

        

        if (isset($langContent)) {
            $lang = $langContent;

//            $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
//            $database->setQuery($query);
//            $lang = $database->loadResult();

            $lang_m = "AND ( m.langDescription='$lang' or m.langDescription='*' or ".
                    " m.langDescription is null or m.langDescription='')";
            $lang = "AND ( other_table.langDescription='$lang' or other_table.langDescription='*' or 
                other_table.langDescription is null or other_table.langDescription='')";
        } else {
            $lang = "";
            $lang_m = "";
        }


        $query = "SELECT COUNT(DISTINCT other_table.id)  FROM #__medialibrary AS other_table " 
       . "\nLEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid=other_table.id" 
       . "\nLEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid" 
       . "\nWHERE other_table.published='1' AND other_table.approved='1' AND c.published='1' AND ({$s}) $lang";
        $database->setQuery($query);
        $total = $database->loadResult();

        $query = "SELECT library.id, library.media_type, library.media_id,"
        . " library.hits, library.checked_out, GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
        . " library.fk_lendid,library.date, 
            GROUP_CONCAT(p.people_name SEPARATOR ', ') AS game_studio_name,  "
        . " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, "
        . " other_table.URL as URL, other_table.imageURL as imageURL, price,priceunit, catid,
            GROUP_CONCAT(p.id SEPARATOR ', ') AS game_studio_id, p.id as author_id, p.people_name as people_name"
        . " FROM #__medialibrary AS library "
        . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
        . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid "
        . " LEFT JOIN (
                SELECT id,title,rating,URL,imageURL,'game' as type, price,priceunit, 
                langDescription FROM #__medialibrary_game "
            . " UNION all SELECT id,title,rating,URL,imageURL,'music' as type, price,priceunit, 
                langDescription   FROM #__medialibrary_music "
            . " UNION all SELECT id,title,rating,URL,imageURL,'book'  as type, price,priceunit, 
                langDescription  FROM #__medialibrary_book "
            . " UNION all SELECT id,title,rating,URL,imageURL,'video' as type, price,priceunit, 
                langDescription  FROM #__medialibrary_video 
            ) "
        . " AS other_table ON other_table.id = library.media_id and 
            other_table.type = library.media_type"
        ."  LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = library.id "
        ."  LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
        . " WHERE library.published='1' $lang AND library.approved='1' "
        . "     AND c.published='1' AND ({$s}) " . " GROUP BY library.id " . " ORDER BY " . 
                $sort_string;
        $interesting_source = array();
        if ($layout == 'video-play' || $layout == 'video-play-list' ||
            $layout == 'music-play' || $layout == 'music-play-list') {
            $type_connect_media = 'game';
            $pageNav = actions_for_player($interesting_source, $query, $type_connect_media,$layout, $lang_m);
        } else {
            $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
            $query .= " LIMIT $pageNav->limitstart,$pageNav->limit;";
        }
        $database->setQuery($query);
        $medias = $database->loadObjectList(); // game_studio_name game_studio_id
        sort_media_items($medias, $layout, $lang_m, $interesting_source);

        $category = new stdClass();
        //getting the current category informations
        $category->title = $category->name = _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL . " " 
            . _MEDIALIBRARY_LABEL_MEDIA_TYPE; // _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME
        $category->description = "";
        $category->image = "";
        if (isset($medias[0])){
            $category->catid = $medias[0]->catid;
        } else {
            $category->catid = 0;
        }

        $currentcat = NULL;
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
        }

        //*************************   end add for  Manager mail to: button 'mail to'  
        $params->def('header', $menu_name); // for 1.6
        $params->def('pageclass_sfx', '');
        $params->def('category_name', $category->title);
        $params->def('show_search', '1');
        if (checkAccess_ML($medialibrary_configuration['search_field']['registrationlevel'], 'RECURSE', 
                userGID_ML($my->id), $acl) && $medialibrary_configuration['search_field']['show']) {
            $params->def('search_fieldshow', 1);
        }
        if (checkAccess_ML($medialibrary_configuration['advsearch']['registrationlevel'], 'RECURSE', 
                userGID_ML($my->id), $acl) && $medialibrary_configuration['advsearch']['show']) {
            $params->def('advsearch_show', 1);
        }
        
        $path_way = $mainframe->getPathway();
        $path_way->addItem($category->name, " ");
        if (($medialibrary_configuration['lendstatus']['show'])) {
            $params->def('show_lendstatus', 1);
            if (checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_lendrequest', 1);
            }
        }
        
        //add for show in category picture
        if (($medialibrary_configuration['cat_pic']['show'])) $params->def('show_cat_pic', 1);
        $params->def('show_rating', 1);
        $params->def('hits', 1);
        $params->def('back_button', $mainframe->getCfg('back_button'));
        $params->def('media_type', 'game');
        $currentcat = new stdClass();
        $currentcat->descrip = $category->description;
        // page image
        $currentcat->img = null;
        $path = $mosConfig_live_site . '/images/stories/';
        if ($category->image != null && count($category->image) > 0) {
            $currentcat->img = $path . $category->image;
            $currentcat->align = $category->image_position;
        }
        $currentcat->header = '';
        if ($category->name <> '') {
            $currentcat->header = $category->name;
        } else {
            $currentcat->header = $params->get('header');
        }
        $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header . ": ") : ("")) 
            . $category->title;
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        $params->def('sort_arr_order_direction', $sort_arr['order_direction']);
        $params->def('sort_arr_order_field', $sort_arr['order_field']);
        $params->def('view_type', $medialibrary_configuration['view_type']);
        // print_r($medias);exit;
        $task = 'allmedia';
        
        switch ($printItem) {
            default: 
                HTML_medialibrary::displayMedias($medias, $currentcat, $params, $tabclass, 0, 0, 
                    false, $pageNav, "allgame", $layout, $category, $task);
            break;
        }
    }
    /*************************Show all games******************************/
    function actions_for_player(&$interesting_source, &$query, $type_connect_media, $layout, $lang_m){
        global $database, $medialibrary_configuration, $limitstart;
        if (strpos($layout, 'video') !== false){
            $query2 = " SELECT vs.id FROM #__medialibrary_video_source as vs " 
                    ."  LEFT JOIN #__medialibrary as m ON vs.fk_media_id = m.id "
                    ." WHERE 1 $lang_m "
                    ."  AND m.media_type = '$type_connect_media' "
                    . " GROUP BY vs.sequence_number";
        } else {
            $query2 = " SELECT vs.id FROM #__medialibrary_audio_source as vs " 
                    ."  LEFT JOIN #__medialibrary as m ON vs.fk_media_id = m.id "
                    ."  WHERE 1 $lang_m "
                    ."  AND m.media_type = '$type_connect_media' "
                    ."  GROUP BY vs.sequence_number";
        }
        $database->setQuery($query2);
        $media_ids =  $database->loadColumn();
        //////////
        if ($media_ids != []){
            $total = count($media_ids);
            // $media_ids = implode(',', $media_ids);
            if (strpos($layout, 'video') !== false){
                $limit = $medialibrary_configuration['video_player']['items'];
                $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
                $query2 = " SELECT vs.id, fk_media_id, vs.id, sequence_number, vs.title "
                        . " FROM #__medialibrary_video_source as vs " 
                        . " LEFT JOIN #__medialibrary as m ON vs.fk_media_id = m.id "
                        . " WHERE 1 $lang_m "
                        . " AND m.media_type = '$type_connect_media' "
                        . " GROUP BY vs.sequence_number"
                        . " LIMIT $pageNav->limitstart, $pageNav->limit;";
            } else {
                $limit = $medialibrary_configuration['audio_player']['items'];
                $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
                $query2 = " SELECT vs.id, fk_media_id, vs.id, sequence_number, vs.title "
                        . " FROM #__medialibrary_audio_source as vs " 
                        . " LEFT JOIN #__medialibrary as m ON vs.fk_media_id = m.id "
                        . " WHERE 1 $lang_m "
                        . " AND m.media_type = '$type_connect_media' "
                        . " GROUP BY vs.sequence_number"
                        . " LIMIT $pageNav->limitstart, $pageNav->limit;";
            }
            $database->setQuery($query2);
            $medias = $database->loadObjectList();
            $media_ids = array();
            foreach ($medias as $value) {
                array_push($interesting_source, $value->sequence_number);
                array_push($media_ids, $value->fk_media_id);
            } 
            $QUERY = explode('WHERE', $query);
            $QUERY[count($QUERY)-1] = " library.id IN ('".implode("', '", $media_ids)."') AND "
                                        .$QUERY[count($QUERY)-1];
            $query = implode('WHERE', $QUERY);
            return $pageNav;
        }
    }
    function sort_media_items(&$medias, $layout, $lang_m, $interesting_source){
        global $database, $medialibrary_configuration, $limitstart;
        $people_type_for_id = ['producer_id' => 'producer_name', 
                               'actor_id' => 'actor_name', 
                               'studio_id' => 'studio_name', 
                               'director_id' => 'director_name', 
                               'artist_id' => 'artist_name', 
                               'game_studio_id' => 'game_studio_name', 
                               'author_id' => 'author_name'];
        $type_for_id = ['producer_id' => 'producer', 
                        'actor_id' => 'actor', 
                        'studio_id' => 'studio', 
                        'director_id' => 'director', 
                        'artist_id' => 'artist', 
                        'game_studio_id' => 'game_studio', 
                        'author_id' => 'author'];
        foreach ($medias as $media) {
            $peope_type_arr = [];
            foreach (['producer_id', 'actor_id', 'studio_id', 'director_id', 'artist_id',
                              'game_studio_id', 'author_id'] as $peoples_id) {
                if (isset($media->$peoples_id)){
                    if(strpos($media->$peoples_id,',')){
                        $ps_id = explode(',',$media->$peoples_id);
                    } else {
                        $ps_id = array($media->$peoples_id);
                    }
                    if (isset($media->{$people_type_for_id[$peoples_id]})){
                        if (strpos($media->{$people_type_for_id[$peoples_id]},',')){
                          $ps_name = explode(',',$media->{$people_type_for_id[$peoples_id]});
                        } else {
                          $ps_name = array($media->{$people_type_for_id[$peoples_id]});
                        }
                        $peole_array = [];
                        for ($i=0; $i < count($ps_id); $i++) { 
                            $peole_array[] = ['id' => $ps_id[$i], 'name' => $ps_name[$i]];
                        }
                        $peope_type_arr[$type_for_id[$peoples_id]] = $peole_array;
                    }
                }
            }
            $media->people_by_types = $peope_type_arr ;   
            if(!empty($media->id)) {
                $query_a = "SELECT a.id, src, sequence_number ,title
                    FROM #__medialibrary_audio_source AS a
                  LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
                  WHERE a.fk_media_id ='".$media->id."' $lang_m";
                $database->setQuery($query_a);
                $temp_audios = $database->loadObjectlist();
                $media->group_audios = [];
                if ($temp_audios){
                    foreach ($temp_audios as $temp_audio) {
                        if ($temp_audio->sequence_number){
                            if(!isset($interesting_source) || 
                                    in_array($temp_audio->sequence_number, $interesting_source)){
                                $media->group_audios[$temp_audio->sequence_number][] = $temp_audio;
                            }
                        }   
                    }
                }
                $query_a = "SELECT a.id, src, youtube, sequence_number ,title
                    FROM #__medialibrary_video_source AS a
                  LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
                  WHERE a.fk_media_id ='".$media->id."' $lang_m";
                $database->setQuery($query_a);
                $temp_videos = $database->loadObjectlist();
                $media->group_videos = [];
                if ($temp_videos){
                    foreach ($temp_videos as $temp_video) {
                        if ($temp_video->sequence_number){
                            if(!isset($interesting_source) || 
                                    in_array($temp_video->sequence_number, $interesting_source)){
                                $media->group_videos[$temp_video->sequence_number][] = $temp_video;
                            }
                        }   
                    }
                }
                $query_a = "SELECT a.id, sequence_number,fk_media_id,src,kind,scrlang,label
                    FROM #__medialibrary_track_source AS a
                  LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
                  WHERE a.fk_media_id =".$media->id;
                $database->setQuery($query_a);
                $temp_tracks = $database->loadObjectlist();
                $media->group_tracks = [];
                if ($temp_tracks){
                    foreach ($temp_tracks as $temp_track) {
                        if ($temp_track->sequence_number){
                            $media->group_tracks[$temp_track->sequence_number][] = $temp_track;
                        } else {
                            $media->group_tracks[$temp_track->id][] = $temp_track;
                        }
                    }
                }
            }
        }
    }
    /************************Show all video*************************/
    /************************Show all music**************************/
    /**
     * This function is used to show a list of all books
     */
    function showCategory($catid, $printItem, $layout) {
        global $mainframe, $database, $acl, $my, $params, $limit, $total, $limitstart, $langContent;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $doc;

      
        if (isset($langContent)) {
        $lang = $langContent;
        // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
        // $database->setQuery($query);
        // $lang = $database->loadResult();
        $lang = "AND ( other_table.langDescription='$lang' or other_table.langDescription='*' or 
            other_table.langDescription is null or other_table.langDescription='')";
        } else {
            $lang = "";
        }
        $doc->addStyleSheet($mosConfig_live_site 
            . '/components/com_medialibrary/includes/medialibrary.css');
        addTitleAndMetaTags();
        $layout = '';
        $query = "SELECT params FROM #__menu WHERE id =" . $Itemid;
        $database->setQuery($query);
        $params2 = $database->loadResult();
        $object_params = json_decode($params2);

        if (isset($object_params->alonecategory) && $object_params && 
                $object_params->alonecategory != '')
            $layout = $object_params->alonecategory;
        if (!$layout) {
            $query = "SELECT params2 FROM #__medialibrary_main_categories WHERE id =" 
                . $catid;;
            $database->setQuery($query);
            $params2 = $database->loadResult();
            $object_params = unserialize($params2);
            if($object_params){
                $layout = $object_params->alonecategory;
            }
        }

        if (!$layout) $layout = $medialibrary_configuration['view_type_single'];
        //getting the current category informations
        if (version_compare(JVERSION, '1.6', 'lt')) {
            if ($catid == '') {
                $catid = 47;
            }
        }

        $database->setQuery("SELECT * FROM #__medialibrary_main_categories WHERE id='$catid'");
        $category = $database->loadObjectList();
        if (isset($category[0])) $category = $category[0];
        else {
            echo _MEDIALIBRARY_ERROR_ACCESS_PAGE;
            return;
        }
        if ($category->params == '')
                $category->params = '-2';
        if (!checkAccess_ML($category->params, 'RECURSE', userGID_ML($my->id), $acl)) {
            echo _MEDIALIBRARY_ERROR_ACCESS_PAGE;
            return;
        }
        $item_session = JFactory::getSession();
        $sort_arr = $item_session->get('ml_MEDIALIBRARY_CATEGORY_mediasort', '');
        if (is_array($sort_arr)) {

            $tmp1 = protectInjectionWithoutQuote('order_direction');
            if ($tmp1 != '') {
                $sort_arr['order_direction'] = $tmp1;
            }
            $tmp1 = protectInjectionWithoutQuote('order_field');
            if ($tmp1 != '') {
                $sort_arr['order_field'] = $tmp1;
            }
            $item_session->set('ml_MEDIALIBRARY_CATEGORY_mediasort', $sort_arr);
        } else {
            $sort_arr = array();
            $ordertype = $GLOBALS['all_order_type'];
            if ($ordertype == 0) {
                $sort_arr['order_field'] = 'title';
                $sort_arr['order_direction'] = 'asc';
            } else if ($ordertype == 1) {
                $sort_arr['order_field'] = 'title';
                $sort_arr['order_direction'] = 'desc';
            } else if ($ordertype == 2) {
                $sort_arr['order_field'] = 'ext1';
                $sort_arr['order_direction'] = 'asc';
            } else if ($ordertype == 3) {
                $sort_arr['order_field'] = 'ext1';
                $sort_arr['order_direction'] = 'desc';
            }
            $item_session->set('ml_MEDIALIBRARY_CATEGORY_mediasort', $sort_arr);


        }
        if ($sort_arr['order_field'] == "price") $sort_string = "CAST( " . $sort_arr['order_field'] 
                . " AS DECIMAL(15,2))" . " " . $sort_arr['order_direction'];
        else $sort_string = $sort_arr['order_field'] . " " . $sort_arr['order_direction'];
        //getting groups of user
        $s = getWhereUsergroupsString("c");
        $query = "SELECT COUNT(DISTINCT library.id)"
      . " FROM #__medialibrary AS library "
        . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
        . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id = mc.catid "
        . " LEFT JOIN (SELECT id,title,rating,URL,imageURL,'game' as type, price,priceunit, 
            langDescription FROM #__medialibrary_game "
        . " UNION all SELECT id,title,rating,URL,imageURL,'music' as type, price,priceunit, 
            langDescription   FROM #__medialibrary_music "
        . " UNION all SELECT id,title,rating,URL,imageURL,'book'  as type, price,priceunit, 
            langDescription  FROM #__medialibrary_book "
        . " UNION all SELECT id,title,rating,URL,imageURL,'video' as type, price,priceunit, 
            langDescription  FROM #__medialibrary_video ) "
        . " AS other_table ON other_table.id = library.media_id and 
            other_table.type = library.media_type"
        . " WHERE  library.published='1'  AND library.approved='1' "
        . " AND c.published='1' AND mc.catid = '{$catid}' and ({$s}) $lang";
        $database->setQuery($query);
        $total = $database->loadResult();

        $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
        $query = "SELECT library.id, library.media_type, library.media_id,"
        . " library.hits, library.checked_out, GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
        . " library.fk_lendid,library.date,"
        . " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, "
        . " other_table.URL as URL, other_table.imageURL as imageURL, price,priceunit, 
            p.id as author_id, p.id as author_id, p.people_name,p.id as people_id, catid  "
        . " FROM #__medialibrary AS library "
        . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
        . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id = mc.catid "
        . " LEFT JOIN (SELECT id,title,rating,URL,imageURL,'game' as type, price,
            priceunit, langDescription FROM #__medialibrary_game "
        . " UNION all SELECT id,title,rating,URL,imageURL,'music' as type, price,
            priceunit, langDescription   FROM #__medialibrary_music "
        . " UNION all SELECT id,title,rating,URL,imageURL,'book'  as type, price,
            priceunit, langDescription  FROM #__medialibrary_book "
        . " UNION all SELECT id,title,rating,URL,imageURL,'video' as type, price,
            priceunit, langDescription  FROM #__medialibrary_video ) "
        . " AS other_table ON other_table.id = library.media_id and 
            other_table.type = library.media_type"
        ."  LEFT JOIN #__medialibrary_people_connect AS pc 
            ON pc.fk_media_id = library.id "
            ." LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
        . " WHERE  library.published='1'  AND library.approved='1' "
        . " AND c.published='1' AND mc.catid = '{$catid}' and ({$s}) "
        .$lang. " GROUP BY library.id " . " ORDER BY " . $sort_string 
            . " LIMIT $pageNav->limitstart,$pageNav->limit;";
        $database->setQuery($query);
        $medias = $database->loadObjectList();

        //********************************************* 
        // metka rating cat
        for ($i = 0;$i < count($medias, 1);$i++) {
            if ($medias[$i]->rating == 0) {
                $query = "SELECT sum(rating) as sum, count(rating) as counts 
                    FROM #__medialibrary_review WHERE fk_mediaid = " . $medias[$i]->id;
                $database->setQuery($query);
                $temp = $database->loadObjectList();
                if ($temp[0]->sum == "") $temp[0]->sum = 0;
                if ($temp[0]->counts <> 0) $medias[$i]->rating = round($temp[0]->sum / $temp[0]->counts);
                else $medias[$i]->rating = 0;
            }
        }
        //*********************************************************************** 
        //getting the current category informations
        $query = "SELECT * FROM #__medialibrary_main_categories WHERE id='$catid'";
        $database->setQuery($query);
        $category = $database->loadObjectList();
        $category = $category[0];
        if (isset($medias[0])){
            $category->catid = $medias[0]->catid;
        } else {
            $category->catid = 0;
        }

        $query = "select m.*, c.id,c.parent_id, COUNT(mc.mediaid) AS medias, c.title, 
            c.image, '1' AS display" .
        " FROM  #__medialibrary_main_categories as c
        LEFT JOIN #__medialibrary_categories AS mc ON c.id=mc.catid \n
        LEFT JOIN #__medialibrary AS m ON m.id=mc.mediaid AND m.published=1 AND m.approved=1
        WHERE  c.section='com_medialibrary'
          AND c.published=1 AND ({$s})
        GROUP BY c.id \n
        ORDER BY parent_id DESC, c.ordering ";
        $database->setQuery($query);
        $cat_all = $database->loadObjectList();
        foreach($cat_all as $k1 => $cat_item1) {
            if (is_exist_curr_and_subcategory_medias($cat_all[$k1]->id)) {
                foreach($cat_all as $cat_item2) {
                    if ($cat_item1->id == $cat_item2->parent_id) {
                        $cat_all[$k1]->medias+= $cat_item2->medias;
                    }
                }
            } else $cat_all[$k1]->display = 0;
        }
        //$currentcat = NULL;
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params->loadString($menu->params);
            $params->def('header', $menu_name); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('category_name', $category->title);
            $params->def('show_search', '1');
        } else {
            $menu = new mosMenu($database); // for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', $menu_name); // for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('category_name', $category->title);
            $params->def('show_search', '1');
        }
        if (($medialibrary_configuration['lendstatus']['show'])) {
            $params->def('show_lendstatus', 1);
            if (checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_lendrequest', 1);
            }
        }

        if (checkAccess_ML($medialibrary_configuration['search_field']['registrationlevel'], 'RECURSE',
                 userGID_ML($my->id), $acl) && $medialibrary_configuration['search_field']['show']) {
            $params->def('search_fieldshow', 1);
        }
        if (checkAccess_ML($medialibrary_configuration['advsearch']['registrationlevel'], 'RECURSE',
                 userGID_ML($my->id), $acl) && $medialibrary_configuration['advsearch']['show']) {
            $params->def('advsearch_show', 1);
        }
        //add to path category name
        constructMediaPathway($category);
        $path_way = $mainframe->getPathway();
        $path_way->addItem($category->name, " ");
        //add for show in category picture
        if (($medialibrary_configuration['cat_pic']['show'])) $params->def('show_cat_pic', 1);
        $params->def('show_rating', 1);
        $params->def('hits', 1);
        $params->def('back_button', $mainframe->getCfg('back_button'));
        $currentcat = new stdClass();
        $currentcat->descrip = $category->description;
        // page image
        $currentcat->img = null;
        $path = $mosConfig_live_site . '/images/stories/';
        if ($category->image != null && count($category->image) > 0) {
            $currentcat->img = $path . $category->image;
            $currentcat->align = $category->image_position;
        }
        $currentcat->header = '';
        if ($category->name <> '') {
            $currentcat->header = $category->name;
        } else {
            $currentcat->header = $params->get('header');
        }
        $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header 
                . ": ") : ("")) . $category->title;
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        $params->def('sort_arr_order_direction', $sort_arr['order_direction']);
        $params->def('sort_arr_order_field', $sort_arr['order_field']);
        $params->def('view_type', $medialibrary_configuration['view_type']);
        $params->def('singlecategory01', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_01,xhtml}");
        $params->def('singlecategory02', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_02,xhtml}");
        $params->def('singlecategory03', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_03,xhtml}");
        $params->def('singlecategory04', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_04,xhtml}");
        $params->def('singlecategory05', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_05,xhtml}");
        $params->def('singlecategory06', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_06,xhtml}");
        $params->def('singlecategory07', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_07,xhtml}");
        $params->def('singlecategory08', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_08,xhtml}");
        $params->def('singlecategory09', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_09,xhtml}");
        $params->def('singlecategory10', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_10,xhtml}");
        $params->def('singlecategory11', 
            "{loadposition com_medialibrary_single_MEDIALIBRARY_CATEGORY_11,xhtml}");



        
        switch ($printItem) {
            default:
                $cat_name = "";

                HTML_medialibrary::displayMedias($medias, $currentcat, $params, $tabclass, $catid, 
                        $cat_all, is_exist_subcategory_books($catid), $pageNav, $cat_name, $layout, 
                        $category);
            break;
        }
    }


    function showItemML($id, $catid, $printItem, $layout = 'default') {
        global $mainframe, $database, $my, $acl, $option;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $doc;
        $doc->addStyleSheet($mosConfig_live_site 
                . '/components/com_medialibrary/includes/medialibrary.css');
        addTitleAndMetaTags();
        //for 1.6
        $mosConfig_live_site = JURI::root(true);
        $doc = JFactory::getDocument();
        //$doc->addStyleSheet( $mosConfig_live_site.'/components/com_medialibrary/includes/custom.css' );
        $path_way = $mainframe->getPathway(); // variant 2
        // --
        if (!empty($catid)) {
            //add to path category name
            //getting the current category informations
          $query = "SELECT * FROM #__medialibrary_main_categories WHERE id='$catid'";
            $database->setQuery($query);
            $category = $database->loadObjectList();
            if(!empty($category)) {
              $category = $category[0];
              constructMediaPathway($category);
            }
            if (!empty($category)) {
              $path_way->addItem($category->title, sefRelToAbs('index.php?option=' . $option 
                . '&task=alonecategory&catid=' . $catid . '&Itemid=' . $Itemid)); // for 1.6
              $pathway = sefRelToAbs('index.php?option=' . $option . '&task=alonecategory&catid=' 
                . $category->id . '&Itemid=' . $Itemid);
              $pathway_name = $category->name;
           }
        }
        //Record the hit
        $sql = "UPDATE #__medialibrary SET hits = hits + 1 WHERE id = " . $id . "";
        $database->setQuery($sql);
        $database->query();
        $sql2 = "UPDATE #__medialibrary SET featured_clicks = featured_clicks - 1 
                WHERE featured_clicks > 0 and id = " . $id . "";
        $database->setQuery($sql2);
        $database->query();
        $sql3 = "UPDATE #__medialibrary SET featured_shows = featured_shows - 1 
                WHERE featured_shows > 0";
        $database->setQuery($sql3);
        $database->query();
        //load the Media
        $media = new mosMediaLibrary($database);
        $media->load($id);
        //check access to media
        $access = $media->getAccessMedia();
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }

        if (!checkAccess_ML($access, 'RECURSE', userGID_ML($my->id), $acl)) {
            echo _MEDIALIBRARY_ERROR_ACCESS_PAGE;
            return;
        }
          // print_r($access);exit;
        if(!empty($media->id)) {
        $query_v = "SELECT src,type,youtube FROM #__medialibrary_video_source AS v
          LEFT JOIN  #__medialibrary AS m ON v.fk_media_id=m.id
          WHERE v.fk_media_id =" . $media->id;
        $database->setQuery($query_v);
        $videos = $database->loadObjectList();
        }
        if(!empty($media->id)) {
        $query_a = "SELECT src,type FROM #__medialibrary_audio_source AS a
          LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
          WHERE a.fk_media_id =" . $media->id;
        $database->setQuery($query_a);
        $audios = $database->loadObjectList();
        }
        if(!empty($media->id)) {
        $query_t = "SELECT src,kind,scrlang,label FROM #__medialibrary_track_source AS t
          LEFT JOIN  #__medialibrary AS m ON t.fk_media_id = m.id
          WHERE t.fk_media_id = " . $media->id;
        $database->setQuery($query_t);
        $tracks = $database->loadObjectList();
        }
        if(!empty($media->id)) {
        $query = "select * " .
        " from  #__medialibrary_emedia_files AS f " .
        " where f.fk_emedia_id=" . $media->id .
        " ORDER BY f.id ";
        $database->setQuery($query);
        $emedia_files = $database->loadObjectList();
        }
        //end check access to media
        $media_type_class = '';
        switch ($media->media_type) {
            case 'book':
                $media_type_class = new mosMedialibrary_book($database);
                $media_type_class->load($media->media_id);
                $media_type_class->emediaURL = $emedia_files;
            break;
            case 'video':
                $media_type_class = new mosMedialibrary_video($database);
                $media_type_class->load($media->media_id);
                $media_type_class->emediaURL = $emedia_files;
            break;
            case 'music':
                $media_type_class = new mosMedialibrary_music($database);
                $media_type_class->load($media->media_id);
                $media_type_class->emediaURL = $emedia_files;
            break;
            case 'game':
                $media_type_class = new mosMedialibrary_game($database);
                $media_type_class->load($media->media_id);
                $media_type_class->emediaURL = $emedia_files;
            break;
        }
        // added view type alone media
        if(!empty($media->id)) {
            $query_a = "SELECT a.id, src, youtube, sequence_number ,title
                FROM #__medialibrary_video_source AS a
              LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
              WHERE a.fk_media_id =".$media->id;
            $database->setQuery($query_a);
            $temp_videos = $database->loadObjectlist();
            $media_type_class->group_videos = [];
            if ($temp_videos){
                foreach ($temp_videos as $temp_video) {
                    if ($temp_video->sequence_number){
                        $media_type_class->group_videos[$temp_video->sequence_number][] = $temp_video;
                    } else {
                        $media_type_class->group_videos[$temp_video->id][] = $temp_video;
                    }
                }
            }
            $query_a = "SELECT a.id, sequence_number,fk_media_id,src,kind,scrlang,label 
                FROM #__medialibrary_track_source AS a
              LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
              WHERE a.fk_media_id =".$media->id;
            $database->setQuery($query_a);
            $temp_tracks = $database->loadObjectlist();
            $media_type_class->group_tracks = [];
            if ($temp_tracks){
                foreach ($temp_tracks as $temp_track) {
                    if ($temp_track->sequence_number){
                        $media_type_class->group_tracks[$temp_track->sequence_number][] = $temp_track;
                    } else {
                        $media_type_class->group_tracks[$temp_track->id][] = $temp_track;
                    }
                }
            }    
        }
        if(!empty($media->id)) {
            $query_a = "SELECT a.id, src, sequence_number, title FROM #__medialibrary_audio_source AS a
              LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
              WHERE a.fk_media_id =".$media->id;
            $database->setQuery($query_a);
            $temp_audios = $database->loadObjectlist();
            $media_type_class->group_audios = [];
            if ($temp_audios){
                foreach ($temp_audios as $temp_audio) {
                    if ($temp_audio->sequence_number){
                        $media_type_class->group_audios[$temp_audio->sequence_number][] = $temp_audio;
                    } else {
                        $media_type_class->group_audios[$temp_audio->id][] = $temp_audio;
                    }
                }
            }
        }
        $database->setQuery("SELECT id FROM #__menu 
                WHERE link='index.php?option=com_medialibrary&view=allcategories' AND `published`=1");
        $menuId = $database->loadResult();
        ///// checed display one medias / Anoxi
        $database->setQuery("SELECT params FROM #__menu WHERE id = " . $Itemid . " AND `published`=1");
        $params = $database->LoadResult();
        $typeAloneMedia = 'display' . (string)$media->media_type;
        $params_obj = json_decode($params);
        if ($params_obj) {
            if(isset($params_obj->showsearchmedialayout)){
                $layout = $params_obj->showsearchmedialayout;
            } else {
                @$params_trr = $params_obj->$typeAloneMedia;
                $layout = $params_trr;
            }
        }
        if (!$layout) {
            if ($catid == 0) {
                $query = "SELECT params2 FROM #__medialibrary_main_categories 
                    WHERE title ='" . $media->media_type . "'";
                $database->setQuery($query);
                $params2 = $database->loadResult();
                $typeAloneMedia = 'view_type_display_' . (string)$media->media_type;
                $params_obj = unserialize($params2);
            } else {
                $query = "SELECT params2 FROM #__medialibrary_main_categories WHERE id =" . $catid;
                $database->setQuery($query);
                $params2 = $database->loadResult();
                $typeAloneMedia = 'view_type_display_' . (string)$media->media_type;
                $params_obj = unserialize($params2);
            }
            if ($params_obj) {
                $params_trr = $params_obj->$typeAloneMedia;
                $layout = $params_trr;
            }
            if (!$layout) {
                $temp = 'view_type_display_' . $media->media_type;
                $layout = $medialibrary_configuration[$temp];
            }
        }
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params->loadString($menu->params);
            $params->def('header', $menu_name); //for 1.6
            $params->def('pageclass_sfx', '');
        } else {
            $menu = new mosMenu($database); // for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', $menu_name); //for 1.6
            $params->def('pageclass_sfx', '');
        }
        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        //*************************   end add for  Manager mail to: button 'mail to'  
        if (($medialibrary_configuration['lendstatus']['show'])) {
            $params->def('show_lendstatus', 1);
            if (checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_lendrequest', 1);
            }
        }
        if (($medialibrary_configuration['reviews']['show'])) {
            $params->def('show_reviews', 1);
            if (checkAccess_ML($medialibrary_configuration['reviews']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_inputreviews', 1);
            }
        }
        if (($medialibrary_configuration['emedias']['show'])) {
            $params->def('show_emediastatus', 1);
            if (checkAccess_ML($medialibrary_configuration['emedias']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_emedisrequest', 1);
            }
        }
        if (($medialibrary_configuration['price']['show'])) {
            $params->def('show_pricestatus', 1);
            if (checkAccess_ML($medialibrary_configuration['price']['registrationlevel'], 
                    'RECURSE', userGID_ML($my->id), $acl)) {
                $params->def('show_pricerequest', 1);
            }
        }
        //************   begin add button 'buy now'   ***************************
        if (($medialibrary_configuration['buy_now']['show'])) {
            $params->def('show_buy_now', 1);
            $s = explode(',', $medialibrary_configuration['buy_now']['allow']['categories']);
            foreach($s as $i) {
                if ($i == $catid || $i == - 2) {
                    $params->def('show_input_buy_now', 1);
                    break;
                }
            }
        }
        //************   end add button 'buy now'   ********************************

        if (($medialibrary_configuration['videos_tracks']['allow'] )) {
            $params->def('videos_tracks_allow', 1);
        }
        if (($medialibrary_configuration['audios']['allow'])) {
            $params->def('audios_allow', 1);
        }

        
        $params->def('pageclass_sfx', '');
        $params->def('item_description', 1);
        $params->def('lend_request', $medialibrary_configuration['lendrequest']['registrationlevel']);
        $params->def('show_price', $medialibrary_configuration['price']['show']);
        $params->def('back_button', $mainframe->getCfg('back_button'));
        $params->def('printItem', $printItem);
        $params->def('video_player_skin', $medialibrary_configuration['video_player']['skin']);
        $params->def('audio_player_skin', $medialibrary_configuration['audio_player']['skin']);
        $params->def('playId', protectInjectionWithoutQuote('playId', ''));
        $params->def('playSub', protectInjectionWithoutQuote('playSub', ''));
        $params->def('lenSub', protectInjectionWithoutQuote('lenSub', ''));
        $params->def('currTime', protectInjectionWithoutQuote('currTime', ''));
        if (protectInjectionWithoutQuote('playVideo', '') == ''){$params->def('playVideo', 0);}
        else {$params->def('playVideo', 1);}
        if (protectInjectionWithoutQuote('playAudio', '') == ''){$params->def('playAudio', 0);}
        else {$params->def('playAudio', 1);}
        

        $currentcat = new stdClass();
        // page header
        $currentcat->header = $params->get('header');
         if(isset($category->title)) {
        $currentcat->header = (($currentcat->header == "") ? (ucfirst($category->title) 
                . " : ") : ("")) . $media_type_class->title;}
          else {
        $currentcat->header = (($currentcat->header != "") ? ($currentcat->header 
                . ": ") : ("")) . $media_type_class->title;
          }
        // show the book
        if ($media_type_class->rating == 0) {
            $database->setQuery("SELECT ROUND(avg(rating) ) 
                FROM #__medialibrary_review WHERE published=1 AND fk_mediaid = " . $media->id 
                    . " group by  fk_mediaid  ");
            $media->rating = $database->loadResult();
            if ($media->rating == null) $media->rating = 0;
        }
        $database->setQuery("SELECT username FROM #__users WHERE id ='$media->owner_ID'");
        $media->ownername = $database->loadResult();
        // for 1.6
        $s = getWhereUsergroupsString("mc"); // get user acces level
        $query_c = "SELECT * FROM #__medialibrary_categories AS bc
                LEFT JOIN  #__medialibrary_main_categories  AS mc
                ON bc.catid=mc.id AND ($s)
                WHERE bc.mediaid=" . $media->id;
        $database->setQuery($query_c);
        $categories = $database->loadObjectList();
        $currencys = explode(';', $medialibrary_configuration['currency']);
        foreach($currencys as $row) {
            $row = explode("=", $row);
            if (!empty($row[0])) {
                $row[1] = $media_type_class->price * $row[1];
                $currency[] = $row;
            }
        }

        $query_director = "SELECT p.people_name as  name,p.id as id FROM #__medialibrary_people AS p"
                        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                        ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                        ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'director'"
                        ."\n GROUP BY name";
              // print_r($query_auth);exit;
        $database->setQuery($query_director);
        $media_type_class->directors = $database->loadObjectList();

        $query_actor = "SELECT p.people_name as  name,p.id as id FROM #__medialibrary_people AS p"
                        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                        ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                        ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'actor'"
                        ."\n GROUP BY name";
             //  print_r($query_actor);exit;
        $database->setQuery($query_actor);
        $media_type_class->actors = $database->loadObjectList();

        if ($media->media_type == 'video'){
            $query_studio = "SELECT p.people_name as  name,p.id as id  
                FROM #__medialibrary_people AS p"
                    ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                    ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                    ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'video_studio'"
                ."\n GROUP BY name";
                  // print_r($query_studio);exit;
            $database->setQuery($query_studio);
            $media_type_class->studio = $database->loadObjectList();
        } else {
            $query_studio = "SELECT p.people_name as  name,p.id as id  
                FROM #__medialibrary_people AS p"
                    ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                    ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                    ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'game_studio'"
                ."\n GROUP BY name";
                  // print_r($query_studio);exit;
            $database->setQuery($query_studio);
            $media_type_class->studio = $database->loadObjectList();
        }
        
        $query_producer = "SELECT p.people_name as  name,p.id as id FROM #__medialibrary_people AS p"
                        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                        ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                        ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'producer'"
                        ."\n GROUP BY name";
              // print_r($query_producer);exit;
        $database->setQuery($query_producer);
        $media_type_class->producers = $database->loadObjectList();

        $query_artist = "SELECT p.people_name as  name,p.id as id FROM #__medialibrary_people AS p"
                        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                        ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                        ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'artist'"
                        ."\n GROUP BY name";
              // print_r($query_producer);exit;
        $database->setQuery($query_artist);
        $media_type_class->artists = $database->loadObjectList();

        $query_author = "SELECT p.people_name as  name,p.id as id FROM #__medialibrary_people AS p"
                        ."\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_people_id = p.id "
                        ."\n LEFT JOIN #__medialibrary AS m ON m.id = pc.fk_media_id"
                        ."\n WHERE pc.fk_media_id = ".$media->id. " AND p.type = 'author'"
                        ."\n GROUP BY name";
              // print_r($query_producer);exit;
        $database->setQuery($query_author);
        $media_type_class->authors = $database->loadObjectList();
        $media_type_class->global_id = $media->id;

//print_r($media_type_class);exit;


//      print_r($media_type_class);exit;
        switch ($printItem) {
            default:
                HTML_medialibrary::displayMedia($media, $media_type_class, $tabclass, $params, 
                        $currentcat, $categories, $id, $catid, $videos, $audios, $tracks, $layout);
            break;
        }
    }
    //**************   begin gevi direct url   *************************
    function new_direct_url($id) {
        global $database;
        //load the Media
        $media = new mosMediaLibrary($database);
        $media->load($id);
        $media_type_class = '';
        switch ($media->media_type) {
            case 'book':
                $media_type_class = new mosMedialibrary_book($database);
                $media_type_class->load($media->media_id);
            break;
            case 'video':
                $media_type_class = new mosMedialibrary_video($database);
                $media_type_class->load($media->media_id);
            break;
            case 'music':
                $media_type_class = new mosMedialibrary_music($database);
                $media_type_class->load($media->media_id);
            break;
            case 'game':
                $media_type_class = new mosMedialibrary_game($database);
                $media_type_class->load($media->media_id);
            break;
        }
        header("Location: " . $media_type_class->URL);
    }
    //************   end gevi direct url   ******************************
    function showSearchMedias($options, $catid, $option, $layout = 'default') {
        global $mainframe, $database, $my, $langContent, $acl, $medialibrary_configuration;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $doc;


        $doc->addStyleSheet($mosConfig_live_site 
            . '/components/com_medialibrary/includes/medialibrary.css');
        addTitleAndMetaTags();
        $currentcat = new stdClass();
        // Parameters
        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $params = new JRegistry;
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params->loadString($menu->params);
            $params->def( 'header', $menu_name );//for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        } else {
            $menu = new mosMenu($database); //for 1.6
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
            $params->def('header', $menu_name); //for 1.6
            $params->def('pageclass_sfx', '');
            $params->def('show_search', '1');
            $params->def('back_button', $mainframe->getCfg('back_button'));
        }
        if (checkAccess_ML($medialibrary_configuration['search_field']['registrationlevel'], 'RECURSE',
                 userGID_ML($my->id), $acl) && $medialibrary_configuration['search_field']['show']) {
            $params->def('search_fieldshow', 1);
        }
        //
        $currentcat->descrip = _MEDIALIBRARY_SEARCH_DESC1;
        $currentcat->align = 'right';
        // page image
        $currentcat->img = "" . $mosConfig_live_site 
            . "/components/com_medialibrary/images/medialibrary_logo.png";
        $currentcat->header = $params->get('header');
        $currentcat->header = $currentcat->header . ": " . _MEDIALIBRARY_LABEL_SEARCH;
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');
        $categories[] = mosHTML::makeOption('0', _MEDIALIBRARY_LABEL_SEARCH_MEDIALIBRARY_LABEL_CATEGORY);
        $clist = categoryParentList(0, '', true, $categories);
        if (count($categories) < 1) {
            mosRedirect(sefRelToAbs("index.php?option=categories&section=" . $option 
                . "&Itemid=" . $Itemid . "&err_msg=You must first create category for that section."));
        }
        
        $db = JFactory::getDBO();
        

        $query = "(SELECT price FROM #__medialibrary_book )
                  UNION (SELECT price FROM #__medialibrary_game )
                  UNION (SELECT price FROM #__medialibrary_music )
                  UNION (SELECT price FROM #__medialibrary_video )
                  ORDER BY CAST(price AS DECIMAL(10,2)) DESC";
        $database->setQuery($query);
        if (version_compare(JVERSION, "3.0.0", "lt"))
            $prices = $database->loadResultArray();
        else
            $prices = $database->loadColumn();
        $max_price = $prices[0];
        $min_price = $prices[count($prices)-1];
        $params->def('max_price', intval($max_price)+1);
        $params->def('min_price', intval($min_price));

      HTML_medialibrary::showSearchMedias($params, $currentcat, $clist, $option, $layout);
    }




    function searchMedias($options, $catid, $option, $ownername = '') {
        global $mainframe, $database, $acl, $my, $params, $limit, $total, $limitstart, $langContent;
        global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
        global $cur_template, $Itemid, $medialibrary_configuration, $hide_js, $doc;

        $doc->addStyleSheet($mosConfig_live_site 
                . '/components/com_medialibrary/includes/medialibrary.css');
        addTitleAndMetaTags();
        
        $where = array();
        $item_session = JFactory::getSession();
        $s = getWhereUsergroupsString("c");
        $type_desired = protectInjectionWithoutQuote('type_desired', 'media');
        $sort_arr = $item_session->get('ml_mediasort', '');
        $exactly = protectInjectionWithoutQuote('exactly', '');
        $poisk_search = strtolower(trim(protectInjectionWithoutQuote('searchtext')));
        $printItem = protectInjectionWithoutQuote('printItem');

        if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($database);
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new JRegistry;
            $params->loadString($menu->params);
        } else {
            $menu = new mosMenu($database);
            $menu->load($Itemid);
            $menu_name = set_header_name_ml($menu, $Itemid);
            $params = new mosParameters($menu->params);
        }
        //parameters
        $menu_name = set_header_name_ml($menu, $Itemid);
        $params->def('header', $menu_name); //for 1.6
        $params->def('pageclass_sfx', '');
        $params->def('category_name', _MEDIALIBRARY_LABEL_SEARCH);
        $params->def('search_request', '1');
        $params->def('hits', 1);
        $params->def('show_rating', 1);
                
        $params->def('singleuser01', "{loadposition com_medialibrary_music_play_list_01,xhtml}");
        $params->def('singleuser02', "{loadposition com_medialibrary_single_user_media_02,xhtml}");
        $params->def('singleuser03', "{loadposition com_medialibrary_single_user_media_03,xhtml}");
        $params->def('singleuser04', "{loadposition com_medialibrary_single_user_media_04,xhtml}");
        $params->def('singleuser05', "{loadposition com_medialibrary_single_user_media_05,xhtml}");
        $params->def('singleuser06', "{loadposition com_medialibrary_single_user_media_06,xhtml}");
        $params->def('singlecategory01', "{loadposition com_medialibrary_singlecategory01,xhtml}");
        $params->def('singlecategory02', "{loadposition com_medialibrary_singlecategory02,xhtml}");
        $params->def('singlecategory03', "{loadposition com_medialibrary_singlecategory03,xhtml}");
        $params->def('singlecategory04', "{loadposition com_medialibrary_singlecategory04,xhtml}");
        $params->def('singlecategory05', "{loadposition com_medialibrary_singlecategory05,xhtml}");
        $params->def('singlecategory06', "{loadposition com_medialibrary_singlecategory06,xhtml}");
        $params->def('search_no_found01', "{loadposition com_medialibrary_search_no_found01,xhtml}");
        $params->def('search_no_found02', "{loadposition com_medialibrary_search_mod1,xhtml}");
        $params->def('search_mod1', '{loadposition com_medialibrary_search_mod1,xhtml}');
        $params->def('search_mod2', '{loadposition com_medialibrary_search_mod2,xhtml}');
        $params->def('search_mod3', '{loadposition com_medialibrary_search_mod3,xhtml}');
        
        $params->def('video_player_skin', $medialibrary_configuration['video_player']['skin']);
        $params->def('playId', protectInjectionWithoutQuote('playId', ''));
        $params->def('playVideo', protectInjectionWithoutQuote('playVideo', ''));
        $params->def('playSub', protectInjectionWithoutQuote('$playSub', ''));
        $params->def('lenSub', protectInjectionWithoutQuote('lenSub', ''));
        $params->def('currTime', protectInjectionWithoutQuote('currTime', ''));   
        

        
        $type_type_search = '';
        $has_bean_add = 0;
        $type_search = array();
        if (protectInjectionWithoutQuote('game') != ''){
            $type_type_search .= " SELECT id,title,rating,URL,imageURL,'game' as type, price,
                    priceunit, langDescription FROM #__medialibrary_game ";
            array_push($type_search, 'game');
            $has_bean_add = 1;
        }
        if (protectInjectionWithoutQuote('music') != ''){
            if ($has_bean_add){
                $type_type_search .= ' UNION all ';
            }
            $type_type_search .= " SELECT id,title,rating,URL,imageURL,'music' as type, price,
                priceunit, langDescription   FROM #__medialibrary_music ";
            array_push($type_search, 'music');
            $has_bean_add = 1;
        }
        if (protectInjectionWithoutQuote('book') != ''){
            if ($has_bean_add){
                $type_type_search .= ' UNION all ';
            }
            $type_type_search .= " SELECT id,title,rating,URL,imageURL,'book'  as type, price,
                priceunit, langDescription  FROM #__medialibrary_book ";
            array_push($type_search, 'book');
            $has_bean_add = 1;
        }
        if (protectInjectionWithoutQuote('video') != ''){
            if ($has_bean_add){
                $type_type_search .= ' UNION all ';
            }
            $type_type_search .= " SELECT id,title,rating,URL,imageURL,'video' as type, price,
                priceunit, langDescription  FROM #__medialibrary_video ";
            array_push($type_search, 'video');
            $has_bean_add = 1;
        }
        $where = '';
        if ($exactly){
            $where = " lower(s.title) LIKE '" . $poisk_search . "' ";
            if ($type_desired == 'video') $where .= " OR lower(youtube) LIKE '" . $poisk_search . "' ";
        } else {
            $where .= " lower(s.title) LIKE '%" . $poisk_search . "%' ";
            if ($type_desired == 'video') $where .= " OR lower(youtube) LIKE '" . $poisk_search . "' ";
            $pos = strpos($poisk_search, ' ');
            if ($pos){
                $where .= " OR lower(s.title) LIKE '%". implode('_', explode(' ', $poisk_search))."%' ";
                if ($type_desired == 'video') 
                    $where .= " OR lower(youtube) LIKE '%". implode('_', explode(' ', $poisk_search))."%' ";
            }
        }
        $pricefrom = intval(mosGetParam($_REQUEST, 'pricefrom', ''));
        $priceto = intval(mosGetParam($_REQUEST, 'priceto', ''));
        $where_price = '';
        if ($pricefrom > 0) {
            $where_price .= " AND CAST( other_table.price AS SIGNED) >= $pricefrom ";
        }
        if ($priceto > 0) {
            $where_price .= " AND CAST( other_table.price AS SIGNED) <= $priceto ";
        }

        // $database->setQuery("SELECT language FROM #__menu WHERE id = '$Itemid'");
        // $lang_menu = $database->loadResult();

        if (isset($langContent)) {
             $lang = $langContent;
            // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
            // $database->setQuery($query);
            //$lang = $database->loadResult();
            $lang = "AND ( m.langDescription='$lang' or m.langDescription='*' or ".
            " m.langDescription is null or m.langDescription='')";
        } else {
            $lang = "";
        }
        
        if ($type_desired == 'audio'){
            $query = "  SELECT s.id FROM #__medialibrary_audio_source as s " 
                    ."  LEFT JOIN #__medialibrary as m ON s.fk_media_id = m.id "
                    . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id "
                    . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid and {$s} and c.published='1' "
                    . " WHERE ( $where ) $lang "
                    . " and m.published='1' and m.approved='1' "
                    ."  AND m.media_type IN ('".implode("', '", $type_search)."') "
                    ."  GROUP BY s.sequence_number";
            $database->setQuery($query);
            $media_ids =  $database->loadColumn();
            //////////

                if ($media_ids != []){
                $total = count($media_ids);

                // $media_ids = implode(',', $media_ids);
                $limit = $medialibrary_configuration['audio_player']['items'];
                $pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6


                $query = " SELECT s.id, fk_media_id, s.id, sequence_number, s.title 
                        FROM #__medialibrary_audio_source as s " 
                        ."  LEFT JOIN #__medialibrary as m ON s.fk_media_id = m.id "
                        . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id "
                        . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid and {$s} and c.published='1' "
                        . " WHERE ( $where ) $lang "
                        . " and m.published='1' and m.approved='1' "
                        . "  AND m.media_type IN ('".implode("', '", $type_search)."') "
                        . " GROUP BY s.sequence_number"
                        . " LIMIT $pageNav->limitstart, $pageNav->limit;";
                $database->setQuery($query);
                $medias = $database->loadObjectList();
                $interesting_source = array();

                $media_ids = array();
                foreach ($medias as $value) {
                    array_push($interesting_source, $value->sequence_number);
                    array_push($media_ids, $value->fk_media_id);
                }

                $query = "SELECT library.id, library.media_type, library.media_id,"
                . " library.hits, library.checked_out, c.title, "
                . " library.fk_lendid,library.date, p.people_name, "
                . " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, "
                . " other_table.URL as URL, other_table.imageURL as imageURL, other_table.price ,priceunit,  "
                . " GROUP_CONCAT(actor_people.actor separator ',') as actor_name,  "
                . " GROUP_CONCAT(author_people.author separator ',') as author_name,  "
                . " GROUP_CONCAT(studio_people.studio separator ',') as studio_name,  "
                . " GROUP_CONCAT(game_studio_people.game_studio separator ',') as game_studio_name,  "
                . " GROUP_CONCAT(director_people.director separator ',') as director_name,  "
                . " GROUP_CONCAT(producer_people.producer separator ',') as producer_name, "
                . " GROUP_CONCAT(artist_people.artist separator ',') as artist_name,  "
                . " GROUP_CONCAT(producer_people.id separator ',') as producer_id,  "
                . " GROUP_CONCAT(actor_people.id separator ',') as actor_id,  "
                . " GROUP_CONCAT(author_people.id separator ',') as author_id,  "
                . " GROUP_CONCAT(studio_people.id separator ',') as studio_id,  "
                . " GROUP_CONCAT(game_studio_people.id separator ',') as game_studio_id,  "
                . " GROUP_CONCAT(director_people.id separator ',') as director_id,  "
                . " GROUP_CONCAT(artist_people.id separator ',') as artist_id,  "
                . " catid"
                . " FROM #__medialibrary AS library "
                . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
                . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid "
                . " LEFT JOIN (".$type_type_search. ") AS other_table ON other_table.id = library.media_id and 
                    other_table.type = library.media_type"
                ."  LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = library.id "
                ." LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
                 ."\n LEFT JOIN (select id,  people_name as actor from #__medialibrary_people 
                    where type = 'actor') "
                ."\n as actor_people on actor_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as artist from #__medialibrary_people 
                    where type = 'artist') "
                ."\n as artist_people on artist_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as author from #__medialibrary_people 
                    where type = 'author') "
                ."\n as author_people on author_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as studio from #__medialibrary_people 
                    where type = 'video_studio') "
                ."\n as studio_people on studio_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as game_studio from #__medialibrary_people 
                    where type = 'game_studio') "
                ."\n as game_studio_people on game_studio_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id ,  people_name as producer from #__medialibrary_people 
                    where type = 'producer') "
                ."\n as producer_people on producer_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id ,  people_name as director from #__medialibrary_people 
                    where type = 'director') "
                ."\n as director_people on director_people.id = pc.fk_people_id "
                . " WHERE library.id IN ('".implode("', '", $media_ids)."') $where_price "
                . " GROUP BY library.id";
                if ($type_type_search != ''){
                    $database->setQuery($query);
                    $medias = $database->loadObjectList();
                } else { 
                    $medias = array();
                } 

                $people_type_for_id = ['producer_id' => 'producer_name', 
                                       'actor_id' => 'actor_name', 
                                       'studio_id' => 'studio_name', 
                                       'director_id' => 'director_name', 
                                       'artist_id' => 'artist_name', 
                                       'game_studio_id' => 'game_studio_name', 
                                       'author_id' => 'author_name'];
                $type_for_id = ['producer_id' => 'producer', 
                                'actor_id' => 'actor', 
                                'studio_id' => 'studio', 
                                'director_id' => 'director', 
                                'artist_id' => 'artist', 
                                'game_studio_id' => 'game_studio', 
                                'author_id' => 'author'];

                foreach ($medias as $media) {
                    $peope_type_arr = [];
                    foreach (['producer_id', 'actor_id', 'studio_id', 'director_id', 'artist_id',
                              'game_studio_id', 'author_id'] as $peoples_id) {
                        if (strpos($media->$peoples_id,',')){
                          $ps_id = explode(',',$media->$peoples_id);
                        } else {
                          $ps_id = array($media->$peoples_id);
                        }
                        if (isset($media->{$people_type_for_id[$peoples_id]}) ){
                          if( strpos($media->{$people_type_for_id[$peoples_id]},',')){
                            $ps_name = explode(',',$media->{$people_type_for_id[$peoples_id]} );
                          } else {
                            $ps_name = array($media->{$people_type_for_id[$peoples_id]} );
                          }
                          $peole_array = [];
                          for ($i=0; $i < count($ps_id); $i++) { 
                              $peole_array[] = ['id' => $ps_id[$i], 'name' => $ps_name[$i]];
                          }
                          $peope_type_arr[$type_for_id[$peoples_id]] = $peole_array;
                        }
                    }
                    $media->people_by_types = $peope_type_arr ;   
                    if(!empty($media->id)) {
                        $query_a = "SELECT s.id, src, sequence_number, s.title FROM #__medialibrary_audio_source AS s
                          LEFT JOIN  #__medialibrary AS m ON s.fk_media_id=m.id
                          WHERE s.fk_media_id =".$media->id." AND $where;";
                        $database->setQuery($query_a);
                        $temp_audios = $database->loadObjectlist();
                        $media->group_audios = [];
                        if ($temp_audios){
                            foreach ($temp_audios as $temp_audio) {
                                if ($temp_audio->sequence_number){
                                    if(in_array($temp_audio->sequence_number, $interesting_source)){
                                        $media->group_audios[$temp_audio->sequence_number][] = $temp_audio;
                                    }
                                }
                            }
                        }
                    }
                }
                $tabclass = array('sectiontableentry1', 'sectiontableentry2');
                $catid = mosGetParam($_REQUEST, 'catid', "");
                


                $category = new stdClass();
                //getting the current category informations
                $category->title = $category->name = _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL . " " 
                    . _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME;
                $category->description = "";
                $category->image = "";
                if (isset($medias[0])){
                    $category->catid = $medias[0]->catid;
                } else {
                    $category->catid = 0;
                }

                $currentcat = NULL;
                $currentcat = new stdClass();
                $currentcat->descrip = $category->description;
                // page image
                $currentcat->img = null;
                $path = $mosConfig_live_site . '/images/stories/';
                if ($category->image != null && count($category->image) > 0) {
                    $currentcat->img = $path . $category->image;
                    $currentcat->align = $category->image_position;
                }
                $currentcat->header = '';
                if ($category->name <> '') {
                    $currentcat->header = $category->name;
                } else {
                    $currentcat->header = $params->get('header');
                }
                $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header 
                        . ": ") : ("")) . $category->title;

                $layout = 'music-play-list';
                switch ($printItem) {
                    default:
                        HTML_medialibrary::displayMediasMusic($medias, $currentcat, $params, $tabclass, 0, 0, 
                                false, $pageNav, "resultsearch", $layout, $category);
                    break;
                }
            }
            else {


                if ($option != "com_medialibrary") {
                    if (isset($_REQUEST['userId'])) {
                        if ($my->id == $_REQUEST['userId']) {
                           showTabs();
                        }
                    } else {
                        showTabs();
                    }
                }
                positions_ml($params->get('search_no_found01'));
                positions_ml($params->get('singlecategory01')); 
                positions_ml($params->get('search_mod'));
                echo "<h1 class='ml_nofound_title'><center>" . _MEDIALIBRARY_NOTHING_FOUND . "</center></h1>";
                positions_ml($params->get('singleuser02'));
                positions_ml($params->get('search_no_found02'));
                positions_ml($params->get('singlecategory02'));                
                ?>
                <br />
                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="basictable">
                    <tr>
                        <td width="48%">&nbsp;</td>
                        <td width="2%" nowrap>
                            <?php mosHTML::BackButton($params, $hide_js);?>
                        </td>
                        <td width="48%">&nbsp;</td>
                    </tr>
                </table>
            <?php 
            }

        } else if ($type_desired == 'video'){
            $query = " SELECT s.id FROM #__medialibrary_video_source as s " 
                    ."  LEFT JOIN #__medialibrary as m ON s.fk_media_id = m.id "
                    . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id "
                    . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid and {$s} and c.published='1' "
                    ."  WHERE ( $where ) $lang"
                    . " and m.published='1' and m.approved='1' "
                    ."  AND m.media_type IN ('".implode("', '", $type_search)."') "
                    ."  GROUP BY s.sequence_number";
            $database->setQuery($query);
            $media_ids =  $database->loadColumn();
            if ($media_ids != []){
                $total = count($media_ids);
                // $media_ids = implode(',', $media_ids);
                $limit = $medialibrary_configuration['video_player']['items'];
                $pageNav = new JPagination($total, $limitstart, $limit); 

                $query = " SELECT s.id, fk_media_id, s.id, sequence_number, s.title 
                        FROM #__medialibrary_video_source as s " 
                        ."  LEFT JOIN #__medialibrary as m ON s.fk_media_id = m.id "
                        . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id "
                        . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid and {$s} and c.published='1' "
                        . " WHERE ( $where ) $lang "
                        . " and m.published='1' and m.approved='1' "
                        . " AND m.media_type IN ('".implode("', '", $type_search)."') "
                        . " GROUP BY s.sequence_number"
                        . " LIMIT $pageNav->limitstart, $pageNav->limit;";
                $database->setQuery($query);
                $medias = $database->loadObjectList();

                $interesting_source = array();
                $media_ids = array();
                foreach ($medias as $value) {
                    array_push($interesting_source, $value->sequence_number);
                    array_push($media_ids, $value->fk_media_id);
                }

                $query = "SELECT library.id, library.media_type, library.media_id,"
                . " library.hits, library.checked_out, c.title, "
                . " library.fk_lendid,library.date, p.people_name, "
                . " other_table.id as media_type_id, other_table.title as title, other_table.rating as rating, "
                . " other_table.URL as URL, other_table.imageURL as imageURL, other_table.price ,priceunit,  "
                . " GROUP_CONCAT(actor_people.actor separator ',') as actor_name,  "
                . " GROUP_CONCAT(author_people.author separator ',') as author_name,  "
                . " GROUP_CONCAT(studio_people.studio separator ',') as studio_name,  "
                . " GROUP_CONCAT(game_studio_people.game_studio separator ',') as game_studio_name,  "
                . " GROUP_CONCAT(director_people.director separator ',') as director_name,  "
                . " GROUP_CONCAT(producer_people.producer separator ',') as producer_name, "
                . " GROUP_CONCAT(artist_people.artist separator ',') as artist_name,  "
                . " GROUP_CONCAT(producer_people.id separator ',') as producer_id,  "
                . " GROUP_CONCAT(actor_people.id separator ',') as actor_id,  "
                . " GROUP_CONCAT(author_people.id separator ',') as author_id,  "
                . " GROUP_CONCAT(studio_people.id separator ',') as studio_id,  "
                . " GROUP_CONCAT(game_studio_people.id separator ',') as game_studio_id,  "
                . " GROUP_CONCAT(director_people.id separator ',') as director_id,  "
                . " GROUP_CONCAT(artist_people.id separator ',') as artist_id,  "
                . " catid"
                . " FROM #__medialibrary AS library "
                . " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id "
                . " LEFT JOIN #__medialibrary_main_categories AS c ON c.id=mc.catid "
                . " LEFT JOIN (".$type_type_search. ") AS other_table ON other_table.id = library.media_id and 
                    other_table.type = library.media_type"
                ."  LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = library.id "
                ." LEFT JOIN #__medialibrary_people AS p ON p.id = pc.fk_people_id"
                 ."\n LEFT JOIN (select id,  people_name as actor from #__medialibrary_people 
                    where type = 'actor') "
                ."\n as actor_people on actor_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as artist from #__medialibrary_people 
                    where type = 'artist') "
                ."\n as artist_people on artist_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as author from #__medialibrary_people 
                    where type = 'author') "
                ."\n as author_people on author_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as studio from #__medialibrary_people 
                    where type = 'video_studio') "
                ."\n as studio_people on studio_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id,people_name as game_studio from #__medialibrary_people 
                    where type = 'game_studio') "
                ."\n as game_studio_people on game_studio_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id ,  people_name as producer from #__medialibrary_people 
                    where type = 'producer') "
                ."\n as producer_people on producer_people.id = pc.fk_people_id "
                ."\n LEFT JOIN (select id ,  people_name as director from #__medialibrary_people 
                    where type = 'director') "
                ."\n as director_people on director_people.id = pc.fk_people_id "
                . " WHERE library.id IN ('".implode("', '", $media_ids)."') $where_price "
                . " GROUP BY library.id";
                if ($type_type_search != ''){
                    $database->setQuery($query);
                    $medias = $database->loadObjectList();
                } else { 
                    $medias = array();
                } 
                $people_type_for_id = ['producer_id' => 'producer_name', 
                                       'actor_id' => 'actor_name', 
                                       'studio_id' => 'studio_name', 
                                       'director_id' => 'director_name', 
                                       'artist_id' => 'artist_name', 
                                       'game_studio_id' => 'game_studio_name', 
                                       'author_id' => 'author_name'];
                $type_for_id = ['producer_id' => 'producer', 
                                'actor_id' => 'actor', 
                                'studio_id' => 'studio', 
                                'director_id' => 'director', 
                                'artist_id' => 'artist', 
                                'game_studio_id' => 'game_studio', 
                                'author_id' => 'author'];
                foreach ($medias as $media) {
                    $peope_type_arr = [];
                    foreach (['producer_id', 'actor_id', 'studio_id', 'director_id', 'artist_id',
                              'game_studio_id', 'author_id'] as $peoples_id) {
                        if (strpos($media->$peoples_id,',')){
                        $ps_id = explode(',',$media->$peoples_id);
                        } else {
                            $ps_id = array($media->$peoples_id);
                        }
                        if (isset($media->{$people_type_for_id[$peoples_id]}) ){

                          if( strpos($media->{$people_type_for_id[$peoples_id]},',')){
                          $ps_name = explode(',',$media->{$people_type_for_id[$peoples_id]} );
                          } else {
                              $ps_name = array($media->{$people_type_for_id[$peoples_id]} );
                          }
                          $peole_array = [];
                          for ($i=0; $i < count($ps_id); $i++) { 
                              $peole_array[] = ['id' => $ps_id[$i], 'name' => $ps_name[$i]];
                          }
                          $peope_type_arr[$type_for_id[$peoples_id]] = $peole_array;
                        }
                    }
                    $media->people_by_types = $peope_type_arr ;   
                    if(!empty($media->id)) {
                        $query_a = "SELECT s.id, src, youtube, sequence_number , title
                            FROM #__medialibrary_video_source AS s
                          LEFT JOIN  #__medialibrary AS m ON s.fk_media_id=m.id
                          WHERE s.fk_media_id =".$media->id." AND ( $where ) $lang"
                        ."  AND m.media_type IN ('".implode("', '", $type_search)."') ;";
                        $database->setQuery($query_a);
                        $temp_videos = $database->loadObjectlist();
                        $media->group_videos = [];
                        if ($temp_videos){
                            foreach ($temp_videos as $temp_video) {
                                if ($temp_video->sequence_number){
                                    if(in_array($temp_video->sequence_number, $interesting_source)){
                                        $media->group_videos[$temp_video->sequence_number][] = $temp_video;
                                    }
                                }
                            }
                        }
                        $query_a = "SELECT a.id, sequence_number,fk_media_id,src,kind,scrlang,label 
                            FROM #__medialibrary_track_source AS a
                          LEFT JOIN  #__medialibrary AS m ON a.fk_media_id=m.id
                          WHERE a.fk_media_id =".$media->id;
                        $database->setQuery($query_a);
                        $temp_tracks = $database->loadObjectlist();
                        $media->group_tracks = [];
                        if ($temp_tracks){
                            foreach ($temp_tracks as $temp_track) {
                                if ($temp_track->sequence_number){
                                    if(in_array($temp_track->sequence_number, $interesting_source)){
                                        $media->group_tracks[$temp_track->sequence_number][] = $temp_track;
                                    }
                                }
                            }
                        }    
                    }
                }
                $tabclass = array('sectiontableentry1', 'sectiontableentry2');
                $catid = mosGetParam($_REQUEST, 'catid', "");
                
                


                $category = new stdClass();
                //getting the current category informations
                $category->title = $category->name = _MEDIALIBRARY_SHOW_SEARCH_FOR_ALL . " " 
                    . _MEDIALIBRARY_LABEL_MEDIA_TYPE_GAME;
                $category->description = "";
                $category->image = "";
                if (isset($medias[0])){
                    $category->catid = $medias[0]->catid;
                } else {
                    $category->catid = 0;
                }

                $currentcat = NULL;
                $currentcat = new stdClass();
                $currentcat->descrip = $category->description;
                // page image
                $currentcat->img = null;
                $path = $mosConfig_live_site . '/images/stories/';
                if ($category->image != null && count($category->image) > 0) {
                    $currentcat->img = $path . $category->image;
                    $currentcat->align = $category->image_position;
                }
                $currentcat->header = '';
                if ($category->name <> '') {
                    $currentcat->header = $category->name;
                } else {
                    $currentcat->header = $params->get('header');
                }
                $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header 
                        . ": ") : ("")) . $category->title;

                $layout = 'video-play-list';
                switch ($printItem) {
                    default:
                        HTML_medialibrary::displayMediasVideo($medias, $currentcat, $params, $tabclass, 0, 0, 
                                false, $pageNav, "resultsearch", $layout, $category);
                    break;
                }
            } else {
                if ($option != "com_medialibrary") {
                    if (isset($_REQUEST['userId'])) {
                        if ($my->id == $_REQUEST['userId']) {
                           showTabs();
                        }
                    } else {
                        showTabs();
                    }
                }

                positions_ml($params->get('search_no_found01'));
                positions_ml($params->get('singlecategory01')); 
                positions_ml($params->get('search_mod'));
                echo "<h1 class='ml_nofound_title'><center>" . _MEDIALIBRARY_NOTHING_FOUND . "</center></h1>";
                positions_ml($params->get('singleuser02'));
                positions_ml($params->get('search_no_found02'));
                positions_ml($params->get('singlecategory02'));                
                ?>
                <br />
                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="basictable">
                    <tr>
                        <td width="48%">&nbsp;</td>
                        <td width="2%" nowrap>
                            <?php mosHTML::BackButton($params, $hide_js);?>
                        </td>
                        <td width="48%">&nbsp;</td>
                    </tr>
                </table>
            <?php 
            }
                
        } else {
          
            $where = [];
            if (is_array($sort_arr)) {
                $tmp1 = protectInjectionWithoutQuote('order_direction');
                if ($tmp1 != '') {
                    $sort_arr['order_direction'] = $tmp1;
                }
                $tmp1 = protectInjectionWithoutQuote('order_field');
                if ($tmp1 != '') {
                    $sort_arr['order_field'] = $tmp1;
                }
                $item_session->set('ml_mediasort', $sort_arr);
            } else {
                $sort_arr = array();
                $ordertype = $GLOBALS['book_order_type'];
                if ($ordertype == 0) {
                    $sort_arr['order_field'] = 'title';
                    $sort_arr['order_direction'] = 'asc';
                } else if ($ordertype == 1) {
                    $sort_arr['order_field'] = 'title';
                    $sort_arr['order_direction'] = 'desc';
                } else if ($ordertype == 2) {
                    $sort_arr['order_field'] = 'people_name';
                    $sort_arr['order_direction'] = 'asc';
                } else if ($ordertype == 3) {
                    $sort_arr['order_field'] = 'people_name';
                    $sort_arr['order_direction'] = 'desc';
                }
                $item_session->set('ml_mediasort', $sort_arr);
            }

                if ($sort_arr['order_field'] == "price"){
                    $sort_string = "CAST( " . $sort_arr['order_field'] . " AS DECIMAL(15,2))" . " " 
                        . $sort_arr['order_direction'];
                } else if ($sort_arr['order_field'] == "title") {
                    $sort_string = $sort_arr['order_field'] . " " . $sort_arr['order_direction'];
                } else {
                    $sort_string = "date " . $sort_arr['order_direction'];
                }

            $session = JFactory::getSession(); 
            if ($ownername == '') {
                  $app = JFactory::getApplication();
                  $path_way = $app->getPathway();
                  $pathway = sefRelToAbs('' . $mosConfig_live_site . 'index.php?option=' . $option 
                        . '&task=show_search&Itemid=' . $Itemid);
                  $pathway_name = _MEDIALIBRARY_LABEL_SEARCH;
                  $path_way->addItem($pathway_name, $pathway);
              }
            // text for search
            if (array_key_exists("searchtext", $_REQUEST)) {
                $search = protectInjectionWithoutQuote('searchtext', '');
                $search = addslashes($search);
                $session->set("poisk", $search);
            }
    //       this is needed for function viewUserMedias
            else if ($ownername != "") {
                $session->set("poisk", $ownername);
            }

            $poisk_search = $session->get("poisk", "");
            if (isset($_REQUEST['exactly']) && $_REQUEST['exactly'] == "on") {
                $exactly = true;
            } else {
                $exactly = false;
            }
            if (isset($_REQUEST['release_date_from']) && trim($_REQUEST['release_date_from']) != "" && 
                    isset($_REQUEST['release_date_to']) && trim($_REQUEST['release_date_to']) != "") {
                $year = " (medias.release_date > '" . $_REQUEST['release_date_from'] 
                    . "' and medias.release_date < '" . $_REQUEST['release_date_to'] . "') ";
            } elseif (isset($_REQUEST['release_date_from']) && trim($_REQUEST['release_date_from']) != "") {
                $year = " medias.release_date >= '" . $_REQUEST['release_date_from'] . "' ";
            } elseif (isset($_REQUEST['release_date_to']) && trim($_REQUEST['release_date_to']) != "") {
                $year = " medias.release_date <= '" . $_REQUEST['release_date_to'] . "' ";
            }
            // price conditions
            $pricefrom = intval(mosGetParam($_REQUEST, 'pricefrom', ''));
            $priceto = intval(mosGetParam($_REQUEST, 'priceto', ''));
            if ($pricefrom > 0) {
                $where[] = " CAST( medias.price AS SIGNED) >= $pricefrom ";
            }
            if ($priceto > 0) {
                $where[] = " CAST( medias.price AS SIGNED) <= $priceto ";
            }

            //********owners search by ID

            $is_add_or = false;
            $is_owner_search = false;
            $ownerid = "";
            if ($poisk_search != '' && isset($_REQUEST['ownername']) && $_REQUEST['ownername'] == "on") {
                $ownername = " ";
            }
            //????????
            // if ($poisk_search){
            //     $poisk_search = substr($poisk_search, 2, -2) ;
            // } 
            //????????
            if ($poisk_search == '') {
                if ($ownername && $ownername != ' '){
                    $poisk_search = $ownername;
                }
            }

    //        for exactly search
            if ($exactly) {
                $ownername = "$exactly";
            }
            if ($ownername != '' && $ownername != '%%') {
                $is_owner_search = true;
                $query = "SELECT u.id  FROM #__users AS u " 
                        ."\n WHERE LOWER(u.name)" . (($exactly) ? (" =  '$poisk_search';") : (" LIKE '%" 
                                . $poisk_search . "%';"));
                $database->setQuery($query);
                if (version_compare(JVERSION, '3.0', 'ge')) {
                    $ownerids = $database->loadColumn();
                } else {
                    $ownerids = $database->loadResultArray();
                }
                $ownerid = "";
                if (count($ownerids)) {
                    foreach($ownerids as $ownerid_) {
                        if ($is_add_or) $ownerid.= " or ";
                        $is_add_or = true;
                        $ownerid.= " m.owner_ID='$ownerid_'";
                    }
                }
            }
            //********
    //        search by date
            $search_date_from = protectInjection('lend_from', '');
            $search_date_from = addslashes($search_date_from);
            $search_date_until = protectInjection('search_date_until', '');
            $search_date_until = addslashes($search_date_until);
            if (protectInjectionWithoutQuote('lend_from', '') != '')
                $search_date_from = date_format(date_create_from_format('d-Y-m', 
                                        protectInjectionWithoutQuote('lend_from', '')), 'Y-m-d');
            if (protectInjectionWithoutQuote('search_date_until', '') != '')
                $search_date_until = date_format(date_create_from_format('d-Y-m', 
                                        protectInjectionWithoutQuote('search_date_until', '')), 'Y-m-d');


            $LendSQL = "";
            $LendSQL_JOIN_1 = "";
            $LendSQL_JOIN_2 = "";
            if (isset($_REQUEST['lend_from']) && (trim($_REQUEST['lend_from'])) && trim($_REQUEST[
                    'search_date_until']) == "") {
                $LendSQL = "  ( fk_lendid = 0 OR
                NOT EXISTS (select dd.fk_mediaid from #__medialibrary_lend AS dd where dd.lend_until > '" 
                    . $search_date_from
                . "' and dd.lend_from < '" . $search_date_from . "' and dd.fk_mediaid=m.id ) ) ";
                if ($is_add_or) $LendSQL.= " AND ";
                $LendSQL_JOIN_1 = "\nLEFT JOIN #__medialibrary_lend AS d ";
                $LendSQL_JOIN_2 = "\nON d.fk_mediaid=m.id ";
            }
            if (isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until'])) && 
                    trim($_REQUEST['lend_from']) == "") {
                $LendSQL = "  (  fk_lendid = 0  OR
                NOT EXISTS (select dd.fk_mediaid from #__medialibrary_lend AS dd where dd.lend_from < '" 
                    . $search_date_until
                . "' and dd.lend_until > '" . $search_date_until . "' and dd.fk_mediaid=m.id ) ) ";
                if ($is_add_or) $LendSQL.= " AND ";
                $LendSQL_JOIN_1 = "\nLEFT JOIN #__medialibrary_lend AS d ";
                $LendSQL_JOIN_2 = "\nON d.fk_mediaid=m.id ";
            }
            if (isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until'])) &&
                isset($_REQUEST['lend_from']) && (trim($_REQUEST['lend_from']))) {
                $LendSQL = "  ( fk_lendid = 0  OR
            NOT EXISTS (select dd.fk_mediaid from #__medialibrary_lend AS dd where  ( dd.lend_until > '"
                . $search_date_from . "' and dd.lend_from < '" . $search_date_from . "' ) or " 
                . " ( dd.lend_from < '"
                . $search_date_until . "' and dd.lend_until > '" . $search_date_until . "' ) or " 
                . " ( dd.lend_from > '"
                . $search_date_from . "' and dd.lend_until < '" . $search_date_until . "' ) ) ) ";
                if ($is_add_or) $LendSQL.= " ";//" AND ";
                $LendSQL_JOIN_1 = "\nLEFT JOIN #__medialibrary_lend AS d ";
                $LendSQL_JOIN_2 = "\nON d.fk_mediaid=m.id ";
            }

            
              if( trim($LendSQL) !="" ) array_push($where, $LendSQL );

                 if(isset($price))
                   {
                   array_push($where, $price);
                  }
                  if(isset($year))
                  {
                   array_push($where, $year);
                  }
               if($catid!=0){
                $where[]="c.id=$catid";
                }

            //select category, to which user has access
            $where[] = " ({$s}) ";
            array_push($where, "c.published='1'");
            array_push($where, "m.published='1'");
            array_push($where, "m.approved='1'");
            array_push($where, "m.archived=0");
            $search_fields = get_search_fields();
            $select_fields = array();
            $select_from_table = array();
            $select_from_table_total = array();
            $search_from_people = array();
            if (array_key_exists('searchtype', $_REQUEST) && $_REQUEST['searchtype'] == 'simplesearch') {
                $simple = 1;
            } else $simple = 0;
            

            foreach($search_fields as $type => $search_field) {

                $select_fields = null;
                $select_fields = array();
                $where_tmp = array();
                $search_from_people[$type] = [];
                foreach($search_field as $search_title => $search_colon) {
                    if (($type == 'game' && ($search_title == 'studio'))  ||
                        ($type == 'music' && ($search_title == 'artist')) ||
                        ($type == 'book' && ($search_title == 'authors')) ||
                        ($type == 'video' && ($search_title == 'producer' || $search_title == 'director' || 
                                              $search_title == 'studio'   || $search_title == 'actors'))){
                        if (mosGetParam($_GET, $type . '-' . $search_title, '')){
                            if ($search_title != 'studio'){
                                if ( substr($search_title, -1) != 's'){
                                    $search_from_people[$type][] = $search_title;
                                } else {
                                    $search_from_people[$type][] = substr($search_title, 0, -1);
                                }
                            } else {
                                $search_from_people[$type][] = $type."_".$search_title;
                            }
                        }
                    }
                    switch ($search_title) {
                        case "isbn":
                        case "asin":
                            $field_end = "ext1";
                        break;
                        case "authors":
                        case "director":
                        case "producer":
                        case "studio":
                        case "artist":
                        case "actors":
                            $field_end = "ext2";
                        break;
                        case "manufacturer":
                        case "binding":
                        case "tracklist":
                        case "format":
                            $field_end = "ext3";
                        break;
                        default:
                            if (is_numeric($search_title)) {
                                $field_end = $search_colon;
                            } else {
                                $field_end = $search_title;
                            };
                        
                    }
                    if (mosGetParam($_GET, $type . '-' . $search_title, '') || 
                            mosGetParam($_GET, $field_end, '') || 
                            $simple) {
                        if ($field_end != "ext2")$select_fields[] = "LOWER(medias." . $field_end . ")" 
                            . (($exactly) ? (" = '$poisk_search'") : (" LIKE '%" . $poisk_search . "%'"));
                        if ($field_end == "ext2") $select_fields[] = "LOWER(studio_people." . $field_end.")"
                             . (($exactly) ? (" = '$poisk_search'") : (" LIKE '%" . $poisk_search . "%'"));
                    }
                }

              
                $pricefrom = intval(protectInjectionWithoutQuote('pricefrom2', ''));
                $priceto = intval(protectInjectionWithoutQuote('priceto2', ''));
                if ($pricefrom > 0)
                    $where[] = " CAST( medias.price AS SIGNED) >= $pricefrom ";
                if ($priceto > 0)
                    $where[] = " CAST( medias.price AS SIGNED) <= $priceto ";

                if ($ownerid != "" && ($is_owner_search || count($select_fields) > 0)) 
                        $select_fields[] = $ownerid;
                //   write all conditions togather
                $where_tmp = $where;

                if (!empty($select_fields)) $where_tmp[] = " (" . implode(' OR ', $select_fields) . ") ";
                if (count($select_fields) > 0 || isset($_REQUEST[$type])) {

              
                if (isset($langContent)) {
                    $lang = $langContent;
                    // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
                    // $database->setQuery($query);
                    // $lang = $database->loadResult();
                } else {
                    $lang = "";
                }
                
                if ($type == "book" || $type == "music" || $type == "game" || $type == "video" ){
                   

                    $where_tmp[] = " ( m.langDescription = '$lang' or m.langDescription like 'all' or 
                        m.langDescription like '' or m.langDescription like '*' or 
                        m.langDescription is null) ";
                    $where_tmp[] = "  ( c.langDescription = '$lang' or c.langDescription like 'all' or 
                        c.langDescription like '' or c.langDescription like '*' or 
                        c.langDescription is null) ";

                    switch ($type) {
                        case "book":
                             $select_from_table_total[$type] = " SELECT m.id  FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id,  people_name as ext2 
                                    from #__medialibrary_people where type = 'author') "
                              . "\n AS studio_people ON studio_people.id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id, isbn as ext1,title,rating,URL,imageURL,language,
                                    comment,release_date, "
                              . "\n manufacturer as ext3,price,priceunit,'" . $type . "' as media_type 
                                    FROM #__medialibrary_" . $type . ") "
                              . "\n AS medias ON medias.id = m.media_id and 
                                    medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp) ? "\n WHERE " 
                                . implode(' AND ', $where_tmp) : "");
                            $select_from_table[$type] = " SELECT distinct  m.id, m.hits,m.fk_lendid,m.date,"
                              . "\n c.ordering AS category_ordering, 
                                    GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
                              . "\n medias.title,medias.price,medias.priceunit,medias.language,
                                    medias.ext1,studio_people.ext2 as people_name,people_id, "
                              . "\n medias.comment, medias.rating, medias.URL, medias.imageURL, 
                                medias.media_type  "
                              . "\n FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id as people_id, people_name as ext2 
                                    from #__medialibrary_people AS p where type = 'author') "
                              . "\n AS studio_people ON studio_people.people_id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id,isbn as ext1, title,rating,URL,imageURL,language
                                    , comment,release_date, "
                              . "\n manufacturer as ext3,price,priceunit,'"
                              . $type . "' as media_type, langDescription FROM #__medialibrary_". $type .") "
                              ."\n AS medias ON medias.id = m.media_id and medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp)
                              ? "\n WHERE " . implode(' AND ', $where_tmp) : "").
                                " GROUP BY m.id ";
                        break;
                        case "music":
                             $select_from_table_total[$type] = " SELECT m.id  FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id,  people_name as ext2 from #__medialibrary_people 
                                    where type = 'artist') "
                              . "\n AS studio_people ON studio_people.id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id, tracklist,asin as ext1,title,rating,URL,imageURL,
                                language,comment,release_date, "
                              . "\n binding as ext3,price,priceunit,'" . $type . "' as media_type 
                                FROM #__medialibrary_" . $type . ") "
                              . "\n AS medias ON medias.id = m.media_id and 
                                medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp) ? "\n WHERE " 
                                . implode(' AND ', $where_tmp) : "");
                            $select_from_table[$type] = " SELECT distinct  m.id, m.hits,m.fk_lendid,m.date,"
                              . "\n c.ordering AS category_ordering, 
                                GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
                              . "\n medias.title,medias.price,medias.priceunit,medias.language,
                                medias.ext1,studio_people.ext2 as people_name,people_id, "
                              . "\n medias.comment, medias.rating, medias.URL, medias.imageURL, 
                                medias.media_type  "
                              . "\n FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id as people_id, people_name as ext2 
                                    from #__medialibrary_people AS p where type = 'artist') "
                              . "\n AS studio_people ON studio_people.people_id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id,asin as ext1, tracklist,title,rating,URL,imageURL,
                                language, comment,release_date, "
                              . "\n binding as ext3,price,priceunit,'"
                              . $type . "' as media_type, langDescription FROM #__medialibrary_". $type.") "
                              ."\n AS medias ON medias.id = m.media_id and medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp)
                              ? "\n WHERE " . implode(' AND ', $where_tmp) : "").
                                " GROUP BY m.id ";
                        break;
                        case "game":
                            $select_from_table_total[$type] = " SELECT m.id  FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id, people_name as ext2 from #__medialibrary_people  
                                    where type IN ('".implode("', '", $search_from_people[$type])."')) "
                              . "\n AS studio_people ON studio_people.id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id, platform,asin as ext1,title,rating,URL,imageURL,
                                language,comment,release_date, "
                              . "\n binding as ext3,price,priceunit,'" . $type . "' as media_type 
                                FROM #__medialibrary_" . $type . ") "
                              . "\n AS medias ON medias.id = m.media_id and 
                                medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp) ? "\n WHERE " 
                                . implode(' AND ', $where_tmp) : "");
                            $select_from_table[$type] = " SELECT distinct  m.id, m.hits,m.fk_lendid, 
                                m.date, "
                              . "\n c.ordering AS category_ordering, 
                                GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
                              . "\n medias.title,medias.price,medias.priceunit,medias.language,
                                medias.ext1,studio_people.ext2 as people_name, people_id, "
                              . "\n medias.comment, medias.rating, medias.URL, medias.imageURL, 
                                medias.media_type  "
                              . "\n FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                               . "\n LEFT JOIN #__medialibrary_people_connect AS pc 
                                ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id as people_id, people_name as ext2 
                                    from #__medialibrary_people AS p  
                                    where type IN ('".implode("', '", $search_from_people[$type])."')) "
                              . "\n AS studio_people ON studio_people.people_id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id,asin as ext1, platform,title,rating,URL,imageURL,
                                language, comment,release_date, "
                              . "\n binding as ext3,price,priceunit,'"
                              . $type . "' as media_type, langDescription 
                                FROM #__medialibrary_". $type . ") "
                              . "\n AS medias ON medias.id = m.media_id and 
                                medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp)
                              ? "\n WHERE " . implode(' AND ', $where_tmp) : "").
                             " GROUP BY m.id ";
                        break;

                        case "video":
                            $select_from_table_total[$type] = " SELECT m.id  FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id,  people_name as ext2 from #__medialibrary_people 
                                    where type IN ('".implode("', '", $search_from_people[$type])."')) "
                              . "\n AS studio_people ON studio_people.id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id, asin as ext1,title,rating,URL,imageURL,language,
                                comment,release_date, "
                              . "\n format as ext3,price,priceunit,'" . $type . "' as media_type 
                                FROM #__medialibrary_" . $type . ") "
                              . "\n AS medias ON medias.id = m.media_id and 
                                medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp) ? "\n WHERE " 
                                . implode(' AND ', $where_tmp) : "");
                            $select_from_table[$type] = " SELECT distinct  m.id, m.hits,m.fk_lendid, m.date,"
                              . "\n c.ordering AS category_ordering, 
                                GROUP_CONCAT(c.title SEPARATOR ', ') AS category, "
                              . "\n medias.title,medias.price,medias.priceunit,medias.language,
                                medias.ext1,studio_people.ext2 as people_name,people_id , "
                              . "\n medias.comment, medias.rating, medias.URL, medias.imageURL, 
                                medias.media_type  "
                              . "\n FROM #__medialibrary AS m "
                              . "\n LEFT JOIN #__medialibrary_categories AS mc ON m.id=mc.mediaid "
                              . "\n LEFT JOIN #__medialibrary_main_categories AS c ON mc.catid = c.id "
                              . "\n LEFT JOIN #__medialibrary_people_connect AS pc ON pc.fk_media_id = m.id "
                              . "\n LEFT JOIN (SELECT id as people_id, people_name as ext2 
                                    from #__medialibrary_people AS p  
                                    where type IN ('".implode("', '", $search_from_people[$type])."')) "
                              . "\n AS studio_people ON studio_people.people_id = pc.fk_people_id "
                              . "\n JOIN ( SELECT id,asin as ext1,title,rating,URL,imageURL,language, 
                                comment,release_date, "
                              . "\n format as ext3,price,priceunit,'"
                              . $type . "' as media_type, langDescription FROM #__medialibrary_".$type.") "
                              ."\n AS medias ON medias.id = m.media_id and medias.media_type = m.media_type "
                              . $LendSQL_JOIN_1 . $LendSQL_JOIN_2 . (count($where_tmp)
                              ? "\n WHERE " . implode(' AND ', $where_tmp) : "").
                                " GROUP BY m.id ";
                        break;
                        default:
                    }
                }
            }
        }
 //                    print_r($select_from_table);exit;

            
        if (count($select_from_table_total) > 0) {
            $select_from_tables_total = " SELECT COUNT(DISTINCT id) from (\n " . implode("\n UNION ", 
                    $select_from_table_total)  . " ) as r ";
            $database->setQuery($select_from_tables_total);
            $total = $database->loadResult();
            $pageNav = new JPagination($total, $limitstart, $limit);
            $selectstring = " SELECT distinct  id, hits,fk_lendid, "." category_ordering, date, category, "
              . " title,price,priceunit,language,ext1,people_name,people_id, " 
              . " comment, rating, URL, imageURL, media_type   " .
              " from (\n " . implode("\n UNION ", $select_from_table) . " ) as r ";
            $selectstring.= " ORDER BY ". $sort_string . " LIMIT $pageNav->limitstart,$pageNav->limit  "; 
            $database->setQuery($selectstring);
            $medias = $database->loadObjectList();

        }else $medias = array();
        //print_r($medias);exit;

        $params->def('sort_arr_order_direction', $sort_arr['order_direction']);
        $params->def('sort_arr_order_field', $sort_arr['order_field']);
        $params->def('view_type', $medialibrary_configuration['view_type']);
        $params->def('printItem', $printItem);     


        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }
        if (($medialibrary_configuration['lendstatus']['show'])) {
            $params->def('show_lendstatus', 1);
            if (checkAccess_ML($medialibrary_configuration['lendrequest']['registrationlevel'], 'RECURSE', 
                userGID_ML($my->id), $acl)) {
                $params->def('show_lendrequest', 1);
            }
        }
        

        //add for show in category picture
        if (($medialibrary_configuration['cat_pic']['show'])) $params->def('show_cat_pic', 1);
        $params->def('back_button', $mainframe->getCfg('back_button'));
        $currentcat = new stdClass();
        $currentcat->descrip = _MEDIALIBRARY_SEARCH_DESC2;
        $currentcat->align = 'right';
        $currentcat->header = $params->get('header');

        // page image
        if ($option == 'com_simplemembership') {
            $currentcat->header = ((trim($currentcat->header) != "") ? ($currentcat->header . " ") : (""));
        } else {
            $currentcat->img = "".$mosConfig_live_site
                ."/components/com_medialibrary/images/medialibrary_logo.png";
            // $currentcat->header = ((trim($currentcat->header)!="")?($currentcat->header.": "):("")) 
                //. _MEDIALIBRARY_LABEL_SEARCH;
            //  for old version we have already $currentcat->header
        }
        // used to show table rows in alternating colours
        $tabclass = array('sectiontableentry1', 'sectiontableentry2');


        if (!isset($my->id)) { //for 1.6
            $my->id = 0;
        }

        $printItem = trim(mosGetParam($_REQUEST, 'printItem', ""));


        
            
        


        if (count($medias)) {


                switch ($printItem) {
                    default:
                    
                        HTML_medialibrary::displayMedias($medias, $currentcat, $params, $tabclass, $catid,
                             null, false, $pageNav, $layout = 'list');
                    break;
                }
                
        } else {



          positions_ml($params->get('singleuser01'));
          positions_ml($params->get('search_no_found01'));
          positions_ml($params->get('singlecategory01')); 
          positions_ml($params->get('search_mod'));
          echo "<h1 class='ml_nofound_title'><center>" . _MEDIALIBRARY_NOTHING_FOUND . "</center></h1>";
          positions_ml($params->get('singleuser02'));
          positions_ml($params->get('search_no_found02'));
          positions_ml($params->get('singlecategory02'));
    ?>
          <br />
          <table width="100%" border="0" cellspacing="0" cellpadding="0" class="basictable">
            <tr>
              <td width="48%">&nbsp;
              </td>
              <td width="2%" nowrap>
                <?php
            mosHTML::BackButton($params, $hide_js);
    ?>
              </td>
               <td width="48%">&nbsp;
              </td>
            </tr>
          </table>
          <?php
        }
    }
}


function get_search_fields() {
    return array('book' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                'isbn' => _MEDIALIBRARY_LABEL_ISBN, 
                                'id' => _MEDIALIBRARY_LABEL_BOOKID, 
                                'authors' => _MEDIALIBRARY_SHOW_SEARCH_FOR_AVTORS, 
                                'manufacturer' => _MEDIALIBRARY_LABEL_MANUFACTURER, 
                                'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                'comment' => _MEDIALIBRARY_LABEL_COMMENT), 
                 'game' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                 'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                 'id' => _MEDIALIBRARY_LABEL_GAMEID, 
                                 'platform' => _MEDIALIBRARY_LABEL_PLATFORM, 
                                 'studio' => _MEDIALIBRARY_LABEL_STUDIO, 
                                 'binding' => _MEDIALIBRARY_LABEL_BINDING, 
                                 'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                 'comment' => _MEDIALIBRARY_LABEL_COMMENT), 
                 'music' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                  'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                  'id' => _MEDIALIBRARY_LABEL_MUSICID, 
                                  'artist' => _MEDIALIBRARY_LABEL_ARTIST, 
                                  'tracklist' => _MEDIALIBRARY_LABEL_TRACKLIST, 
                                  'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                  'comment' => _MEDIALIBRARY_LABEL_COMMENT), 
                 'video' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                  'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                  'id' => _MEDIALIBRARY_LABEL_VIDEOID, 
                                  'actors' => _MEDIALIBRARY_LABEL_ACTORS, 
                                  'producer' => _MEDIALIBRARY_LABEL_PRODUCER, 
                                  'director' => _MEDIALIBRARY_LABEL_DIRECTOR, 
                                  'studio' => _MEDIALIBRARY_LABEL_STUDIO, 
                                  'format' => _MEDIALIBRARY_LABEL_FORMAT, 
                                  'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                  'comment' => _MEDIALIBRARY_LABEL_COMMENT));
}

function get_search_fields_for_defoult() {
    return array('book' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                'isbn' => _MEDIALIBRARY_LABEL_ISBN, 
                                // 'id' => _MEDIALIBRARY_LABEL_BOOKID, 
                                'authors' => _MEDIALIBRARY_SHOW_SEARCH_FOR_AVTORS, 
                                // 'manufacturer' => _MEDIALIBRARY_LABEL_MANUFACTURER, 
                                // 'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                // 'comment' => _MEDIALIBRARY_LABEL_COMMENT
                                ), 
                 'game' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                 'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                 // 'id' => _MEDIALIBRARY_LABEL_GAMEID, 
                                 // 'platform' => _MEDIALIBRARY_LABEL_PLATFORM, 
                                 'studio' => _MEDIALIBRARY_LABEL_STUDIO, 
                                 // 'binding' => _MEDIALIBRARY_LABEL_BINDING, 
                                 // 'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                 // 'comment' => _MEDIALIBRARY_LABEL_COMMENT
                                 ), 
                 'music' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                  'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                  // 'id' => _MEDIALIBRARY_LABEL_MUSICID, 
                                  'artist' => _MEDIALIBRARY_LABEL_ARTIST, 
                                  // 'tracklist' => _MEDIALIBRARY_LABEL_TRACKLIST, 
                                  // 'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                  // 'comment' => _MEDIALIBRARY_LABEL_COMMENT
                                  ), 
                 'video' => array('title' => _MEDIALIBRARY_LABEL_TITLE, 
                                  'asin' => _MEDIALIBRARY_LABEL_ASIN, 
                                  // 'id' => _MEDIALIBRARY_LABEL_VIDEOID, 
                                  'actors' => _MEDIALIBRARY_LABEL_ACTORS, 
                                  'producer' => _MEDIALIBRARY_LABEL_PRODUCER, 
                                  'director' => _MEDIALIBRARY_LABEL_DIRECTOR, 
                                  'studio' => _MEDIALIBRARY_LABEL_STUDIO, 
                                  // 'format' => _MEDIALIBRARY_LABEL_FORMAT, 
                                  // 'language' => _MEDIALIBRARY_LABEL_LANGUAGE, 
                                  // 'comment' => _MEDIALIBRARY_LABEL_COMMENT
                                  )
                );
}
function get_file_search_fields() {
    return array('book' => array(), 
                 'game' => array(), 
                 'music' => array(), 
                 'video' => array());
}

function categoryParentList($id, $action, $is_new, $options = array()) {
    global $database, $langContent;
    if (isset($langContent)){
        $lang = $langContent;
        // $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
        // $database->setQuery($query);
        // $lang = $database->loadResult();
        $lang = " AND (c.langDescription like 'all' or c.langDescription like '' or " . 
            " c.langDescription like '*' or c.langDescription is null or c.langDescription like '$lang') ";
    } else {
        $lang = "";
    }
    $list0 = CAT_Utils::categoryArray($lang);
    $list = $list0;
    $cat = new mainMedialibraryCategories($database); //for 1.6
    $cat->load($id);
    $this_treename = '';
    $childs_ids = Array();
    foreach($list as $item) {
        if ($item->id == $cat->id || array_key_exists($item->parent_id, $childs_ids)) 
            $childs_ids[$item->id] = $item->id;
    }
    foreach($list as $item) {
        if ($this_treename) {
            if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false && 
                array_key_exists($item->id, $childs_ids) === false) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            }
        } else {
            if ($item->id != $cat->id) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            } else {
                $this_treename = "$item->treename/";
            }
        }
    }
    $parent = null;
    $parent = mosHTML::selectList($options, 'catid', 'class="inputbox" size="1"', 'value', 'text', 
        $cat->parent_id);
    return $parent;
}
class CAT_Utils {
    static function categoryArray($lang = '') {
        global $database, $my;
        // get a list of the menu items
        $s = getWhereUsergroupsString("c");
        $query = "SELECT c.id, c.parent_id ,COUNT(bc.mediaid) AS medias, c.title, 
            c.image, '1' AS display, c.parent_id AS parent, c.name
         \n FROM #__medialibrary_main_categories c
         \n LEFT JOIN #__medialibrary_categories AS bc ON c.id=bc.catid
         \n LEFT JOIN #__medialibrary AS b ON b.id=bc.mediaid AND b.published=1 AND b.approved=1
         \n WHERE c.section='com_medialibrary'
          \n AND c.published=1 AND ({$s})  $lang
          \n GROUP BY c.id \n
         \n ORDER BY  parent_id DESC, c.ordering";
        $database->setQuery($query);
        $items = $database->loadObjectList();
        // establish the hierarchy of the menu
        $children = array();
        // first pass - collect children
        foreach($items as $v) {
            $pt = $v->parent;
            $list = @$children[$pt] ? $children[$pt] : array();
            array_push($list, $v);
            $children[$pt] = $list;
        }
        // second pass - get an indent list of the items
        $array = medialibraryTreeRecurse(0, '', array(), $children);
        return $array;
    }
}

//get current user groups
function getUserGroupsML() {
    $my = JFactory::getUser();
    $acl = JFactory::getACL();
    $usergroups = $acl->get_group_parents($my->gid, 'ARO', 'NORECURSE');
    if ($usergroups) $usergroups = ',' . implode(',', $usergroups);
    else $usergroups = '';
    return '-2,' . $my->gid . $usergroups;
}



function showTabs() {
    global $mosConfig_live_site, $medialibrary_configuration, $database, $Itemid, $my, $option, $doc, 
        $acl;
    $doc->addStyleSheet($mosConfig_live_site . '/components/com_medialibrary/includes/medialibrary.css');
    if (version_compare(JVERSION, '3.0', 'ge')) {
        $menu = new JTableMenu($database);
        $menu->load($Itemid);
        $params = new JRegistry;
        $params->loadString($menu->params);
    } else {
        $menu = new mosMenu($database);
        $menu->load($Itemid);
        $params = new mosParameters($menu->params);
    }
  
    $userid = $my->id;
    $query = "SELECT u.id, u.name AS username FROM #__users AS u WHERE u.id = " . $userid;
    $database->setQuery($query);
    $ownerslist = $database->loadObjectList();
    foreach($ownerslist as $owner) {
        $username = $owner->username;
    }
    $query = "SELECT m.owner_ID FROM #__medialibrary AS m" 
        . " INNER JOIN #__medialibrary_lend_request AS r ON m.id=r.fk_mediaid "
             . " WHERE m.owner_ID = '" . $my->id . "' AND r.status=0";
    $database->setQuery($query);
    $ownermedia = $database->loadObjectList();
    foreach($ownermedia as $mowner) {
        $mediaowner = $mowner->owner_ID;
        break;
    }
    $query = "SELECT * FROM #__medialibrary_lend AS l WHERE l.user_name = '$my->name'";
    $database->setQuery($query);
    $current_user_lend_history_array = $database->loadObjectList();
    $check_for_show_lend_history = 0;
    if (isset($current_user_lend_history_array)) {
        foreach($current_user_lend_history_array as $temp) {
            if ($temp->user_name == $my->name) $check_for_show_lend_history = 1;
        }
    }
    if (($medialibrary_configuration['cb_mymedia']['show'])) {
        $params->def('show_cb', 1);
        $i = checkAccess_ML($medialibrary_configuration['cb_mymedia']['registrationlevel'], 'NORECURSE', 
            userGID_ML($my->id), $acl);
        if ($i) $params->def('show_cb_registrationlevel', 1);
    }
    if (($medialibrary_configuration['cb_edit']['show'])) {
        $params->def('show_edit', 1);
        $i = checkAccess_ML($medialibrary_configuration['cb_edit']['registrationlevel'], 'NORECURSE', 
            userGID_ML($my->id), $acl);
        if ($i) $params->def('show_edit_registrationlevel', 1);
    }
    if (isset($mediaowner) && $my->email == $mediaowner) {
        if (($medialibrary_configuration['cb_lend']['show'])) {
            $params->def('show_lend', 1);
            $i = checkAccess_ML($medialibrary_configuration['cb_lend']['registrationlevel'], 
                    'NORECURSE', userGID_ML($my->id), $acl);
            if ($i) $params->def('show_lend_registrationlevel', 1);
        }
    }
    if ($check_for_show_lend_history != 0) {
        if (($medialibrary_configuration['cb_history']['show'])) {
            $params->def('show_history', 1);
            $i = checkAccess_ML($medialibrary_configuration['cb_history']['registrationlevel'], 
                    'NORECURSE', userGID_ML($my->id), $acl);
            if ($i) $params->def('show_history_registrationlevel', 1);
        }
    }
    $doc->addStyleSheet($mosConfig_live_site . '/components/com_medialibrary/includes/medialibrary.css');
    HTML_medialibrary::showTabs($params, $userid, $username, $comprofiler, $option);
}


function com_MEDIALIBRARY_CATEGORYTreeList($id, $action, $is_new, &$options = array(), $lang='') {
    global $database;
     if($lang){
            $list = com_MEDIALIBRARY_CATEGORYArray($lang);
        } else {
            $list = com_MEDIALIBRARY_CATEGORYArray();
        }
    //$list = com_MEDIALIBRARY_CATEGORYArray();
    $cat = new mainMedialibraryCategories($database); //for 1.6
    $cat->load($id);
    $this_treename = '';
    $childs_ids = Array();
    foreach($list as $item) {
        if ($item->id == $cat->id || array_key_exists($item->parent_id, $childs_ids)) 
            $childs_ids[$item->id] = $item->id;
    }
    foreach($list as $item) {
        if ($this_treename) {
            if ($item->id != $cat->id && strpos($item->treename, $this_treename) === false && 
                    array_key_exists($item->id, $childs_ids) === false) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            }
        } else {
            if ($item->id != $cat->id) {
                $options[] = mosHTML::makeOption($item->id, $item->treename);
            } else {
                $this_treename = "$item->treename/";
            }
        }
    }
    $parent = null;
    $parent = mosHTML::selectList($options, 'catid', 'class="inputbox" size="1" style="width: 140px"', 
            'value', 'text', $cat->parent_id);
    return $parent;
}


function com_MEDIALIBRARY_CATEGORYArray($lang='') {
    global $database, $my, $acl;
    // get a list of the menu items
    if($lang){
        $query = "SELECT c.*, c.parent_id AS parent, c.params AS access"
        . "\n FROM #__medialibrary_main_categories c"
        . "\n WHERE section='com_medialibrary'"
        . "\n AND published =1"
        . "\n AND $lang"
        . "\n ORDER BY ordering";
        $database->setQuery($query);
        $items = $database->loadObjectList();
    } else {
       $query = "SELECT c.*, c.parent_id AS parent, c.params AS access"
        . "\n FROM #__medialibrary_main_categories c"
        . "\n WHERE section='com_medialibrary'"
        . "\n AND published =1"
        . "\n ORDER BY ordering";
        $database->setQuery($query);
        $items = $database->loadObjectList();
    }

    foreach($items as $r => $cat_item) {
        if (!checkAccess_ML($cat_item->access, 'RECURSE', userGID_ML($my->id), $acl)) { 
            //if have not access then remove book from search
            unset($items[$r]);
        }
    }
    $items = array_values($items);
    // establish the hierarchy of the menu
    $children = array();
    // first pass - collect children
    foreach($items as $v) {
        $pt = $v->parent;
        $list = @$children[$pt] ? $children[$pt] : array();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $array = mosTreeRecurse(0, '', array(), $children);
    return $array;
}


function lend($option, $mid) {
    global $database, $my;
    addTitleAndMetaTags();
    if (!is_array($mid) || count($mid) !== 1) {
        echo "<script> alert('" . _MEDIALIBRARY_SELECT_ONE_ITEM_TO_LEND 
            . "'); window.history.go(-1);</script>\n";
        exit;
    }

    foreach($mid as $mid_to_intval) {
        $mid_check[] = intval($mid_to_intval);
    }
    $mids = implode(',', $mid_check);
    $select = "SELECT allmedia.id, allmedia.title, allmedia.mediaid, l.fk_userid, 
        m.id AS mainid, m.media_type,".
          " cc.name AS category, l.lend_from AS lend_from, " .
          "\nl.lend_return AS lend_return, l.lend_until AS lend_until, " .
          "\nl.user_name AS user_name, l.user_email AS user_email, u.name " .
          "\nFROM #__medialibrary AS m" .
          "\nLEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id" .
                    "\nLEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid" .
                    "\nLEFT JOIN #__medialibrary_lend AS l ON l.id = m.fk_lendid" .
                    "\nLEFT JOIN #__users AS u ON u.id=fk_userid" .
                    "\nLEFT JOIN (SELECT id, title, game_id AS mediaid, 'game' AS type 
                        FROM #__medialibrary_game " .
                    "\nUNION all SELECT id, title, music_id AS mediaid, 'music' AS type 
                        FROM #__medialibrary_music " .
                    "\nUNION all SELECT id, title, book_id AS mediaid, 'book' AS type 
                        FROM #__medialibrary_book " .
                    "\nUNION all SELECT id, title, video_id AS mediaid, 'video' AS type 
                        FROM #__medialibrary_video) " .
                    "\nAS allmedia ON allmedia.id = m.media_id AND allmedia.type = m.media_type" .
                    "\nWHERE m.id = $mids";
    $database->setQuery($select);
    if (!$database->query()) {
        echo "<script> alert('" . addslashes(preg_replace('~[\r\n]~', ' ', 
                $database->getErrorMsg())) . "'); window.history.go(-1); </script>\n";
        exit();
    }
    $medias = $database->loadObject();

    $bids_assoc = getAssociatMedias($mids);
    $medias_assoc[] = $medias;
    if($bids_assoc) {
        $selectstring = "SELECT library.id, library.media_type, library.media_id as mediaid," .
        "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
        " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
        " l.lend_until as lend_until, l.user_name as user_name , l.lend_return, " .
        " l.user_email AS user_email, l.fk_userid as fk_userid ," .
        " other_table.id as media_type_id,  other_table.title as title  " .
        " FROM #__medialibrary AS library " .
        " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
        " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
        " LEFT JOIN #__medialibrary_lend AS l ON l.id = library.fk_lendid" .
        " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
        " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
        " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
        " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
        " AS other_table ON other_table.id = library.media_id and 
            other_table.type = library.media_type" .
        " WHERE library.id in (" . $bids_assoc . ")";
        $database->setQuery($selectstring);
        $medias_assoc = $database->loadObjectList();
    }
    // get list of categories
    $userlist[] = mosHTML::makeOption('-1', '----------');
    $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
    $userlist = array_merge($userlist, $database->loadObjectList());
    $usermenu = mosHTML::selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 
            'text', '-1');
    showTabs();
    HTML_medialibrary::showLendMedias($option, $medias, $medias_assoc, $usermenu, "lend");
}


function saveLend($option, $mids, $task = "") {
    global $database, $Itemid, $medialibrary_configuration, $my;
    $checkmedia = mosGetParam($_REQUEST, 'checkMedia');
    if ($checkmedia != "on") {
        echo "<script> alert('Select an item to lend'); window.history.go(-1);</script>\n";
        exit;
    }
    $data = JFactory::getDBO();
    $mediaid = mosGetParam($_REQUEST, 'mediaid');
    $id = mosGetParam($_REQUEST, 'id');
    $ids = getAssociatMedias($id);
    if ($ids == "") $ids = $id;
    $ids = explode(',', $ids);

    $lend_from = protectInjection('lend_from');
    $lend_until = protectInjection('lend_until');
  for ($i = 0, $n = count($ids);$i < $n;$i++) {

    $lend = new mosMediaLibrary_lend($database);
    if ($task == "edit_lend") $lend->load($mids[0]);
    $query = "SELECT * FROM #__medialibrary_lend where fk_mediaid= " . $ids[$i] 
        . " AND lend_return is NULL ";
    $data->setQuery($query);
    $lendTerm = $data->loadObjectList();
    $lend_from = date_format(date_create_from_format('d-Y-m', substr($lend_from, 1, 10)), 'Y-m-d');
    $lend_until = date_format(date_create_from_format('d-Y-m', substr($lend_until, 1, 10)), 'Y-m-d');
    if ($lend_from > $lend_until) {
        echo "<script> alert('" . $lend_from . " more then " . $lend_until 
            . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if(isset($lendTerm[0])) {
        for($e = 0, $m = count($lendTerm);$e < $m;$e++) {
            if($task == "edit_lend" && $mids[0] == $lendTerm[$e]->id)
                    continue;
            $lendTerm[$e]->lend_from = substr($lendTerm[$e]->lend_from, 0, 10);
            $lendTerm[$e]->lend_until = substr($lendTerm[$e]->lend_until, 0, 10);
            //Lend check
            if(($lend_from >= $lendTerm[$e]->lend_from && $lend_from <= $lendTerm[$e]->lend_until) ||
                   ($lend_from <= $lendTerm[$e]->lend_from && $lend_until>= $lendTerm[$e]->lend_until) ||
                 ($lend_until >= $lendTerm[$e]->lend_from && $lend_until <= $lendTerm[$e]->lend_until)) {
                echo "<script> alert('Sorry, this object already lend out from " 
                    . $lendTerm[$e]->lend_from . " to " . $lendTerm[$e]->lend_until 
                    . "'); window.history.go(-1); </script>\n";
                exit();
            }
        }
    }
    if (mosGetParam($_REQUEST, 'lend_from') != "")
            $lend->lend_from = mosGetParam($_REQUEST, 'lend_from');
    else
            $lend->lend_from = null;

    if (mosGetParam($_REQUEST, 'lend_until') != "")
            $lend->lend_until = mosGetParam($_REQUEST, 'lend_until');
    else
            $lend->lend_until = null;

        $d_format = str_replace("%", '', $medialibrary_configuration["date_format"]);
        $from = DateTime::createFromFormat($d_format, trim($_REQUEST["lend_from"]));
        $until = DateTime::createFromFormat($d_format, trim($_REQUEST["lend_until"]));
        if ($from === FALSE or $until === FALSE) {
              echo "<script> alert('Bad date format'); window.history.go(-1); </script>\n";
            // exit;
        }
        $lend->lend_from = $from->format('Y-m-d');
        $lend->lend_until = $until->format('Y-m-d');;

    $lend->fk_mediaid = $ids[$i];
    $userid = mosGetParam($_REQUEST, 'userid');
    if ($my->id != 0)
            $lend->fk_userid = $my->id;
    if ($userid == "-1") {
        $lend->user_name = protectInjection('user_name', '');
        $lend->user_email = protectInjection('user_email', '');
    } else {
        $lend->getLendTo(intval($userid));
    }
    if (!$lend->check($lend)) {
        echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
    if (!$lend->store()) {
        echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    }
    $lend->checkin();
    $media = new mosMediaLibrary($database);
    $media->load($ids[$i]);
    $media->fk_lendid = $lend->id;
    $media->store();
    $media->checkin();
    if ($option == 'com_comprofiler') {
        $link_for_mosRedirect = "index.php?option=" . $option 
            . "&task=mymedias&tab=getmymediasTab&Itemid=" . $Itemid;
    } else {
        $link_for_mosRedirect = JRoute::_("index.php?option=" . $option 
                . "&task=mymedias&Itemid=" . $Itemid, false);
    }
 }
    mosRedirect($link_for_mosRedirect);
}

function lend_return($option, $mid) {
    global $database, $my, $Itemid;
    addTitleAndMetaTags();
    if (!is_array($mid) || count($mid) !== 1) {
        echo "<script> alert('" . _MEDIALIBRARY_SELECT_ONE_ITEM_TO_LEND 
            . "'); window.history.go(-1);</script>\n";
        exit;
    }
    $mids = implode(',', $mid);
    $select = "SELECT allmedia.id, allmedia.title, allmedia.mediaid, l.id AS lid, l.fk_userid, 
                    m.id AS mainid," .
                      "m.media_type, cc.name AS category, l.lend_from AS lend_from, " .
                      "l.lend_return AS lend_return, l.lend_until AS lend_until, " .
                      "l.user_name AS user_name, l.user_email AS user_email, u.name " .
                      "\nFROM #__medialibrary AS m" .
                      "\nLEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = m.id" .
                      "\nLEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid" .
                      "\nLEFT JOIN #__medialibrary_lend AS l ON l.fk_mediaid = m.id" .
                      "\nLEFT JOIN #__users AS u ON l.fk_userid = u.id" .
                      "\nLEFT JOIN (SELECT id, title, game_id AS mediaid, 'game' AS type 
                        FROM #__medialibrary_game " .
                      "\nUNION all SELECT id, title, music_id AS mediaid, 'music' AS type
                        FROM #__medialibrary_music " .
                      "\nUNION all SELECT id, title, book_id AS mediaid, 'book' AS type 
                        FROM #__medialibrary_book " .
                      "\nUNION all SELECT id, title, video_id AS mediaid, 'video' AS type 
                        FROM #__medialibrary_video) " .
                      "\nAS allmedia ON allmedia.id = m.media_id AND allmedia.type = m.media_type" .
                      "\nWHERE l.fk_mediaid IN (" . $mids . ")";
    $database->setQuery($select);
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit;
    }
    $medias = $database->loadObject();
    $count = count($medias);

    if (((@$medias->lend_from) == '') && ((@$medias->lend_return) == '')) {
?>
            <script type="text/JavaScript" language = "JavaScript">
                alert('You cannot return medias that were not lent out!');
                window.history.go(-1);
            </script>
<?php
        exit;
    }
        $bids = getAssociatMedias($mids);
        if($bids == ""){
           $bids = $mids;
        }
        $medias_lends_assoc = array();
        $title_assoc = array();
        if($bids) {
          $selectstring = "SELECT library.*," .
          "cc.title AS category, mc.catid, " . " l.id as lendid, l.lend_from as lend_from, " .
            " l.lend_from as lend_from, library.fk_lendid as fk_lendid, " .
            " l.lend_until as lend_until, l.lend_return as lend_return, l.user_name as user_name ," .
              " l.user_email as user_email, l.fk_userid as fk_userid ," .
              " other_table.id as media_type_id,  other_table.title as title  " .
                " FROM #__medialibrary_lend AS l, #__medialibrary AS library " .
                " LEFT JOIN #__medialibrary_categories AS mc ON mc.mediaid = library.id " .
                  " LEFT JOIN #__medialibrary_main_categories AS cc ON cc.id = mc.catid " .
                  " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
                    " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
                    " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
                      " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
                      " AS other_table ON other_table.id = library.media_id and 
                        other_table.type = library.media_type" .
                        " WHERE library.id in (" . $bids . ")";
          $database->setQuery($selectstring);
          $medias_lends_assoc = $database->loadObjectList();

          $selectstring = "SELECT DISTINCT other_table.id, other_table.title as title  " .
          " FROM #__medialibrary_lend AS l, #__medialibrary AS library " .
          " LEFT JOIN (SELECT id, title, 'game' as type FROM #__medialibrary_game " .
          " UNION all SELECT id, title, 'music' as type FROM #__medialibrary_music " .
          " UNION all SELECT id, title, 'book' as type FROM #__medialibrary_book " .
          " UNION all SELECT id, title, 'video' as type FROM #__medialibrary_video) " .
          " AS other_table ON other_table.id = library.media_id and 
            other_table.type = library.media_type " .
          "\nWHERE library.id in ($bids)";
          $database->setQuery($selectstring);
          $title_assoc = $database->loadObjectList();

          $is_lend_out = false;
          for ($i = 0;$i < count($medias_lends_assoc);$i++) {
              if ($medias_lends_assoc[$i]->lend_from != '' && 
                    $medias_lends_assoc[$i]->lend_return == '') {
                  $is_lend_out = true;
                  break;
              }
          }
          if (!$is_lend_out) { ?>
              <script type = "text/JavaScript" language = "JavaScript">
                  alert("<?php echo _MEDIALIBRARY_CANNOT_RETURN_BOOK_THAT_WERE_NOT_LEND_OUT; ?>");
                  window.history.go(-1);
              </script>
              <?php
              exit;
          }
        //check lend_return == null count for all assosiate
        $ids = explode(',', $bids);
        $lend_count = - 1;
        $all_assosiate_lend = array();
        $count = count($ids);
        for ($i=0;$i<$count;$i++) {
            $query = "SELECT * FROM #__medialibrary_lend WHERE fk_mediaid = " . $ids[$i] .
                     " and lend_return is null ORDER BY lend_from";
            $database->setQuery($query);
            $all_assosiate_lend_item = $database->loadObjectList();
            if ($lend_count != - 1 && $lend_count != count($all_assosiate_lend_item)) {
?>
                <script type = "text/JavaScript" language = "JavaScript">
                    alert("<?php echo _MEDIALIBRARY_ERROR_IN_LEND_FOR_ASSOCIATED; ?>");
                    window.history.go(-1);
                </script>
                <?php
                exit;
            }
            $lend_count = count($all_assosiate_lend_item);
            $all_assosiate_lend[] = $all_assosiate_lend_item;
        }
    }
    // get list of users
    $userlist[] = mosHTML::makeOption('-1', '----------');
    $database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
    $userlist = array_merge($userlist, $database->loadObjectList());
    $usermenu = mosHTML::selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 
            'text', '-1');
    showTabs();
    HTML_medialibrary::editLendMedias($option, $medias, $medias_lends_assoc, $title_assoc, 
            $all_assosiate_lend, $usermenu, "lend_return");
}


function saveLend_return($option, $lids) {
    global $database, $my, $Itemid;
    $mediaid = mosGetParam($_REQUEST, 'mediaid');
    $id = mosGetParam($_REQUEST, 'id');
    $lend_from = protectInjection('lend_from');
    $lend_until = protectInjection('lend_until');
    if (!is_array($lids) || count($lids) < 1) {
        echo "<script> alert('Select an item to return'); window.history.go(-1);</script>\n";
        exit;
    }
    for ($i = 0, $n = count($lids);$i < $n;$i++) {
        $lend = new mosMediaLibrary_lend($database);
        $lend->load($lids[$i]);
        if ($lend->lend_return != null) {
            echo "<script> alert('Media already returned'); window.history.go(-1);</script>\n";
            exit;
        }
        $lend->lend_return = date("Y-m-d H:i:s");
        if (!$lend->check($lend)) {
            echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
            exit;
        }
        if (!$lend->store()) {
            echo "<script> alert('" . $lend->getError() . "'); window.history.go(-1); </script>\n";
            exit;
        }
        $lend->checkin();
        $media = new mosMediaLibrary($database);
        $media->load($id);
        $media->fk_lendid = 0;
        $media->store();
        $media->checkin();
    }
    if ($option == 'com_comprofiler') {
        $link_for_mosRedirect = "index.php?option=" . $option 
            . "&task=mymedias&tab=getmymediasTab&Itemid=" . $Itemid;
    } else {
        $link_for_mosRedirect = "index.php?option=" . $option . "&task=mymedias&Itemid=" . $Itemid;
    }
    mosRedirect($link_for_mosRedirect);
}



