<?php
/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */

	//check if user logged in or not
	//if not redirect them into login page

	//first we need to check if the user has "remember me" cookie or not
	//make sure the cookie value is in the correct format and length (20-60 chars)
	$mf_remember_cookie = $_COOKIE['mf_remember'] ?? '';
	$mf_remember_valid  = is_string($mf_remember_cookie) && preg_match('/^[a-f0-9]{48}$/', $mf_remember_cookie) === 1;

	if($mf_remember_valid && empty($_SESSION['mf_logged_in'])){
		$dbh	= mf_connect_db();
		$query  = "SELECT
						`user_id`,
						`priv_administer`,
						`priv_new_forms`,
						`priv_new_themes`
					FROM
						`".MF_TABLE_PREFIX."users`
					WHERE
						CAST(`cookie_hash` AS BINARY)=? and LENGTH(`cookie_hash`) = 48 and `status`=1";
		$params = array($mf_remember_cookie);
		
		$sth = mf_do_query($query,$params,$dbh);
		$row = mf_do_fetch_result($sth);

		$mf_user_id 		  = $row['user_id'];
		$mf_priv_administer	  = (int) $row['priv_administer'];
		$mf_priv_new_forms	  = (int) $row['priv_new_forms'];
		$mf_priv_new_themes	  = (int) $row['priv_new_themes'];

		if(!empty($mf_user_id)){
			$_SESSION['mf_logged_in'] = true;
			$_SESSION['mf_user_id']	  = $mf_user_id;
			$_SESSION['mf_user_privileges']['priv_administer'] = $mf_priv_administer;
			$_SESSION['mf_user_privileges']['priv_new_forms']  = $mf_priv_new_forms;
			$_SESSION['mf_user_privileges']['priv_new_themes'] = $mf_priv_new_themes;

			$mf_just_reauthed_from_remember = true;
		}

	}

	if(empty($_SESSION['mf_logged_in'])){
		$current_dir = dirname($_SERVER['PHP_SELF']);
      	if($current_dir == "/" || $current_dir == "\\"){
			$current_dir = '';
		}
		
		if(!empty($is_ajax) && $is_ajax === true){
			//if this is an AJAX request, return JSON response with "session_expired" status, so the client side can handle it accordingly
			$expiry_title 	= "You have been signed out";
			$expiry_message = "For your security, your session has timed out. <br>Please sign in again to continue. <br><br><em>You'll be returned to this page after signing in.</em>";

			echo json_encode(['status' => 'session_expired', 'expiry_title' => $expiry_title, 'expiry_message' => $expiry_message]);
			exit;
		}else{
			//otherwise, if this is a normal page request, redirect to login page with the current URL as "from" parameter
			$_SESSION['MF_LOGIN_ERROR'] = 'Your session has expired. Please login.';
			
			header("Location: ".$current_dir.'/index.php?from='.base64_encode($_SERVER['REQUEST_URI']));
			exit;
		}
	}

	//ensure the CSRF token is always present for an authenticated user
	if(empty($_SESSION['mf_csrf_token'])){
		$posted_token = '';

        if(!empty($_POST['csrf_token']) && is_string($_POST['csrf_token'])){
            $posted_token = trim($_POST['csrf_token']);
        }

        //if data posted as JSON, try to get the token from the JSON body
        if($posted_token === ''){
            $content_type = $_SERVER['CONTENT_TYPE'] ?? '';
            if(stripos($content_type, 'application/json') !== false){
                $raw_body = file_get_contents('php://input');
                if(is_string($raw_body) && $raw_body !== ''){
                    $decoded = json_decode($raw_body, true);
                    if(is_array($decoded) && !empty($decoded['csrf_token']) && is_string($decoded['csrf_token'])){
                        $posted_token = trim($decoded['csrf_token']);
                    }
                }
            }
        }

		//preserver the CSRF token if the user just re-authenticated from "remember me" cookie, and the posted token is in the correct format and length (40-80 chars)
        if($mf_just_reauthed_from_remember && preg_match('/^[a-f0-9]{40,80}$/', $posted_token) === 1){
            $_SESSION['mf_csrf_token'] = $posted_token;
        }else{
            $_SESSION['mf_csrf_token'] = bin2hex(random_bytes(24));
        }
	}
