<?php

function readJSON($path)
{
   if (!file_exists($path) || filesize($path) <= 0) {
      return null;
   }
   $jsonFile = fopen($path, 'r');
   $jsonStr = fread($jsonFile, filesize($path));
   fclose($jsonFile);
   return json_decode($jsonStr, true);
}

function writeJSON($path, $jsonArray)
{
   $jsonStr = json_encode($jsonArray);
   $jsonFile = fopen($path, 'w') or die("can't create file: " . $path);
   fwrite($jsonFile, $jsonStr);
   fclose($jsonFile);
}

function getConfig()
{
   @session_start();
   if (!isset($_SESSION['config'])) {
      return getConfigNoCache();
   }
   if (!isset($_SESSION['instancePath']) || $_SESSION['instancePath'] != __FILE__) {
      return getConfigNoCache();
   }
   return $_SESSION['config'];
}

function getConfigNoCache()
{
   @session_start();
   $_SESSION['instancePath'] = __FILE__;
   $_SESSION['config'] = readJSON(dirname(__FILE__) . "/config.json");
   return $_SESSION['config'];
}

function writeConfig($config)
{
   @session_start();
   $_SESSION['config'] = $config;
   writeJSON(dirname(__FILE__) . "/config.json", $config);
}

function authenticated($username, $password)
{
   if (!isset($username) || !isset($password)) return false;
   $config = getConfig();
   if ($config['usercode'] == "" && $config['passcode'] == "") {
      return true;  // open access for new installations
   }
   return (crypt($username, 'raspberry') == $config['usercode'] && crypt($password, 'raspberry') == $config['passcode']);
}

function authenticate()
{
   if (!isset($_SERVER['PHP_AUTH_USER']) ||
       !authenticated($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
      header('WWW-Authenticate: Basic realm="gallery login"');
      header('HTTP/1.0 401 Unauthorized');
      echo 'Gallery login failed';
      exit;
   }
}

function rmAllDir($path)
{
  @array_map('unlink',glob($path . '/*'));
  @rmdir($path);
}

?>
