<?php
/*
Plugin Name: Multisite Access debug
Plugin URI: http://therooftop.io
Description: Only activate in times of need. This plugin diagnoses ddos attacks
Version: 1.0.0
Author: Roi Ezra
*/


class Multisite_Access_Debug{

    public function __construct()
    {

        add_action( 'init', array($this, 'log_visitors') );

        /*
         CREATE TABLE `blog_access_debug` (
              `id` int(11) NOT NULL,
              `url` varchar(1000) NOT NULL,
              `uri` varchar(1000) DEFAULT NULL,
              `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
              `ip` varchar(50) NOT NULL,
              `blog_id` int(11) NOT NULL,
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
         */

    }

    public function log_visitors(){
        global $wp;
        global $wpdb;

        $customdb = new wpdb('efexorg_trafficreports01','nF!!i6{f9$yO','efexorg_trafficreports01','localhost');

        //$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
        $uri = $_SERVER['REQUEST_URI'];
        $table = 'blog_access_debug';

        if ( !is_user_logged_in() && !is_admin()) {

            $data = array(
                'url' => $actual_link,
                'uri' => $uri,
                'ip' => $this->get_ip_address(),
                'blog_id' => get_current_blog_id()); //'headers' => json_encode(getallheaders()

            $format = array('%s','%s','%s','%d');

            $customdb->insert($table,$data,$format);
            //$my_id = $customdb->insert_id;
        }
    }

    function get_ip_address() {
        $ip_keys = array('HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED');
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) return false;
                    return $ip;
                }
            }
        }
        return '0';
    }
}

new Multisite_Access_Debug();