<?php 

# Login and user session

# Session lifetime can be set here. Default is 43200 (12 hours)
$sesslifetime = 43200;


# Set session. There is an alternative following
ini_set('session.gc_maxlifetime',$sesslifetime);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
ini_set('session.use_cookies',1);
ini_set('session.cookie_lifetime',$sesslifetime);
ini_set('session.save_path','session');

session_name('MON');
session_start();
# Set session END
#
#
# Below is the local session alternative PHP 7.1 and above
# OPTIONS are available. This is an alternative of the above, including extra options : sid bits per character and sid length
# and also a name instead of calling session_name() function.

#session_start(['name'=>'MON',
#                'gc_maxlifetime' => $sesslifetime,
#                'gc_probability' => 1,
#                'gc_divisor' => 1,
#                'use_cookies' => 1,
#                'cookie_lifetime' => $sesslifetime,
#                'save_path' => 'session',
#                'sid_bits_per_character' => 5,
#                'sid_length' => 32
#                ]);





if (session_name() == 'MON')
    if (!isset($_SESSION['username'])) {

        # Failed login attempts before blocking a user
        $block = 8;

        # Minutes passed to unblock a user
        $unblock = 12;

        # Get user ip
        $user = $_SERVER['REMOTE_ADDR'];


        $ips = 'filesinfo/address.xml';
        $address_info = simplexml_load_file($ips);


        $block_message = '<span style="font-weight:bold; font-size:14px; font-family:arial">Access denied</span>';
        $log_ip = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><ipinfo></ipinfo>');


        $unbl = 0;

        foreach($address_info as $ip_time_out) {

            if (time() - $ip_time_out->on < 60 * $unblock) {

                $bl = $log_ip->addChild('ip','');
                $bl->addChild('addr',$ip_time_out->addr);
                $bl->addChild('on',$ip_time_out->on);
                $bl->addChild('attem',$ip_time_out->attem);
            }

            else 
                $unbl++;
        }    


            if ($unbl == 0) {
                $log_ip = $log_ip->asXML();
                $log_ip = simplexml_load_string($log_ip);
            }

            else {
                $log_ip->asXML($ips);
                $log_ip = simplexml_load_file($ips);
            }


            foreach($log_ip as $blocked_ips) {

                if ( $blocked_ips->addr !== false && $blocked_ips->addr == $user && $blocked_ips->attem >= $block) {
                    echo $block_message;
                    exit();
                
                }

            }
            
        
            $monousers = new simpleXMLElement('filesinfo/log.xml',null,true);
            
        
            
            $u=0;
            foreach($monousers->user as $usersinfo) {

                $username = $usersinfo->name;
                $password = $usersinfo->pshs;            
                
                
                    
                
                if ( isset($_POST['password']) && password_verify($_POST['password'],$password) && isset($_POST['username']) && $username == $_POST['username'] ) {

                    
                    include 'set-cost.php';

                    if (password_needs_rehash($password, PASSWORD_DEFAULT, ["cost" => $cost])) 
                        $usersinfo->pshs = password_hash($_POST['password'], PASSWORD_DEFAULT, ["cost" => $cost]);

                    
                    # New session id
                    session_regenerate_id(true);
                    
                    # Username
                    $_SESSION['username'] = $_POST['username'];
                    
                    # Sort results in posts
                    $_SESSION['MONSORT'] = 'sortbytime';
                    
                    # Timeout session
                    $t = time();
                    $_SESSION['MONtimeout'] = $t;
                    
                    
                    $_SESSION['User_logged_in'] = true;
                    
                    
                    include 'log.php';

                    $_SESSION['userID'] = get_account($_POST['username'])['userID'];
                    $monousers->user[$u]->login = date('m/d/Y, H:i:s',$t);
                    $monousers->user[$u]->ip = $_SERVER['REMOTE_ADDR'];
                    $monousers->asXML('filesinfo/log.xml');


                    if (isset($loginpage))
                        header('Location: opensaved.php');
                        #no exit().

                    break;
                }
                
                $u++;
            }


            if ( !isset($_GET['logout']) && isset($_POST['username']) && !isset($_SESSION['username']) ) {

                # This is a failed login attempt
                $_SESSION['MONfailedlogin'] = true;

                $log_ip = new SimpleXMLElement($ips,null,true);

                
                
                $c=0;
                foreach($log_ip as $obj){

                    if ($obj->addr == $user) {

                        $attempts = $obj->attem;
                        $log_ip->ip[$c]->on = time();
                        $log_ip->ip[$c]->attem = $attempts + 1;


                        if ($attempts == $block) {
                            $log_ip->asXML($ips);
                            header('Location: login.php');
                            exit();
                        }

                        
                        $final_ip = $log_ip->asXML($ips);

                        break;


                    }

                    $c++;    

                }


                if(!isset($final_ip)) {

                    $new = $log_ip->addChild('ip','');
                    $new->addChild('addr',$user);
                    $new->addChild('on',time());
                    $new->addChild('attem',1);

                    $log_ip->asXML($ips);
                }

                    $t = time();

                    include 'log.php';
                    $td = date('m/d/Y, H:i:s',$t);
                    update_log('failed',$td);
                    header('Location:login.php');
                    exit();

                }


                if (!isset($loginpage)) {
                    
                    $base = basename($_SERVER['PHP_SELF']);
                    
                    if ($base == 'icon-set.php' || $base == 'upload_icon.php' || $base == 'post.php' || $base == 'pagepost.php')
                        echo '<span title="Please login to your account">Please login to your account</span>';
                    else
                        header('Location:login.php');
                    
                    exit();
                }
}


else
    

{

    if (isset($loginpage))
        header('Location: opensaved.php');
        # no exit();
    
    

    # log out
    if (isset($_GET['logout'])) {
        
        setcookie(session_name(),'',time()-1,'/');
        session_destroy();
        header('Location: login.php?bye');
    
    }

}

?>