<?php  if (!defined('BASEPATH')) { exit('No direct script access allowed'); }
/**
 * CodeIgniter helper
 *
 * @category CodeIgniter
 * @license /_licenses/untermStrich/agb_normal.pdf
 * @author Christian Koller
 * @copyright 2009 untermStrich
 * @package helpers
 * @version $Id$
 */

if ( ! function_exists('header_no_cache')) {
    /**
     * No Cache
     */
    function header_no_cache()
    {
        if (!headers_sent()) {
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Cache-Control: no-cache, max-age=0, no-store, must-revalidate, proxy-revalidate, no-transform');
            header('Pragma: no-cache');
        } else {
        }
    }
}

if ( ! function_exists('bool_leftcheck')) {
    /**
     * Create the boolean html for the leftcheck menu
     *
     * @param       boolean     $val        Boolean value
     * @param       string      $id         Optional An id for the div
     * @param       boolean     $as_span    Optional As span
     * @return      string
     */
    function bool_leftcheck($val, $id='', $as_span=false)
    {
        if($id !== '') {
            $id = ' id="'.$id.'"';
        }
        
        if ($as_span) {
            $elem = 'span';
        } else {
            $elem = 'div';
        }
        
        return ($val) ? '<'.$elem.' class="dialog_make_btn14 yess"'.$id.'></'.$elem.'>' : '<'.$elem.' class="dialog_make_btn14 nos"'.$id.'></'.$elem.'>';
    }
}

if ( ! function_exists('img_url')) {
    /**
     * Create an image url
     *
     * @param       string  $image_uri  The image uri - e.g.: 'section/image id'
     * @return      string
     */
    function img_url($image_uri)
    {
        return site_url().'start/image/'.str_ireplace(
                        array('.jpeg', '.jpg', '.png', '.bmp'),
                        '',
                        $image_uri ?? ''
                );
    }
}

if ( ! function_exists('img_html')) {
    /**
     * Create an image in html
     *
     * @param       string  $image_uri  The image uri - e.g.: 'section/image id'
     * @param       string  $class      Optional A class to add
     * @return      string
     */
    function img_html($image_uri, $class='')
    {
        $url = img_url($image_uri);
        return '<a href="'.$url.'" rel="imgpop"><img src="'.$url.'" class="'.$class.'" /></a> ';
    }
}


if ( ! function_exists('prepare_string')) {
    /**
     * Prepare a string for usage in .html() and .viewAlert()
     *
     * @param       string  $message    The string
     * @param       boolean $nl2br      Optional Use nl2br
     * @param       boolean $for_double Optional Prepare for double quotes " (Else for single ')
     * @param       boolean $no_shy     Optional Remove &shy;
     * @param       boolean $multiline  Optional Allow multiline or not;
     * @return      string
     */
    function prepare_string($message, $nl2br=true, $for_double=true, $no_shy=false, $multiline=false)
    {
        $from = array(
            '\\',
            "\xe2\x80\xa8", //UNICODE LINE SEPARATOR 2028
            "\n",
            "\r",            
        );
        $to = array(
            '\\\\',
            '',
        );
        
        if ($multiline) {
            array_push($to, '\\n');
            array_push($to, '\\r');
        } else {
            array_push($to, '');
            array_push($to, '');
        }
        
        if ($for_double==='FORJS') {
            array_push($from, '\'');
            array_push($to, '\\\'');
        } elseif ($for_double) {
            array_push($from, '"');
            array_push($to, '\'');
        } else {
            array_push($from, '\'');
            array_push($to, '"');
        }
        
        if ($no_shy) {
            array_push($from, '&shy;');
            array_push($to, '');
        }


        $from = (is_array($from)) ? $from : strval($from);
        $to = (is_array($to)) ? $to : strval($to);
        $message = (is_array($message)) ? $message : strval($message ?? '');

        return str_replace(
            $from, $to,
            ($nl2br) ? nl2br($message ?? '') : $message ?? ''
        );
    }
}

if ( ! function_exists('processresult_message')) {
    /**
     * Create message
     *
     * @param       string      $message        The string
     * @param       bool        $for_detail     For detail info block
     * @param       bool        $add_br         Add <br> when for_detail
     * @return      void
     */
    function processresult_message($message, bool $for_detail=false, bool $add_br=true)
    {
        echo '<script type="text/javascript">';
        if ($for_detail) {
            echo '$("#progressmessagedetail").append("'.prepare_string($message ?? '').($add_br ? '<br />' : '').'");';
        } else {
            echo '$("#progressmessage").html("'.prepare_string($message ?? '').'");';
        }
        echo '</script>'."\n";
    }
}

if ( ! function_exists('processresult_hide')) {
    /**
     * Hide message popup
     *
     * @return      void
     */
    function processresult_hide()
    {
        echo '<script type="text/javascript">';
        echo '$("#progressmessage").hide();';
        echo '</script>'."\n";
    }
}

if ( ! function_exists('manylist_elem_html')) {
    /**
     * Create a many items list in html
     *
     * @param       string      $name       HTML name of the element
     * @param       string      $title      The element title to display
     * @param       mixed       $id         The element ID
     * @param       string      $class      Optional Element class
     * @param       boolean     $inactive   Optional Inactive flag
     * @return      string
     */
    function manylist_elem_html($name, $title, $id, $class='', $inactive=null, $row_style=null)
    {
        $iacflg = '';
        if ($inactive!==null) {
            $CI = CI_Controller::get_instance();
            $iacflg = '<input type=\'checkbox\' name=\''.$name.'_inactive[]\' value=\''.$id.'\' title=\''.$CI->lang->line('basic_inactive').'\' ';
            if ($inactive) {
                $iacflg .= ' checked=\'checked\' ';
            }
            $iacflg .= ' />&nbsp;&nbsp;';
        }
        
        $title_css = '';
        
        $classes = explode(' ', $class);
        $no_id = false;
        $no_id_method = '';
        $no_id_icon = '';
        foreach ($classes as &$val) {
            if (substr($val, 0, 5) === 'no_id') {
                $no_id = true;
                $no_id_method = substr($val, 6 );
                $val = 'no_id';//clean
            }
        }
        
        if ($no_id) {
            $title_css = 'color:red';
            $no_id_icon = '<span class=\'search\' onclick=\''.$no_id_method.';\'></span>';
        }
        
        if ($row_style !== null) {
            $title_css = $row_style;
        }
        
        $title = str_replace(array("\n", "\r"), '', prepare_string($title ?? ''));
        
        return '<p class=\''.$class.'\'>'.
                $iacflg.
                '<input type=\'hidden\' name=\''.$name.'[]\' value=\''.$id.'\' />'.
                '<span class=\'title\' style=\''.$title_css.'\'>'.$title.'</span><span class=\'delete\'></span>'.$no_id_icon.
                '</p>';
    }
}


if ( ! function_exists('filelink_html')) {
    /**
     * Create a file link
     *
     * @param       string      $url                            The file url
     * @param       string      $url_type                       Optional The file type
     * @param       integer     $row_id                         Optional The row ID
     * @param       boolean     $show_link_depending_on_item    Optional Show the link depending on the item
     * @param       stdClass    $item                           Optional An item stdClass
     * @param       boolean     $return_url                     Optional Return url only
     * @return      string
     */
    function filelink_html($url, $url_type=false, $row_id=false, $show_link_depending_on_item=false, stdClass $item=null, $return_url=false)
    {
        if (!empty($url)) {
            $CI = CI_Controller::get_instance();
            $CI->load->helper('crypt');
            
            $url_ending4 = strtolower(substr($url, -4));
            $url_ending5 = strtolower(substr($url, -5));            

            $mode = $CI->web_settings->get_max_filemanager();
            
            $add_to_action_url = '';
            $snd_param__module = '';
            $thrd_param__send_to_server = '';
            $frth_param__filename = '';
            
            $title = '';
            
            switch ($url_type) {
                case 'folder':
                    if ($mode==4) {
                        return '';
                    } 
                    $action_to_call = 'open'; //direct via untermStrich X
                    $action = 'OPENFOLDER';
                    $icon_css = 'open_folder';
                    $title = $CI->lang->line('basic_open_folder').' - ';
                    break;
                case 'msgfrstbtn':
                case 'msg':
                    $action_to_call = 'open_download'; //direct via untermStrich X
                    $action = 'OPENMSG';
                    $icon_css = $action_to_call;
                    if ($url_type==='msgfrstbtn') {
                        $icon_css .= ' frstbtn';
                    }
                    break;
                case 'txt':
                    $action_to_call = 'open_download'; //direct via untermStrich X
                    $action = 'OPENTXT';
                    $icon_css = $action_to_call;
                    break;
                case 'spread':
                    $action_to_call = 'open_download'; //direct via untermStrich X
                    $action = 'OPENSPREAD';
                    $icon_css = $action_to_call;
                    break;
                case 'correspondence_4vx':
                case 'correspondence_4vx_print':
                    $action_to_call = 'open_correspondence'; //Either open via module, connector or plugin
                    $action = 'OPEN';
                    
                    switch ($url_type) {
                        case 'correspondence_4vx':
                            $icon_css = 'open_win';
                            $snd_action = 1;
                            break;
                        case 'correspondence_4vx_print':
                            $action_to_call = 'open_correspondence_old'; //Via module only
                            $icon_css = 'print';
                            $title = $CI->lang->line('basic_print').' - ';
                            $snd_action = 3;
                            break;
                    }

                    $row_ids = explode('_', $row_id);
                    
                    $info_snd = $CI->login->get_user_id();
                    $info_snd .= '|'.$CI->login->get_active_user_id();
                    $info_snd .= '|10|'.$snd_action.'|'.trim($row_ids[0]);
                    
                    $snd_param__module = Two_way_crypt::encode('MODULE').'/'.Two_way_crypt::encode($info_snd);
                    
                    $thrd_param__send_to_server = 'correspondence:'.$row_id;
                    break;
                case 'correspondence_attachment':    
                    $action_to_call = 'open_correspondence'; //Either open via module, connector or plugin
                    $action = 'OPEN';
                    $icon_css = 'open';
                    $snd_action = 1;
                    
                    
                    $thrd_param__send_to_server = 'correspondence_attachment:'.$row_id;
                    break;
                case 'correspondence_enc_no_office':
                    $action_to_call = 'open_correspondence_enc_no_office';
                    $action = 'OPEN_ENC_CORR';
                    $add_to_action_url = $row_id;
                    $icon_css = 'open_win';
                    break;
                case 'correspondence_any':
                case 'correspondence_new':
                    require_once(APPPATHLIVE.'libraries/filesystem_creators/Filesystem_creator.php');
                    $thrd_param__send_to_server = 'correspondence:'.$row_id;
                    $action_to_call = 'open';
                    if ($item instanceof stdClass && isset($item->project_path_correspondence) && strtoupper(substr($item->project_path_correspondence, 0, 5)) === Filesystem_creator::FS_O365.':') {
                        $action_to_call.='o365';
                    }
                    if ($item instanceof stdClass && intval($item->security) < 3) {
                        $action = 'OPENSEC'.intval($item->security);
                        $add_to_action_url = $row_id;
                    } else {
                        $action = 'OPEN'; //No security mode
                        $add_to_action_url = $row_id;
                    }
                    $icon_css = $action_to_call;
                    break;
                case 'correspondence_old':
                    require_once(APPPATHLIVE.'libraries/filesystem_creators/Filesystem_creator.php');
                    $thrd_param__send_to_server = 'correspondence:'.$row_id;
                    $action_to_call = 'open';
                    if ($item instanceof stdClass && isset($item->project_path_correspondence) && strtoupper(substr($item->project_path_correspondence, 0, 5)) === Filesystem_creator::FS_O365.':') {
                        $action_to_call.='o365';
                    }
                    if ($item instanceof stdClass && intval($item->security) < 3) {
                        $action = 'OPENSEC'.intval($item->security).'READONLY';
                        $add_to_action_url = $row_id;
                    } else {
                        $action = 'OPENREADONLY'; //No security mode
                        $add_to_action_url = $row_id;
                    }
                    $icon_css = 'open_correspondence_old';
                    break;
                case 'correspondence_type_new':
                    $thrd_param__send_to_server = 'correspondence_type:'.$row_id;
                    $action_to_call = 'open';
                    if ($item instanceof stdClass && intval($item->security) < 3) {
                        $action = ($mode === 4) ? 'OPEN_CORR_TYPE_SEC' : 'OPENSEC';
                        $action.= intval($item->security);
                        $add_to_action_url = 'corrtype'.$row_id;
                    } else {
                        $action = 'OPEN'; //No security mode
                        $add_to_action_url = 'corrtype'.$row_id;
                    }
                    $icon_css = 'print';
                    break;
                case 'file_preview':
                    if ($item instanceof stdClass && intval($item->security) < 3) {
                        return '';
                    }
                case 'simplefolder':
                case 'simplefolderfrstbtn':
                    $icon_css = ($mode==4) ? 'open_download' : 'open';
                case 'file':
                case 'filefrstbtn':
                default:
                    $action_to_call = ($mode==4) ? 'open_download' : 'open';
                    $action = 'OPEN';
                    if (!isset($icon_css)) {
                        $icon_css =  ($mode==4) ? 'open_download' : 'open_win';
                    }
                    if ($url_type==='filefrstbtn' || $url_type==='simplefolderfrstbtn') {
                        $icon_css .= ' frstbtn';
                    }
            }

            require_once(APPPATHLIVE.'libraries/filesystem_creators/Filesystem_creator.php');
            if (strtoupper(substr($url, 0, 5)) === Filesystem_creator::FS_O365.':') {
                $action_to_call = 'openo365';
                $thrd_param__send_to_server = (($item instanceof stdClass && intval($item->security) == 3) || empty($thrd_param__send_to_server)) ? 'openo365:'.base64_encode($url) : $thrd_param__send_to_server;
            }
            
            if ($mode==3) {
                switch ($action_to_call) {
                    case 'open':
                    case 'open_correspondence':
                        $frth_param__filename = base64_encode($url);
                        break;
                }
            }
            
            $open_href = sprintf(
                'usComm.filemanager.%s(\'%s%s\', \'%s\', \'%s\', \'%s\')',
                $action_to_call,
                Two_way_crypt::encode($action).'/'.Two_way_crypt::encode($url),
                ($add_to_action_url!=='') ? '/'.$add_to_action_url : '',
                $snd_param__module,
                $thrd_param__send_to_server,
                $frth_param__filename
            );
            
            if ($return_url) {
                return $open_href;
            }
            
            $reply = sprintf(
                '<a onclick="%s; return false;" href="#"
                    class="dialog_make_btn16 %s smallbtns ui-corner-all"
                    title="%s"
                    > </a>',
                $open_href,
                $icon_css, //CSS class
                $title.us_htmlentities($url, ENT_COMPAT).' - ID:'.trim($row_id)
            );
            
            if ($action == 'OPEN') {
                if ($url_type === 'file_preview') {
                    $reply = '';
                }
                if ($url_ending4=='.pdf') {
                    $openurl = Two_way_crypt::encode('OPENPDF').'/'.Two_way_crypt::encode($url);
                    $reply .= sprintf(
                        '<a href="%s" onclick="%s; return false;"
                            class="pdftooltip dialog_make_btn16 pdf smallbtns ui-corner-all"
                            title="%s"
                            ></a>',
                        site_url('/start/open/basic/view_pdf/'.$CI->login->get_xsrf().'/'.$openurl),
                        $open_href,
                        $CI->lang->line('basic_pdf')
                    );
                } elseif ($url_ending4=='.gif' || $url_ending4=='.png' || $url_ending4=='.bmp'  || $url_ending4=='.jpg' || $url_ending5=='.jpeg') {
                    $openurl = Two_way_crypt::encode('OPEN').'/'.Two_way_crypt::encode($url);
                    $reply .= sprintf(
                        '<a href="%s" onclick="%s; return false;"
                            class="imgtooltip dialog_make_btn16 png smallbtns ui-corner-all"
                            title="%s"
                            ></a>',
                        site_url('/start/file/'.$openurl),
                        $open_href,
                        'Bild'
                    );
                }
            }
            
            return $reply;
        } else {
            return '';
        }
    }
}

if ( ! function_exists('address_long')) {
    /**
     * Takes an address object and creates the address long title
     *
     * @param       object  $address_info   The address info
     * @return      string
     */
    function address_long($address_info)
    {
        $reply = $address_info->name;
        if (empty($address_info->contact_person)) {
            if (!empty($address_info->first_name)) {
                $reply .= ' '.$address_info->first_name;
            }
            if (!empty($address_info->academic_title)) {
                $reply .= ' '.$address_info->academic_title;
            }
        } else {
            $reply .= ',';
            if (!empty($address_info->academic_title)) {
                $reply .= ' '.$address_info->academic_title;
            }
            if (!empty($address_info->first_name)) {
                $reply .= ' '.$address_info->first_name;
            }
            $reply .= ' '.$address_info->contact_person;
            if (!empty($address_info->master_title)) {
                $reply .= ' '.$address_info->master_title;
            }            
        }

        if (!empty($address_info->comp_supp)) {
            $reply .= ', '.$address_info->comp_supp;
        }

        return $reply;
    }
}

if ( ! function_exists('json_clean')) {
    /**
     * Cleans a string for us_json_encode
     *
     * @param   string  $string     The string to clean
     * @return  string  Cleaned string
     */
    function json_clean($string)
    {
        return str_replace(
            array(
                '<',
                '>',
                '&',
                '\'',
            ),
            array(
                "\u003C",
                "\u003E",
                "\u0026",
                "\u0027",
            ),
            $string ?? ''
        );
    }
}

if ( ! function_exists('us_json_encode')) {
    /**
     * Creates a clean json string
     *
     * @param   object  $object                 The element to encode
     * @param   boolean $convert_objects        Optional: convert some object types in given $object to arrays
     * @return  string  Cleaned string
     */
    function us_json_encode($object, $convert_objects=false)
    {
        if($convert_objects === true){
            $object = prepare_object_for_json_encode($object);
        }
        
        return json_encode($object, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP);
    }
}

if ( ! function_exists('us_xml_clean')) {
    /**
     * Cleans a string for XML
     *
     * @param   string  $string     The string to clean
     * @return  string  Cleaned string
     */
    function us_xml_clean($string)
    {
        return str_replace(
            array(
                '\''
            ),
            array(
                '&#039;'
            ),
            $string ?? ''
        );
    }
}

if ( ! function_exists('prepare_object_for_json_encode')) {
    /**
     * Convert some object types to array (recursive)
     * 
     * Converted objects are: StdClass, UsBasicDateTime
     *
     * @param   object  $object         The element to prepare
     * @return  array   Cleaned object/array as assoziative array
     */
    function prepare_object_for_json_encode($object)
    {
        $tmp = array();
        if($object instanceof stdClass){
            foreach ($object as $key => $val) {
                $tmp[$key] = $val;
            }
            $object = $tmp;
        }
        
        if($object instanceof stdClass || is_array($object)){
            foreach ($object as $key => &$val) {
                if($val instanceof UsBasicDateTime){
                    $tmp = array();
                    $tmp['date'] = $val->format('Y-m-d H:i:s'); //!use ->format() not mysql() cause of "null"
                    $tmp['timezone'] = $val->format('e');
                    $object[$key] = $tmp;
                } elseif ($val instanceof stdClass || is_array($val)) {
                    $val = prepare_object_for_json_encode($val);
                }
            }            
        }
        return $object;
    }
}

if ( ! function_exists('string_to_phone')) {
    /**
     * Creates a phone number out of a string
     *
     * @param   string  $string                     The number string
     * @param   array   $sys_phone                  Optional: The phone system settings
     * @param   boolean $replace_leading_plus       Optional: Replace the leading plus
     * @return  string  Cleaned string
     */
    function string_to_phone($string, $sys_phone=array(), $replace_leading_plus=true)
    {
        $from = array(
            '+',
            ' ',
            '-',
            '/',
            '\\', #Just a quoted
            '(0)', #Verkehrsausscheidungsziffer entfernen
            '(',
            ')',
        );
        $to = array(
            '00',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
        );
        if (!$replace_leading_plus) {
            unset($from[0]);
            unset($to[0]);
        }
        
        $string_phone = str_replace($from, $to, $string ?? '');
        
        if ($replace_leading_plus && !empty($sys_phone['country'])) {
            $prefix = $sys_phone['country'];
            if (substr($string_phone, 0, strlen($prefix)) === $prefix) {
                $string_phone = substr($string_phone, strlen($prefix));
            }
            
            if (strpos($string_phone, '0')!==0) {
                $string_phone = '0'.$string_phone;
            }
        }
        
        return $string_phone;
    }
}

if ( ! function_exists('image_to_base64')) {
    /**
     * Loads an image from file as base64
     *
     * @param   string  $file_path  File to load
     * @return  string  Image as string
     */
    function image_to_base64($file_path)
    {
        if (is_null($file_path) || stripos($file_path, 'data:image')===0) {
            return $file_path;
        }
        
        if (!is_readable($file_path)) {
            return 'F-X';
        }
        
        $mime_type = get_file_type($file_path);
        if (stripos($mime_type, 'png')!==false) {
            $type = 'png';
        } elseif (stripos($mime_type, 'jpg')!==false) {
            $type = 'jpg';
        } elseif (stripos($mime_type, 'jpeg')!==false) {
            $type = 'jpg';
        } elseif (stripos($mime_type, 'gif')!==false) {
            $type = 'gif';
        } else {
            return 'F-T';
        }
        
        $content = file_get_contents($file_path);
        return 'data:image/'.$type.';base64,'.base64_encode($content);
    }
}

if ( ! function_exists('get_file_type')) {
    /**
     * Get (if possible) mime type, else the file extension
     *
     * @param   string  $file_path  File to load
     * @return  string  Mime or extension
     */
    function get_file_type($file_path)
    {
        if(function_exists('finfo_fopen')) {
            return finfo_open(FILEINFO_MIME, $file_path ?? '');
        } elseif (function_exists('mime_content_type')) {
            return mime_content_type($file_path ?? '');
        }
        return pathinfo($file_path ?? '', PATHINFO_EXTENSION);
    }
}

if ( ! function_exists('us_htmlentities')) {
    /**
     * Calls htmlentities according to PHP version
     *
     * @param   string|null     $string         The input string.
     * @param   integer         $quote_style    Quote style parameter
     * @return  string  The encoded string
     */
    function us_htmlentities(?string $string, $quote_style=ENT_COMPAT)
    {
        if (!is_int($quote_style)) {
            $quote_style=ENT_COMPAT;
        }
        try {
            return htmlentities($string ?? '', $quote_style | ENT_SUBSTITUTE, 'UTF-8');
        } catch (Exception $exc) {
            log_message('error', 'Call to htmlentities: '.$exc->getMessage());
        }
    }
}

if ( ! function_exists('us_htmlsrcdoc')) {
    /**
     * Create srcdoc compatible output
     *
     * @param   string  $string                 The input string.
     * @return  string  The encoded string
     */
    function us_htmlsrcdoc($string)
    {
        return htmlspecialchars(preg_replace( "/\r|\n/", ' ', $string ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if ( ! function_exists('us_uniqid')) {
    /**
     * Get a unique ID
     * 
     * @param   string  $prefix         Optional Prefix string
     * @param   boolean $more_entropy   Optional Add additional entropy
     * @return  string
     */
    function us_uniqid($prefix='', $more_entropy=false)
    {
        $CI = CI_Controller::get_instance();
        
        if ($more_entropy) {
            return $prefix.$CI->security->get_token();
        } else {
            return $prefix.mb_substr($CI->security->get_token(), 0, 13);
        }
    }
}

if ( ! function_exists('us_substr')) {
    /**
     * Get substring - Only for old butler
     *
     * @param   string  $string     The string
     * @param   integer $start      Start
     * @param   integer $length     Optional Length
     * @return  string
     */
    function us_substr($string, $start, $length=null)
    {
        if ($length!==null && !empty($length)) {
            return mb_substr($string ?? '', $start, intval($length));
        } else {
            return mb_substr($string ?? '', $start);
        }
    }    
}

if ( ! function_exists('us_use_latin1_access')) {
    /**
     * Never use latin1 access mode - Only for butler
     *
     * @return  boolean
     */
    function us_use_latin1_access()
    {
        return false;
    }
}

if ( ! function_exists('us_backslash_to_slash')) {
    /**
     * Use latin1 access mode
     *
     * @param   string  $filename       File name
     * @return  string
     */
    function us_backslash_to_slash($filename)
    {
        if (strtoupper(substr(PHP_OS, 0, 3))==='WIN') {
            return $filename ?? '';
        }
        
        return str_replace('\\', '/', $filename ?? '');
    }
}

if ( ! function_exists('us_slash_to_backslash')) {
    /**
     * Convert slashes to backslashes
     *
     * @param   string  $filename   File name
     * @return  string
     */
    function us_slash_to_backslash($filename)
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            return str_replace('/', '\\', $filename ?? '');
        }

        return $filename ?? '';
    }
}


if ( ! function_exists('us_use_nfd_mac')) {
    /**
     * Use UTF-8 NFD access mode
     *
     * @return  boolean
     */
    function us_use_nfd_mac()
    {
        return (strtoupper(substr(PHP_OS, 0, 6))==='DARWIN') ? true : false;
    }
}

if ( ! function_exists('get_fileicon_path')) {
    /**
     * Get the path of icon file
     *     
     * @param   string  $filename       The filename
     * @param   string  $special        Optional Special subtype
     * @return  string
     */
    function get_fileicon_path($filename, $special='')
    {
        $CI = CI_Controller::get_instance();
        
        $file_extension = 'file'; //default file icon
        $a_filename = explode('.', $filename);
        if(is_array($a_filename) && count($a_filename) > 1) {
            switch (strtolower($a_filename[count($a_filename)-1])) {
                case 'txt':
                case 'txm':
                    $file_extension = 'txt';
                    break;  
                case 'doc':
                case 'docx':
                case 'docm':
                    $file_extension = 'doc';
                    break;                 
                case 'ods':
                    $file_extension = 'ods';
                    break;
                case 'odt':
                    $file_extension = 'odt';
                    break;  
                case 'xls':
                case 'xlsx':
                case 'xlsm':
                    $file_extension = 'xls';
                    break;
                case 'jpg':
                case 'jpeg':
                    $file_extension = 'jpg';
                    break;
                case 'png':
                case 'gif':
                case 'tif':
                    $file_extension = 'png';
                    break;                         
                case 'csv':
                    $file_extension = 'csv';
                    break;                        
                case 'xml':
                    $file_extension = 'xml';
                    break;
                case 'htm':
                case 'html':
                    $file_extension = 'html';
                    break;
                case 'pdf':
                    $file_extension = 'pdf';
                    break;
                case 'ics':
                    $file_extension = 'ics';
                    break;    
                case 'vcf':
                    $file_extension = 'vcf';
                    break;                  
                case 'svg':
                    $file_extension = 'svg';
                    break;                 
                case 'zip':
                    $file_extension = 'zip';
                    break;
                default:
                    break;
            }            
        }
        
        return $CI->config->item('base_url').'images/fileicons/'.$file_extension.$special.'.png';
    }
}

if ( ! function_exists('us_is_readable')) {
    /**
     * Tells whether a file exists and is readable
     *     
     * @param   string  $filename     The filename / folder
     * @return  string
     */
    function us_is_readable($filename)
    {
        $CI = CI_Controller::get_instance();
        return $CI->load->filesystem($filename)->us_is_readable();
    }
}

if ( ! function_exists('us_utf8_clean')) {
    /**
     * Return a cleaned UTF8 string
     *
     * @param   string  $string   The string
     * @return  string
     */
    function us_utf8_clean($string)
    {
        $orig_mb_substitute_character = mb_substitute_character();
        mb_substitute_character('none');
        $string = mb_convert_encoding($string ?? '', 'UTF-8', 'UTF-8');
        mb_substitute_character($orig_mb_substitute_character);
        
        $string = preg_replace('/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
         '|[\x00-\x7F][\x80-\xBF]+'.
         '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
         '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
         '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/',
         '', $string );

        $string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
         '|\xED[\xA0-\xBF][\x80-\xBF]/S','', $string );
        
        $string = preg_replace ('/[^\x09\x0A\x0D\x20-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $string);
        
        return $string;
    }
}

if ( ! function_exists('us_prepare_email_filename')) {
    /**
     * Return an usabel e-mail filename
     *
     * @param   string  $string   The string
     * @return  string
     */
    function us_prepare_email_filename($string)
    {
        return str_replace(
            array('#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', '$', '"', ':', '@', '`', '|', '='), 
            '-', 
            us_utf8_clean($string ?? '')
        );
    }
}

/* End of file us_html_helper.php */
