<?php
// AuthPro.com integration script v1.2
// Maintains .htaccess protection on local directory
// (c) 2021 AuthPro.com


// CONFIG

$account='Your AuthPro account username';
$api_key='Your AuthPro account API key';

$folder_name='Members area';
$folder_path[0]='/home/website/www/members/'; // Primary path, must be defined
$folder_path[1]=''; // specify additional folders if needed

$force_htaccess=true; // force creting .htaccess file if it does not exists
$sync_htpasswd=false; // set to true to check primary htpasswd file for updates and sync them with AuthPro account members

// END OF CONFIG


$folder_cnt=count($folder_path);

if ($account=='') { echo "Please specify your Authpro account username"; exit; }
if ($api_key=='') { echo "Please specify your Authpro account API key"; exit; }
if ($folder_path[0]=='') { echo "Please specify local folder path. We are here: ".getcwd(); exit; }
if (! file_exists ($folder_path[0]) ) { echo "Invalid primary folder path - ".$folder_path[0]; exit; }
if (! is_writable ($folder_path[0]) ) { echo "Primary folder path must be writable - ".$folder_path[0]; exit; }


for ($i = 0; $i < $folder_cnt; $i++) {
  if ($folder_path[$i] == '') { continue; }
  if (! file_exists ($folder_path[$i]) ) { echo "Invalid local folder path - ".$folder_path[$i]; exit; }
  if ($force_htaccess) {
    if (! is_writable ($folder_path[$i]) ) { echo "Local folder path must be writable - ".$folder_path[$i]; exit; }
    if (! file_exists ( $folder_path[$i].'.htaccess' ) ) {
      $htafile = fopen($folder_path[$i].'.htaccess', "w") or die("Unable to create .htaccess file!");
      fwrite($htafile, "AuthUserFile $folder_path[0].htpasswd\n");
      fwrite($htafile, "AuthGroupFile /dev/null\n");
      fwrite($htafile, "AuthName $folder_name\n");
      fwrite($htafile, "AuthType Basic\n");
      fwrite($htafile, "<Limit GET>\n");
      fwrite($htafile, "require valid-user\n");
      fwrite($htafile, "</Limit>\n");
      fclose($htafile);
    }
  }
}

// cache requests for 10 sec
$fkl=''; $fks=10; $fkr=''; if (isset($_GET['force_key'])) { $fkr=$_GET['force_key']; }
if ( (file_exists($folder_path[0].'.htpasswd')) && (time()-filemtime($folder_path[0].'.htpasswd')<$fks) && (($fkl=='') || ($fkl!=$fkr)) ) { echo '// OK, cached'; exit; }

$authpro_api_url='https://www.authpro.com/cgi-bin/auth.fcgi';

$authpro_api_data=array (
        'mode' => 'API',
        'action' => 'list',
        'user' => $account,
        'api_key' => $api_key,
        'record' => '{login}:{encpass}',
        'status' => 'A'
);

$members = file_get_contents($authpro_api_url, false, stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => http_build_query($authpro_api_data)
            )
            )));


if ( ($sync_htpasswd) && (file_exists ( $folder_path[0].'.htpasswd' ) ) ) {

  $apm = explode("\n", $members);
  foreach ($apm as $apmr) {
    if ($apmr == '') { continue; }
    list($apmu, $apmp) = explode(":",$apmr,2);
    $apmp=trim($apmp);
    $apma[$apmu] = $apmp;
  }

  $htph = fopen($folder_path[0].'.htpasswd', "r");
  while (!feof($htph)) {
    $htps = trim(fgets($htph));
    if ($htps == '') { continue; }
    list($mu, $mp) = explode(":",$htps,2);
    if ($mu == '') { continue; }
    //$htpm[$mu] = $mp;
    if (! isset($apma[$mu])) {
      // Add member to AuthPro account
      $authpro_api_data=array (
        'mode' => 'API',
        'action' => 'create',
        'user' => $account,
        'api_key' => $api_key,
        '_login' => $mu,
        '_password' => "#HASH\{$mp\}"
      );
      $res = file_get_contents($authpro_api_url, false, stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => http_build_query($authpro_api_data)
            )
            )));
      echo "// Adding $mu: $res\n";
      $members.="$mu:$mp\n";
    } 
  }
  fclose($htph);

}


$htpfile = fopen($folder_path[0].'.htpasswd', "w") or die("Unable to create .htpasswd file!");
fwrite($htpfile, $members);
fclose($htpfile);

echo '// OK, updated';

?>