<?php
require_once(__DIR__."/../apl_config.php");
require_once(__DIR__."/../apl_ver.php");
require_once(__DIR__."/../apl_settings.php");


if (isset($_SERVER['REMOTE_ADDR'])) {$ip_address=$_SERVER['REMOTE_ADDR'];}
if (isset($_SERVER['HTTP_REFERER'])) {$refer=$_SERVER['HTTP_REFERER'];}
if (isset($_SERVER['REQUEST_URI'])) {$requested_page=$_SERVER['REQUEST_URI'];}
if (isset($_SERVER['SCRIPT_FILENAME'])) {$script_filename=basename($_SERVER['SCRIPT_FILENAME']);}
if (isset($_SERVER['HTTP_USER_AGENT'])) {$user_agent=$_SERVER['HTTP_USER_AGENT'];}


$action_success=0; //will be changed to 1 later only if everything OK
$error_detected=0; //will be changed to 1 later if error occurs
$error_details=null; //will be filled with errors (if any)
$added_records=0;
$updated_records=0;
$removed_records=0;


$api_action_success=0;
$api_error_detected=0;
$api_error_details=null;
$logged_admin_id=null; //used for compatibility with createReport function in the same file in /apl_admin directory. since admin is not logged in when API is called, $logged_admin_id must be null


if (!empty($_POST) && is_array($_POST) && array_walk($_POST, "sanitizeSubmittedData", array("script_filename"=>$script_filename, "html_fields"=>$FORM_FIELDS_WITH_TAGS))) //sanitize super variable with all POST values
    {
    extract($_POST, EXTR_SKIP); //extract sanitized data (don't overwrite existing variables)
    }


if (!empty($api_key_secret) && !empty($api_function) && $api_post_key==hash("sha256", $ROOT_URL) && $submit_ok=="Submit" && $refer=="$ROOT_URL/apl_api/api.php" && in_array($user_agent, $SUPPORTED_BROWSERS_ARRAY)) //prevent someone from posting to this file directly
    {
    if ($API_STATUS==1 && in_array($api_function, $SUPPORTED_API_FUNCTIONS_ARRAY))
        {
        $api_key_rows_array=fetchRow("SELECT * FROM apl_api_keys WHERE api_key_secret=? AND api_key_status=?", array($api_key_secret, 1), array("s", "i"));
        if (empty($api_key_rows_array))
            {
            $api_error_detected=1;
            $api_error_details.="Invalid or inactive API key.<br>";
            }
        else
            {
            foreach ($api_key_rows_array as $api_key_row)
                {
                extract($api_key_row);
                }

            if (!empty($api_key_ip))
                {
                $api_key_ip_array=explode(",", $api_key_ip);
                if (!in_array($ip_address, $api_key_ip_array))
                    {
                    $api_error_detected=1;
                    $api_error_details.="Invalid IP address.<br>";
                    }
                }

            $api_permissions_name="api_key_".$api_function; //since each permission in database starts with api_key_ prefix, add this prefix to name of function submitted by user for quick permissions check
            if ($$api_permissions_name!=1)
                {
                $api_error_detected=1;
                $api_error_details.="Invalid API key permissions.<br>";
                }

            if ($api_error_detected!=1 && $$api_permissions_name==1)
                {
                $api_action_success=1;
                }
            }
        }
    else
        {
        $api_error_detected=1;
        $api_error_details.="API not enabled or invalid API function.<br>";
        }

    if ($api_action_success==1) //everything OK
        {
        $optional_api_parameters_array=array("banned_host_comments"); //optional API parameters for this page
        foreach ($optional_api_parameters_array as $optional_api_parameter) //in case some required parameter was not submitted, set its value to null to prevent "undefined variable" errors
            {
            if (!isset($$optional_api_parameter))
                {
                $$optional_api_parameter=null;
                }
            }

        if (isset($submit_ok)) //code between {} tags is identical in files with the same name in /apl_admin and /apl_api directories
            {
            if (filter_var($banned_host_ip, FILTER_VALIDATE_IP))
                {
                if ($error_detected!=1)
                    {
                    $banned_host_date=date("Y-m-d");

                    $added_records=insertRow("INSERT IGNORE INTO apl_banned_hosts (banned_host_ip, banned_host_comments, banned_host_date) VALUES (?, ?, ?)", array($banned_host_ip, $banned_host_comments, $banned_host_date), array("s", "s", "s"));
                    if ($added_records<1)
                        {
                        $error_detected=1;
                        $error_details.="Invalid record details or duplicated record (no new data).<br>";
                        }
                    else
                        {
                        $action_success=1;
                        }
                    }
                }
            else
                {
                $error_detected=1;
                $error_details.="Invalid IP address.<br>";
                }

            if ($action_success==1) //everything OK
                {
                $page_message="Banned host $banned_host_ip added to the database.";
                createReport(strip_tags($page_message), $logged_admin_id, 1, $error_detected);
                $page_message_class="alert alert-success";
                }
            else //display error message
                {
                $page_message="The database could not be updated because of this error: <br><br>$error_details";
                $page_message_class="alert alert-danger";
                }
            }
        }
    else //display error message
        {
        $page_message="The action could not be completed because of this error:<br><br>$api_error_details";
        }


    echo $page_message;
    }