<?php
// csv.php
// Include file for Google Charts csv Spreadsheet integration purposes
// RJM Programming
// October, 2015

$isoneorother=0;

function latlongmassage($inll) {
  global $isoneorother;
  $gch="-0123456789.";
  $foi=0;
  $llfactor=1.0;
  $nfcis=1.0;
  $isoneorother=0;
  if (is_numeric($inll)) return '' . $inll;
  if (strpos(strtolower($inll),"n") !== false) $isoneorother=-1;
  if (strpos(strtolower($inll),"s") !== false) $llfactor=-1.0;
  if (strpos(strtolower($inll),"s") !== false) $isoneorother=-1;
  if (strpos(strtolower($inll),"e") !== false) $isoneorother=1;
  if (strpos(strtolower($inll),"e") !== false) $llfactor=-1.0;
  if (strpos(strtolower($inll),"w") !== false) $isoneorother=1;
  $pvalis=0.0;
  $cpvalis="";
  if ($llfactor == -1) $inll=str_replace("-","",$inll);
  for ($iwe=0; $iwe<strlen('' . $inll); $iwe++) {
    if (strpos($gch, substr(('' . $inll), $iwe, 1)) !== false) {
      $cpvalis.=substr(('' . $inll), $iwe, 1);
    } else {
      if ($foi == 0 && $cpvalis != "") {
        $pvalis+=$cpvalis;
        if (strpos($cpvalis, ".") !== false) return '' . ($pvalis * $llfactor);
        $cpvalis="";
        $nfcis=60.0;
        $foi=1;
      } else if ($foi == 1 && $cpvalis != "") {
        $pvalis+=($cpvalis / 60.0);
        if (strpos($cpvalis, ".") !== false) return '' . ($pvalis * $llfactor);
        $nfcis=3600.0;
        $cpvalis="";
        $foi=2;
      } else if ($cpvalis != "") {
        $pvalis+=($cpvalis / 3600.0);
        if (1 == 1) return '' . ($pvalis * $llfactor);
        $cpvalis="";
      }
    }
  }
  if ($cpvalis != "") {
        $pvalis+=($cpvalis / $nfcis);
        $cpvalis="";
        return '' . $cpvalis . ($pvalis * $llfactor);
  } else if ($nfcis > 1.1) {
        return '' . ($pvalis * $llfactor);
  }
  return '' . $inll;
}

function read_and_array($viaurl, $calledby) {
  global $isoneorother;
  $onei=1;
  $onev=3;
  $placefirst=true;
  $latpos=0;
  $longpos=1;
  $outcsvis="";
  $outcsvisd=",";
  if (strpos(('`' . str_replace('https','http',strtolower($viaurl))), "`http;") !== false) {
  $conturl=substr(str_replace('https','http',str_replace('HTTP','http',str_replace('Http','http',$viaurl))),5);
  } else {
  $conturl=@file_get_contents(str_replace("Https:","http:",str_replace("HTTPS:","http:",str_replace("https:","http:",$viaurl))));
  }
  
//echo str_replace("Https:","http:",str_replace("HTTPS:","http:",str_replace("https:","http:",$viaurl))) . "Prehere " . $conturl;
  if ($conturl != "") {
   if (strpos($calledby, ".php") !== false && strpos($calledby, "map") !== false) {  // Map Chart via csv data place,lat,long or lat,long,place ... can be very simple <tr><td>place</td><td>lat</td><td>long</td></tr> or <tr><td>lat</td><td>long</td><td>place</td></tr> table records
   if ((strpos(strtolower($conturl), "</td><td>") === false || strpos(strtolower($conturl), "<tr><td>") === false) && strpos(strtolower($conturl), '</td>') !== false) {
     $nbits=explode("<t", strtolower((' ' . $conturl)));
     $newconturl=$nbits[0];
     for ($iyu=1; $iyu<sizeof($nbits); $iyu++) {
       $newconturl.="<t" . substr($nbits[$iyu],0,1) . ">" . substr($nbits[$iyu], strlen(explode(">", $nbits[$iyu])[0] . " "));
     }
     $conturl=$newconturl;
     $onev=2;
//echo "there " . sizeof($nbits) . " " . str_replace("<","&lt;",str_replace(">","&gt;",$conturl));
    }
    if (strpos($conturl, "'") !== false && strpos($conturl, '"') === false) {
     $conturl=str_replace("'", '"', $conturl);
    } else if (strpos($conturl, "'") === false && strpos($conturl, '"') === false && strpos($conturl, ',') !== false) {
     $conturl=str_replace(",,",",",str_replace("\n",",",str_replace('""','"',str_replace("<tr>",' "',str_replace("</tr>",'" ', str_replace("<td>",' ',str_replace("</td>",' ',  str_replace("<tr><td>",' "',str_replace("</td></tr>",'" ',  str_replace("</td><td>", ",", $conturl))))))))));
    }
    if (strpos(strtolower($conturl), "</td><td>") !== false && strpos($conturl, ',') === false) {
     $conturl=str_replace(",,",",",str_replace("\n"," ",str_replace('""','"',str_replace("<tr>",' "',str_replace("</tr>",'" ', str_replace("<td>",' ',str_replace("</td>",' ',  str_replace("<tr><td>",' "',str_replace("</td></tr>",'" ',  str_replace("</td><td>", ",", strtolower($conturl)))))))))));
     $onev=2;
    } 
    if (strpos($conturl, '",') !== false || strpos($conturl, ',"') !== false || strpos($conturl, ',') !== false) {
     $pcbits=explode('",', $conturl);
     if (sizeof($pcbits) <= 1) {
         $placefirst=false;
         $pcbits=explode(',"', $conturl);
     }
     if (sizeof($pcbits) <= 1) {
         $pcbits=explode(',', $conturl);
         if (sizeof($pcbits) > 2) {
           $onei=$onev;  // "hgfhg hgfhj,45.8,123.6" "hgfhg hgfhj,45.8,123.6"
           if (is_numeric(latlongmassage(explode('"',$pcbits[1])[0])) && is_numeric(latlongmassage(explode('"',$pcbits[2])[0])) && is_numeric(latlongmassage(explode('"',$pcbits[0])[0]))) {

             if (!is_numeric(substr($pcbits[0],0,2)) && is_numeric(substr($pcbits[2],0,2))) {
              $placefirst=true;
             } else {
              $placefirst=false;
             }
           } else if (!is_numeric(latlongmassage(explode('"',$pcbits[0])[0]))) {
             $placefirst=true;
             //echo "true" . latlongmassage(explode('"',$pcbits[2])[0]);
           } else {
             $placefirst=false;
             //echo "false" . latlongmassage(explode('"',$pcbits[2])[0]) . " " . explode('"',$pcbits[2])[0];
           }
         }
     }
     
     if (sizeof($pcbits) > 1) {
       for ($ic=1; $ic<sizeof($pcbits); $ic+=$onei) {
         if ($onei > 1) {
           if (strpos($conturl, '",') === false && strpos($conturl, ',"') === false) {
           if ($placefirst) {
            $zer=0;
            //if (substr(trim($pcbits[-1 + $ic]),0,1) == '"') $zer=1;
            if (sizeof(explode('"',$pcbits[-1 + $ic])) > 1) {
            //$pcbits[-1 + $ic]="" . explode(' ',explode('"',substr(trim($pcbits[-1 + $ic]),$zer))[-1 + sizeof(explode('"',$pcbits[-1 + $ic]))])[0] . '"';
            $pcbits[-1 + $ic]="" . explode('"',substr(trim($pcbits[-1 + $ic]),$zer))[-1 + sizeof(explode('"',$pcbits[-1 + $ic]))] . '"';
//echo "HERE" . $pcbits[-1 + $ic] . " ... next" . $onei . " ... " . $pcbits[-1 + $ic + $onei] . " " . $conturl;
            } else {
            //$pcbits[-1 + $ic]="" . explode(' ',explode('"',substr(trim($pcbits[-1 + $ic]),$zer))[0])[0] . '"';
            $pcbits[-1 + $ic]="" . explode('"',substr(trim($pcbits[-1 + $ic]),$zer))[0] . '"';
            }
            //$pcbits[$ic]='"' . $pcbits[$ic] . '"'; 
            $pcbits[$ic].="," . $pcbits[1 + $ic];
            $rpi=0;
            
//echo "hERE " . $pcbits[-1 + $ic];
           } else {
            $pcbits[-1 + $ic]=$pcbits[-1 + $ic] . "," . $pcbits[$ic];
            $pcbits[$ic]='' . $pcbits[1 + $ic] . '"';
            //$pcbits[$ic]='"' . $pcbits[$ic] . ''; 
    //echo $pcbits[$ic] . " ConTurl=" . $conturl;
    //exit;
           }
           } 
         } else {
           $rpi=(-1 + sizeof(explode('"',$pcbits[-1 + $ic])));
         }
         if ($placefirst) {
          $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$latpos]);
          if ($outcsvisd == "" && ($rlatis > 90.0  || $rlatis < -90.0 || $isoneorother == 1)) {
           $latpos=(1 - $latpos);
           $longpos=(1 - $longpos);
           $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$latpos]);
          }
         } else {
          $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          if ($outcsvisd == "" && ($rlatis > 90.0  || $rlatis < -90.0)) {
           $latpos=(1 - $latpos);
           $longpos=(1 - $longpos);
           $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          }
         }
         if ($placefirst) {
          $rlongis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$longpos]);
         } else {
          $rlongis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $longpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
         }
         if ($placefirst) {
          //$rplaceis="~" . explode('"',$pcbits[-1 + $ic])[-1 + sizeof(explode('"',$pcbits[-1 + $ic]))] . "~";
          $rplaceis="~" . explode('"',$pcbits[-1 + $ic])[$rpi] . "~";
    //echo $rplaceis . " ConTuRl=" . $conturl . "?" . $pcbits[-1 + $ic];
    //exit;
         } else {
          $rplaceis="~" . explode('"',$pcbits[$ic])[0] . "~";
         }
         $outcsvis.=$outcsvisd . "[" . $rlatis . "," . $rlongis . "," . $rplaceis . "]";
         $outcsvisd=",";
       }
     }      
     
    }
    //echo "done";
    //file_put_contents("huhhuhtwo.cSv", $outcsvis);
    return $outcsvis;
   }
  } 
  return $viaurl;
}

function datefixes($inch) {
  $ouch=$inch;
  $dbits=explode("new Date(", $inch);
  $dtwobits=explode("newDate(", $inch);
  if (sizeof($dbits) > 1) {
    if (substr($ouch, 0, 1) == ",") $ouch="Date" . $ouch;
    for ($i=(sizeof($dbits) - 1); $i>=0; $i--) {
      $dhuhs=explode(")", $dbits[$i]);
      $ymd=explode(",", $dhuhs[0]);
      $ouch=str_replace("new Date(" . $dhuhs[0] . ")", $ymd[2] . "/" . ($ymd[1] + 1) . "/" . $ymd[0], $ouch);
    }
  }
  if (sizeof($dtwobits) > 1) {
    if (substr($ouch, 0, 1) == ",") $ouch="Date" . $ouch;
    for ($i=(sizeof($dtwobits) - 1); $i>=0; $i--) {
      $dhuhs=explode(")", $dtwobits[$i]);
      $ymd=explode(",", $dhuhs[0]);
      $ouch=str_replace("newDate(" . $dhuhs[0] . ")", $ymd[2] . "/" . ($ymd[1] + 1) . "/" . $ymd[0], $ouch);
    }
  }
  return $ouch;
}

$csv_file_content="";
$datais="";
if (isset($_GET['data'])) $datais=$_GET['data'];
if (isset($_POST['data'])) $datais=$_POST['data'];
if ($datais == "" && strpos($_SERVER['QUERY_STRING'], "&data=") !== false) {
       $things=explode("&data=", $_SERVER['QUERY_STRING']);
       if (sizeof($things) > 1) {
        $subthings=explode("&", $things[1]);
        $datais = $subthings[0];
       }
}
if ($datais != "" && strpos($datais, "[") !== false && strpos($datais, "[") < strpos($datais, ",")) {
       $datais="," . $datais;
}
$csvprefix="";
if (isset($_GET['label'])) $csvprefix.=$_GET['label'];
if (isset($_POST['label'])) $csvprefix.=$_POST['label'];
if (isset($_GET['task'])) $csvprefix.=$_GET['task'];
if (isset($_POST['task'])) $csvprefix.=$_POST['task'];
if (isset($_GET['country'])) $csvprefix.=$_GET['country'];
if (isset($_POST['country'])) $csvprefix.=$_POST['country'];
if (strpos(urldecode($datais), '),newDate(') !== false && strpos(urldecode($datais), ')]') === false && $csvprefix == '') {
$csvprefix='"Task ID","Task Description","Start Date","End Date","Duration","Percent Complete","Dependencies"';
} else if (strpos(urldecode($datais), '),new Date(') !== false && $csvprefix == '') {
if (isset($_GET['desc'])) $csvprefix='"' . $_GET['desc'] . '","Start Date","End Date"';
if (isset($_POST['desc'])) $csvprefix='"' . $_POST['desc'] . '","Start Date","End Date"';
} else {
if (isset($_GET['popularity'])) $csvprefix.="~" . $_GET['popularity'];
if (isset($_POST['popularity'])) $csvprefix.="~" . $_POST['popularity'];
if (isset($_GET['population'])) $csvprefix.="~" . $_GET['population'];
if (isset($_POST['population'])) $csvprefix.="~" . $_POST['population'];
if (isset($_GET['value'])) $csvprefix.="~" . $_GET['value'];
if (isset($_POST['value'])) $csvprefix.="~" . $_POST['value'];
if (isset($_GET['desc'])) $csvprefix.="~" . $_GET['desc'];
if (isset($_POST['desc'])) $csvprefix.="~" . $_POST['desc'];
if ($csvprefix == "") {
  if (isset($_GET['title'])) $csvprefix.=$_GET['title'];
  if (isset($_POST['desc'])) $csvprefix.=$_POST['title'];
  if ($csvprefix != "") {
   $csvprefix="Date for " . $csvprefix;
   if (isset($_GET['desc1'])) $csvprefix.="~" . $_GET['desc1'];
   if (isset($_POST['desc1'])) $csvprefix.="~" . $_POST['desc1'];
   if (isset($_GET['title1'])) $csvprefix.="~" . $_GET['title1'];
   if (isset($_POST['title1'])) $csvprefix.="~" . $_POST['title1'];
   if (isset($_GET['text1'])) $csvprefix.="~" . $_GET['text1'];
   if (isset($_POST['text1'])) $csvprefix.="~" . $_POST['text1'];
   if (isset($_GET['desc2'])) $csvprefix.="~" . $_GET['desc2'];
   if (isset($_POST['desc2'])) $csvprefix.="~" . $_POST['desc2'];
   if (isset($_GET['title2'])) $csvprefix.="~" . $_GET['title2'];
   if (isset($_POST['title2'])) $csvprefix.="~" . $_POST['title2'];
   if (isset($_GET['text2'])) $csvprefix.="~" . $_GET['text2'];
   if (isset($_POST['text2'])) $csvprefix.="~" . $_POST['text2'];
  }
}
}
$csvprefix=str_replace("~", ",",str_replace("~,", ",",str_replace(",~", ",",$csvprefix)));
$ioc="";
if (isset($_GET['onclick'])) $ioc=$_GET['onclick'];
if (isset($_POST['onclick'])) $ioc=$_POST['onclick'];
$csvfile="";
if (isset($_GET['csv'])) $csvfile=$_GET['csv'];
if (isset($_POST['csv'])) $csvfile=$_POST['csv'];
if (strlen($ioc) > 0 && strlen($csvfile) > 0 && strpos(strtolower($csvfile) . "~", ".csv~") !== false) {
  $csv_file_content=datefixes(str_replace("\n\n","\n",str_replace('~','"',str_replace("[","",str_replace("]","",str_replace(", [","\n",str_replace(",[","\n",str_replace("'", '"', urldecode($csvprefix)) . "\n" . urldecode($datais))))))));
  if (strpos($csv_file_content," ") === false) $csv_file_content=(str_replace("'","",$csv_file_content));
  if (1 == 2) file_put_contents($csvfile0, $csv_file_content);
  // Thanks to http://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in-php-that-excel-will-read-properly
  if (strlen($csv_file_content) > 0) {
   header('Content-Description: File Transfer');
   header('Content-Type: application/octet-stream');
   $hdr='Content-Disposition: attachment; filename=' . $csvfile;
   header($hdr);
   header('Content-Transfer-Encoding: binary');
   header('Expires: 0');
   header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
   header('Pragma: public');
   echo "\xEF\xBB\xBF"; // UTF-8 BOM
   echo $csv_file_content;
   exit();
  }
}
$csvfile0="";
$datais0="";
if (isset($_GET['data0'])) $datais0=$_GET['data0'];
if (isset($_POST['data0'])) $datais0=$_POST['data0'];
if ($datais0 == "" && strpos($_SERVER['QUERY_STRING'], "&data0=") !== false) {
       $things=explode("&data0=", $_SERVER['QUERY_STRING']);
       if (sizeof($things) > 1) {
        $subthings=explode("&", $things[1]);
        $datais0 = $subthings[0];
       }
}
if ($datais0 != "" && strpos($datais0, "[") !== false && strpos($datais0, "[") < strpos($datais0, ",")) {
       $datais0="," . $datais0;
}
if (isset($_GET['csv0'])) $csvfile0=$_GET['csv0'];
if (isset($_POST['csv0'])) $csvfile0=$_POST['csv0'];
if (strlen($ioc) > 0 && strlen($csvfile0) > 0 && strpos(strtolower($csvfile0) . "~", ".csv~") !== false) {
  //$csv_file_content=datefixes(str_replace("\n\n","\n",str_replace('~','"',str_replace("[","",str_replace("]","",str_replace(", [","\n",str_replace(",[","\n",urldecode($csvprefix . "\n" . $datais0))))))));
  $csv_file_content=datefixes(str_replace("\n\n","\n",str_replace('~','"',str_replace("[","",str_replace("]","",str_replace(", [","\n",str_replace(",[","\n",str_replace("'", '"', urldecode($csvprefix)) . "\n" . urldecode($datais0))))))));
  if (strpos($csv_file_content," ") === false) $csv_file_content=(str_replace("'","",$csv_file_content));
  if (1 == 2) file_put_contents($csvfile0, $csv_file_content);
  // Thanks to http://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in-php-that-excel-will-read-properly
  if (strlen($csv_file_content) > 0) {
   header('Content-Description: File Transfer');
   header('Content-Type: application/octet-stream');
   $hdr='Content-Disposition: attachment; filename=' . $csvfile0;
   header($hdr);
   header('Content-Transfer-Encoding: binary');
   header('Expires: 0');
   header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
   header('Pragma: public');
   echo "\xEF\xBB\xBF"; // UTF-8 BOM
   echo $csv_file_content;
   exit();
  }
}

?>
