<?php
    /**
     * @author Webfairy MediaT CMS - www.Webfairy.net
     */
    include dirname(__FILE__).'/lib/engine.php';
        $Webfairy = new Webfairy();
            $Webfairy->start();

    if ($Webfairy->isLoggedIn() == true) {
        $Webfairy->return_to();
    }

    $Webfairy->loadClass('formbuilder', 'tools');

    $Form = new FormBuilder('login', tr('login'), tr('welcome'), true, false);

    $msg = '';
    if (isset($_GET['code']) == true) {
        switch ($_GET['code']) {
            case 'RECOVER_SENT':
               $msg = $Webfairy->alert_html(tr('password_reset_emailed'), 'success');
            break;

            case 'PASS_SENT':
               $msg = $Webfairy->alert_html(tr('new_password_emailed'), 'success');
            break;

            case 'REQUIRE_LOGIN':
                $msg = $Webfairy->alert_html(tr('require_login'), 'danger');
            break;
        }
    }
    $Webfairy->smarty->assign('msg', $msg);

    $Form->addField(array(
            'id' => 'username',
            'type' => 'textbox',
            'label' => tr('username'),
            'required' => true,
            'maxlength' => 100,
            'headerinjectioncheck' => 'full',
        )
    );

    $Form->addField(array(
            'id' => 'password',
            'type' => 'password',
            'label' => tr('password'),
            'required' => true,
            
            'headerinjectioncheck' => 'full',
        )
    );
    
    $Form->addField(array(
            'id' => 'remember',
            'type' => 'radio',
            'inline' => true,
            'label' => tr('remember_me'),
            'instructions' => sprintf('<a href="%s"><small>%s</small></a>', $Webfairy->url('recover.html'), tr('forgot_password')),
            'radiolabels' => array(tr('yes'), tr('no')),
            'radiovalues' => array(1, 0),
            'defaultvalue' => 1,
        )
    );

    if ($Form->formSuccess()) {
        $username = $Webfairy->plaintext($_POST['username']);
        $password = $_POST['password'];
        $remember = (isset($_POST['remember']) == true) ? (boolean) $_POST['remember'] : false;

        if ($userData = $Webfairy->db->users('username', $username)->fetch()) {
            $hash = hash('sha256', $userData['salt'].hash('sha256', $password));
            if ($hash == $userData['password']) {
                $Webfairy->validateUser($userData['id'],$remember);
                $Webfairy->return_to();
            } else {
                $Form->forceErrorMessage('password', tr('incorrect_password'));
            }
        } else {
            $Form->forceErrorMessage('username', ftr('user_not_found', array($username)));
        }
    }

    $Webfairy->smarty->assign('renderForm', $Form->renderForm());

    $options = array(
        'noindex' => true,
    );

    $Webfairy->display('login.tpl', array(tr('login')), $options);
