<?php

$cms['modules']['admin.mod.php'] = array(
    'name' => __('Admin'),
    'description' => __('Admin module'),
    'url_title' => __('Module page'),
    'url_link' => 'https://coffee-cms.com/modules/admin/',
    'author' => __('Coffee CMS team'),
    'version' => '20.05',
    'files' => array(
        '.cms/mod/admin.mod.php',
        '.cms/js/admin.js',
    ),
    'sort'    => 20,
);

// Return if module disabled
if ( isset($cms['config']['admin.mod.php']['disabled'])
&& $cms['config']['admin.mod.php']['disabled'] === true ) return;

// Find and switch lang
if ( empty( $cms['config']['locale'] ) ) {
    foreach( glob( 'lang/*',  GLOB_ONLYDIR ) as $locale ) {
        $locale = preg_replace( '/.*\//', '', $locale );
        $cms['config']['locale'] = $locale;
        setlocale( LC_ALL, $cms['config']['locale'] );
        $cms['config']['lang'] = substr( $cms['config']['locale'], 0, 2 );
        break;
    }
    if ( empty( $cms['config']['lang'] ) ) {
        $cms['config']['lang'] = 'en';
    }
    cms_save_config();
}
if ( !empty( $cms['config']['locale'] ) ) {
    $translit = $cms['cms_dir'].'/lang/'.$cms['config']['locale'].'/translit.php';
    if ( file_exists( $translit ) ) {
        include_once( $translit );
    }
}

/* На этапе установки URL админки еще не задан.
   Возьмем текущий URL и будем считать что он админский
*/
if ( empty($cms['config']['admin.mod.php']['admin_url']) ) {
    $cms['config']['admin.mod.php']['admin_url'] = $cms['base_url'];
}


/* Добавим в перехватчик URLов переход на этап admin при посещении админского URL */
$cms['urls']['^'.$cms['config']['admin.mod.php']['admin_url'].'$'] = 'admin';

cms_add_function('admin', 'cms_admin_admin', 9999);
cms_add_function('ajax', 'cms_admin_ajax');
cms_add_function('admin_header', function () {
    global $cms;
    echo '
        <script type="text/javascript">
            $hide_admin_menu = "'.__("Hide Admin Menu?").'";
            $not_empty_container = "'.__("Not Empty Container").'";
            $disable_module = "'.__("Disable Module?").'";
            $connection_lost = "'.__("Connection lost").'";
        </script>
';});


function is_admin() {
    global $cms;
    return 
      isset($_COOKIE['admin_login']) && 
      isset($_COOKIE['admin_password']) &&
      isset($cms['config']['admin.mod.php']['admin_login']) &&
      isset($cms['config']['admin.mod.php']['admin_salt']) &&
      ($_COOKIE['admin_login'] === sha1($cms['config']['admin.mod.php']['admin_login'].$cms['config']['admin.mod.php']['admin_salt'])) &&
      ($_COOKIE['admin_password'] === sha1($cms['config']['admin.mod.php']['admin_password'].$cms['config']['admin.mod.php']['admin_salt']));
}


// Построение админ меню
function cms_admin_menu() {
    global $cms;

    // Создаем секции в постоянных настройках
    if ( !isset( $cms['config']['admin_sections'] ) ) {
        $cms['config']['admin_sections'] = array();
    }

    // Добавляем секции из модулей в постоянные секции, хранимые в настройках
    foreach( $cms['config'] as $mod => $mod_cfg ) {
        // Настройки модуля заканчиваются на .mod.php и имеют подмассив 'menu'
        if ( substr( $mod, -8, 8 ) == '.mod.php' && empty($mod_cfg['disabled']) && isset( $mod_cfg['menu'] ) ) {
            // Перебираем каждый пункт меню у модуля (их может быть много)
            foreach( $mod_cfg['menu'] as $menu => $menu_cfg ) {
                $section = $menu_cfg['section'];
                if ( !isset( $cms['config']['admin_sections'][$section] ) ) {
                    $cms['config']['admin_sections'][$section] = array(
                        'title' => __($section),
                        'sort'  => 10,
                        'hide'  => false,
                    );
                }
            }
        }
    }

    $cms['admin_sections'] = $cms['config']['admin_sections'];

    // Перебираем настройки модулей
    foreach( $cms['config'] as $mod => $mod_cfg ) {
        // Настройки модуля заканчиваются на .mod.php и имеют подмассив 'menu'
        if ( substr( $mod, -8, 8 ) == '.mod.php' && empty($mod_cfg['disabled']) && isset( $mod_cfg['menu'] ) ) {
            // Перебираем каждый пункт меню у модуля (их может быть много)
            foreach( $mod_cfg['menu'] as $menu => $menu_cfg ) {
                $section = $menu_cfg['section'];
                $conf = $menu_cfg;
                //$conf['page'] = &$cms['admin_pages'][$menu]; // FIXME видимо не используется
                $conf['module'] = $mod;
                $cms['admin_sections'][$section]['items'][$menu] = $conf;
            }
        }
    }

    // Сортируем секции
    cms_asort( $cms['admin_sections'] );

    // Сортируем пункты внутри секции
    foreach( $cms['admin_sections'] as $section_name => $section ) {
        cms_asort( $cms['admin_sections'][$section_name]['items'] );
    }
}

function cms_admin_admin() {
    global $cms;
    $cms['template'] = 'admin';
    $cms['status'] = '200';
    $cms['stages']['write']['disabled'] = true;
    
    if (!is_admin()) return;
    
    // Save settings
    if (!empty($_POST['change_admin_login'])) {
        //$cms['config']['locale'] = trim($_POST['locale']);
        $cms['config']['admin.mod.php']['admin_login'] = trim($_POST['admin_login']);
        if (!empty(trim($_POST['admin_password']))) {
            $cms['config']['admin.mod.php']['admin_password'] = trim($_POST['admin_password']);
        }
        cms_save_config();
        header('Location: ' . $cms["config"]["admin.mod.php"]["admin_url"]);
        exit;
    }
    
    // Display settings
    $form = "
<div class='db-grid'>
    <div class='dbbox'>
        <form method=post class=bdf>
            <div class=field>
                <div class='field-name-bd'>".__("Login or Email")."</div>
                <input name=admin_login type=text value='{$cms['config']['admin.mod.php']['admin_login']}' autocomplete=off class='settingx sto'>
            </div>
            <div class=field>
                <div class='field-name-bd'>".__("Password")."</div>
                <input name=admin_password type=text value='' autocomplete=off class='settingx sto'>
            </div>
            <input type=submit value='".__("Save")."' name=change_admin_login class=button-save>
        </form>
    </div>
    
    <div class='dbmanual'>
        <div class=info>
            <h1>".__('Change login and password')."</h1>
            <p>".__('You do not need to enter a password to change the login').".</p>
            <p>".__('To change the password, enter a new password').".</p>
        </div>
    </div>
    
</div>";
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['login'] ) ) {
        $cms['config']['admin.mod.php']['menu']['login'] = array(
            'title'    => 'Login',
            'sort'     => 10,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['login'] = $form;

   
    // PHP Info

    ob_start();
    phpinfo();
    preg_match( '/<body>(.+)<\/body>/s', ob_get_clean(), $m );
    $page = $m[1] . '
    <style type="text/css">
    [data-settings=phpinfo] {color: #222; font-family: sans-serif;}
    [data-settings=phpinfo] pre {margin: 0; font-family: monospace;}
    [data-settings=phpinfo] table {border-collapse: collapse; border: 0; width: 934px; }
    [data-settings=phpinfo] .center {text-align: center;}
    [data-settings=phpinfo] .center table {margin: 1em auto; text-align: left;}
    [data-settings=phpinfo] .center th {text-align: center !important;}
    [data-settings=phpinfo] td, th {border: 1px solid #666; font-size: 75%; vertical-align: baseline; padding: 4px 5px;}
    [data-settings=phpinfo] th {position: sticky; top: 0; background: inherit;}
    [data-settings=phpinfo] h1 {font-size: 150%;}
    [data-settings=phpinfo] h2 {font-size: 125%;}
    [data-settings=phpinfo] .p {text-align: left;}
    [data-settings=phpinfo] .e {background-color: #ccf; width: 300px; font-weight: bold;}
    [data-settings=phpinfo] .h {background-color: #99c; font-weight: bold;}
    [data-settings=phpinfo] .v {background-color: #ddd; max-width: 300px; overflow-x: auto; word-wrap: break-word;}
    [data-settings=phpinfo] .v i {color: #999;}
    [data-settings=phpinfo] img {float: right; border: 0;}
    [data-settings=phpinfo] hr {width: 934px; background-color: #ccc; border: 0; height: 1px;}
    </style>';
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['phpinfo'] ) ) {
        $cms['config']['admin.mod.php']['menu']['phpinfo'] = array(
            'title'    => 'PHP Info',
            'sort'     => 30,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['phpinfo'] = $page;


    // Список модулей
    $admin_menu = '<div class=wrapper-page-grid>';
    // Перебираем config и ищем модули
    foreach( $cms['modules'] as $mod => $mod_cfg ) {
        if ( isset( $cms['config'][$mod]['disabled'] ) && $cms['config'][$mod]['disabled'] === true ) {
            $status = 'disabled';
            $disabled = __('(Disabled)');
        } else {
            $status = 'enabled';
            $disabled = '';
        }
        $descr = "{$mod_cfg['description']}";
        $v     = "<span class=module-version>".__('Version').": {$mod_cfg['version']}</span> ";
        $v    .= "<span class=module-site><a href='{$mod_cfg['url_link']}' target=_blank class=module-link>{$mod_cfg['url_title']}</a></span> ";
        $v    .= "<span class=module-author>".__('Author').": {$mod_cfg['author']}</span> ";
        $admin_menu .= "
            <div class='pages-box'>
                <div class='cpline style-module' data-module={$mod}>

                    <div class='admin-checkpageline {$status}'></div>
                    
                    <h1 class='{$status}'>{$mod_cfg['name']} {$disabled}</h1>

                    <p class=module-descr>{$descr}</p>

                    <p class=module-val>{$v}</p>
                    
                    <div class='admin-pagesetting'>
                        <a href=# class='disable' data-module-enable={$mod} data-module-status={$status}>".__('On')."</a> 
                        <a href=# class='disable' data-module-disable={$mod} data-module-status={$status}>".__('Off')."</a> 
                        <span class='a-red'>
                        <a href='#' class=module-del data-module-del={$mod}>".__('Delete')."</a>
                        </span>
                    </div>
                    
                </div>
            </div>
        ";
    }
    $admin_menu .= '</div>';
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['modules'] ) ) {
        $cms['config']['admin.mod.php']['menu']['modules'] = array(
            'title'    => 'Modules',
            'sort'     => 50,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['modules'] = $admin_menu;


    // Настройка админского меню

    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['admin_menu'] ) ) {
        $cms['config']['admin.mod.php']['menu']['admin_menu'] = array(
            'title'    => 'Admin Menu',
            'sort'     => 40,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    
    cms_admin_menu();

    // Перечень секций для перемещения в них модулей
    $parents = '';
    foreach( $cms['admin_sections'] as $section_name => $section ) {
        $parents .= "<option value='{$section_name}'>".__($section['title'])."</option>";
    }

    // Цикл контейнеров
    $admin_menu = '<div class=wrapper-page-grid>';
    foreach( $cms['admin_sections'] as $section_name => $section ) {
        if ( isset($section['hide']) && $section['hide'] === true ) {
            $status = 'hidden';
            $hidden = __('(Container Hidden)');
        } else {
            $status = 'showed';
            $hidden = __('(Container)');
        }
        $admin_menu .= "
        <div class='pages-box'>
            <div class='hotsetting' data-am-prop={$section_name} data-type=section>
                <h1 class='hotsetting'>".__('CONTAINER PROPERTIES')."</h1>
                <div class='sett-grid-container'>

                    <div class='Sett-LefgGrid'>
                        <div class='sett-attribute prop-title'>
                            <div class='settinput-text'>".__('Title').":</div>
                            <div><input name='title' type='text' class='settingx' value='{$section['title']}'></div>
                        </div>
                    </div>
                
                    <div class='Sett-RightGrid'>
                        <div class='sett-attribute prop-sort'>
                            <div class='settinput-text'>".__('Sort').":</div>
                            <div><input name='sort' type='text' class='settingx-right-order' value='{$section['sort']}'></div>
                        </div>
                    </div>
                
                </div>
                
                <div class='hotbott'>
                    <a href=# data-am-cancel={$section_name} class='button-close'>".__('Cancel')."</a>
                    <a href=# data-am-delete={$section_name} class='button-delete'>".__('Delete Container')."</a>
                    <a href=# data-am-save={$section_name} class='button-save'>".__('Save')."</a>
                </div>

            </div>
            <div class='cpline style-admin-container' data-am-item={$section_name}>
                     
                <div class='admin-checkpageline {$status}'></div>

                <h1 class='{$status}'>{$section['title']} {$hidden}</h1>
                
                <div class='admin-pagesetting'>
                    <a href=# class=open-prop      data-am-prop-open={$section_name}>".__('Properties')."</a> 
                    <a href=# class='hide' data-am-show={$section_name} data-am-status={$status}>".__('Show')."</a> 
                    <a href=# class='hide' data-am-hide={$section_name} data-am-status={$status}>".__('Hide')."</a>
                </div>
                
                

            </div>
            <div class='subbox-grid open' data-am-childs={$section_name}>
        ";

        // Цикл пунктов в контейнере
        if ( !empty( $cms['admin_sections'][$section_name]['items'] ) )
        foreach( $cms['admin_sections'][$section_name]['items'] as $iname => $item ) {
            if ( isset( $item['hide'] ) && $item['hide'] === true ) {
                $status = 'hidden';
                $hidden = __('(Hidden)');
            } else {
                $status = 'showed';
                $hidden = '';
            }
            $title = __($item['title'],$item['module']);
            $admin_menu .= "
                <div class='pages-box'>
                    <div class='hotsetting' data-module={$item['module']} data-am-prop={$iname} data-type=menu data-parent-section={$section_name}>
                        <h1 class='hotsetting'>".__('ITEM PROPERTIES')." − {$title}</h1>
                        <div class='sett-grid-container'>
                            <div class='Sett-LefgGrid'>
                                <div class='sett-attribute prop-parent'>
                                    <div class='settinput-text'>".__('Container').":</div>
                                    <div class=select2-wrapper>
                                        <select class='settingx-right parents-list' data-am-parent='{$section_name}' name=section>
                                            {$parents}
                                        </select>
                                    </div>
                                </div>
                            </div>
                        
                            <div class='Sett-RightGrid'>
                                <div class='sett-attribute prop-sort'>
                                    <div class='settinput-text'>".__('Sort').":</div>
                                    <div><input name='sort' type='text' class='settingx-right-order' value='{$item['sort']}'></div>
                                </div>
                            </div>
                        
                        </div>
                        
                        <div class='hotbott'>
                            <a href='#' data-am-cancel={$iname} class='button-close'>".__('Cancel')."</a>
                            <a href='#' data-am-save={$iname} class='button-save'>".__('Save')."</a>
                        </div>
                
                    </div>

                    <div class='cpline style-admin-menu' data-am-item={$iname}>

                        <div class='admin-checkpageline {$status}'></div>
                        
                        <h1 class='{$status}'>{$title} {$hidden}</h1>

                        <div class='admin-pagesetting'>
                            <a href=# class=open-prop      data-am-prop-open={$iname}>".__('Properties')."</a> 
                            <a href=# class='hide' data-am-show={$iname} data-am-status={$status}>".__('Show')."</a> 
                            <a href=# class='hide' data-am-hide={$iname} data-am-status={$status}>".__('Hide')."</a>
                        </div>
                        
                    </div>
                </div>
            ";
        }
        // Закрытие цикла пунктов в контейнере
        $admin_menu .= "</div></div>";
    }


    // Закрытие цикла контейнеров
    $admin_menu .= '</div>';
    $admin_menu .= '
    <div class=bottompanell>
        <a data-am-add-section class="add-button add-section" href=#>'.__('Add Container').'</a>
    </div>';

    $cms['admin_pages']['admin_menu'] = $admin_menu;

}


function cms_admin_ajax() {
    global $cms;

    // Login
    if ( !empty( $_POST['fn'] ) && $_POST['fn'] == 'login' ) {
        $cms['status'] = '200';
        // Install process
        if ( empty($cms['config']['admin.mod.php']['admin_login'])
         && empty($cms['config']['admin.mod.php']['admin_password'])
         && (!empty(trim($_POST['login'])) || !empty(trim($_POST['password']))) ) {
            $cms['config']['admin.mod.php']['admin_login']    = trim($_POST['login']);
            $cms['config']['admin.mod.php']['admin_password'] = trim($_POST['password']);
            $cms['config']['admin.mod.php']['admin_salt']     = cms_admin_pass_gen(8);
            $cms['config']['admin.mod.php']['admin_url']      = $cms['base_url'].'-admin';
            $link = $cms['protocol'].'://'.$_SERVER['SERVER_NAME'].$cms['config']['admin.mod.php']['admin_url'];
            if (cms_save_config()) {
                if ( preg_match( '/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,9})(\]?)$/', $cms['config']['admin.mod.php']['admin_login'] ) ) {
                    $subject = __('Install finished');
                    $body = "<h2>".__('Congratulations!')."</h2>";
                    $body .= "<p>".__('Install finished').".</p>";
                    $body .= "<h4>".__('Credentials for login')."</h4>";
                    $body .= "<p>".__('Login URL').": <a href='{$link}'>{$link}</a></p>";
                    $body .= "<p>".__('Login').": {$_POST['login']}</p>";
                    $body .= "<p>".__('Password').": {$_POST['password']}</p>";
                    $body .= "<p></p><p>".__('Please login and setup database').".</p><p></p>";
                    cms_email(array(
                        'from_email' => 'noreply@'.$_SERVER['SERVER_NAME'],
                        'from_name' => $_SERVER['SERVER_NAME'],
                        'to_email' => $_POST['login'],
                        'subject' => $subject,
                        'email_body' => $body
                        ));
                }
            } else {
                exit( json_encode( array(
                    'info_text'  => __("config.php write protection error"),
                    'info_class' => 'info-error',
                    'info_time'  => 5000,
                ) ) );
            }
        }
        // Check login and password
        if ( $_POST['login'] === $cms['config']['admin.mod.php']['admin_login'] && 
            $_POST['password'] === $cms['config']['admin.mod.php']['admin_password'] )
        {
            setcookie('admin_login', sha1($cms['config']['admin.mod.php']['admin_login'].$cms['config']['admin.mod.php']['admin_salt']));
            setcookie('admin_password', sha1($cms['config']['admin.mod.php']['admin_password'].$cms['config']['admin.mod.php']['admin_salt']));
            if (!empty($link)) {
                exit( json_encode( array(
                    'link'  => $link,
                ) ) );
            } else {
                exit( json_encode( array(
                    'result'  => 'ok',
                ) ) );
            }
        } else {
            exit( json_encode( array(
                'info_text'  => __("Access denied"),
                'info_class' => 'info-error',
                'info_time'  => 5000,
            ) ) );
        }
    }

    // Logout and Admin Menu
    if ( !empty( $_POST['fn'] ) && is_admin() ) {
        switch ( $_POST['fn'] ) {

            case 'logout':
                $cms['status'] = '200';
                setcookie('admin_login', '');
                setcookie('admin_password', '');
                echo 'logout';
            break;

            case 'admin_menu_save':
                $cms['status'] = '200';
                switch ($_POST['type']) {
                    case 'section':
                        $cms['config']['admin_sections'][ $_POST['item'] ]['title'] = $_POST['title'];
                        $cms['config']['admin_sections'][ $_POST['item'] ]['sort']  = (int)$_POST['sort'];
                        break;
                    case 'menu':
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['section'] = $_POST['section'];
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['sort']    = (int)$_POST['sort'];
                        break;
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'admin_menu_hide':
                $cms['status'] = '200';
                $hide = $_POST['hide'] === 'true';
                switch ($_POST['type']) {
                    case 'section':
                        $cms['config']['admin_sections'][ $_POST['item'] ]['hide'] = $hide;
                        break;
                    case 'menu':
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['hide'] = $hide;
                        break;
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'admin_menu_add_section':
                $cms['status'] = '200';
                $n = 1;
                while ( isset( $cms['config']['admin_sections']['Container'.$n] ) ) {
                    $n++;
                }
                $cms['config']['admin_sections']['Container'.$n] = array(
                    'title' => 'Container'.$n,
                    'sort'  => (count($cms['config']['admin_sections'])+1)*10,
                    'hide' => false,
                );
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'admin_menu_del':
                $cms['status'] = '200';
                unset($cms['config']['admin_sections'][ $_POST['item'] ]);
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'module_disable':
                $cms['status'] = '200';
                if ( in_array( $_POST['module'], array(
                    'admin.mod.php',
                    'base.mod.php',
                    'menu.mod.php',
                    'pages.mod.php',
                    //'sitemap.mod.php',
                    'template.mod.php', ) ) )
                {
                    exit( json_encode( array(
                        'info_text'  => __('See how-to').' <a href="https://coffee-cms.com/" target=_blank>'.__('Disable standard modules').'</a>',
                        'info_class' => 'info-error',
                        'info_time'  => 0,
                    ) ) );
                }
                if ( $_POST['disable'] === 'true' ) {
                    $cms['config'][$_POST['module']]['disabled'] = true;
                } else {
                    unset($cms['config'][$_POST['module']]['disabled']);
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'module_del':
                $cms['status'] = '200';
                if ( in_array( $_POST['module'], array(
                    'admin.mod.php',
                    'base.mod.php',
                    'menu.mod.php',
                    'pages.mod.php',
                    'sitemap.mod.php',
                    'template.mod.php', ) ) )
                {
                    $text = __('Delete following files:');
                    foreach( $cms['modules'][$_POST['module']]['files'] as $file ) {
                        $text .= "<br>{$file}";
                    }
                    $class = 'info-error';
                    $time  = 0;
                } else {
                    foreach( $cms['modules'][$_POST['module']]['files'] as $file ) {
                        unlink($cms['site_dir'].'/'.$file);
                    }
                    $text  = __('OK');
                    $class = 'info-success';
                    $time  = 2000;
                }
                exit( json_encode( array(
                    'info_text'  => $text,
                    'info_class' => $class,
                    'info_time'  => $time,
                ) ) );
            break;
        }
        
    }
}


function cms_admin_pass_gen($count = 8) {
    $chars = '0123456789AaBbCcDdEeFfGgHhiJjKkLMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $strlen = strlen($chars)-1;
    $password = '';
    while ($count--) {
        $password .= $chars[rand(0,$strlen)];
    }
    return $password;
}
