<?php

/*
 *  Stockpile-O-Mat is a PHP Script to deal with foodcollections for
 *  emergency preparedness.
 *
 *  Copyright (c) 2009, Karsten Kruse tecneeq@tecneeq.de
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following  disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

$debug "false"// Set to true to turn on debugging
$my_version "\$Id$"// CVS-ID
$people_added "none";
$cookielifetime time() + (86400 365 10);

if (
$debug == "true") {
  
error_reporting(E_ALL E_STRICT);
}

// If someone wants to see the source.
if (isset($_GET['show_source'])) { die(highlight_file(__FILE__1)); }

// Start session in any case
session_name("Stockpile-O-Mat-Session");
session_start();

// In case the session should be deleted on user request.
if (isset($HTTP_POST_VARS["delete_session"])) {
  
session_unset();
  
session_destroy();
  
setcookie('Stockpile-O-Mat-Session''delete'time()-42000); // Why doesn't this work?
  
setcookie('Stockpile-O-Mat-Username','delete',time()-42000);
  
setcookie('Stockpile-O-Mat-Stockpile''delete'time()-42000);
  
setcookie('Stockpile-O-Mat-Persons''delete'time()-42000);
  
$_SESSION = array();
} else { 
// Begin Session

  // Sometimes the server will remove the session if session vars aren't changed all the time,
  // so let's change a session variable.
  
if ( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 ) {
    
$_SESSION['last_access'] = time();
  }

  require 
"product_db.php"// Product database
  
require "demands_db.php"// Nutritional demands database

  // Set up username
  
if ((!isset($_SESSION['username'])) || (empty($_SESSION['username']))) { // username not in session or empty
    
if (isset($_COOKIE['Stockpile-O-Mat-Username'])) { // username not in session, but maybe in a cookie?
      
$_SESSION['username'] = $_COOKIE['Stockpile-O-Mat-Username'];
    } else { 
// username first setup
      
$_SESSION['username'] = "";
    }
  }
  if (isset(
$HTTP_POST_VARS["username"])) { // we have a new user ...
    
if (!empty($HTTP_POST_VARS["username"])) { // ... and name is not empty!
      
$_SESSION['username'] = $HTTP_POST_VARS["username"];
    } else { 
// ... but his name is empty
      
$_SESSION['username'] = "";
    }
  }
  
setcookie('Stockpile-O-Mat-Username',$_SESSION['username'],$cookielifetime);

  
// Set up stockpile and recalculate if needed.
  // Format: "product_id1|amount1 product_id2|amount2"
  // Example: $_SESSION['stockpile'] = "23|4 36|0.5 13|4 37|2 9|12 40|0.9 27|5 22|0.9 24|4"
  
if (!isset($_SESSION['stockpile'])) { // stockpile not in session
    
if (isset($_COOKIE['Stockpile-O-Mat-Stockpile'])) { // or in a cookie?
      
$_SESSION['stockpile'] = $_COOKIE['Stockpile-O-Mat-Stockpile'];
    } else { 
// stockpile first setup
      
$_SESSION['stockpile'] = "";
    }
  }
  if (isset(
$HTTP_POST_VARS["adjust_stockpile"])) { // recalculation is needed
    
if (empty($HTTP_POST_VARS["weight"])) {
      echo 
"Horrific error: Need amount in Kilo to add/remove food. <a href=\"{$_SERVER["SCRIPT_NAME"]}\">Go Back</a>."; exit();
    } else {
      
$stockpile_item explode(" "$_SESSION['stockpile']);
      
array_multisort($stockpile_itemSORT_NUMERIC);
      if (
$HTTP_POST_VARS['submit'] == "Add to list") { // add to list
        
$product_added"no";
        foreach (
$stockpile_item as $value) { // go through stockpile
          
list($current_id$current_weight) = explode("|"$value);
          if ((
is_numeric($current_id)) && (is_numeric($current_weight))) {
            if (
$HTTP_POST_VARS['product_id'] == $current_id) {
              
$current_weight $current_weight $HTTP_POST_VARS["weight"];
              
$product_added "ok";
            }
            if (empty(
$new_stockpile)) {
              
$new_stockpile "$current_id|$current_weight";
            } else {
              
$new_stockpile "$new_stockpile $current_id|$current_weight";
            }
          }
        }
        if (
$product_added != "ok") { // product not yet added!
          
if (empty($new_stockpile)) {
            
$new_stockpile "{$HTTP_POST_VARS["product_id"]}|{$HTTP_POST_VARS["weight"]}";
          } else {
            
$new_stockpile "$new_stockpile {$HTTP_POST_VARS["product_id"]}|{$HTTP_POST_VARS["weight"]}";
          }
        }
      } else { 
// Remove from list
        
foreach ($stockpile_item as $value) { // go through stockpile
          
list($current_id$current_weight) = explode("|"$value);
          if ((
is_numeric($current_id)) && (is_numeric($current_weight))) {
            if (
$HTTP_POST_VARS['product_id'] == $current_id) {
              
$current_weight $current_weight $HTTP_POST_VARS["weight"];
            }
            if ( 
$current_weight) { // only if the new weight would be a positive number
              
if (empty($new_stockpile)) {
                
$new_stockpile "$current_id|$current_weight";
              } else {
                
$new_stockpile "$new_stockpile $current_id|$current_weight";
              }
            }
          }
        }
      }
    }
    
$_SESSION['stockpile'] = $new_stockpile;
  }
  
setcookie('Stockpile-O-Mat-Stockpile',$_SESSION['stockpile'],$cookielifetime);


/*
  // Set up private products and recalculate if needed.
  // Format: "product_id1|product_name1|protein1|carbs1|fat1 product_id2|product_name2|protein2|carbs2|fat2"
  // product_id had to be bigger than 1000, 1 to 999 are reserved for the standard food database
  // Example: $_SESSION['products'] = "1001|Pork, canned|26|1|22 1002|Beef, canned|27|1|18"
  if (!isset($_SESSION['myproducts'])) { // private not in session
    if (isset($_COOKIE['Stockpile-O-Mat-Myproducts'])) { // or in a cookie?
      $_SESSION['myproducts'] = $_COOKIE['Stockpile-O-Mat-Myproducts'];
    } else { // myproducts first setup
      $_SESSION['myproducts'] = "";
    }
  }
  if (isset($HTTP_POST_VARS["adjust_myproducts"])) { // recalculation is needed
    if (empty($HTTP_POST_VARS["protein"])) {
      echo "Horrific error: Need percentage of protein to add/remove food. <a href=\"{$_SERVER["SCRIPT_NAME"]}\">Go Back</a>."; exit();
    } elseif (empty($HTTP_POST_VARS["carbs"])) {
      echo "Horrific error: Need percentage of carbohydrates to add/remove food. <a href=\"{$_SERVER["SCRIPT_NAME"]}\">Go Back</a>."; exit();
    } elseif (empty($HTTP_POST_VARS["fat"])) {
      echo "Horrific error: Need percentage of fat to add/remove food. <a href=\"{$_SERVER["SCRIPT_NAME"]}\">Go Back</a>."; exit();
    } elseif (empty($HTTP_POST_VARS["name"])) {
      echo "Horrific error: Need descriptive name to add/remove food. <a href=\"{$_SERVER["SCRIPT_NAME"]}\">Go Back</a>."; exit();
    } else {
      $myproducts_item = explode(" ", $_SESSION['myproducts']);
      array_multisort($myproducts_item, SORT_NUMERIC);
      if ($HTTP_POST_VARS['submit'] == "Add to list") { // add to list

        $myproducts_added= "no";
        foreach ($myproducts_item as $value) { // go through myproducts
          list($current_id, $current_protein, $current_carbs, $current_fat) = explode("|", $value);
          if ((is_numeric($current_id)) && (is_numeric($current_weight))) {
            if ($HTTP_POST_VARS['product_id'] == $current_id) {
              $current_weight = $current_weight + $HTTP_POST_VARS["weight"];
              $product_added = "ok";
            }
            if (empty($new_stockpile)) {
              $new_stockpile = "$current_id|$current_weight";
            } else {
              $new_stockpile = "$new_stockpile $current_id|$current_weight";
            }
          }
        }
        if ($product_added != "ok") { // product not yet added!
          if (empty($new_stockpile)) {
            $new_stockpile = "{$HTTP_POST_VARS["product_id"]}|{$HTTP_POST_VARS["weight"]}";
          } else {
            $new_stockpile = "$new_stockpile {$HTTP_POST_VARS["product_id"]}|{$HTTP_POST_VARS["weight"]}";
          }
        }


      } else { // Remove from list
        foreach ($stockpile_item as $value) { // go through stockpile
          list($current_id, $current_weight) = explode("|", $value);
          if ((is_numeric($current_id)) && (is_numeric($current_weight))) {
            if ($HTTP_POST_VARS['product_id'] == $current_id) {
              $current_weight = $current_weight - $HTTP_POST_VARS["weight"];
            }
            if ( 0 < $current_weight) { // only if the new weight would be a positive number
              if (empty($new_stockpile)) {
                $new_stockpile = "$current_id|$current_weight";
              } else {
                $new_stockpile = "$new_stockpile $current_id|$current_weight";
              }
            }
          }
        }
      }
    }
    $_SESSION['produtcs'] = $new_products;
  }
  setcookie('Stockpile-O-Mat-Stockpile',$_SESSION['stockpile'],$cookielifetime);
*/

  // Set up persons and recalculate if needed.
  // Format: "person_id1|amount1 person_id2|amount2"
  // Example: $persons = "1|1 2|1 4|1 5|1 6|2"
  
if (!isset($_SESSION['persons'])) { // persons not in session
    
if (isset($_COOKIE['Stockpile-O-Mat-Persons'])) { // or in a cookie?
      
$_SESSION['persons'] = $_COOKIE['Stockpile-O-Mat-Persons'];
    } else { 
// persons first setup
      
$_SESSION['persons'] = "";
    }
  }
  if (isset(
$HTTP_POST_VARS["adjust_persons"])) { // recalculation is needed
    
$persons_item explode(" "$_SESSION['persons']);
    
array_multisort($persons_itemSORT_NUMERIC);
    if (
$HTTP_POST_VARS['submit'] == "Add person to list") { // add  person to list
      
foreach ($persons_item as $value) { // go through persons
        
list($current_id$current_number) = explode("|"$value);
        if ((
is_numeric($current_id)) && (is_numeric($current_number))) {
          if (
$HTTP_POST_VARS['person_id'] == $current_id) {
            
$current_number $current_number 1;
            
$people_added "ok";
          }
          if (empty(
$new_persons)) {
            
$new_persons "$current_id|$current_number";
          } else {
            
$new_persons "$new_persons $current_id|$current_number";
          }
        }
      }
      if (
$people_added != "ok") { // people not yet added!
        
if (empty($new_persons)) {
          
$new_persons "{$HTTP_POST_VARS['person_id']}|1";
        } else {
          
$new_persons "$new_persons {$HTTP_POST_VARS['person_id']}|1";
        }
      }
    } else { 
// Remove from list
      
foreach ($persons_item as $value) { // go through persons
        
list($current_id$current_number) = explode("|"$value);
        if ((
is_numeric($current_id)) && (is_numeric($current_number))) {
          if (
$HTTP_POST_VARS['person_id'] == $current_id) {
            
$current_number $current_number 1;
          }
          if ( 
$current_number) { // only if the new number would be a positive number
            
if (empty($new_persons)) {
              
$new_persons "$current_id|$current_number";
            } else {
              
$new_persons "$new_persons $current_id|$current_number";
            }
          }
        }
      }
    }
    
$_SESSION['persons'] = $new_persons;
  }
  
setcookie('Stockpile-O-Mat-Persons',$_SESSION['persons'],$cookielifetime);

  
// Calculate how much nutrition we need per day, based on the list of persons
  
if (!empty($_SESSION['persons'])) {
    
$daily_needed_carbs 0;
    
$daily_needed_protein 0;
    
$daily_needed_fat 0;
    
$daily_needed_water 0;
    
$persons_item explode(" "$_SESSION['persons']);
    foreach (
$persons_item as $value) { // go through persons
      
list($current_id$current_number) = explode("|"$value);
      
$daily_needed_carbs $daily_needed_carbs + ($demands["$current_id"]["carbs"] * $current_number);
      
$daily_needed_protein $daily_needed_protein + ($demands["$current_id"]["protein"] * $current_number);
      
$daily_needed_fat $daily_needed_fat + ($demands["$current_id"]["fat"] * $current_number);
      
$daily_needed_water $daily_needed_water + ($demands["$current_id"]["water"] * $current_number);
    }
  }

// End Begin Session Area

if ($debug == "true") {
  echo 
"<pre>  \$HTTP_POST_VARS "print_r($HTTP_POST_VARS), "\n
  \$_SESSION "
print_r($_SESSION), "\n
  \$_COOKIE "
print_r($_COOKIE), "</pre>\n";
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

  <head>
    <title>The awesome Stockpile-O-Mat!</title>
    <meta name="author" content="Karsten Kruse">
    <meta name="description" content="A emergency preparedness planner where you say what food you have and how many persons depend on it, and the site says how long it lasts.">
    <meta name="keywords" lang="en" content="Emergency, preparedness, foodplanner, food, survival, nutrition">
    <meta name="keywords" lang="de" content="Notfall, Vorbereitung, Ernährungsplaner, Ernährung, Survial, Nährwerte">
    <meta name="robots" content="index">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
<!--
/* Stylesheet common to screen, handheld and print */
  body { color:black; background-color:white; }
  body,h1,h2,h3,h4,p,ul,ol,li,dl,dt,dd,div,td,th,address,blockquote { font-family:Arial,sans-serif; }
  h1 { font-size:26px; margin-bottom:18px; }
  h1.ph1 { font-size:21px; margin-bottom:18px; }
  h2 { font-size:21px; margin-bottom:18px; }
  h3 { font-size:16px; }
  h4 { font-size:13.4px; }
  p,ul,ol,li,dl,dt,dd,div,td,th,address,blockquote { font-size:13.4px; }
  li,dt { margin-top:3px; }
  pre { font-family:"Courier New",Courier,monospace; font-size:13.4px; color:#0000C0; background-color:#FFFFE0; border:10px solid #EEEEEE; padding:10px; white-space:pre; }
  td pre { border-style:none; padding:0; }
  code,kbd,tt { font-family:"Courier New",Courier,monospace; color:#0000C0; }
  var { font-style:normal; color:#0000C0; }
  blockquote,cite { font-style:italic; }
  a:link { color:#AA5522; font-weight:bold; text-decoration:underline; }
  a:visited { color:#772200; font-weight:bold; text-decoration:underline; }
  a:active { color:#000000; font-weight:bold; text-decoration:none; }

@media screen {

}
@media handheld {

}
@media print {

}
-->
    </style>
  </head>

  <body bgcolor="white">

    <h1>The awesome Stockpile-O-Mat!</h1>

    <p>This program should help you gain new insights into the pile of food that you have accumulated.
    How much people can live off it for how long? How well did you balance nutritional values? What's
    missing? The nutritional analysis is based on the number of people you have, what their
    nutritional demands are and what you actually have in your pantry. The results are estimates, but
    they should be close enough to reality. Finally, this program tells you how much drinking water you
    should store and gives some general hints about food storage.</p>

<?php

if ((!isset($_SESSION['username'])) || (empty($_SESSION['username']))) { // We have no session

?>
    <form name="create_session" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
    <p>Hello guest, you have not yet created a Stockpile-O-Mat Username Cookie on your Computer. Please
    do so by typing a name that you like.<br><br>
    <input name="username" type="text" size="10" maxlength="10"><input type="submit" value="Send Username"></p>
    </form>

    <br><br>

    <p align="center">Copyright 2009 <a href="mailto:tecneeq@tecneeq.de">Karsten Kruse</a> |
    BSD Licensed Sourcecode:
    <a target="_blank" href="<?php echo $_SERVER["SCRIPT_NAME"]; ?>?show_source">Application</a> |
    <a target="_blank" href="product_db.php?show_source">Nutrition DB</a> |
    <a target="_blank" href="demands_db.php?show_source">People DB</a></p>

<?php

  
die();
// End we have no session

?>
    <form name="delete_session" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
    <input type="hidden" name="delete_session" value="true">
    <p>Hello <b><?php echo $_SESSION['username']; ?></b>! Click here to delete the Stockpile-O-Mat Cookie from your Computer. <input type="submit" value="Delete Session"></p>
    </form>

    <table cellspacing="0" cellpadding="3" border="1">
      <tbody>
<?php

if ( empty($_SESSION['stockpile']) ) {

?>
        <tr>
          <td colspan="8"><font size="+1" color="red">Your stockpile is empty! You'll have to starve! Add products!</font></td>
        </tr>
<?php

} else { // $_SESSION['stockpile'] not empty

?>
        <tr>
          <td bgcolor="#6699cc">Product</td>
          <td bgcolor="#6699cc">Amount</td>
          <td bgcolor="#6699cc">Calorific&nbsp;Value</td>
          <td bgcolor="#6699cc">Carbohydrates</td>
          <td bgcolor="#6699cc">Protein</td>
          <td bgcolor="#6699cc">Fat</td>
          <td bgcolor="#6699cc">Fiber</td>
          <td bgcolor="#6699cc">Sodium</td>
        </tr>
<?php

  
// initialize some vars used for nutritional analysis
  
$product_sum 0;
  
$protein_sum 0;
  
$carbs_sum 0;
  
$fat_sum 0;
  
$kjoule_sum 0;

  
$stockpile_item explode(" "$_SESSION['stockpile']);
  
array_multisort($stockpile_itemSORT_NUMERIC);
  
$counter 1;
  while ( 
$counter <= count($stockpile_item) ) { // go through each stockpile item
    
$key = ($counter 1);
    if (
is_float($key/2)) { //determine background color of the row
      
$rowcolor "#ffffff" ;
    } else {
      
$rowcolor "#ffffcc" ;
    }
    list(
$product_id$product_amount) = explode("|"$stockpile_item[$key]);

    
// shorten the variables so that it all becomes more manageable in the output
    // also calculate overall sums for the nutritional analysys
    
$product_sum $product_sum $product_amount;
    
$product $products[$product_id]["product"];
    
$product_de $products[$product_id]["product_de"];
    
$details $products[$product_id]["details"];
    
$details_de $products[$product_id]["details_de"];
    
$protein $products[$product_id]["protein"];
    
$protein_overall $products[$product_id]["protein"] * $product_amount 100;
    
$protein_sum round($protein_sum $protein_overall,3);
    
$carbs $products[$product_id]["carbs"];
    
$carbs_overall $products[$product_id]["carbs"] * $product_amount 100;
    
$carbs_sum round($carbs_sum $carbs_overall,3);
    
$sugar_in_carbs $products[$product_id]["sugar_in_carbs"];
    
$sugar_in_carbs_overall $products[$product_id]["sugar_in_carbs"] * $product_amount 100;
    
$fat $products[$product_id]["fat"];
    
$fat_overall $products[$product_id]["fat"] * $product_amount 100;
    
$fat_sum round($fat_sum $fat_overall,3);
    
$saturated_fatty_acids $products[$product_id]["saturated_fatty_acids"];
    
$saturated_fatty_acids_overall $products[$product_id]["saturated_fatty_acids"] * $product_amount 100;
    
$fiber $products[$product_id]["fiber"];
    
$fiber_overall $products[$product_id]["fiber"] * $product_amount 100;
    
$kjoule $products[$product_id]["kjoule"];
    
$kjoule_overall $products[$product_id]["kjoule"] * 10 $product_amount;
    
$kjoule_sum $kjoule_sum $kjoule_overall;
    
$sodium $products[$product_id]["sodium"];
    
$sodium_overall $products[$product_id]["sodium"] * $product_amount 100;

    
// Begin nutritional analysis
    
if (!empty($_SESSION['persons'])) {
      
$carbs_days floor($carbs_sum 1000 $daily_needed_carbs);
      
$protein_days floor($protein_sum 1000 $daily_needed_protein);
      
$fat_days floor($fat_sum 1000 $daily_needed_fat);
      
// here we try to give nutritional hints
      
$mindays min($carbs_days$protein_days$fat_days);
      
$maxdays max($carbs_days$protein_days$fat_days);
      if (
$maxdays == $carbs_days) {
        
$analysis "You have enough carbs, consider adding more";
        if (
$protein_days $fat_days) {
          
$analysis "$analysis fat and a tiny bit more protein to get more days out of your stockpile.";
        } else {
          
$analysis "$analysis protein and a tiny bit more fat to get more days out of your stockpile.";
        }
      } elseif (
$maxdays == $protein_days) {
        
$analysis "You have enough protein, consider adding more";
        if (
$carbs_days $fat_days) {
          
$analysis "$analysis fat and a tiny bit more carbs to get more days out of your stockpile.";
        } else {
          
$analysis "$analysis carbs and a tiny bit more fat to get more days out of your stockpile.";
        }
      } elseif (
$maxdays == $fat_days) {
        
$analysis "You have enough fat, consider adding more";
        if (
$protein_days $carbs_days) {
          
$analysis "$analysis carbs and a tiny bit more protein to get more days out of your stockpile.";
        } else {
          
$analysis "$analysis protein and a tiny bit more carbs to get more days out of your stockpile.";
        }
      }
    } else {
      
$carbs_days 0;
      
$protein_days 0;
      
$fat_days ;
    }
    
// End nutritional analysis

    // begin output stockpile table
    
echo "        <tr>
          <td bgcolor=\"
$rowcolor\">$product<br><small>$details</small></td>
          <td bgcolor=\"
$rowcolor\">$product_amount&nbsp;kg</td>
          <td bgcolor=\"
$rowcolor\">$kjoule&nbsp;kJ/100g<br>$kjoule_overall&nbsp;kJ</td>\n";
    if (
$products[$product_id]["sugar_in_carbs"] <= 1) {
      echo 
"          <td bgcolor=\"$rowcolor\">$carbs&nbsp;%<br>$carbs_overall&nbsp;kg</td>\n";
    } else {
      echo 
"          <td bgcolor=\"$rowcolor\">$carbs&nbsp;%&nbsp;<small>($sugar_in_carbs&nbsp;%&nbsp;in&nbsp;sugar)</small><br>$carbs_overall&nbsp;kg&nbsp;<small>($sugar_in_carbs_overall&nbsp;kg&nbsp;in&nbsp;sugar)</small></td>\n";
    }
    echo 
"          <td bgcolor=\"$rowcolor\">$protein&nbsp;%<br>$protein_overall&nbsp;kg</td>\n";
    if ( empty(
$saturated_fatty_acids) ) {
      echo 
"           <td bgcolor=\"$rowcolor\">$fat&nbsp;%<br>$fat_overall&nbsp;kg</td>\n";
    } else {
      echo 
"          <td bgcolor=\"$rowcolor\">$fat&nbsp;%&nbsp;<small>($saturated_fatty_acids&nbsp;%&nbsp;sat.&nbsp;fatty&nbsp;acids)</small><br>$fat_overall&nbsp;kg&nbsp;<small>($saturated_fatty_acids_overall&nbsp;kg&nbsp;sat.&nbsp;fatty&nbsp;acids)</small></td>\n";
    }
    if ( empty(
$fiber) ) {
      echo 
"          <td bgcolor=\"$rowcolor\">&nbsp</td>\n";
    } else {
      echo 
"          <td bgcolor=\"$rowcolor\">$fiber&nbsp;%<br>$fiber_overall&nbsp;kg</td>\n";
    }
    if ( empty(
$sodium) ) {
      echo 
"          <td bgcolor=\"$rowcolor\">&nbsp</td>\n";
    } else {
      echo 
"          <td bgcolor=\"$rowcolor\">$sodium&nbsp;%<br>$sodium_overall&nbsp;kg</td>\n";
    }
    echo 
"        </tr>\n";
    
$counter++;
  } 
// End while loop
  
echo "        <tr>
          <td bgcolor=\"#cccccc\">&nbsp;</td>
          <td bgcolor=\"#cccccc\">
$product_sum&nbsp;kg&nbsp;overall</td>
          <td bgcolor=\"#cccccc\">
$kjoule_sum&nbsp;kJ&nbsp;overall</td>
          <td bgcolor=\"#cccccc\">
$carbs_sum&nbsp;kg&nbsp;overall<br><small>(About&nbsp;$carbs_days&nbsp;days)</small></td>
          <td bgcolor=\"#cccccc\">
$protein_sum&nbsp;kg&nbsp;overall<br><small>(About&nbsp;$protein_days&nbsp;days)</small></td>
          <td bgcolor=\"#cccccc\">
$fat_sum&nbsp;kg&nbsp;overall<br><small>(About&nbsp;$fat_days&nbsp;days)</small></td>
          <td bgcolor=\"#cccccc\" colspan=\"2\">&nbsp;</td>
        </tr>\n"
;
// end output stockpile table

?>
        <tr>
          <td colspan="8" bgcolor="#6699cc">Manage products in your Stockpile-O-Mat list<br><small>(Kilo is added or
          substracted from existing kilos. If you remove all kilos from a product, the product is removed. For
          simplicity, liter equals kilo, it's close enough.)</small><br><br>
          <form name="adjust_stockpile" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
          <input type="hidden" name="adjust_stockpile" value="true">
          <input name="weight" type=text size="4" maxlength="4"> kilo
          <select name=product_id>
<?php

  $product_id
=1;
  while ( 
is_array($products[$product_id]) ) {
    
$product $products[$product_id]["product"] ;
    
$details $products[$product_id]["details"] ;
    if ( empty(
$details) ) {
      echo 
"            <option value=\"$product_id\">$product</option>\n";
    } else {
      echo 
"            <option value=\"$product_id\">$product$details</option>\n";
    }
    
$product_id++;
  }
?>
          </select><input type="submit" name="submit" value="Add to list"><input type="submit" name="remove" value="Remove from list">
          </form>
          </td>
        </tr>
        <tr>
          <td colspan="8" bgcolor="#6699cc">Add or remove persons that depend on your stockpile.<br><small>(Quantity, age
          and gender are used to calculate the nutritional demands.)</small><br><br>
          <form name="adjust_persons" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
          <input type="hidden" name="adjust_persons" value="true">
          <select name=person_id>
<?php
  $counter 
0;
  while ( 
$counter++ != count($demands) ) { // go through each person item
    
echo "            <option value=\"$counter\">{$demands["$counter"]["type"]}</option>\n";
  }
?>
          </select>
          <input type="submit" name="submit" value="Add person to list"><input type="submit" name="submit" value="Remove person from list"><br>
          </form>
          </td>
        </tr>
        <tr>
          <td colspan="8">Number of people that depend on your food:<br><br>
<?php
  
if (empty($_SESSION['persons'])) {
    echo 
"<font size=\"+1\" color=\"red\">You need people in your calculations! Add a person!</font>";
  } else {
    
$persons_item explode(" "$_SESSION['persons']);
    
array_multisort($persons_itemSORT_NUMERIC);
    foreach (
$persons_item as $value) { // go through persons
      
list($current_id$current_number) = explode("|"$value);
      echo 
"          $current_number x {$demands["$current_id"]["type"]}<br>\n";
    }
    echo 
"<br>Your group needs $daily_needed_carbs g carbohydrates, $daily_needed_protein g protein, $daily_needed_fat g fat and $daily_needed_water g water each day.\n";
  }
?>
          </td>
        </tr>
      </tbody>
    </table>

    <h2><a name="analysis"></a>Analysis</h2>

    <p>The analysis is based on <a href="#nutrition">these</a> amounts and should be considered a rough
    estimate. On top of that, nutritional values change slightly because of food processing and raw food quality.
    Considering all that, i am confident enough to tell you this:</p>

<?php if (!empty($mindays)) { ?>
    <ul>
      <li>Based on your list of persons, your food should last about <?php echo $mindays?> days, if you try to balance
      macro nutrients like carbs, protein and fat.</li>
      <li><?php echo $analysis?></li>
      <li>To last <?php echo $mindays?> days you should also store about <?php echo round($mindays $daily_needed_water 1000,0); ?>
      liters of water in drinking quality. This can be reduced a bit if your pantry consists mainly of non dehydrated stuff, like
      canned soup/beans/applesauce and so on. It should be more if you live in a very hot area or expect to do hard work.</li>
      <li>Remember to store enough fuel to cook for at least <?php echo $mindays?> days. I use a camping propane cooker because it's
      clean and can be used inside your kitchen if you open a window.</li>
      <li>I would add good vitamine pills or similar products that also have trace elements like calcium, potassium, iron and such.</li>
      <li>Don't forget salt and spices.</li>
      <li>Think about paperplates so you don't have to waste precious drinking water for washing the dishes.</li>
    </ul>

<?php } else { ?>
    <p><b>I couldn't give you a result :(. There just isn't enough data. Add food. Add people.</b></p>
<?php ?>

    <br>

    <h2><a name="nutrition"></a>About Nutrition</h2>

    <p>Nutritional values used here:</p>

    <table cellspacing="0" cellpadding="3" border="1">
      <tbody>
        <tr>
          <td bgcolor="#cccccc">Person</td>
          <td bgcolor="#cccccc">Carbohydrates</td>
          <td bgcolor="#cccccc">Protein</td>
          <td bgcolor="#cccccc">Fat</td>
          <td bgcolor="#cccccc">Fiber</td>
          <td bgcolor="#cccccc">Sodium</td>
          <td bgcolor="#cccccc">Water</td>
        </tr>
<?php
  $counter 
0;
  while ( 
$counter++ != count($demands) ) { // go through each person item
    
if (is_float($counter/2)) { // determine background color of the row
      
$rowcolor "#ffffff" ;
    } else {
      
$rowcolor "#ffffcc" ;
    }
    echo 
"        <tr>
          <td bgcolor=\"#cccccc\">
{$demands["$counter"]["type"]}</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["carbs"]}&nbsp;g/d</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["protein"]}&nbsp;g/d</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["fat"]}&nbsp;g/d</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["fiber"]}&nbsp;g/d</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["sodium"]}&nbsp;g/d</td>
          <td bgcolor=\"
$rowcolor\">{$demands["$counter"]["water"]}&nbsp;g/d</td>
        </tr>\n"
;
  }
?>
      </tbody>
    </table>

    <h2><a name="why_storage"></a>Why food storage?</h2>

    <ul type="circle">
      <li>Q: There is plenty food at the supermarket, why should i store it at home? A: Because your supermarket is vulnerable. As a chain of delivery it is not immune to desaster or disorder or technical breakdown. In 2006 a unauthorised trucker strike left people with empty supermarkets after less than a week in Spain. What if due to massive rains you could not leave/enter town because you car can't swim? What if there was a snow front of epic proportions? What if there was icerain that kept you at home? Storms? Earthquakes? These emergencys, happen even in the most developed regions.</li>
      <li>Q: If there was some kind of food shortage, the government would surely bring me something to eat. Why should i bother? A: If you are snowed in during a storm and nobody can reach you, you are on your own and that's the reality of the situation. There are literally dozens of scenarios where the government simply needs time to install a new chain of delivery. In 2003, during the Oder floodings in germany, it took days to get fresh water to those that could not leave their houses. Some even had to wait a week. This is not out of some SciFi book, it happens in real life.</li>
      <li>Q: Food storage surely costs money? I have nothing to spare for costly MRE/EPA, freezedried stuff, emergency rations! A: You don't need to spend extra money, i promise. You don't need MRE (US military rations, three MRE=MealReadyToEat are enough for one day) either, in fact, i recommend against them. Unlike popular belief they are not ,,good for ages'' but loose nutritional value, texture and aroma like every other shelfstable foodstuff after some time. The same is true for EPA (German military rations, one EPA=EinmannPAckung is enough for one day) and emergency rations like BP5/Mayday bars and such. Besides, that stuff isn't exactly cheap and has little to do with ,,real'' food ;).</li>
    </ul>

    <h2><a name="howto_start"></a>How to get started.</h2>

    <p>To get your stockpile of foodstuffs started you just use this easy method. I will use canned tomatoes as an example. So, you plan to make pizza and need one can of canned tomatoes. Instead of one, you buy two cans. One can for consumption, one for storage. Next month you will make pizza again, you buy two cans again. This time you put both cans into storage and use the one month old from your storage. Next month it's pizza time again. You buy two cans, put both into storage and use one of the cans you bought last month for consumption. Next month you buy two cans, put them in storage and take the oldest can for consumption. You have 4 cans of tomatoes in storage.</p>

    <p>That's it. Nothing goes to waste, your stuff in storage stays fresh enough and you don't spend money you wouldn't have to spend anyways. In fact, you can look out for special prices on canned tomatoes. If you find them for less money you buy ten or twenty cans instead of two. You know they are good for three years storage according to the best before date. Since you use one each month, you could get 35 cans into storage, and never eat anything that is over the best before date.</p>

    <h2><a name="howto_storage"></a>How to store food properly.</h2>

    <p>To store food you have to consider five main factors:</p>

    <ol>
      <li>Light. Light destroys macro nutrients in foodstuffs over time. It quickly destroys vitamins. You want to store in the dark.</li>

      <li>Humidity. Humidity in the air can cause mildew and rusty cans, wich then get microleaks. If you store below 15% humidity you are fine. Everyone else needs to make sure there is no condensating water and plenty of fresh air.</li>

      <li>Oxygen. A bag of flour will slowly oxydize and get spoiled. In an airtight bag that might be slowed a bit, but note that most plastic resins let oxygen through over time. In an oxygen barrier, like glas, a tincan or Mylar bags this will not happen, therefore storage time is a lot better. Hardcore food collectors use wheat kernels instead of flour, seal them into a Mylar bag as a barrier for light/oxygen and humidity and even add oxygen absorbers into the sealed bags. Foodstuffs like wheat keep for decades prepared like that.</li>

      <li>Heat. 10°C more heat reduces the storage time by half. Try to store below 18°C, but above 5°C to prevent frost. A steady temperature is better than peaks between cold and warm.</li>

      <li>Critters and bugs. You need to keep mice and rats away, obviously. There are commercial traps for rodents, moth and ants that are very effective. Before you put stuff like dried lentils/beans/rolled oats/raw müsli and such into storage put it in a freezer for a week or so, to kill insects that might live in it. If you can't control the critters, ask a specialist.</li>

    </ol>

    <h2><a name="notes"></a>Notes</h2>

    <ul type="circle">
      <li>If you want to fix something, send me a unified diff (<code>diff -u</code>, UTF-8 is the charset).</li>
      <li>Measurements are gram and kilogram. Other measurements are added later.</li>
      <li>No data about you or your food is saved on the server, after your session is deleted. If you do not delete a session, the data is kept on the server for about 20 minutes. After that, data has to be retrieved from your cookie. If the cookie is lost, or you disable cookies in your browser, your data is lost if the session runs out on the server.</li>
      <li>The data used for our food databases is compiled from various sources and is only a rough estimate.</li>
    </ul>

    <h2><a name="links"></a>Links</h2>

    <p>Links that might be of interest:</p>

    <ul type="circle">
      <li>Lists of foodstuffs with their nutrients:<br>
          US list <a href="http://www.nal.usda.gov/fnic/foodcomp/search/">http://www.nal.usda.gov/fnic/foodcomp/search/</a><br>
          Swiss list <a href="http://www.swissfir.ethz.ch/datenbank/index_EN">http://www.swissfir.ethz.ch/datenbank/index_EN</a><br>
          Danish list <a href="http://www.foodcomp.dk/v7/fcdb_default.asp">http://www.foodcomp.dk/v7/fcdb_default.asp</a></li>
      <li>Other (inferior, if i may say so) food storage calculators:<br>
          <a href="http://providentliving.org/content/display/0,11666,7624-1-4071-1,00.html">http://providentliving.org/content/display/0,11666,7624-1-4071-1,00.html</a><br>
          <a href="http://www.simplylivingsmart.com/calculators-spreadsheets/article/11-calculators/35-food-storage-calculator.html">http://www.simplylivingsmart.com/calculators-spreadsheets/article/11-calculators/35-food-storage-calculator.html</a><br>
          <a href="http://lds.about.com/library/bl/faq/blcalculator.htm">http://lds.about.com/library/bl/faq/blcalculator.htm</a><br>
          <a href="http://kruessmann.de/notvorrat/index.php">http://kruessmann.de/notvorrat/index.php</a>
      </li>
    </ul>

    <h2><a name="todo"></a>Todo!</h2>

    <ul type="circle">
      <li><strike>Priority 0: Implement session handling and username/foodstuff in a cookie.</strike></li>
      <li><strike>Priority 0: Implement changing of the Stockpile-O-Mat list with system foodstuffs in a cookie.</strike></li>
      <li><strike>Priority 0: Implement nutritional analysis.</strike></li>
      <li><strike>Priority 1: Implement adding and removing people that depend on the food, consider their nutritional demands in the analysis.</strike></li>
      <li>Priority 1: Implement checking of input strings.</li>
      <li>Priority 1: Implement adding, removing and adjusting of private foodstuffs in a cookie.</li>
      <li>Priority 1: Changeable measurements from kilo to oz/pound for our friends in Liberia, USA and Burma (everyone else uses the kilo).</li>
      <li>Priority 2: Implement proper localisation for text strings and float values, also spellcheck.</li>
      <li>Priority 3: Implement export/import of Stockile-O-Mat lists.</li>
      <li>Priority 3: Implement saving a Stockpile-O-Mat list on the server, lists should be shared read-only/read-write.</li>
      <li>Priority 4: The nutritional analysis is based on GDAs for the US. Implement switch to other models, like the one proposed by the EU.</li>
      <li>Priority 4: UI polishing.</li>
    </ul>

<!--
    <br><br>

Add a new product to the database:
<form name="new_product" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post" >
  <input type="text" name="nproduct" size="10" value="needed!"> Short name of the product<br>
  <input type="text" name="nproduct_de" size="10"> Short german name of the product<br>
  <input type="text" name="ndetails" size="10"> Short list of properties, dried, canned, like that<br>
  <input type="text" name="ndetails_de" size="10"> Short list of german properties, dried, canned, like that<br>
  <input type="text" name="nprotein" size="10" value="needed!"> Protein content in %<br>
  <input type="text" name="ncarbs" size="10" value="needed!"> Carbohydrate content in % (includes sugars)<br>
  <input type="text" name="nsugar_in_carbs" size="10"> Sugar content in %<br>
  <input type="text" name="nfat" size="10" value="needed!"> Fat content in % (includes saturated fatty acids)<br>
  <input type="text" name="nsaturated_fatty_acids" size="10"> Saturated fatty acids content in %<br>
  <input type="text" name="nfiber" size="10"> Fiber content in %<br>
  <input type="text" name="nkjoule" size="10" value="needed!"> KiloJoule per 100g<br>
  <input type="text" name="nsodium" size="10"> Sodium content in %<br>
  <input type="text" name="npicture" size="10"> A picture that you have made yourself (not from other websites).<br>
  <input type="submit" value="Add product">
</form>

<br><br>

    Download Stockpile-O-Mat list to your Computer<br>
    <form name="import_csv" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post" enctype="multipart/form-data">
      <input name="file" type="file" size="10" maxlength="100000" accept="text/comma-separated-values">
      <input type="submit" value="Upload Stockpile in CVS-format" size="30">
    </form>
    <form name="save_on_server" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
      <input name="username" type=text size="10" value="Listname"><input name="password" type=text size="10" value="Password"><input type="submit" value="Save Stockpile on Server" size="30">
    </form>
      <form name="get_from_server" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>" method="post">
        <input name="username" type=text size="10" value="Listname"><input name="password" type=text size="10" value="Password">
        <input type="submit" value="Get stockpile" size="30">
      </form>
-->
<br>
    <p align="center">Copyright 2009 <a href="mailto:tecneeq@tecneeq.de">Karsten Kruse</a> |
    BSD Licensed Sourcecode:
    <a target="_blank" href="<?php echo $_SERVER["SCRIPT_NAME"]; ?>?show_source">Application</a> |
    <a target="_blank" href="product_db.php?show_source">Nutrition DB</a> |
    <a target="_blank" href="demands_db.php?show_source">People DB</a></p>

  </body>
</html>