<?php
/*
  FC, 20170825, issu et débogué de :
  https://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php?rq=1
  http://www.supportduweb.com/scripts_tutoriaux-code-source-65-php-compteur-de-visites-scripts-php.html
  https://www.developpez.net/forums/d255221/php/langage/fonctions/tableaux-compter-nombre-telechargement-d-logiciel/
*/

$www = '/srv/www/data/';  // www-data doit y avoir accès rw.
$dl = $www . 'aecf-downloads-1.0.txt';
$site = 'https://specfun.inria.fr/chyzak/aecf-distrib/pdf/';
$aecf = 'aecf-screen-1.0.pdf';

/*
  Voici d'abord la fonction de comptage/loggage, qui trouve une bonne
  approximation de l'url du demandeur (fonctions juste dessous).
 */
function log_download($f) {
  $ha = fopen($f, 'a');
  fputs($ha, date(DateTime::W3C) . ' ' . get_ip_address() . "\n");
  fclose($ha);
}

function get_ip_address() {
  // Check for shared internet/ISP IP
  if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP']))
    return $_SERVER['HTTP_CLIENT_IP'];

  // Check for IPs passing through proxies
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    // Check if multiple IP addresses exist in var
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    foreach ($iplist as $ip) {
      if (validate_ip($ip))
        return $ip;
    }
  }

  if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
   return $_SERVER['HTTP_X_FORWARDED'];
  if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
   return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
  if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
   return $_SERVER['HTTP_FORWARDED_FOR'];
  if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
   return $_SERVER['HTTP_FORWARDED'];

  // Return unreliable IP address since all else failed
  return $_SERVER['REMOTE_ADDR'];
}

 /**
  * Ensures an IP address is both a valid IP address and does not fall within
  * a private network range.
  *
  * @param string $ip
  */
function validate_ip($ip) {
  if (filter_var($ip, FILTER_VALIDATE_IP,
                      FILTER_FLAG_IPV4 |
                      FILTER_FLAG_IPV6 |
                      FILTER_FLAG_NO_PRIV_RANGE |
                      FILTER_FLAG_NO_RES_RANGE) === false)
    return false;
  return true;
}

// Mieux que application/octet-stream.
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $aecf . '"');
readfile($site . $aecf);
log_download($dl);
?>