<?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
 *
 */
/**
 * This file provides compatibility for MediaLibrary on Joomla! 1.0.x and Joomla! 1.5
 *
 */
/**
 * Legacy function, use <jdoc:include type="module" /> instead
 *
 * @deprecated        As of version 1.5
 */
$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;

require_once ($mosConfig_absolute_path . "/components/com_medialibrary/compat.joomla1.5.php");
require_once $mosConfig_absolute_path . "/administrator/components/com_medialibrary/admin.medialibrary.class.conf.php";


if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!function_exists('mosLoadModule')) {
    function mosLoadModule($name, $style = - 1) {
?><jdoc:include type="module" name="<?php echo $name ?>" style="<?php echo $style ?>" /><?php
    }
}
/**
 * Legacy function, using <jdoc:include type="modules" /> instead
 *
 * @deprecated  As of version 1.5
 */

if(!function_exists('available_dates')){
  function available_dates($media_id){
    global $database,$realestatemanager_configuration;
    $date_NA = array();
    $query = "SELECT lend_from, lend_until FROM #__medialibrary_lend WHERE fk_mediaid='".$media_id.
      "' AND lend_return is null";
    $database->setQuery($query);
    $calenDate = $database->loadObjectList();
    foreach($calenDate as $calenDate){     
      $not_av_from = $calenDate->lend_from;
      $not_av_until = $calenDate->lend_until;
      $not_av_from_begin = new DateTime( $not_av_from);
      $not_av_until_end = new DateTime( $not_av_until);
     
        $not_av_until_end = $not_av_until_end->modify( '+1 day' ); 
      
      $interval = new DateInterval('P1D');
      $daterange = new DatePeriod($not_av_from_begin, $interval, $not_av_until_end);
      foreach($daterange as $datess){
          $date_NA[] = $datess->format("Y-m-d");
          $date_NA[] = $datess->format("d-m-Y");
      }
    }               
  return $date_NA;
  }   
}

if(!function_exists('transforDateFromPhpToJqueryML')){
  function transforDateFromPhpToJqueryML(){
    global $medialibrary_configuration;
    $DateToFormat = str_replace("d",'dd',(str_replace("m",'mm',(str_replace("Y",'yy',(
      str_replace('%','',$medialibrary_configuration['date_format'])))))));
    return $DateToFormat;
  }
}


if (!function_exists('mosMail')) {
    function mosMail($from, $fromname, $recipient, $subject, $body, $mode = 0, $cc = NULL, $bcc = NULL, 
        $attachment = NULL, $replyto = NULL, $replytoname = NULL) {
        $mail = JFactory::getMailer();
        return $mail->sendMail($from, $fromname, $recipient, $subject, $body, $mode, $cc, $bcc, 
                $attachment, $replyto, $replytoname);
    }
}
if (!function_exists('mosLoadAdminModules')) {
    function mosLoadAdminModules($position = 'left', $style = 0) {
        // Select the module chrome function
        if (is_numeric($style)) {
            switch ($style) {
                case 2:
                    $style = 'xhtml';
                break;
                case 0:
                default:
                    $style = 'raw';
                break;
            }
        }
?><jdoc:include type="modules" name="<?php echo $position ?>" style="<?php echo $style ?>" /><?php
    }
}
/**
 * Legacy function, using <jdoc:include type="module" /> instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosLoadAdminModule')) {
    function mosLoadAdminModule($name, $style = 0) {
?><jdoc:include type="module" name="<?php echo $name ?>" style="<?php echo $style ?>" /><?php
    }
}
/**
 * Legacy function, always use {@link JRequest::getVar()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosStripslashes')) {
    function mosStripslashes(&$value) {
        $ret = '';
        if (is_string($value)) {
            $ret = stripslashes($value);
        } else {
            if (is_array($value)) {
                $ret = array();
                foreach($value as $key => $val) {
                    $ret[$key] = mosStripslashes($val);
                }
            } else {
                $ret = $value;
            }
        }
        return $ret;
    }
}
/**
 * Legacy function, use {@link JFolder::files()} or {@link JFolder::folders()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosReadDirectory')) {
    function mosReadDirectory($path, $filter = '.', $recurse = false, $fullpath = false) {
        $arr = array(null);
        // Get the files and folders
        jimport('joomla.filesystem.folder');
        $files = JFolder::files($path, $filter, $recurse, $fullpath);
        $folders = JFolder::folders($path, $filter, $recurse, $fullpath);
        // Merge files and folders into one array
        $arr = array_merge($files, $folders);
        // Sort them all
        asort($arr);
        return $arr;
    }
}
/**
 * Legacy function, use {@link JApplication::redirect() JApplication->redirect()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosRedirect')) {
    function mosRedirect($url, $msg = '') {
        //global $mainframe;
        $mainframe = JFactory::getApplication(); // for J 1.6
        $mainframe->redirect($url, $msg);
    }
}
/**
 * Legacy function, use {@link JArrayHelper::getValue()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosGetParam')) {
    function mosGetParam(&$arr, $name, $def = null, $mask = 0) {
        // Static input filters for specific settings
        static $noHtmlFilter = null;
        static $safeHtmlFilter = null;
        $var = JArrayHelper::getValue($arr, $name, $def, '');
        // If the no trim flag is not set, trim the variable
        if (!($mask & 1) && is_string($var)) {
            $var = trim($var);
        }
        // Now we handle input filtering
        if ($mask & 2) {
            // If the allow html flag is set, apply a safe html filter to the variable
            if (is_null($safeHtmlFilter)) {
                $safeHtmlFilter = JFilterInput::getInstance(null, null, 1, 1);
            }
            $var = $safeHtmlFilter->clean($var, 'none');
        } elseif ($mask & 4) {
            // If the allow raw flag is set, do not modify the variable
            $var = $var;
        } else {
            // Since no allow flags were set, we will apply the most strict filter to the variable
            if (is_null($noHtmlFilter)) {
                $noHtmlFilter = JFilterInput::getInstance( /* $tags, $attr, $tag_method, 
                    $attr_method, $xss_auto */
                );
            }
            $var = $noHtmlFilter->clean($var, 'none');
        }
        return $var;
    }
}
//format money
if (!function_exists("formatMoney")) {
    function formatMoney($number, $fractional = false, $pattern = ".") {
        if ($fractional) {
            $number = sprintf('%.2f', $number);
        }
        if ($pattern == ".") $number = str_replace(".", ",", $number);
        while (true) {
            $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1' . $pattern . '$2', $number);
            //echo $replaced."<br>";
            if ($replaced != $number) {
                $number = $replaced;
            } else {
                break;
            }
        }
        // $number = preg_replace('/\^/', $number, $pattern);
        return $number;
    }
}
/**
 * Legacy function, use {@link JEditor::save()} or {@link JEditor::getContent()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('getEditorContents')) {
    function getEditorContents($editorArea, $hiddenField) {
        jimport('joomla.html.editor');
        $editor = JFactory::getEditor();
        echo $editor->save($hiddenField);
    }
}
/**
 * Legacy function, use {@link JFilterOutput::objectHTMLSafe()} instead
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosMakeHtmlSafe')) {
    function mosMakeHtmlSafe(&$mixed, $quote_style = ENT_QUOTES, $exclude_keys = '') {
        JFilterOutput::objectHTMLSafe($mixed, $quote_style, $exclude_keys);
    }
}
/**
 * Legacy utility function to provide ToolTips
 *
 * @deprecated As of version 1.5
 */
if (!function_exists('mosToolTip')) {
    function mosToolTip($tooltip, $title = '', $width = '', $image = 'tooltip.png', $text = '', 
            $href = '', $link = 1) {
        // Initialize the toolips if required
        static $init;
        if (!$init) {
            JHTML::_('behavior.tooltip');
            $init = true;
        }
        return JHTML::_('tooltip', $tooltip, $title, $image, $text, $href, $link);
    }
}
/**
 * Legacy function to replaces &amp; with & for xhtml compliance
 *
 * @deprecated  As of version 1.5
 */
if (!function_exists('mosTreeRecurse')) {
    function mosTreeRecurse($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, $type = 1) {
        jimport('joomla.html.html');
        return JHTML::_('menu.treerecurse', $id, $indent, $list, $children, $maxlevel, $level, $type);
    }
}
// [author]: Wonderer
// [description]: Analogue of
//    $usergroups = $acl->get_group_parents($my->gid,'ARO','RECURSE');
//    for 1.6
// [call]: $usergroups = getGroupsByUser ($my->id,'RECURSE');   $usergroups = getGroupsByUser 
// ($my->id,'');
// [date]: 03 June 2011
if (!function_exists('getGroupsByUser')) {
    function getGroupsByUser($uid, $recurse) {
        if (version_compare(JVERSION, "1.6.0", "lt")) {
        } else if (version_compare(JVERSION, "1.6.0", "ge")) {
            $database = JFactory::getDBO();
            // Variant with standard functions...
            /*if ( $recurse == 'RECURSE' ){
            return JAccess::getGroupsByUser ( $uid, true );
            } else{
            return JAccess::getGroupsByUser ( $uid, false );
            }*/
            // Custom algorythm
            $usergroups = array();
            if ($recurse == 'RECURSE') {
                // [1]: Recurse getting the usergroups
                $id_group = array();
                $q1 = "SELECT group_id FROM `#__user_usergroup_map` WHERE user_id={$uid}";
                $database->setQuery($q1);
                $rows1 = $database->loadObjectList();
                foreach($rows1 as $v) {
                    $id_group[] = $v->group_id;
                }
                for ($k = 0;$k < count($id_group);$k++) {
                    $q = "SELECT g2.id 
                          FROM `#__usergroups` g1 LEFT JOIN `#__usergroups` g2 
                          ON g1.lft > g2.lft AND g1.lft < g2.rgt 
                          WHERE g1.id={$id_group[$k]} 
                          ORDER BY g2.lft";
                    $database->setQuery($q);
                    $rows = $database->loadObjectList();
                    foreach($rows as $r) {
                        $usergroups[] = $r->id;
                    }
                }
                $usergroups = array_unique($usergroups);
            }
            // [2]: Non-Recurse getting usergroups
            $q = "SELECT * FROM #__user_usergroup_map WHERE user_id = {$uid}";
            $database->setQuery($q);
            $rows = $database->loadObjectList();
            foreach($rows as $k => $v) {
                $usergroups[] = $rows[$k]->group_id;
            }
            // If user is unregistered, Joomla contains it into standard group (Public by default).
            // So, groupId for anonymous users is 1 (by default).
            // But custom algorythm doesnt do this: if user is not autorised, he will NOT 
            // connected to any group.
            // And groupId will be 0.
            if (count($rows) == 0) {
                $usergroups[] = - 2;
            }
            return $usergroups;
        } else {
            echo "Sanity test. Error version check!";
            exit;
        }
    }
}
if (!function_exists('MediaLibraryTreeRecurse')) {
    function MediaLibraryTreeRecurse($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, 
            $type = 1) {
        if (@$children[$id] && $level <= $maxlevel) {
            $parent_id = $id;
            foreach($children[$id] as $v) {
                $id = $v->id;
                if ($type) {
                    $pre = 'L ';
                    $spacer = '.      ';
                } else {
                    $pre = '- ';
                    $spacer = '  ';
                }
                if ($v->parent == 0) {
                    $txt = $v->name;
                } else {
                    $txt = $pre . $v->name;
                }
                $pt = $v->parent;
                $list[$id] = $v;
                $list[$id]->treename = "$indent$txt";
                $list[$id]->children = (isset($children[$id]) && is_array($children[$id])) ? count(@$children[$id]) : 0;
                $list[$id]->all_fields_in_list = count(@$children[$parent_id]);
                $list = MediaLibraryTreeRecurse($id, $indent . $spacer, $list, $children, $maxlevel, 
                        $level + 1, $type);
            }
        }
        return $list;
    }
}
// [author]: Wonderer
// [description]:
//  Returns a string for WHERE condition
// instead of using $usergroups.
// Now we replace an old (c.params IN ('.$usergroups.') construction
// with ({$s}).
// [call]: $s = getWhereUsergroupsString ( "alias_name" );
// (alias_name) its a `#__medialibrary_main_categories` table alias.
// (alias_name) depends of the particular query, as usual its "c", "cc" or something like this.
// [date]: 13 June 2011
if (!function_exists('getWhereUsergroupsString')) {
    function getWhereUsergroupsString($table_alias) {
        global $my;
        if (isset($my->id) AND $my->id != 0) {
            $usergroups_sh = getGroupsByUser($my->id, '');
            //$usergroups_sh = '-2'.$usergroups_sh;

        } else {
            $usergroups_sh = array();
        }
        $usergroups_sh[] = - 2;
        $s = '';
        for ($i = 0;$i < count($usergroups_sh);$i++) {
            $g = $usergroups_sh[$i];
            $s.= " $table_alias.params LIKE '%,{$g}' or $table_alias.params = '{$g}' or $table_alias."
                ."params LIKE '{$g},%' or $table_alias.params LIKE '%,{$g},%' ";
            if (($i + 1) < count($usergroups_sh)) $s.= ' or ';
        }
        return $s;
    }
}
if (!function_exists('checkAccess_ML')) {
    function checkAccess_ML($accessgroupid, $recurse, $usersgroupid, $acl) {
        if (!is_array($usersgroupid)) {
            $usersgroupid = $usersgroupid * 1;
            if (!(is_int($usersgroupid))) return false;
            else {
                if (is_int($usersgroupid) AND isset($usersgroupid) AND $usersgroupid > 0) {
                    $t = $usersgroupid;
                    $usersgroupid = (array)$usersgroupid; // force to array
                    $usersgroupid[] = $t;
                } elseif (is_int($usersgroupid) AND isset($usersgroupid) AND $usersgroupid == 0) {
                    $usersgroupid = (array)$usersgroupid; // force to array
                    $usersgroupid[] = 0;
                }
            }
        }
        //parse usergroups
        $tempArr = array();
        $tempArr = explode(',', $accessgroupid);
        for ($i = 0;$i < count($tempArr);$i++) {
            if (((!is_array($usersgroupid) && $tempArr[$i] == $usersgroupid) OR 
                (is_array($usersgroupid) && in_array($tempArr[$i], $usersgroupid))) || 
                $tempArr[$i] == - 2) {
                //allow access
                return true;
            } else {
                if ($recurse == 'RECURSE') {
                    if (is_array($usersgroupid)) {
                        for ($j = 0;$j < count($usersgroupid);$j++) if (in_array($usersgroupid[$j], 
                                $tempArr)) return 1;
                    } else {
                        if (in_array($usersgroupid, $tempArr)) return 1;
                    }
                }
            }
        } // end for
        //deny access
        return 0;
    } // End of checkAccess_ML()

}
if (!function_exists('addSubMenumedialibrary')) {
    function addSubmenuMediaLibrary($vName) {
        if (!defined('_MEDIALIBRARY_HEADER_NUMBER')) loadConstMedia();
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_HEADER_NUMBER), 
            'index.php?option=com_medialibrary', $vName == 'Media');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_SHOW_PEOPLE), 
            'index.php?option=com_medialibrary&task=manage_author', $vName == 'Add people');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_CATEGORIES_NAME), 
            'index.php?option=com_medialibrary&section=categories', $vName == 'Categories');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_LABEL_REVIEWS), 
            'index.php?option=com_medialibrary&task=manage_review', $vName == 'Reviews');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_SHOW_LEND_REQUESTS), 
            'index.php?option=com_medialibrary&task=lend_requests', $vName == 'Lend Requests');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_USER_LEND_HISTORY), 
            'index.php?option=com_medialibrary&task=user_lend_history', $vName == 'User Lend History');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_SHOW_IMPORT_EXPORT), 
            'index.php?option=com_medialibrary&task=show_import_export', $vName == 'Import/Export');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_LANGUAGE_MANAGER), 
            'index.php?option=com_medialibrary&section=language_manager', $vName == 'Language Manager');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_SHOW_SETTINGS), 
            'index.php?option=com_medialibrary&task=config', $vName == 'Settings');
        JSubMenuHelper::addEntry(JText::_(_MEDIALIBRARY_ADMIN_ABOUT_ABOUT), 
            'index.php?option=com_medialibrary&task=about', $vName == 'About');
    }
}




if (!function_exists('loadConstMedia')) {
  function loadConstMedia() {
    global $database, $mosConfig_absolute_path;
    $is_exception = false;
    $database->setQuery("SELECT * FROM #__medialibrary_languages");
    $langs = $database->loadObjectList();
    $component_path = JPath::clean($mosConfig_absolute_path . '/components/com_medialibrary/language/');
    $component_constans = array();
    if (is_dir($component_path) && ($component_constans =
      JFolder::files($component_path, '^[^_]*\.php$', false, true))) {
        //check and add constants file in DB
        foreach ($component_constans as $i => $file) {
          $file_name = pathinfo($file);
          $file_name = $file_name['filename'];
          if ($file_name === 'constant') {
            require($mosConfig_absolute_path . "/components/com_medialibrary/language/$file_name.php");
            foreach ($constMas as $mas) {
              $database->setQuery(
                "INSERT IGNORE INTO #__medialibrary_const (const, sys_type) VALUES ('".
                $mas["const"]."','".$mas["sys_type"]."')");
              $database->query();
            }
          }
        }
        //check and add new text files in DB
        $flag1=true;
        print_r("<b>These constants exit in Languages files but not exist in file constants:</b>
                <br><br>");
        foreach ($component_constans as $i => $file) {
          $file_name = pathinfo($file);
          $file_name = $file_name['filename'];
          $LangLocal = '';
          if ($file_name != 'constant') {
            require($mosConfig_absolute_path . "/components/com_medialibrary/language/$file_name.php");
            try {
              $database->setQuery("INSERT IGNORE INTO #__medialibrary_languages (lang_code,title) 
                                   VALUES ('"
                        . $LangLocal['lang_code'] . "','" . $LangLocal['title'] . "')");
              $database->query();
              $database->setQuery("SELECT id FROM #__medialibrary_languages " .
                 " WHERE lang_code = '" . $LangLocal['lang_code'] 
                 . "' AND title='".$LangLocal['title']."'");
              $idLang = $database->loadResult();
              foreach ($constLang as $item) {
                //if(!isset($item['value_const'])) var_dump($item);
                $database->setQuery("SELECT id FROM #__medialibrary_const WHERE const = '" 
                    . $item['const'] . "'");
                $idConst = $database->loadResult();
                if(!array_key_exists ( 'value_const'  , $item ) || !$idConst){
                     print_r($item['const']." not exist in file <b>'constant'</b> for this language: <b>"
                   . $LangLocal['title']."</b>.");
                   $flag1 = false;
                } else {
                  $database->setQuery(
                   "INSERT IGNORE INTO #__medialibrary_const_languages (
                    fk_constid,fk_languagesid,value_const) "
                   . " VALUES ($idConst, $idLang, " . $database->quote($item['value_const']) . ")");
                  $database->query();
                }
              }
            } catch (Exception $e) {
              $is_exception = true;
              //echo 'Send exception, please write to admin for language check: ',  
              // $e->getMessage(), "\n";
            }
          }
        }
        if($flag1){
          print_r("<br /><p style='color:green;'><b>Everything is [ OK ]</b></p><br />");
        }
        else{
          print_r("<br><b style='color:red;'>This constants not loaded.!</b><br><br>");
        }

        //if text constant missing recover they in DB
        if (!defined('_HEADER_NUMBER')) {
              $query = "SELECT c.const, cl.value_const ";
              $query .= "FROM #__medialibrary_const_languages as cl ";
              $query .= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
              $query .= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id ";
              $query .= "WHERE l.lang_code = 'en-GB'";
              $database->setQuery($query);
              $langConst = $database->loadObjectList();
          foreach ($langConst as $item) {
            if(!defined($item->const)){
              defined($item->const) or define($item->const, $item->value_const);
            }
          }
        }
    }

    //if some language file missing recover it
    $component_path = JPath::clean($mosConfig_absolute_path . '/components/com_medialibrary/language/');
    $component_constans = array();
    if (is_dir($component_path) && ($component_constans = JFolder::files($component_path, 
        '^[^_]*\.php$', false, true))) {
      foreach ($component_constans as $i => $file) {
        $isLang = 0;
        $file_name = pathinfo($file);
        $file_name = $file_name['filename'];
        if ($file_name != 'constant') {
          require($mosConfig_absolute_path . "/components/com_medialibrary/language/$file_name.php");
          //$fileMas[] = $LangLocal;
          $fileMas[] = $LangLocal['title'];
        }
      }
    }

    $database->setQuery("SELECT title FROM #__medialibrary_languages");
    if (version_compare(JVERSION, '3.0', 'lt')) {
      $langs = $database->loadResultArray();
    } else {
      $langs = $database->loadColumn();
    }

    if (count($langs) > count($fileMas)) {
      $results = array_diff($langs, $fileMas);
      foreach ($results as $result) {
        $database->setQuery("SELECT lang_code FROM #__medialibrary_languages WHERE title = '$result'");
        $lang_code = $database->loadResult();
        $langfile = "<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) 
            die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );";
        $langfile.= "\n/**\n*\n* @package  Medialibrary\n* ";
        $langfile.= "@copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); ";
        $langfile.= "Rob de Cleen(rob@decleen.com);\n* Homepage: https://ordasoft.com\n* ";
        $langfile.= "@version: 4.5 Pro\n*\n* */\n";
        $langfile.= "\$LangLocal = array('lang_code'=>'$lang_code', 'title'=>'$result');\n";
        $langfile.= "\$constLang = array();\n";
        $query = "SELECT c.const, cl.value_const ";
        $query.= "FROM #__medialibrary_const_languages as cl ";
        $query.= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
        $query.= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id ";
        $query.= "WHERE l.title = '$result'";
        $database->setQuery($query);
        $constlanguages = $database->loadObjectList();
        foreach ($constlanguages as $constlanguage) {
            $langfile .= "\$constLang[] = array('const'=>'" . $constlanguage->const
             . "', 'value_const'=>'" . $database->quote($constlanguage->value_const) . "');\n";
        }
        // Write out new initialization file
        $fd = fopen($mosConfig_absolute_path . "/components/com_medialibrary/language/$result.php", "w")
         or die("Cannot create language file.");
        fwrite($fd, $langfile);
        fclose($fd);
      }
    }
  }
}

if (!function_exists('language_check')) {
  function language_check($component_db_name = 'medialibrary' ) {
    global $database;
    $database->setQuery("SELECT * FROM #__".$component_db_name."_languages");
    $langIds = $database->loadObjectList();
    $flag2=true;
    print_r("<br /><b>These constants exit in file constants but not exist in Languages files:</b>
            <br />");
    foreach ($langIds as $langId){
      $query = " SELECT  lc.*  FROM    #__".$component_db_name."_const as lc ";
      $query .= " WHERE  NOT EXISTS ";
      $query .= " ( SELECT  l1.*  FROM #__".$component_db_name."_const_languages as l1 ";
      $query .= " WHERE lc.id = l1.`fk_constid` and l1.fk_languagesid = ".$langId->id.") ";
      $database->setQuery($query);
      $badLangConsts = $database->loadObjectList();
        if($badLangConsts){
          $flag2 = false;
          print_r("<br />Languages: ".$langId->title."<br />");
          print_r($badLangConsts);
          echo "<br><br>";
        }
      }
      if($flag2)
        print_r("<br /><p style='color:green;'><b>Everything is [ OK ]</b></p><br /><br />");
  }
}


if (!function_exists('remove_langs')) {
    function remove_langs($component_db_name = 'medialibrary' ) {
         global $database;


        $query = " TRUNCATE TABLE #__".$component_db_name."_languages; ";
        $database->setQuery($query);
        $database->query();

        $query = " TRUNCATE TABLE #__".$component_db_name."_const; ";
        $database->setQuery($query);
        $database->query();

        $query = " TRUNCATE TABLE #__".$component_db_name."_const_languages ;";
        $database->setQuery($query);
        $database->query();

    }
}
if (!function_exists('data_transformer_med')) {
    function data_transformer_med($date,$date_format = "from") {
        if ($date_format == "from") {
            global $medialibrary_configuration;
            $mask = str_replace("%", "", $medialibrary_configuration['date_format'] . " " 
                . $medialibrary_configuration['datetime_format']);
        } else if ($date_format == "from_only_data") {
            global $medialibrary_configuration;
            $mask = str_replace("%", "", $medialibrary_configuration['date_format']);
        } else if($date_format == "to"){
            $mask = "Y-m-d H:i:s";
        }
        $unix_time = strtotime($date);
        if ($unix_time > 1000 && $unix_time < 2147483647) {
            $data_transform = date($mask, strtotime($date));
            return $data_transform;
        } else {
            return $mydate;
        }
    }
}

if (!function_exists('data_transformer')) {
    function data_transformer($date, $date_format = "from") {
            global $medialibrary_configuration, $database;
            if (strstr($date, "00:00:00") OR strlen($date) < 11) {
                $format = $medialibrary_configuration['date_format'];
                $formatForDateFormat = 'Y-m-d';
            } else {
                $format = $medialibrary_configuration['date_format'] . " " . $medialibrary_configuration['datetime_format'];
                $formatForDateFormat = 'Y-m-d H:i:s';
            }
            $formatForCreateObjDate = str_replace("%", "", $format);
            if (function_exists('date_format')) {
                $dateObject = date_create_from_format($formatForCreateObjDate, $date);
                if ($dateObject) {
                    $date = date_format($dateObject, $formatForDateFormat);
                    
                } else {
                    $dateObject = date_create_from_format($formatForCreateObjDate, $date);
                    if ($dateObject) {
                        $date = date_format($dateObject, $formatForDateFormat);
                    }
                }
            } else {


                $query = "SELECT STR_TO_DATE('$date','$format')";
                $database->setQuery($query);
                $normaDat = $database->loadResult();
                if (strlen($normaDat) > 0) {
                    $date = $normaDat;
                }
            }
            return $date;
    }
}



if(!function_exists('protectInjection')){
    function protectInjection($element, $def = '', $filter = "STRING",$bypass_get=false){
global $database;
        if(!$bypass_get){
                $value = JFactory::getApplication()->input->get($element, $def, $filter);
                // $value = $element;
             }else{
                $value = $element;
             }

        if(empty($value)) return $value; 


        if(is_array($value)){
            $start_array = $value;
        }else {
            $hash_string_start = md5($value);
        } 

        $value = str_ireplace(array("/*","*/","select", "insert", "update", "drop", "delete", "alter"), "", $value);

        if(is_array($value)){
            $end_array = $value;
        }else {
            $hash_string_end = md5($value);
        } 

        if((!is_array($value) && $hash_string_start != $hash_string_end)
            ||
            is_array($value) && count(array_diff($start_array, $end_array)))
        {
            return protectInjection($value, $def , $filter ,true);
        }

        if(is_array($value)){
            foreach($value as $key=>$item_value){
                $value[$key] = $database->quote($item_value); 
            }
            return $value ;

        }      
        
        return $database->quote($value);
    }

}

if(!function_exists('protectInjectionWithoutQuote')){
    function protectInjectionWithoutQuote($element, $def = '', $filter = "STRING",$bypass_get=false){
global $database;
        if(!$bypass_get){
                $value = JFactory::getApplication()->input->get($element, $def, $filter);
                // $value = $element;
             }else{
                $value = $element;
             }

        if(empty($value)) return $value; 


        if(is_array($value)){
            $start_array = $value;
        }else {
            $hash_string_start = md5($value);
        } 

        $value = str_ireplace(array("/*","*/","select", "insert", "update", "drop", "delete", "alter"), "", $value);

        if(is_array($value)){
            $end_array = $value;
        }else {
            $hash_string_end = md5($value);
        } 

        if((!is_array($value) && $hash_string_start != $hash_string_end)
            ||
            is_array($value) && count(array_diff($start_array, $end_array)))
        {
            return protectInjectionWithoutQuote($value, $def , $filter ,true);
        }
        
        if(is_array($value)){
            foreach($value as $key=>$item_value){
                $value[$key] = $database->escape($item_value); 
            }
            return $value ;

        }

        return $database->escape($value);
    }

}

if (!class_exists('getLayoutPath')) {
    class getLayoutPath {
        static function getLayoutPathCom($components, $type, $layout = 'default') {
            $template = JFactory::getApplication()->getTemplate();
            
            if ( $layout  === "")  $layout = 'default' ;            
            
            $defaultLayout = $layout;
            if (strpos($layout, ':') !== false) {
                // Get the template and file name from the string
                $temp = explode(':', $layout);
                $template = ($temp[0] == '_') ? $template : $temp[0];
                $layout = $temp[1];
                $defaultLayout = ($temp[1]) ? $temp[1] : 'default';
            }
            // Build the template and base path for the layout
            $tPath = JPATH_THEMES . '/' . $template . '/html/' . $components . '/' . $type . '/' 
                . $layout . '.php';
            $cPath = JPATH_BASE . '/components/' . $components . '/views/' . $type . '/tmpl/' 
                . $layout . '.php';
            $dPath = JPATH_BASE . '/components/' . $components . '/views/' . $type 
                . '/tmpl/default.php';
            // If the template has a layout override use it
            if (file_exists($tPath)) {
                return $tPath;
            } else if (file_exists($cPath)) {
                return $cPath;
            } else if (file_exists($dPath)) {
                return $dPath;
            } else {
                echo "Bad layout path, please write to admin";
                exit;
            }
        }
    }
}
function defination_Lang_media() {
//We write our definition language function
//the return value of the function
  $database = JFactory::getDBO();
  $languagelocale = "";
  $query = "SELECT l.title, l.lang_code, l.sef ";
  $query .= "FROM #__medialibrary_const_languages as cl ";
  $query .= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
  $query .= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id ";
  $query .= "GROUP BY  l.title";
  $database->setQuery($query);
  $languages = $database->loadObjectList();
  //print_r($query);exit;

$lang = JFactory::getLanguage();

  foreach ($lang->getLocale() as $locale) {
      foreach ($languages as $language) {

          if ($locale == $language->title || $locale == $language->lang_code ||
                $locale == $language->sef)
          {
              $mosConfig_lang = $locale;
              $languagelocale = $language->lang_code;
              break;
          }
      }
   }

  if ($languagelocale == ''){
      $mosConfig_lang = $lang->getTag();
      $languagelocale = $lang->getTag();
   }

  if ($languagelocale == '')
      $languagelocale = "en-GB";

   // Set content language
   global $langContent;
   if(isset($_REQUEST['lang']))
     {
      $langContent = protectInjectionWithoutQuote('lang','','STRING');
     }
   else{
         $langContent = substr($languagelocale, 0, 2);
      }
   return $langContent;
 }

 function  get_lang_select($media,$mc)
{
 $database = JFactory::getDBO();
 $langContent=defination_Lang_media();
 $langSelect="";
 if (isset($langContent)){

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

    $lang = $database->loadResult();
    $langSelect = "( $media.langDescription like 'all'
                            or $media.langDescription like ''
                            or $media.langDescription like '*'
                            or $media.langDescription is null
                            or $media.langDescription like '$lang'
                           )  AND
                           ($mc.langDescription like 'all'
                            or $mc.langDescription like ''
                            or $mc.langDescription like '*'
                            or $mc.langDescription is null
                            or $mc.langDescription like '$lang'
                           )";


   }
 return $langSelect;
}

 function  get_lang_select_by_media($media)
{
 $database = JFactory::getDBO();
 $langContent= defination_Lang_media();
 $langsSelect="";
 if (isset($langContent)){

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

    $lang = $database->loadResult();
    $langSelect = "( $media.langDescription like 'all'
                            or $media.langDescription like ''
                            or $media.langDescription like '*'
                            or $media.langDescription is null
                            or $media.langDescription like '$lang'
                           )";
   }
 return $langSelect;
}

 function get_lang_constant_media()
{
$database = JFactory::getDbo();
$languagelocale = "";
$query = "SELECT l.title, l.lang_code, l.sef ";
$query .= "FROM #__medialibrary_const_languages as cl ";
$query .= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
$query .= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id ";
$query .= "GROUP BY  l.title";
$database->setQuery( $query );
$languages = $database->loadObjectList();

$lang = JFactory::getLanguage();
foreach ($lang->getLocale() as $locale){
    foreach ($languages as $language){
        if($locale == $language->title || $locale == $language->lang_code ||
$locale == $language->sef) {
                $mosConfig_lang = $locale;
                $languagelocale = $language->lang_code;
                break;
        }
    }
}

if ($languagelocale == ''){
    $mosConfig_lang = $lang->getTag();
    $languagelocale = $lang->getTag();
}
if ($languagelocale == '')
  {
  $languagelocale = "en-GB";
}

//   this sample is necessary to make a separate function
//  a request for the language constants
$query = "SELECT c.const, cl.value_const ";
$query .= "FROM #__medialibrary_const_languages as cl ";
$query .= "LEFT JOIN #__medialibrary_languages AS l ON cl.fk_languagesid=l.id ";
$query .= "LEFT JOIN #__medialibrary_const AS c ON cl.fk_constid=c.id ";
$query .= "WHERE l.lang_code  like '$languagelocale'";
$database->setQuery( $query );
$langConst = $database->loadObjectList();
// constant definition
foreach($langConst as $item) {
    if(!defined($item->const))
    define($item->const, $item->value_const);
}
return $langConst;
}


if (!function_exists('getAssociateOld')) {
    function getAssociateOld() {
        global $database;
        $id_check = JRequest::getVar('id', "");
        $query = "select `associate_media` from #__medialibrary where `id` = " . $id_check . "";
        $database->setQuery($query);
        $oldAssociate = $database->loadResult();
        $oldAssoc_func = unserialize($oldAssociate);
        return $oldAssoc_func;
    }
}

if (!function_exists('getAssociateDiff')) {
    function getAssociateDiff($assocArray1, $assocArray2) {
        global $database;
        $diff_ids = array();
        $diff = array_diff($assocArray1, $assocArray2);
        foreach($diff as $key => $value) {
            if ($value != 0) {
                $diff_ids[] = $value;
            }
        }
        return $diff_ids;
    }
}

if (!function_exists('getAssociatMedias')) {
    function getAssociatMedias($mediaIds) {
        global $database;
        $one = array();
        $query = "select associate_media from #__medialibrary where id = " . $mediaIds 
            . " and associate_media is not null";
        $database->setQuery($query);
        $mediaAssociateMedia = $database->loadResult();

        if (!empty($mediaAssociateMedia)) {
            $mediaIds = unserialize($mediaAssociateMedia);
            foreach($mediaIds as $oneMedia) {
                if ($oneMedia != 0) {
                    $one[] = $oneMedia;
                }
            }
            $bids = implode(',', $one);
            return $bids;
        }
    }
}

if (!function_exists('getAssociateMediasLang')) {
    function getAssociateMediasLang($mediaIds) {
        global $database;
        $query = "select associate_media from #__medialibrary where id = " . $mediaIds 
            . " and associate_media is not null";
        $database->setQuery($query);
        $mediaAssociateMedia = $database->loadResult();
        if (!empty($mediaAssociateMedia)) {
            $mediaLangIds = unserialize($mediaAssociateMedia);
            return $mediaLangIds;
        }
    }
}

if (!function_exists('ClearAssociateDiff')) {
    function ClearAssociateDiff() {
        global $database;
        $id_check = JRequest::getVar('id', "");
        $language_post = JRequest::getVar('langDescription', "");
        $oldAssociateArray = getAssociateOld();
        $i = 1;
        $assocArray = array();
        // while (count(JRequest::getVar("associate_media" . $i))) {
        while ( isset($_REQUEST["associate_media" . $i]) ) {
            $langAssoc = JRequest::getVar("associate_media_lang" . $i);
            $valAssoc = JRequest::getVar("language_associate_media" . $i);
            $assocArray[$langAssoc] = $valAssoc;
            $i++;
        }
        $assocArray[$language_post] = $id_check;
        if (!empty($oldAssociateArray) && !empty($assocArray)) $old_ids_assoc = getAssociateDiff(
                $oldAssociateArray, $assocArray);
        if (!empty($old_ids_assoc) && count($old_ids_assoc) > 0) {
            foreach($old_ids_assoc as $key => $value) {
                $diff_assoc2 = getAssociatMedias($value);
                if (!empty($diff_assoc2)) {
                    $ids_assoc_diff2 = explode(',', $diff_assoc2);
                    foreach($ids_assoc_diff2 as $key2 => $value2) {
                        if (!in_array($value2, $old_ids_assoc)) {
                            $assoc_lang = getAssociateMediasLang($value);
                            foreach($assoc_lang as $key3 => $value3) {
                                if ($value3 == $value2) {
                                    $assoc_lang[$key3] = 0;
                                }
                            }
                            $mediaLangIds = serialize($assoc_lang);
                            $query = "UPDATE #__medialibrary SET `associate_media`='" . $mediaLangIds 
                                . "' where `id` = " . $value . "";
                            $database->setQuery($query);
                            $database->query();
                        }
                    }
                }
            }
        }
        if (!empty($oldAssociateArray) && !empty($assocArray)) $new_ids_assoc = getAssociateDiff(
                $assocArray, $oldAssociateArray);
        if (!empty($new_ids_assoc) && count($new_ids_assoc) > 0) {
            foreach($new_ids_assoc as $key => $value) {
                $diff_assoc2 = getAssociatMedias($value);
                if (!empty($diff_assoc2)) {
                    $ids_assoc_diff2 = explode(',', $diff_assoc2);
                    foreach($ids_assoc_diff2 as $key2 => $value2) {
                        if ($value2 == $value || $value2 == 0) continue;
                        $assoc_lang = getAssociateMediasLang($value2);
                        foreach($assoc_lang as $key3 => $value3) {
                            if ($value3 == $value) {
                                $assoc_lang[$key3] = 0;
                            }
                        }
                        $mediaLangIds = serialize($assoc_lang);
                        $query = "UPDATE #__medialibrary SET `associate_media`='" . $mediaLangIds 
                            . "' where `id` = " . $value2 . "";
                        $database->setQuery($query);
                        $database->query();
                    }
                }
            }
        }
    }
}

if (!function_exists('save_media_associate')) {
    function save_media_associate() {
        global $database;
        $id_check = JRequest::getVar('id', "");
        $id_true = JRequest::getVar('idtrue', "");
        $language_post = JRequest::getVar('langDescription', "");
        if ($id_check) {
            if (empty($id_true)) {
                //----------get new values (what media we choose for chaque language) -----//
                $i = 1;
                $assocArray = array();
                $assocMediaId = array();
                // while (count(JRequest::getVar("associate_media" . $i))) {
                while ( isset($_REQUEST["associate_media" . $i]) ) {
                    $langAssoc = JRequest::getVar("associate_media_lang" . $i, '');
                    $valAssoc = JRequest::getVar("language_associate_media" . $i, '');
                    if ($valAssoc == '') {
                        $i++;
                        continue;
                    }
                    $assocArray[$langAssoc] = $valAssoc;
                    if ($valAssoc) {
                        $assocMediaId[] = $valAssoc; //----Array of new house_ids
                    }
                    $i++;
                }
                if (count($assocArray) > 0) {
                    $assocArray[$language_post] = $id_check;
                    $assocStr = serialize($assocArray);
                    //-----------slect associate with old values--//
                    $oldAssociateArray = getAssociateOld();
                    //----------------------------------------------------------------//
                    if (!isset($assocMediaId[$id_check])) {
                        $assocMediaId[] = $id_check;
                    }
                    if ($assocArray !== $oldAssociateArray) { //-----------compare old and new values--
                        //---------set null for medias that are not more in associates----------------//
                        ClearAssociateDiff();
                        //---------set new associates for houses that are choosed----------------//
                        $idToChange = implode(',', $assocMediaId); 
                        //--ids of new houses where we set new values for column associate_media
                        if (count($idToChange) && !empty($idToChange)) {
                            $query = "select * from #__medialibrary_lend where `fk_mediaid` in (" 
                                . $idToChange . ") and `lend_return` is NULL";
                            $database->setQuery($query);
                            $CheckAssociate = $database->loadObjectList();
                            if (!empty($CheckAssociate)) {
                                echo "<script> alert(' You must return all medias from rent first! '); 
                                    window.history.go(-1); </script>";
                                exit;
                            }
                            $query = "UPDATE #__medialibrary SET `associate_media`='" . $assocStr 
                                . "' where `id` in (" . $idToChange . ")";
                            $database->setQuery($query);
                            $database->query();
                        } else {
                            $query = "UPDATE #__medialibrary SET `associate_media` = null 
                                      where `id` = " . $id_check . "";
                            $database->setQuery($query);
                            $database->query();
                        }
                    }
                }
            }
        }
    }
}


if (!function_exists('edit_medialibrary_associate')) {
    function edit_medialibrary_associate($media,$media_type,$call_from,$access = '') {
        global $my, $database, $mosConfig_lang;
        $associateArray = array();
        $userid = $my->id;

        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $allLanguages = array();
            $lang = JFactory::getLanguage();
            foreach($lang->getLocale()  as  $locale) {
                if (mb_strlen($locale) == 5 && $locale[2] == '_')
                    $locale[2] = '-';
                    $allLanguages[] = $locale;
            }
        } else {


            $query = "SELECT lang_code FROM `#__languages`";
            $database->setQuery($query);
            $allLanguages = $database->loadColumn();
        }
        
        $from = "#__medialibrary_$media_type";

                   

        //------------------------------------------------------------//
        
   
        if($access || $call_from == 'backend'){

                $query = "SELECT m.id,mb.langDescription,mb.title
                FROM $from as mb
                LEFT JOIN #__medialibrary as m ON m.media_id = mb.id
                WHERE media_type = '$media_type'";

        }else{

                $query = "SELECT m.id,mb.langDescription,mb.title
                FROM $from as mb
                LEFT JOIN #__medialibrary as m ON m.media_id = mb.id
                WHERE m.owner_id = " . $userid . " AND media_type = '$media_type'";

        }
        //------------------------------------------------------------//
               
        
                
        
                  

                


        



        $database->setQuery($query);
        $allmedia = $database->loadObjectlist();


        $query = "select associate_media from #__medialibrary where id =" . $media->id;
        $database->setQuery($query);
        $MediaAssociateMedia = $database->loadResult();
        if (!empty($MediaAssociateMedia)) {
            $MediaAssociateMedia = unserialize($MediaAssociateMedia);
        } else {
            $MediaAssociateMedia = array();
        }
        $i = 0;
        foreach($allLanguages as $oneLang) {
            $i++;
            $associate_media = array();
            $associate_media[] = mosHtml::makeOption(0, 'select');
            foreach($allmedia as & $oneMedia) {
                if ($oneLang == $oneMedia->langDescription && $oneMedia->id != $media->id) {
                    $associate_media[] = mosHtml::makeOption(($oneMedia->id), $oneMedia->title);
                }
            }
            if (isset($media->langDescription) && $media->langDescription != $oneLang) {
                if (isset($MediaAssociateMedia[$oneLang]) && 
                    $MediaAssociateMedia[$oneLang] !== $media->id) {
                    $associateArray[$oneLang]['assocId'] = $MediaAssociateMedia[$oneLang];
                } else {
                    $associateArray[$oneLang]['assocId'] = 0;
                }
                  $associate_media_list = mosHTML::selectList($associate_media, 
                        'language_associate_media' . $i,
                    'class="inputbox" size="1"', 'value', 'text', $associateArray[$oneLang]['assocId']);
            } else {
                 $associate_media_list = null;
            }
               $associateArray[$oneLang]['list'] = $associate_media_list;
            if (isset($MediaAssociateMedia[$oneLang]) && $MediaAssociateMedia[$oneLang] !== $media->id) {
                $associateArray[$oneLang]['assocId'] = $MediaAssociateMedia[$oneLang];
            } else {
                $associateArray[$oneLang]['assocId'] = 0;
            }
        }
        return $associateArray;
    }
}


if (!function_exists('filter')) {
    function filter($value) {
        $value = str_replace(array("/", "|", "\\", "?", ":", ";", "*", "#", "%", "$", "+", "=", ";"
                , " "), "_", $value);
        return $value;
    }
}

if (!function_exists('guid')) {
    function guid() {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000); //optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45); // "-"
            $uuid = //chr(123)// "{"
            substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) 
                . $hyphen .
            substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
            //.chr(125);// "}"
            return $uuid;
        }
    }
}

if (!function_exists('checktype')) {
    function checktype($ext, $filename, $i) {
        $flag = 0;
        $db = JFactory::getDbo();
        $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " 
                . $db->quote($ext));
        $file_db_mimes = $db->loadObjectList();
        $file['type'] = protectInjectionWithoutQuote($_FILES[$filename . $i]['type'], '', "STRING", true);
        foreach ($file_db_mimes as $file_db_mime) {
            if ($file_db_mime->mime_type == $file['type']) {
                return $file_db_mime->mime_type;
                $flag = 1;
            }
        }
        if(!$flag) {
            return $type = "unknown";
        }
    }
}

if (!function_exists('checktypeUrl')) {
    function checktypeUrl($ext) {
        $db = JFactory::getDbo();
        $db->setQuery("SELECT mime_type FROM #__medialibrary_mime_types WHERE `mime_ext` = " 
                . $db->quote($ext));
        $db_mime = $db->loadResult();
        if (!$db_mime) {
            return $type = "unknown";
        } else {
            return $db_mime;
        }
    }
}

if (!function_exists('saveYouTubeCode')) {
    function saveYouTubeCode($youtube_code, $media_id) {
        if ($youtube_code){
            $url = 'https://www.youtube.com/watch?v='.$youtube_code;
            $youtube = "https://www.youtube.com/oembed?url=". $url ."&format=json";

            $curl = curl_init($youtube);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $return = curl_exec($curl);
            curl_close($curl);
            $title = json_decode($return, true)['title'];
            if(strlen($title)>100){
                $title = substr($title,0,100);
            }
        }           
        $db = JFactory::getDBO();
        $db->setQuery("SELECT youtube FROM #__medialibrary_video_source 
                       WHERE youtube != '' AND fk_media_id = $media_id");
        $db->query();
        $youtube = $db->LoadResult();
        
        if ($youtube_code != '') {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_video_source (fk_media_id,youtube, title) 
                           VALUE($media_id,'" . $youtube_code . "', '" . $title . "')");
            $db->query();
            
            $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE 1 ORDER BY id DESC LIMIT 1 ") ;
            $db->query();
            $id_to_change = $db->loadResult();

            $db->setQuery("UPDATE #__medialibrary_video_source SET sequence_number = $id_to_change 
                       WHERE  id = $id_to_change") ;
            $db->query();
        }
    }
}

if (!function_exists('saveVideos')) {
    function saveVideos($src, $media_id, $type, $title_video) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        $title_video = str_replace("'", "''", $title_video);
        if ($src != "" && strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_video_source(fk_media_id,src,type,title)
                           VALUE($media_id,'" . $src . "','" . $type . "','" . $title_video . "')");
            $db->query();
        } else if ($src != "" && !strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_video_source(fk_media_id,src,type,title)
                          VALUE($media_id,'" . $src . "','" . $type . "','" . $title_video . "')");
            $db->query();
            
            $db->setQuery("SELECT id FROM #__medialibrary_video_source WHERE 1 ORDER BY id DESC LIMIT 1 ") ;
            $db->query();
            $id_to_change = $db->loadResult();

            $db->setQuery("UPDATE #__medialibrary_video_source SET sequence_number = $id_to_change 
                       WHERE  id = $id_to_change") ;
            $db->query();
        }
    }
}

if (!function_exists('saveAlternVideos')) {
    function saveAlternVideos($src, $media_id, $type, $media_source_id, $title_video) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        $title_video = str_replace("'", "''", $title_video);
        $db = JFactory::getDBO();
        $db->setQuery("UPDATE #__medialibrary_video_source SET sequence_number = $media_source_id 
                       WHERE  id = $media_source_id") ;
        $db->query();
        if ($src != "" && strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_video_source(
                            fk_media_id,src,type,sequence_number, title) 
                          VALUE($media_id,'" . $src . "','" . $type . "', '".$media_source_id."','" 
                            . $title_video . "')");
            $db->query();
        } else if ($src != "" && !strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_video_source(fk_media_id,src,type,sequence_number, title)
                          VALUE($media_id,'" . $src . "','" . $type . "', '".$media_source_id."','" 
                            . $title_video . "')");
            $db->query();
        }
    }
}

if (!function_exists('med_deleteVideos')) {
    function med_deleteVideos($media_id, $removevideo = 0) {
        global $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_video_source where fk_media_id = $media_id;");
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $vdiles_id = $db->loadResultArray();
        } else {
            $vdiles_id = $db->loadColumn();
        }
        $deleteVid_id = array();

        if ($removevideo) {
            $deleteVid_id = $vdiles_id;
        } else {
            foreach($vdiles_id as $key => $value) {
                if (isset($_POST['video_option_del' . $value])) {
                    array_push($deleteVid_id, JRequest::getVar('video_option_del' . $value, '', 'post'));
                } else if(isset($_POST['youtube_option_del' . $value])) {
                    array_push($deleteVid_id, JRequest::getVar('youtube_option_del' . $value, '', 
                            'post'));
                }
            }
        }
        if (!empty($deleteVid_id['0'])) {
            $del_id = "";
            $sql = "SELECT src FROM #__medialibrary_video_source WHERE id IN (";
            foreach($deleteVid_id as $vid_id) $del_id.= $vid_id . ",";
            $sql.= $del_id . "0)";
            $db->setQuery($sql);
            $videos = $db->loadColumn();
            if ($videos) {
                foreach($videos as $name) {
                    if (substr($name, 0, 4) != "http") unlink($mosConfig_absolute_path 
                        . '/components/com_medialibrary/media/video/'.$name);
                }
            }
            $sql = "DELETE FROM #__medialibrary_video_source WHERE (id IN (" . $del_id 
                    . "0)) and (fk_media_id=$media_id)";
            $db->setQuery($sql);
            $db->query();
        }
    }
}


if (!function_exists('med_storeVideo')) {
    function med_storeVideo(&$media) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        for ($i = 1;isset($_FILES['new_upload_video' . $i]) || isset($_FILES['new_upload_altern_video' 
                . $i]) || 
                array_key_exists('new_upload_video_url' . $i, $_POST) || 
                array_key_exists('new_upload_altern_video' . $i, $_POST) || 
                array_key_exists('video_youtube_code' . $i, $_POST) || 
                array_key_exists('new_upload_video_youtube_code' . $i, $_POST);
                $i++) {
            if (isset($_FILES['new_upload_altern_video' . $i])){
                $altern_add_id = protectInjectionWithoutQuote('new_upload_altern_video' . $i, '');
                $video = JRequest::getVar('new_upload_altern_video' . $i, '', 'files');
                if ($video != '' && $video['error'] != 4){
                    $code = guid();
                    $ext = pathinfo($video['name'], PATHINFO_EXTENSION);
                    $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_video']);
                    $ext = strtolower($ext);

                    if (!in_array($ext, $allowed_exts)) {
                        echo "<script> alert('File ext. not allowed to upload! - " . $ext 
                            . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                    $type = checktype($ext, 'new_upload_altern_video', $i);

                    $title_video = explode('.', filter($video['name']));
                    $title_video = $title_video[0];
                    $video_name = $code . '_' . filter($video['name']);
                    if (intval($video['error']) > 0 && intval($video['error']) < 4) {
                        echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_VIDEO_UPLOAD_ERROR . " - " 
                            . $video_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    } else if (intval($video['error']) != 4) {
                        $video_new = $mosConfig_absolute_path . $medialibrary_configuration['videos'][
                            'location'] . $video_name;

                        if (!move_uploaded_file($video['tmp_name'], $video_new)) {
                            echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_VIDEO_UPLOAD_ERROR 
                                . " - " . $video_name . "'); window.history.go(-1); </script>\n";
                            exit();
                        }
                        saveAlternVideos($video_name, $media->id, $type, $altern_add_id, $title_video);
                    }
                }
            }
            if (array_key_exists('video_youtube_code' . $i, $_POST)){
                $youtube_del = protectInjectionWithoutQuote('youtube_option_del' . $i, '0'); 
                if ($youtube_del != '0'){
                    $youtube_code = protectInjectionWithoutQuote('video_youtube_code' . $i);
                    if (!empty($youtube_code)) {
                        //print_r('DELETE: '.$youtube_code);print_r('. IN MEDIA #: '.$media->id);exit;
                        $db = JFactory::getDBO();
                        $db->setQuery("DELETE FROM #__medialibrary_video_source WHERE youtube = '" 
                                . $youtube_code . "' AND fk_media_id = $media->id");
                        $db->query();
                    } 
                    $uploadVideoYoutubeCode = '';
                }
            }
            if (array_key_exists('new_upload_video_youtube_code' . $i, $_POST) && $_POST[
                    'new_upload_video_youtube_code' . $i] != "") {
                $uploadVideoYoutubeCode = JRequest::getVar('new_upload_video_youtube_code' . $i, 
                        '', 'post');
                $uploadVideoYoutubeCode = strip_tags(trim($uploadVideoYoutubeCode));
                saveYouTubeCode($uploadVideoYoutubeCode, $media->id);
            }

            if (isset($_FILES['new_upload_video' . $i]) && 
                    $_FILES['new_upload_video' . $i]['name'] != "") {
                if (array_key_exists('new_upload_video_youtube_code' . $i, $_POST) && 
                        $_POST['new_upload_video_youtube_code' . $i] == "") {
                    $video = JRequest::getVar('new_upload_video' . $i, '', 'files');
                    $ext = pathinfo($video['name'], PATHINFO_EXTENSION);
                    $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_video']);
                    $ext = strtolower($ext);

                    if (!in_array($ext, $allowed_exts)) {
                        echo "<script> alert('File ext. not allowed to upload! - " . $ext 
                            . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                    $type = checktype($ext, 'new_upload_video', $i);
                    $code = guid();
                    $title_video = explode('.', filter($video['name']));
                    $title_video = $title_video[0];
                    $video_name = $code . '_' . filter($video['name']);
                    //mime_content_type($file_name);
                    //if( !isset($_FILES['new_upload_file'.$i]) ) continue;

                    if (intval($video['error']) > 0 && intval($video['error']) < 4) {
                        echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_VIDEO_UPLOAD_ERROR . " - " 
                            . $video_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    } else if (intval($video['error']) != 4) {
                        $video_new = $mosConfig_absolute_path . $medialibrary_configuration['videos'][
                            'location'] . $video_name;

                        if (!move_uploaded_file($video['tmp_name'], $video_new)) {
                            echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_VIDEO_UPLOAD_ERROR 
                                . " - " . $video_name . "'); window.history.go(-1); </script>\n";
                            exit();
                        }
                        saveVideos($video_name, $media->id, $type, $title_video);
                    }
                }
            }

            if (array_key_exists('new_upload_video_url' . $i, $_POST) && $_POST['new_upload_video_url' 
                    . $i] != "") {
                if (array_key_exists('new_upload_video_youtube_code' . $i, $_POST) && $_POST[
                        'new_upload_video_youtube_code' . $i] == "" &&
                    (isset($_FILES['new_upload_video' . $i]) && 
                            $_FILES['new_upload_video' . $i]['name'] == "")) {
                    $uploadVideoURL = JRequest::getVar('new_upload_video_url' . $i, '', 'post');
                    $ext = pathinfo($uploadVideoURL, PATHINFO_EXTENSION);
                    $uploadVideoURL = strip_tags(trim($uploadVideoURL));
                    $type = checktypeUrl($ext);
                    saveVideos($uploadVideoURL, $media->id, $type, $title_video);
                }
            }
        }
    }
}

if (!function_exists('saveTracks')) {
    function saveTracks($media_id, $src, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel, 
            $con_this_sub_with_video) {
        global $medialibrary_configuration, $mosConfig_absolute_path;

        if ($src != "" && !strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_track_source 
                          (sequence_number,fk_media_id,src,kind,scrlang,label)
                          VALUE ('$con_this_sub_with_video','$media_id','$src','$uploadTrackKind','" 
                          . "$uploadTrackScrlang','$uploadTrackLabel')");
            $db->query();
        } else if ($src != "" && strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_track_source 
                          (sequence_number,fk_media_id,src,kind,scrlang,label)
                          VALUE ('$con_this_sub_with_video','$media_id','$src','$uploadTrackKind','" 
                          . "$uploadTrackScrlang','$uploadTrackLabel')");
            $db->query();
        }
    }
}

if (!function_exists('med_deleteTracks')) {
    function med_deleteTracks($media_id, $removetrack = 0) {
        global $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_track_source where fk_media_id = $media_id;");
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $tdiles_id = $db->loadResultArray();
        } else {
            $tdiles_id = $db->loadColumn();
        }
        $deleteTr_id = array();
        if ($removetrack) {
            $deleteTr_id = $tdiles_id;
        } else {
            foreach($tdiles_id as $key => $value) {
                if (isset($_POST['track_option_del' . $value])) {
                    array_push($deleteTr_id, JRequest::getVar('track_option_del' . $value, '', 'post'));
                }
            }
        }
        if (!empty($deleteTr_id['0'])) {
            $del_tid = "";
            $sql = "SELECT src FROM #__medialibrary_track_source WHERE id IN (";
            foreach($deleteTr_id as $tid_id) $del_tid.= $tid_id . ",";
            $sql.= $del_tid . "0)";
            $db->setQuery($sql);
            $tracks = $db->loadColumn();
            if ($tracks) {
                foreach($tracks as $name) {
                    if (substr($name, 0, 4) != "http") unlink($mosConfig_absolute_path 
                        . '/components/com_medialibrary/media/track/' . $name);
                }
            }
            $sql = "DELETE FROM #__medialibrary_track_source 
                    WHERE (id IN (" . $del_tid . "0)) and (fk_media_id = $media_id)";
            $db->setQuery($sql);
            $db->query();
        }
    }
}

 if (!function_exists('med_storeTrack')) {
    function med_storeTrack(&$media) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        for ($i = 1;isset($_FILES['new_upload_track' . $i]) || 
                array_key_exists('new_upload_track_url' . $i, $_POST);$i++) {
            if (isset($_FILES['new_upload_track' . $i]) && 
                    $_FILES['new_upload_track' . $i]['name'] != "") {
                $con_this_sub_with_video = protectInjectionWithoutQuote('new_upload_track' . $i, '');
                //storing e-Document
                $track = JRequest::getVar('new_upload_track' . $i, '', 'files');
                $ext = pathinfo($track['name'], PATHINFO_EXTENSION);
                $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_track']);
                $ext = strtolower($ext);
                if (!in_array($ext, $allowed_exts)) {
                    echo "<script> alert(' File ext. not allowed to upload! - " . $ext 
                        . "'); window.history.go(-1); </script>\n";
                    exit();
                }
                $code = guid();
                $track_name = $code . '_' . filter($track['name']);
                //mime_content_type($file_name);
                //if( !isset($_FILES['new_upload_file'.$i]) ) continue;
                if (intval($track['error']) > 0 && intval($track['error']) < 4) {
                    echo "<script> alert('" . _MEDIALIBRARY_LABEL_TRACK_UPLOAD_ERROR . " - " 
                        . $track_name . "'); window.history.go(-1); </script>\n";
                    exit();
                } else if (intval($track['error']) != 4) {
                    $track_new = $mosConfig_absolute_path . $medialibrary_configuration['tracks'][
                        'location'] . $track_name;
                    if (!move_uploaded_file($track['tmp_name'], $track_new)) {
                        echo "<script> alert('" . _MEDIALIBRARY_LABEL_TRACK_UPLOAD_ERROR . " - " 
                            . $track_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                }
                if (array_key_exists('new_upload_track_kind' . $i, $_POST) && $_POST[
                        'new_upload_track_kind' . $i] != "") {
                    $uploadTrackKind = JRequest::getVar('new_upload_track_kind' . $i, '', 'post');
                    $uploadTrackKind = strip_tags(trim($uploadTrackKind));
                }
                if (array_key_exists('new_upload_track_scrlang' . $i, $_POST) && $_POST[
                        'new_upload_track_scrlang' . $i] != "") {
                    $uploadTrackScrlang = JRequest::getVar('new_upload_track_scrlang' . $i, '', 'post');
                    $uploadTrackScrlang = strip_tags(trim($uploadTrackScrlang));
                }
                if (array_key_exists('new_upload_track_label' . $i, $_POST) && $_POST[
                       'new_upload_track_label' . $i] != "") {
                    $uploadTrackLabel = JRequest::getVar('new_upload_track_label' . $i, '', 'post');
                    $uploadTrackLabel = strip_tags(trim($uploadTrackLabel));
                }
                saveTracks($media->id, $track_name, $uploadTrackKind, $uploadTrackScrlang, 
                        $uploadTrackLabel, 
                    $con_this_sub_with_video);
            }
            if (array_key_exists('new_upload_track_url' . $i, $_POST) && $_POST['new_upload_track_url' 
                    . $i] != "") {
                if (isset($_FILES['new_upload_track' . $i]) && 
                        $_FILES['new_upload_track' . $i]['name'] == "") {
                    $uploadTrackURL = JRequest::getVar('new_upload_track_url' . $i, '', 'post');
                    $uploadTrackURL = strip_tags(trim($uploadTrackURL));
                    if (array_key_exists('new_upload_track_kind' . $i, $_POST) && 
                            $_POST['new_upload_track_kind' . $i] != "") {
                        $uploadTrackKind = JRequest::getVar('new_upload_track_kind' . $i, '', 'post');
                        $uploadTrackKind = strip_tags(trim($uploadTrackKind));
                    }
                    if (array_key_exists('new_upload_track_scrlang' . $i, $_POST) && 
                            $_POST['new_upload_track_scrlang' . $i] != "") {
                        $uploadTrackScrlang = JRequest::getVar('new_upload_track_scrlang' 
                            . $i, '', 'post');
                        $uploadTrackScrlang = strip_tags(trim($uploadTrackScrlang));
                    }
                    if (array_key_exists('new_upload_track_label' . $i, $_POST) && $_POST[
                            'new_upload_track_label' . $i] != "") {
                        $uploadTrackLabel = JRequest::getVar('new_upload_track_label' . $i, '', 'post');
                        $uploadTrackLabel = strip_tags(trim($uploadTrackLabel));
                    }
                    saveTracks($media->id, $uploadTrackURL, $uploadTrackKind, $uploadTrackScrlang, 
                            $uploadTrackLabel, $con_this_sub_with_video);
                }
            }
        }
    }
}

if (!function_exists('saveAudios')) {
    function saveAudios($src, $media_id, $type, $title_audio) {
        $title_audio = str_replace("'", "\'", $title_audio);
        global $medialibrary_configuration, $mosConfig_absolute_path;
        if ($src != "" && strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_audio_source(fk_media_id,src,type, title) 
                           VALUE($media_id,'" . $src . "','" . $type . "','" . $title_audio . "')");
            $db->query();
        } else if ($src != "" && !strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_audio_source(fk_media_id,src,type, title)
                           VALUE($media_id,'" . $src . "','" . $type . "','" . $title_audio . "')");
            $db->query();

            $db->setQuery("SELECT id FROM #__medialibrary_audio_source WHERE 1 ORDER BY id DESC LIMIT 1 ") ;
            $db->query();
            $id_to_change = $db->loadResult();

            $db->setQuery("UPDATE #__medialibrary_audio_source SET sequence_number = $id_to_change 
                       WHERE  id = $id_to_change") ;
            $db->query();
        }
    }
}

if (!function_exists('saveAlternAudios')) {
    function saveAlternAudios($src, $media_id, $type, $media_source_id, $title_audio) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        $title_audio = str_replace("'", "''", $title_audio);
        $db = JFactory::getDBO();
        $db->setQuery("UPDATE #__medialibrary_audio_source SET sequence_number = $media_source_id 
                       WHERE  id = $media_source_id") ;
        $db->query();
        if ($src != "" && strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_audio_source(
                          fk_media_id,src,type,sequence_number, title) VALUE($media_id,'" . $src . "','" 
                          . $type . "', '".$media_source_id."','" . $title_audio . "')");
            $db->query();
        } else if ($src != "" && !strstr($src, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_audio_source(fk_media_id,src,type,sequence_number, title)
                          VALUE($media_id,'" . $src . "','" . $type . "', '".$media_source_id."','" 
                            . $title_audio . "')");
            $db->query();
        }
    }
}


if (!function_exists('med_deleteAudios')) {
    function med_deleteAudios($media_id, $removeaudio = 0) {
        global $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_audio_source where fk_media_id = $media_id;");
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $adiles_id = $db->loadResultArray();
        } else {
            $adiles_id = $db->loadColumn();
        }
        $deleteAud_id = array();
        if ($removeaudio) {
            $deleteAud_id = $adiles_id;
        } else {
            foreach($adiles_id as $key => $value) {
                if (isset($_POST['audio_option_del' . $value])) {
                    array_push($deleteAud_id, JRequest::getVar('audio_option_del' . $value, '', 'post'));
                }
            }
        }
        if (!empty($deleteAud_id['0'])){
            $del_id = "";
            $sql = "SELECT src FROM #__medialibrary_audio_source WHERE id IN (";
            foreach($deleteAud_id as $aid_id) $del_id.= $aid_id . ",";
            $sql.= $del_id . "0)";
            $db->setQuery($sql);
            $audios = $db->loadColumn();
            if ($audios) {
                foreach($audios as $name) {
                    if (substr($name, 0, 4) != "http") unlink($mosConfig_absolute_path 
                        . '/components/com_medialibrary/media/audio/' . $name);
                }
            }
            $sql = "DELETE FROM #__medialibrary_audio_source 
                    WHERE (id IN (" . $del_id . "0)) and (fk_media_id=$media_id)";
            $db->setQuery($sql);
            $db->query();
        }
    }
}


if (!function_exists('med_storeAudio')) {
    function med_storeAudio(&$media) {
        global $medialibrary_configuration, $mosConfig_absolute_path;

        for ($i = 1;isset($_FILES['new_upload_audio' . $i]) || 
                protectInjectionWithoutQuote('new_upload_altern_audio' . $i, '') || 
                array_key_exists('new_upload_audio_url' . $i, $_POST);$i++) {
            if (isset($_FILES['new_upload_altern_audio' . $i])){
                $altern_add_id = protectInjectionWithoutQuote('new_upload_altern_audio' . $i, '');
                $audio = JRequest::getVar('new_upload_altern_audio' . $i, '', 'files');
                if ($audio != ''){
                    $code = guid();
                    $ext = pathinfo($audio['name'], PATHINFO_EXTENSION);
                    $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_audio']);
                    $ext = strtolower($ext);

                    $type = checktype($ext, 'new_upload_altern_audio', $i);
                    $audio_name = $code . '_' . filter($audio['name']);
                    $title_audio = explode('.', filter($audio['name']));
                    $title_audio = $title_audio[0];
                    $audio_name = join(explode("'", $audio_name));
                    if (intval($audio['error']) > 0 && intval($audio['error']) < 4) {
                        echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_AUDIOS_UPLOAD_ERROR 
                            . " - " . $audio_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    } else if (intval($audio['error']) != 4) {
                        $audio_new = $mosConfig_absolute_path . $medialibrary_configuration['audios'][
                            'location'] . $audio_name;

                        if (!move_uploaded_file($audio['tmp_name'], $audio_new)) {
                            echo "<script> alert('" . _MEDIALIBRARY_ADMIN_LABEL_AUDIOS_UPLOAD_ERROR 
                                . " - " . $audio_name . "'); window.history.go(-1); </script>\n";
                            exit();
                        }
                        saveAlternAudios($audio_name, $media->id, $type, $altern_add_id, $title_audio);
                    }
                }
                    
            }
            
            if (isset($_FILES['new_upload_audio' . $i]) && $_FILES['new_upload_audio' . $i][
                    'name'] != "") {
                //storing e-Document
                $audio = JRequest::getVar('new_upload_audio' . $i, '', 'files');
                $ext = pathinfo($audio['name'], PATHINFO_EXTENSION);
                $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts_audio']);
                $ext = strtolower($ext);
                if (!in_array($ext, $allowed_exts)) {
                    echo "<script> alert(' File ext. not allowed to upload! - " . $ext 
                        . "'); window.history.go(-1); </script>\n";
                    exit();
                }
                $type = checktype($ext, 'new_upload_audio', $i);
                $code = guid();
                $audio_name = $code . '_' . filter($audio['name']);
                $title_audio = explode('.', filter($audio['name']));
                $title_audio = $title_audio[0];
                $audio_name = join(explode("'", $audio_name));
                    //mime_content_type($file_name);
                //if( !isset($_FILES['new_upload_file'.$i]) ) continue;
                if (intval($audio['error']) > 0 && intval($audio['error']) < 4) {
                    echo "<script> alert('" . _MEDIALIBRARY_LABEL_AUDIO_UPLOAD_ERROR . " - " 
                        . $audio_name . "'); window.history.go(-1); </script>\n";
                    exit();
                } else if (intval($audio['error']) != 4) {
                    $audio_new = $mosConfig_absolute_path . $medialibrary_configuration['audios'][
                        'location'] . $audio_name;
                    if (!move_uploaded_file($audio['tmp_name'], $audio_new)) {
                        echo "<script> alert('" . _MEDIALIBRARY_LABEL_AUDIO_UPLOAD_ERROR . " - " 
                            . $audio_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                    saveAudios($audio_name, $media->id, $type, $title_audio);
                }
            }
            if (array_key_exists('new_upload_audio_url' . $i, $_POST) && $_POST['new_upload_audio_url' 
                    . $i] != "") {
                if (isset($_FILES['new_upload_audio' . $i]) && 
                        $_FILES['new_upload_audio' . $i]['name'] == "") {
                    $uploadAudioURL = JRequest::getVar('new_upload_audio_url' . $i, '', 'post');
                    $uploadAudioURL = strip_tags(trim($uploadAudioURL));
                    $ext = pathinfo($uploadAudioURL, PATHINFO_EXTENSION);
                    $uploadAudioURL = strip_tags(trim($uploadAudioURL));
                    $type = checktypeUrl($ext);
                    saveAudios($uploadAudioURL, $media->id, $type, '');
                }
            }
        }
    }
}


if (!function_exists('saveFiles')) {
    function saveFiles($location, $media_id) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        if ($location != "" && strstr($location, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_emedia_files(fk_emedia_id,location) 
                           VALUE($media_id,'" . $location . "')");
            $db->query();
        } else if ($location != "" && !strstr($location, "http")) {
            $db = JFactory::getDBO();
            $db->setQuery("INSERT INTO #__medialibrary_emedia_files(fk_emedia_id,location)
                          VALUE($media_id,'" . $medialibrary_configuration['emedias']['location'] 
                          . $location . "')");
            $db->query();
        }
    }
}

if (!function_exists('med_deleteFiles')) {
    function med_deleteFiles($media_id, $removemedia = 0) {
        global $mosConfig_absolute_path, $mosConfig_live_site, $medialibrary_configuration;
        $db = JFactory::getDBO();
        $db->setQuery("SELECT id FROM #__medialibrary_emedia_files where fk_emedia_id = $media_id;");
        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $ediles_id = $db->loadResultArray();
        } else {
            $ediles_id = $db->loadColumn();
        }
        $delete_id = array();
        if ($removemedia) {
            $delete_id = $ediles_id;
        } else {
            foreach($ediles_id as $key => $value) {
                if (isset($_POST['file_option_del' . $value])) {
                    array_push($delete_id, JRequest::getVar('file_option_del' . $value, '', 'post'));
                }
            }
        }
        if (!empty($delete_id['0'])) {
            $del_id = "";
            $sql = "SELECT location FROM #__medialibrary_emedia_files WHERE id IN (";
            foreach($delete_id as $efl_id) $del_id.= $efl_id . ",";
            $sql.= $del_id . "0)";
            $db->setQuery($sql);
            $efiles = $db->loadColumn();
            if ($efiles) {
                foreach($efiles as $name) {
                    if (substr($name, 0, 4) != "http") unlink($mosConfig_absolute_path . $name);
                }
            }
            $sql = "DELETE FROM #__medialibrary_emedia_files WHERE (id IN (" . $del_id 
                . "0)) and (fk_emedia_id=$media_id)";
            $db->setQuery($sql);
            $db->query();
        }
    }
}


if (!function_exists('med_storeEbook')) {
    function med_storeEbook(&$media) {
        global $medialibrary_configuration, $mosConfig_absolute_path;
        for ($i = 1;isset($_FILES['new_upload_file' . $i]) || array_key_exists('new_upload_file_url' 
                . $i, $_POST);$i++) {
            if (isset($_FILES['new_upload_file' . $i]) && 
                    $_FILES['new_upload_file' . $i]['name'] != "") {
                //storing e-Document
                $file = JRequest::getVar('new_upload_file' . $i, '', 'files');
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $allowed_exts = explode(",", $medialibrary_configuration['allowed_exts']);
                $ext = strtolower($ext);
                if (!in_array($ext, $allowed_exts)) {
                    echo "<script> alert(' File ext. not allowed to upload! - " . $ext 
                        . "'); window.history.go(-1); </script>\n";
                    exit();
                }
                $code = guid();
                $file_name = $code . '_' . filter($file['name']);
                if (intval($file['error']) > 0 && intval($file['error']) < 4) {
                    echo "<script> alert('" . _MEDIALIBRARY_LABEL_EBOOK_UPLOAD_ERROR . " - " 
                        . $file_name . "'); window.history.go(-1); </script>\n";
                    exit();
                } else if (intval($file['error']) != 4) {
                    $file_new = $mosConfig_absolute_path .  $medialibrary_configuration['emedias'][
                        'location'] . $file_name;
                    if (!move_uploaded_file($file['tmp_name'], $file_new)) {
                        echo "<script> alert('" . _MEDIALIBRARY_LABEL_EBOOK_UPLOAD_ERROR . " - " 
                            . $file_name . "'); window.history.go(-1); </script>\n";
                        exit();
                    }
                    saveFiles($file_name, $media->id);
                }
            }
            if (array_key_exists('new_upload_file_url' . $i, $_POST) && $_POST['new_upload_file_url' 
                    . $i] != "") {
                if (isset($_FILES['new_upload_file' . $i]) && 
                        $_FILES['new_upload_file' . $i]['name'] == "") {
                    $uploadFileURL = JRequest::getVar('new_upload_file_url' . $i, '', 'post');
                    $uploadFileURL = strip_tags(trim($uploadFileURL));
                    saveFiles($uploadFileURL, $media->id);
                }
            }
        }
    }
}

if(!function_exists('return_bytes')){
  function return_bytes($val) {
        if (empty($val))
        {
            return 0;
        }

        $val = trim($val);

        preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);

        $last = '';

        if (isset($matches[2]))
        {
            $last = $matches[2];
        }

        if (isset($matches[1]))
        {
            $val = (int) $matches[1];
        }

        switch (strtolower($last))
        {
            case 'g':
            case 'gb':
                $val *= 1024;
            case 'm':
            case 'mb':
                $val *= 1024;
            case 'k':
            case 'kb':
                $val *= 1024;
        }

        return (int) $val;
  }
}

if (!function_exists('save_author_associate_media')) {
    function save_author_associate_media() {
        global $database;
        $id_check = JRequest::getVar('people_id', "");
        $id_true = JRequest::getVar('idtrue', "");
        $language_post = JRequest::getVar('langshow', "");

        if ($id_check) {
            if (empty($id_true)){
                //----------get new values (what book we choose for chaque language) ------//
                $i = 1;
                $assocArray = array();
                $assocAuthorId = array();
                while ( isset($_REQUEST["associate_author" . $i]) ) { 
                    $langAssoc = JRequest::getVar("associate_author_lang" . $i, '');
                    $valAssoc = JRequest::getVar("language_associate_people" . $i, '');
                    if ($valAssoc == '') {
                        $i++;
                        continue;
                    }
                    $assocArray[$langAssoc] = $valAssoc;
                    if ($valAssoc) {
                        $assocAuthorId[] = $valAssoc; //----Array of new house_ids

                    }
                    $i++;
                }
                if (count($assocArray) > 0) {
                    $assocArray[$language_post] = $id_check;
                    $assocStr = serialize($assocArray);
                    //-----------slect associate with old values-------------//

                    $oldAssociateArray = getAssociateOldAuthors_media();
                    //----------------------------------------------------------------//
                    if (!isset($assocAuthorId[$id_check])) {
                        $assocAuthorId[] = $id_check;
                    }
                    if ($assocArray !== $oldAssociateArray) { //-----------compare old and new values--
                        //---------set null for books that are not more in associates----------------//
                        ClearAssociateDiffAuthors_media();
                        //---------set new associates for houses that are choosed----------------//
                        $idToChange = implode(',', $assocAuthorId); 
                        //--ids of new houses where we set new values for column associate_people
                        if (count($idToChange) && !empty($idToChange)) {
                            $query = "UPDATE #__medialibrary_people SET `associate_people`='" 
                                . $assocStr . "' where `id` in (" . $idToChange . ")";
                            $database->setQuery($query);
                            $database->query();
                        } else {
                            $query = "UPDATE #__medialibrary_people 
                                      SET `associate_people`= null 
                                      where `id` = " . $id_check . "";
                            $database->setQuery($query);
                            $database->query();
                        }
                    }
                }
            }
        }
    }
}
if (!function_exists('ClearAssociateDiffAuthors_media')) {
    function ClearAssociateDiffAuthors_media() {
        global $database;
        $id_check = JRequest::getVar('id', "");
        $language_post = JRequest::getVar('langshow', "");
        $oldAssociateArray = getAssociateOldAuthors_media();
        $i = 1;
        $assocArray = array();
        // while (count(JRequest::getVar("associate_people" . $i))) {
        while ( isset($_REQUEST["associate_people" . $i]) ) {
            $langAssoc = JRequest::getVar("associate_people_lang" . $i);
            $valAssoc = JRequest::getVar("language_associate_people" . $i);
            $assocArray[$langAssoc] = $valAssoc;
            $i++;
        }
        $assocArray[$language_post] = $id_check;
        if (!empty($oldAssociateArray) && 
            !empty($assocArray)) $old_ids_assoc = getAssociateDiffAuthor_media(
                $oldAssociateArray, $assocArray);
        if (count($old_ids_assoc) > 0) {
            foreach($old_ids_assoc as $key => $value) {
                $diff_assoc2 = getAssociateAuthors_media($value);
                if (!empty($diff_assoc2)) {
                    $ids_assoc_diff2 = explode(',', $diff_assoc2);
                    foreach($ids_assoc_diff2 as $key2 => $value2) {
                        if (!in_array($value2, $old_ids_assoc)) {
                            $assoc_lang = getAssociateAuthorsLang_media($value);
                            foreach($assoc_lang as $key3 => $value3) {
                                if ($value3 == $value2) {
                                    $assoc_lang[$key3] = 0;
                                }
                            }
                            $AuthorLangIds = serialize($assoc_lang);
                            $query = "UPDATE #__medialibrary_people 
                                      SET `associate_people`='" . $AuthorLangIds . "' 
                                      where `id` = " . $value . "";
                            $database->setQuery($query);
                            $database->query();
                        }
                    }
                }
            }
        }
        if (!empty($oldAssociateArray) && 
            !empty($assocArray)) $new_ids_assoc = getAssociateDiffAuthor_media(
                $assocArray, $oldAssociateArray);
        if (count($new_ids_assoc) > 0) {
            foreach($new_ids_assoc as $key => $value) {
                $diff_assoc2 = getAssociateAuthors_media($value);
                if (!empty($diff_assoc2)) {
                    $ids_assoc_diff2 = explode(',', $diff_assoc2);
                    foreach($ids_assoc_diff2 as $key2 => $value2) {
                        if ($value2 == $value || $value2 == 0) continue;
                        $assoc_lang = getAssociateAuthors_media($value2);
                        foreach($assoc_lang as $key3 => $value3) {
                            if ($value3 == $value) {
                                $assoc_lang[$key3] = 0;
                            }
                        }
                        $AuthorLangIds = serialize($assoc_lang);
                        $query = "UPDATE #__medialibrary_people 
                                  SET `associate_people`='" . $AuthorLangIds . "' 
                                  where `id` = " . $value2 . "";
                        $database->setQuery($query);
                        $database->query();
                    }
                }
            }
        }
    }
}
if (!function_exists('getAssociateAuthors_media')) {
    function getAssociateAuthors_media($AuthorIds) {
        global $database;
        $one = array();
        $query = "SELECT associate_people FROM #__medialibrary_people 
                  where id = " . $AuthorIds . " AND associate_people is not null";
        $database->setQuery($query);
        $AuthorAssociateAuthor = $database->loadResult();
        if (!empty($AuthorAssociateAuthor)) {
            $AuthorIds = unserialize($AuthorAssociateAuthor);
            foreach($AuthorIds as $oneAuthor) {
                if ($oneAuthor != 0) {
                    $one[] = $oneAuthor;
                }
            }
            $bids = implode(',', $one);
            return $bids;
        }
    }
}
if (!function_exists('getAssociateAuthorsLang_media')) {
    function getAssociateAuthorsLang_media($AuthorIds) {
        global $database;
        $query = "SELECT associate_people FROM #__medialibrary_people 
                  where id = " . $AuthorIds . " AND associate_people is not null";
        $database->setQuery($query);
        $AuthorAssociateAuthor = $database->loadResult();
        if (!empty($AuthorAssociateAuthor)) {
            $AuthorLangIds = unserialize($AuthorAssociateAuthor);
            return $AuthorLangIds;
        }
    }
}
if (!function_exists('getAssociateDiffAuthor_media')) {
    function getAssociateDiffAuthor_media($assocArray1, $assocArray2) {
        global $database;
        $diff_ids = array();
        $diff = array_diff($assocArray1, $assocArray2);
        foreach($diff as $key => $value) {
            if ($value != 0) {
                $diff_ids[] = $value;
            }
        }
        return $diff_ids;
    }
}
if (!function_exists('getAssociateOldAuthors_media')) {
    function getAssociateOldAuthors_media() {
        global $database;
        $id_check = JRequest::getVar('people_id', "");
        $query = "SELECT `associate_people` FROM #__medialibrary_people where `id` = " . $id_check . "";
        $database->setQuery($query);
        $oldAssociate = $database->loadResult();
        $oldAssoc_func = unserialize($oldAssociate);
        return $oldAssoc_func;
    }
}
if (!function_exists('edit_author_associate_media')) {
    function edit_author_associate_media($author) {
        global $my, $database;
        $associateArray = array();
        $userid = $my->id;

        if (version_compare(JVERSION, "1.6.0", "lt")) {
            $allLanguages = array();
            $lang = JFactory::getLanguage();
            foreach($lang->getLocale()  as  $locale) {
                if (mb_strlen($locale) == 5 && $locale[2] == '_'){
                    $locale[2] = '-';
                    $allLanguages[] =  $locale;
                }
            }
        } else {
            $query = "SELECT lang_code FROM `#__languages`";
            $database->setQuery($query);
            $allLanguages = $database->loadColumn();
        }
        $query = "SELECT id,langshow, people_name FROM `#__medialibrary_people`";
        $database->setQuery($query);
        $allauthors = $database->loadObjectlist();
        $query = "SELECT associate_people FROM #__medialibrary_people where id =" . $author->id;
        $database->setQuery($query);
        $authorAssociateauthor = $database->loadResult();
        if (!empty($authorAssociateauthor)) {
            $authorAssociateauthor = unserialize($authorAssociateauthor);
        } else {
            $authorAssociateauthor = array();
        }
        $i = 0;
        foreach($allLanguages as $oneLang) {
            $i++;
            $associate_people = array();
            $associate_people[] = mosHtml::makeOption(0, 'select');
            foreach($allauthors as & $oneAuthor) {
                if ($oneLang == $oneAuthor->langshow && $oneAuthor->id != $author->id) {
                    $associate_people[] = mosHTML::makeOption(($oneAuthor->id), $oneAuthor->people_name);
                }
            }
            if ($author->langshow != $oneLang) {
                if (isset($authorAssociateauthor[$oneLang]) && 
                    $authorAssociateauthor[$oneLang] !== $author->id) {
                    $associateArray[$oneLang]['assocId'] = $authorAssociateauthor[$oneLang];
                } else {
                    $associateArray[$oneLang]['assocId'] = 0;
                }
                $associate_people_list = mosHTML::selectList(
                        $associate_people, 'language_associate_people' . $i, 'class="inputbox" size="1"', 
                        'value', 'text', $associateArray[$oneLang]['assocId']);
            } else {
                $associate_people_list = null;
            }
            $associateArray[$oneLang]['list'] = $associate_people_list;
            if (isset($authorAssociateauthor[$oneLang]) && 
                    $authorAssociateauthor[$oneLang] !== $author->id) {
                $associateArray[$oneLang]['assocId'] = $authorAssociateauthor[$oneLang];
            } else {
                $associateArray[$oneLang]['assocId'] = 0;
            }
        }
        return $associateArray;
    }
}

if (!function_exists('createNewNameCover')) {
    function createNewNameCover($name) {
        global $database;
        $regExp = '/^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{10}/';
        if(preg_match($regExp, $name)){
            $substrName = createNewNameCover(mb_substr($name, 36, strlen($name)));
        }else{
            $substrName = $name;
        }
        return $substrName;
    }
}

if (!function_exists('get_ItemId_for_media_by_type')) {
    function get_ItemId_for_media_by_type() {
        global $database, $Itemids_global;

        if (!$Itemids_global){
            $lang_menu = trim( mosGetParam( $_REQUEST, "lang", '*' ) );

            $no_one_fined = 1;
            if ($database == ''){
                $database = JFactory::getDBO();
            }
            $query = "SELECT id, link, menutype, params, home, language FROM #__menu ";
            $database->setQuery($query);
            $Items = $database->loadObjectList();
            foreach ($Items as $value) {
                if ($value->home == '1'){
                    $Home_pages[$value->language] = $value->menutype;
                }
                if (strpos($value->link, 'allbook') !== false){
                    $layout = json_decode($value->params)->allbook;
                    if ($layout == 'list' || $layout == 'default'|| $layout == '' ){
                        $second_option = $Itemids[$value->menutype]['book'] = $value->id;
                        $no_one_fined = 0;
                    }
                } elseif (strpos($value->link, 'allgame') !== false){
                    $layout = json_decode($value->params)->allgame;
                    if ($layout == 'list' || $layout == 'default'|| $layout == ''){
                        $second_option = $Itemids[$value->menutype]['game'] = $value->id;
                        $no_one_fined = 0;
                    }
                } elseif (strpos($value->link, 'allmusic') !== false){
                    $layout = json_decode($value->params)->allmusic;
                    if ($layout == 'list' || $layout == 'default'|| $layout == ''){
                        $second_option = $Itemids[$value->menutype]['music'] = $value->id;
                        $no_one_fined = 0;
                    }
                } elseif (strpos($value->link, 'allvideo') !== false){
                    $layout = json_decode($value->params)->allvideo;
                    if ($layout == 'list' || $layout == 'default'|| $layout == ''){
                        $second_option = $Itemids[$value->menutype]['video'] = $value->id;
                        $no_one_fined = 0;
                    }
                }
            }

            if (!isset($second_option)){$second_option = $Itemid;}
                

            $nead_menu = 0;
            if (isset($Home_pages[$lang_menu])){
                if (isset($Itemids[$Home_pages[$lang_menu]])){
                    $nead_menu = $Home_pages[$lang_menu];
                }
            } 
            if ($nead_menu === 0) {
                if (isset($Home_pages['*'])){
                    if (isset($Itemids[$Home_pages['*']])){
                        $nead_menu = $Home_pages['*'];
                    }
                } 
            }
            foreach ($Itemids as $menutype => $Item) {
                if ($nead_menu){
                    $menutype = $nead_menu;
                }
                if(isset($Itemids[$menutype]['video']) && $Itemids[$menutype]['video'] != ''){
                    $second_option = $Itemids['video'] = $Itemids[$menutype]['video'];
                }
                if(isset($Itemids[$menutype]['music']) && $Itemids[$menutype]['music'] != ''){
                    $second_option = $Itemids['music'] = $Itemids[$menutype]['music'];
                }
                if(isset($Itemids[$menutype]['game']) && $Itemids[$menutype]['game'] != ''){
                    $second_option = $Itemids['game'] = $Itemids[$menutype]['game'];
                }
                if(isset($Itemids[$menutype]['book']) && $Itemids[$menutype]['book'] != ''){
                    $second_option = $Itemids['book'] = $Itemids[$menutype]['book'];
                }
            }
            if (!isset($Itemids['video'])){$Itemids['video'] = $second_option;}
            if (!isset($Itemids['music'])){$Itemids['music'] = $second_option;}
            if (!isset($Itemids['game'])){$Itemids['game'] = $second_option;}
            if (!isset($Itemids['book'])){$Itemids['book'] = $second_option;}
            $Itemids['second_option'] = $second_option;
            $Itemids_global = $Itemids;
            return $Itemids;
        } else {
            return $Itemids_global;
        }
    }
}
if (!function_exists('checkJavaScriptIncluded')) {
    function checkJavaScriptIncluded($name) {
        $doc = JFactory::getDocument();

        foreach($doc->_scripts as $script_path=>$value){
          if(strpos( $script_path, $name ) !== false ) return true ;
        }
        return false;
    }
}

if(!function_exists('addInfoAboutUpdate')){
    function addInfoAboutUpdate() {
        global $mosConfig_absolute_path;
        
        // function for check equivalence versions
        function checkVersion($newversion, $oldversion) {
            $newversion = explode('.', substr($newversion, 0, strpos($newversion, ' ')));
            $oldversion = explode('.', substr($oldversion, 0, strpos($oldversion, ' ')));
            return $oldversion === max($newversion, $oldversion);
          
        }
        // add info about update
        $url="https://ordasoft.com/xml_update/medialibrary.xml"; //file from site Orda
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);

        $data = curl_exec($ch);
        curl_close($ch);

        if (!$data || stristr($data, 'Not Found')) return; // exit from function if not xml
        $xml = simplexml_load_string($data);
        $ordasoftMediaV = (string)$xml->version;
        $ordasoftCreationDate = (string)$xml->creationDate;
        unset($xml);

        $xml = JFactory::getXml($mosConfig_absolute_path . "/administrator/components/com_medialibrary/medialibrary.xml");
        $version = (string)$xml->version; //сurrent version  
        $creationDate = (string)$xml->creationDate;
        unset($xml);

        //-------------------------------------------------
        if (!empty($ordasoftMediaV) && !checkVersion($ordasoftMediaV, $version)) {
            $message = "Available new version Medialibrary $ordasoftMediaV" . 
            ", creation date $ordasoftCreationDate";
            JFactory::getApplication()->enqueueMessage($message);
        }
    }
}  
