<?php 

# Login and user session

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

# unique session name
$usn = 'MON';

# 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');
ini_set('session.cookie_samesite','strict');

session_name($usn);
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'=> $usn,
#                '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,
#                'cookie_samesite' => 'strict' # PHP 7.3.0
#                ]);
#
# Set session alternative END




if (session_name() == $usn)
    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',0,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'];
                    
                    # welcome message
                    $_SESSION['User_logged_in'] = true;
                    
                    # timeout session
                    $t = time();
                    $_SESSION['MONtimeout'] = $t;
                                        
                    include 'log.php';
                    $myinfo = get_account($_POST['username']);

                    $_SESSION['userID'] = $myinfo['userID'];
                    
                    # Sort results in posts & pages
                    $_SESSION['sortposts'] = $myinfo['sortposts'] != '' ? $myinfo['sortposts'] : 'sortbytime';
                    $_SESSION['sortpages'] = $myinfo['sortpages'] != '' ? $myinfo['sortpages'] : 'sortbytime';                    
                    
                    
                    $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)) {

                        if ($_SESSION['userID'] == 'thisismyfirstuserid') {
                            
                            $newid = md5(microtime());
                            edit_useraccount('userID',$newid);
                            
                            $settings = simplexml_object('settings.xml','e',null);
                            $settings->general->ownerid = $newid;
                            simplexml_object_save('settings.xml',$settings,null);
                            
                            $_SESSION['userID'] = $newid;

                        }
                        
                        $hp = (string)$myinfo['cphomepage'];
                        if ($hp == '')
                            $hp = 'opensaved.php';
                        header('Location: '.$hp);
                        #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,0,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)) {
        include 'log.php';    
        $hp = (string)get_account($_SESSION['username'])['cphomepage'];
        if ($hp == '')
            $hp = 'opensaved.php';
        header('Location: '.$hp);
        #no exit();
    }
    
    # log out
    if (isset($_GET['logout'])) {
        
        setcookie(session_name(),'',time()-1,'/');
        session_destroy();
        header('Location: login.php?bye');
    
    }

}

?>