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

$isoneorother=0;
$gcalled_by="";
$monthfirst=-1;
$yearpos=-1;
$yoff=0;
$hdrstuff='';
$shortbody="body";
$longbody="document.body";
$rearrangejs="";
$rearrangestp="";
$rearrangests="";
$rearrangesize="Size";
$rearrangecover="cover";

function csv_server_remote_addr() {
    $rma = $_SERVER['REMOTE_ADDR'];
    $ua = strtolower((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''));
    // you can add different browsers with the same way ..
    if (1 == 1) {
    if(preg_match('/(chromium)[ \/]([\w.]+)/', $ua))
            $rma = '000000'.$rma; 
    elseif(preg_match('/(chrome)[ \/]([\w.]+)/', $ua))
            $rma = '00000'.$rma;
    elseif(preg_match('/(safari)[ \/]([\w.]+)/', $ua))
            $rma = '0000'.$rma;
    elseif(preg_match('/(opera)[ \/]([\w.]+)/', $ua))
            $rma = '000'.$rma;
    elseif(preg_match('/(msie)[ \/]([\w.]+)/', $ua))
            $rma = '00'.$rma;
    elseif(preg_match('/(mozilla)[ \/]([\w.]+)/', $ua))
            $rma = '0'.$rma;
    } 
    return str_replace(':','_',str_replace('.','_',$rma));
}



function titlebits(&$burl, &$GETtitle, &$cdivc, &$bdivstart, &$bdivend, &$nondefs) {

$gtypes = ["audio/wav","audio/x-wav","audio/x-pn-realaudio","audio/x-mpegurl","audio/x-aiff","audio/x-aifc","audio/mpeg","audio/mid",
      "audio/basic","audio/ogg","video/x-sgi-movie","video/x-msvideo","video/quicktime","audio/mp3","video/mp4","video/mpeg",
      "video/x-la-asf","video/ogg","video/webm","audio/mp4", "image/jpeg", "image/jpeg", "image/png", "image/gif", "image/bmp", "image/tif",
      "text/html", "text/html", "text/html", "text/javascript", "text/css", "text/plain", "text/xml", "text/csv",
      "application/vnd.ms-word", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/x-php", "application/pdf",
      "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint",
      "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
$gexts = [".wav",".wav",".ram",".m3u",".aiff",".aifc",".mp3",".rmi",
      ".snd",".ogg",".movie",".avi",".mov",".mp3",".m4v",".mpeg",
      ".lsx",".ogv",".webm",".m4a", ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tif",
      ".htm", ".html", ".htmls", ".js", ".css", ".txt", ".xml", ".csv",
      ".doc", ".docx", ".php", ".pdf",
      ".pptx", ".ppt",
      ".xls", ".xlsx"];

       $ourtitles=explode(";", str_replace(";base64","|base64",urldecode($GETtitle)));
       for ($ipa=0; $ipa<sizeof($ourtitles); $ipa++) {
       $ourtitles[$ipa]=str_replace("|base64",";base64",$ourtitles[$ipa]);
       }
       $GETtitle = str_replace("\\'", "'", $ourtitles[sizeof($ourtitles) - 1]);
       if (sizeof($ourtitles) > 1 && strlen($ourtitles[0]) > 3 && (strpos(strtolower($ourtitles[0]), "//") !== false || strpos(strtolower($ourtitles[0]), "data:") !== false)) {
       while (sizeof($ourtitles) > 1 && strlen($ourtitles[0]) > 3 && (strpos(strtolower($ourtitles[0]), "//") !== false || strpos(strtolower($ourtitles[0]), "data:") !== false)) {
        $burl="";
        // Thanks to https://stackoverflow.com/questions/8828076/how-can-i-hack-a-background-image-into-google-chart-tools-dynamic-javascript-s
        if (strpos($ourtitles[0], "data:") !== false) {
          $burl=str_replace("%2b","+","data:" . explode(" ", explode("data:", substr($ourtitles[0],0,20) . explode(";",substr($ourtitles[0],20))[0] . " "   )[1])[0]);
        } else if (strpos($ourtitles[0], "DATA:") !== false) {
          $burl=str_replace("%2b","+","data:" . explode(" ", explode("DATA:", substr($ourtitles[0],0,20) . explode(";",substr($ourtitles[0],20))[0] . " "   )[1])[0]);
        } else if (strpos($ourtitles[0], "Data:") !== false) {
          $burl=str_replace("%2b","+","data:" . explode(" ", explode("Data:", substr($ourtitles[0],0,20) . explode(";",substr($ourtitles[0],20))[0] . " "   )[1])[0]);
        } else if (strpos($ourtitles[0], "https://") !== false) {
          $burl="https://" . explode(" ", explode("https://", $ourtitles[0])[1])[0];
        } else if (strpos($ourtitles[0], "Https://") !== false) {
          $burl="Https://" . explode(" ", explode("Https://", $ourtitles[0])[1])[0];
        } else if (strpos($ourtitles[0], "HTTPS://") !== false) {
          $burl="HTTPS://" . explode(" ", explode("HTTPS://", $ourtitles[0])[1])[0];
        } else if (strpos($ourtitles[0], "http://") !== false) {
          $burl="http://" . explode(" ", explode("http://", $ourtitles[0])[1])[0];
        } else if (strpos($ourtitles[0], "Http://") !== false) {
          $burl="Http://" . explode(" ", explode("Http://", $ourtitles[0])[1])[0];
        } else if (strpos($ourtitles[0], "HTTP://") !== false) {
          $burl="HTTP://" . explode(" ", explode("HTTP://", $ourtitles[0])[1])[0];
        } else {
          $burl="//" . explode(" ", explode("//", $ourtitles[0])[1])[0];
        }
        if ($burl != "") {
         $ourmimetype="";
         if (strpos($burl, "data:") === false) {
          $ourext=explode(".", $burl)[-1 + sizeof(explode(".", $burl))];
          for ($im=0; $im<sizeof($gexts); $im++) {
           if (strtolower("." . $ourext) == strtolower($gexts[$im])) $ourmimetype=$gtypes[$im] . ";";
          }
         }
         
         
         
         
         if (strpos($burl, "audio/") !== false || strpos($ourmimetype, "audio/") !== false) {
          if ($bdivstart == "") $bdivstart="<div id='bkcol'>";
          if ($bdivend == "") {
           $bdivend="</div><audio type='audio/" . explode(';', explode('audio/', $ourmimetype . $burl)[1])[0] . "' controls autoplay><source src=" . $burl . "></source></audio>";
          } else {
           $bdivend=str_replace("</div>", "</div><audio type='audio/" . explode(';', explode('audio/', $ourmimetype . $burl)[1])[0] . "' controls autoplay><source src=" . $burl . "></source></audio>", $bdivend);
          } 
         } else if (strpos($burl, "video/") !== false || strpos($ourmimetype, "video/") !== false) {
          if ($bdivstart == "") $bdivstart="<div id='bkcol'>";
          if ($bdivend == "") {
           $bdivend="</div><video type='video/" . explode(';', explode('video/', $ourmimetype . $burl)[1])[0] . "' controls autoplay><source src=" . $burl . "></source></video>";
          } else {
           $bdivend=str_replace("</div>", "</div><video type='video/" . explode(';', explode('video/', $ourmimetype . $burl)[1])[0] . "' controls autoplay><source src=" . $burl . "></source></video>", $bdivend);
          }
         } else if (strpos($burl, "youtube.com/embed/") !== false) {
          if ($bdivstart == "") $bdivstart="<div id='bkcol'>";
          if ($bdivend == "") {
           $bdivend="</div><iframe width='560' height='315' src='" . $burl . "' frameborder='0' allow='autoplay; encrypted-media' allowfullscreen></iframe>";
          } else {
           $bdivend=str_replace("</div>", "</div><iframe width='560' height='315' src='" . $burl . "' frameborder='0' allow='autoplay; encrypted-media' allowfullscreen></iframe>", $bdivend);
          }
         } else if ($burl != "") {
          $bdivstart="<div id='bkcol' style=\"background: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),url('" . $burl . "'); background-repeat: repeat;\">";
          if ($bdivend == "") $bdivend="</div>";
         } 
        }
        $cdivc="background-color: none; opacity:1.0;  ";
        array_shift($ourtitles);
       }
       if ($burl != "") {
        if (substr(trim("x" . $nondefs),-1) == ',') {
        $nondefs.="backgroundColor: 'none',";
        } else {
        $nondefs.=",  backgroundColor: 'none' ";
        }
        $ourtitles=explode(";", urldecode($GETtitle));
        if (sizeof($ourtitles) == 1) {
          $GETtitle=$ourtitles[0];
        } else if (sizeof($ourtitles) == 2 && strlen($ourtitles[0]) <= 3) {
          $GETtitle=$ourtitles[0] . ";" . $ourtitles[1];
        }
       } else {
        $nondefs=$nondefs;
       }
      }
}

function is_adate($indm) {
  if (strpos($indm, "new") !== false) return true;
  return false;
}

function datemassage($inll) {
  global $isoneorother, $gcalled_by, $monthfirst, $yearpos, $yoff;
  $dflds=[];
  $inll=trim($inll);
  $inll=str_replace("Jan","01",str_replace("jan","01",str_replace("JAN","01",str_replace("January","01",str_replace("january","01",str_replace("JANUARY","01",$inll))))));
  $inll=str_replace("Feb","02",str_replace("feb","02",str_replace("FEB","02",str_replace("February","02",str_replace("february","02",str_replace("FEBRUARY","02",$inll))))));
  $inll=str_replace("Mar","03",str_replace("mar","03",str_replace("MAR","03",str_replace("March","03",str_replace("march","03",str_replace("MARCH","03",$inll))))));
  $inll=str_replace("Apr","04",str_replace("apr","04",str_replace("APR","04",str_replace("April","04",str_replace("april","04",str_replace("APRIL","04",$inll))))));
  $inll=str_replace("May","05",str_replace("may","05",str_replace("MAY","05",str_replace("May","05",str_replace("may","05",str_replace("MAY","05",$inll))))));
  $inll=str_replace("Jun","06",str_replace("jun","06",str_replace("JUN","06",str_replace("June","06",str_replace("june","06",str_replace("JUNE","06",$inll))))));
  $inll=str_replace("Jul","07",str_replace("jul","07",str_replace("JUL","07",str_replace("July","07",str_replace("july","07",str_replace("JULY","07",$inll))))));
  $inll=str_replace("Aug","08",str_replace("aug","08",str_replace("AUG","08",str_replace("August","08",str_replace("august","08",str_replace("AUGUST","08",$inll))))));
  $inll=str_replace("Sep","09",str_replace("sep","09",str_replace("SEP","09",str_replace("September","09",str_replace("september","09",str_replace("SEPTEMBER","09",$inll))))));
  $inll=str_replace("Oct","10",str_replace("oct","10",str_replace("OCT","10",str_replace("October","10",str_replace("october","10",str_replace("OCTOBER","10",$inll))))));
  $inll=str_replace("Nov","11",str_replace("nov","11",str_replace("NOV","11",str_replace("November","11",str_replace("november","11",str_replace("NOVEMBER","11",$inll))))));
  $inll=str_replace("Dec","12",str_replace("dec","12",str_replace("DEC","12",str_replace("December","12",str_replace("december","12",str_replace("DECEMBER","12",$inll))))));
// month one less
// &data=[~x~,newDate(2018,4,16),newDate(2018,4,17)],[~y~,newDate(2018,4,18),newDate(2018,4,19)],[~z~,newDate(2018,4,20),newDate(2018,4,21)]
  if (strpos($inll,"new Date") !== false) {
    return str_replace("new Date","newDate",$inll);
  } else if (strpos($inll,"newDate") !== false) {
    return $inll;
  } else if (strpos($inll,"/") !== false) {
    $dflds=explode("/",explode(":",$inll)[0]);
  } else if (strpos($inll,"-") !== false) { 
    $dflds=explode("-",explode(":",$inll)[0]);
  } else if (strpos($inll,",") !== false) { 
    $dflds=explode(",",explode(":",$inll)[0]);
  } else if (strpos($inll,":") !== false) { 
    $dflds=explode(":",$inll);
  } else if (strlen($inll) == 6) { 
    date_default_timezone_set('Australia/Perth');
    return "newDate(" . substr(date("Y"),0,2) . substr($inll,0,2) . "," . (-1 + substr($inll,2,2)) . "," . substr($inll,4,2) . ")";
  } else if (strlen($inll) >= 8) { 
    return "newDate(" . substr($inll,0,4) . "," . (-1 + substr($inll,4,2)) . "," . substr($inll,6,2) . ")";
  } else {
    return $inll;
  }
  
  if (sizeof($dflds) == 0) {
    return $inll;
  } else if (sizeof($dflds) == 1) {
    date_default_timezone_set('Australia/Perth');
    return "newDate(" . substr(date("Y"),0,4) . "," . (-1 + substr(date("m"),0,2)) . "," . $dflds[0] . ")";
  } else if (sizeof($dflds) == 2) {
    date_default_timezone_set('Australia/Perth');
    if ($monthfirst < 0) {
    if ($dflds[0] > 12 && $dflds[1] <= 12) {
    $monthfirst=1;
    } else {
    $monthfirst=0;
    }
    }
    return "newDate(" . substr(date("Y"),0,4) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[1 - $monthfirst] . ")";
  } else {
    if (strlen($dflds[2]) > 2) {
      if (substr($dflds[2],2,1) < '0' || substr($dflds[2],2,1) > '9') {
        $dflds[2]=substr($dflds[2],0,2);
        if (substr($dflds[2],1,1) < '0' || substr($dflds[2],1,1) > '9') {
          $dflds[2]=substr($dflds[2],0,1);
        }
      } else if (substr($dflds[2],1,1) < '0' || substr($dflds[2],1,1) > '9') {
        $dflds[2]=substr($dflds[2],0,1);
      }
    } else if (strlen($dflds[2]) > 1) {
      if (substr($dflds[2],1,1) < '0' || substr($dflds[2],1,1) > '9') {
        $dflds[2]=substr($dflds[2],0,1);
      }
    }
    if (strlen($dflds[2]) > 4) $dflds[2]=substr($dflds[2],0,4); 
    if (is_numeric($dflds[2]) && is_numeric($dflds[1]) && is_numeric($dflds[0])) {
    
    
    if ($dflds[0] > 999) {
    
    if ($monthfirst < 0) {
    $yoff=0;
    $yearpos=0;
    if ($dflds[1] > 12 && $dflds[2] <= 12) {
    $monthfirst=2;
    } else {
    $monthfirst=1;
    }
    }

    } else if ($dflds[0] > 31) {
    
    if ($monthfirst < 0) {
    $yearpos=0;
    date_default_timezone_set('Australia/Perth');
    $yoff=(0 + (substr(date("Y"),0,2) . "00"));
    if ($dflds[1] > 12 && $dflds[2] <= 12) {
    $monthfirst=2;
    } else {
    $monthfirst=1;
    }
    }

    } else if ($dflds[2] > 999) {
    
    if ($monthfirst < 0) {
    $yoff=0;
    $yearpos=2;
    if ($dflds[1] > 12 && $dflds[0] <= 12) {
    $monthfirst=0;
    } else {
    $monthfirst=1;
    }
    }

    } else if ($dflds[2] > 31) {
    
    if ($monthfirst < 0) {
    $yearpos=2;
    date_default_timezone_set('Australia/Perth');
    $yoff=(0 + (substr(date("Y"),0,2) . "00"));
    if ($dflds[1] > 12 && $dflds[0] <= 12) {
    $monthfirst=0;
    } else {
    $monthfirst=1;
    }
    }

    } else if ($dflds[1] > 12 && $dflds[0] > 12) {
    
    if ($monthfirst < 0) {
    $yearpos=0;
    date_default_timezone_set('Australia/Perth');
    $yoff=(0 + (substr(date("Y"),0,2) . "00"));
    $monthfirst=2;
    }


    } else if ($dflds[2] > 12 && $dflds[0] > 12) {
    
    if ($monthfirst < 0) {
    $yearpos=2;
    date_default_timezone_set('Australia/Perth');
    $yoff=(0 + (substr(date("Y"),0,2) . "00"));
    $monthfirst=1;
    }

    } else { 
    
    if ($monthfirst < 0) {
    $yearpos=2;
    date_default_timezone_set('Australia/Perth');
    $yoff=(0 + (substr(date("Y"),0,2) . "00"));
    $monthfirst=1;
    }

    
    }
    
    if ($yearpos == 0 && $monthfirst == 1) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[2] . ")";
    } else if ($yearpos == 0 && $monthfirst == 2) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[1] . ")";
    } else if ($yearpos == 1 && $monthfirst == 2) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[0] . ")";
    } else if ($yearpos == 1 && $monthfirst == 0) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[2] . ")";
    } else if ($yearpos == 2 && $monthfirst == 1) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[0] . ")";
    } else if ($yearpos == 2 && $monthfirst == 0) {
    return "newDate(" . ($yoff + $dflds[$yearpos]) . "," . (-1 + $dflds[$monthfirst]) . "," . $dflds[1] . ")";
    } else {
    return "newDate(" . ($yoff + $dflds[2]) . "," . (-1 + $dflds[1]) . "," . $dflds[0] . ")";
    }   
    
    } else {
    return $inll;
    }
  }
}

function latlongmassage($inll) {
  global $isoneorother, $gcalled_by;
  if ($gcalled_by == "pie_chart") return '' . $inll;
  if ($gcalled_by == "intensity_chart") return '' . $inll;
  $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_date_array($viaurl, $calledby) {
  global $isoneorother, $gcalled_by;
// &data=[~x~,newDate(2018,4,16),newDate(2018,4,17)],[~y~,newDate(2018,4,18),newDate(2018,4,19)],[~z~,newDate(2018,4,20),newDate(2018,4,21)]
  $gcalled_by=$called_by;
  $onei=3;
  $onev=3;
  $latpos=0;
  $longpos=1;
  $placefirst=true;
  $ioff=0;
  if (strpos($calledby, ".php") !== false && strpos($calledby, "timeline_chart") !== false) {
    $ioff=1;
    $onev=(4 - $ioff);
  }
  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 if (strpos($viaurl, ",") !== false && strpos($viaurl, "[") === false) {
  $conturl=$viaurl;
  } 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, "timeline_chart") !== false || strpos($calledby, "calendar_chart") !== false)) {  // Timeline Chart ... 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;
    } 
    $foundlines=1;
    if (strpos($conturl, "\n") !== false) {
      $arrconturl=explode("\n", $conturl);
      $foundlines=sizeof($arrconturl);
    }
    for ($ilines=0; $ilines<$foundlines; $ilines++) {
    if ($foundlines > 1) $conturl=$arrconturl[$ilines];
    if (strpos($calledby, ".php") !== false && (strpos($calledby, "calendar_chart") !== false)) {  // Calendar Chart ... 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
       $pcbits=explode(',', $conturl);
       $nfound=false;
       $dfound=false;
       $nis="";
       $dis="";
       for ($ic=0; $ic<sizeof($pcbits); $ic++) {
           if (!$dfound && ((
           strpos(substr((str_replace('"','',str_replace("'","",$pcbits[$ic])) . "  "),1),"/") !== false || 
           strpos(substr((str_replace('"','',str_replace("'","",$pcbits[$ic])) . "  "),1),"-") !== false || 
           strpos(substr((str_replace('"','',str_replace("'","",$pcbits[$ic])) . "  "),1),":") !== false
           ) && is_adate(datemassage(str_replace('"','',str_replace("'","",$pcbits[$ic])))))) {
             $dfound=true;
             $dis=datemassage(str_replace('"','',str_replace("'","",$pcbits[$ic])));
             if ($dfound && $nfound) {
             $outcsvis.=$outcsvisd . "[" . $dis . "," . $nis . "]";
             $outcsvisd=",";
       $nfound=false;
       $dfound=false;
             }
           } else if (!$nfound && is_numeric(str_replace('"','',str_replace("'","",$pcbits[$ic])))) {
             $nfound=true;
             $nis="" . $pcbits[$ic];
             if ($dfound && $nfound) {
             $outcsvis.=$outcsvisd . "[" . $dis . "," . $nis . "]";
             $outcsvisd=",";
       $nfound=false;
       $dfound=false;
             }
           }
       }
    } else { // Timeline chart
    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_adate(datemassage(explode('"',$pcbits[2])[0]))) {
             $placefirst=true;
             //echo "true";
           } else {
             $placefirst=false;
             //echo "false" . explode('"',$pcbits[2])[0];
           }
         }
     }
     
     if (sizeof($pcbits) > 1) {
       //echo sizeof($pcbits) . " and onei=" . $onei . "  ";
       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=datemassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$latpos]);
          if ($outcsvisd == "" && ($isoneorother == 1)) {
           $latpos=(1 - $latpos);
           $longpos=(1 - $longpos);
           $rlatis=datemassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$latpos]);
          }
         } else {
          $rlatis=datemassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          if ($outcsvisd == "") {
           $latpos=(1 - $latpos);
           $longpos=(1 - $longpos);
           $rlatis=datemassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          }
         }
         if ($placefirst) {
          $rlongis=datemassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$longpos]);
         } else {
          $rlongis=datemassage(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 . "[" . $rplaceis . "," . $rlatis . "," . $rlongis . "]";
         $outcsvisd=",";
       }
     }      
     
    }
    }
    }
    //echo "done";
    //file_put_contents("huhhuhtwo.cSv", $outcsvis);
    return $outcsvis;
   }
  }  
  return $viaurl;
}

function read_and_array($viaurl, $calledby) {
  global $isoneorother, $gcalled_by;
  $gcalled_by=$called_by;
  $onei=1;
  $onev=3;
  $placefirst=true;
  $latpos=0;
  $longpos=1;
  $outcsvis="";
  $outcsvisd=",";
  $ioff=0;
  if (strpos($calledby, ".php") !== false && strpos($calledby, "pie_chart") !== false) {
    $ioff=1;
    $onev=(3 - $ioff);
  }
  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, "pie_chart") !== false || strpos($calledby, "intensity_chart") !== false || strpos($calledby, "map") !== false)) {  // Pie Chart, Intensity Chart, 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 - $ioff);
    } 
    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 - $ioff)) {
           $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 - $ioff)])[0])) && is_numeric(latlongmassage(explode('"',$pcbits[0])[0]))) {

             if (!is_numeric(substr($pcbits[0],0,2)) && is_numeric(substr($pcbits[(2 - $ioff)],0,2))) {
              $placefirst=true;
             //echo "True" . latlongmassage(explode('"',$pcbits[(2 - $ioff)])[0]);
             } else {
              $placefirst=false;
             //echo "False" . $onei . $conturl . latlongmassage(explode('"',$pcbits[(2 - $ioff)])[0]) . " " . explode('"',$pcbits[(2 - $ioff)])[0];
             }
           } else if (!is_numeric(latlongmassage(explode('"',$pcbits[0])[0]))) {
             $placefirst=true;
             //echo "true" . latlongmassage(explode('"',$pcbits[(2 - $ioff)])[0]);
           } else {
             $placefirst=false;
             //echo "false" . latlongmassage(explode('"',$pcbits[(2 - $ioff)])[0]) . " " . explode('"',$pcbits[(2 - $ioff)])[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 if ($ioff == 0) {
            $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 == "" && $ioff == 0 && ($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 {
         //echo " " . $latpos , " ... " . (-1 + $ic);
          $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $ioff + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          if ($outcsvisd == "" && $ioff == 0 && ($rlatis > 90.0  || $rlatis < -90.0)) {
           $latpos=(1 - $latpos);
           $longpos=(1 - $longpos);
           $rlatis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $ioff + $latpos + sizeof(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic]))))]);
          }
         }
         if (strpos($calledby, ".php") !== false && strpos($calledby, "pie_chart") !== false) {
          $rlongis=$rlongis;
         } else {
         if ($placefirst) {
          $rlongis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[$ic])))[$longpos]);
         } else {
          $rlongis=latlongmassage(explode(",",str_replace("'","",str_replace('"','',$pcbits[-1 + $ic])))[-2 + $ioff + $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] . "~";
    //echo $rplaceis . " :" . $ic . ":: " . $pcbits[$ic];
         }
         if (strpos($calledby, ".php") !== false && strpos($calledby, "pie_chart") !== false) {
         $outcsvis.=$outcsvisd . "[" . $rplaceis . "," . $rlatis . "]";
         } else if (strpos($calledby, ".php") !== false && strpos($calledby, "intensity_chart") !== false) {
         $outcsvis.=" , " . "[" . strtoupper($rplaceis) . "," . $rlatis . "," . $rlongis . "]";
         } else {
         $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;
}

function ifspacy($dus, $squotethere, $iflenabovezerorepeat) {
  global $hdrstuff, $shortbody, $longbody, $rearrangejs, $rearrangestp, $rearrangests, $rearrangesize, $rearrangecover;
  $shortbody="body";
  $longbody="document.body";
  $rearrangejs="";
  $rearrangestp="";
  $rearrangests="";
  $rearrangesize="Size";
  $rearrangecover="cover";
  $opcd="";
  if (strlen($iflenabovezerorepeat) > 0) {
    $rearrangejs=" setTimeout(function(){ var ohis=parent.document.getElementById('chart_div').outerHTML; if (!parent.document.getElementById('bkcol')) { parent.document.body.innerHTML=parent.document.body.innerHTML.replace(ohis, '<div id=bkcol>' + ohis + '</div>');  } }, 2000); ";
    $shortbody="#bkcol";
    $longbody='document.getElementById("bkcol")';
    $opcd=" #chart_div { opacity: 0.8; } ";
    $rearrangestp=' setTimeout(function(){ if (!parent.document.getElementById("bkcol")) {  var xohis=parent.document.getElementById("chart_div").outerHTML; parent.document.body.innerHTML=parent.document.body.innerHTML.replace(xohis, "<div id=bkcol>" + xohis.replace(" style=" + String.fromCharCode(34)," style=" + String.fromCharCode(34) + "opacity:0.8 !important;") + "</div>");   } ';
    $rearrangests=' }, 3000); ';
    $rearrangesize="Repeat";
    $rearrangecover="repeat";
  }
  
  if (strpos(str_replace('~http','~data',str_replace('~//','~data',('~' . $dus))), '~data') !== false) {
    if (strpos(('~' . $dus), '~http') !== false) {
      $newdus=trim(str_replace('https:','',str_replace('http:','',$dus)));
      if (strpos($newdus, ' ') !== false) {
        if (!$squotethere) {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){ parent.document.body.innerHTML+=\"<style> " . $shortbody . " { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39) + newdus + String.fromCharCode(39) + \") !important; " . $opcd . "  } </style>\"; }, 4000);  </scr" . "ipt></head>";
            file_put_contents('xz.xz', $hdrstuff);
            return ''; //'"'" . str_replace('"', "\\" . '"', $newdus) . "'";
        } else {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){  parent.document.body.innerHTML+=\"<style> " . $shortbody . " { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39)  + newdus + String.fromCharCode(39) + \") !important; " . $opcd . "   } </style>\"; }, 4000);  </scr" . "ipt></head>";
            file_put_contents('xzz.xzz', $hdrstuff);
            return ''; //'"" . str_replace('"', "\\" . '"', $newdus) . "";
        }
     } else {
        $dus=$newdus;
     }
   } else if (strpos(('~' . $dus), '~//') !== false) {
      $newdus=trim($dus);
      if (strpos($newdus, ' ') !== false) {
        if (!$squotethere) {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){ parent.document.body.innerHTML+=\"<style> " . $shortbody . " { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39) + newdus + String.fromCharCode(39) + \") !important; " . $opcd . "   } </style>\";    }, 4000);  </scr" . "ipt></head>";
            file_put_contents('xza.xza', $hdrstuff);
            return ''; //'"'" . str_replace('"', "\\" . '"', $newdus) . "'";
        } else {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){  parent.document.body.innerHTML+=\"<style> " . $shortbody . " { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39)  + newdus + String.fromCharCode(39) + \") !important; " . $opcd . "   } </style>\";    }, 4000);  </scr" . "ipt></head>";
            file_put_contents('xzza.xzza', $hdrstuff);
            return ''; //'"" . str_replace('"', "\\" . '"', $newdus) . "";
        }
     } else {
        $dus=$newdus;
     }
   } else if (strpos($dus, base64_encode(';utf8,')) !== false || strpos(('~' . $dus), '~data:') === false) {
      $newdus='data' . base64_decode(substr($dus,4));
      if (strpos($newdus, ' ') !== false) {
        if (!$squotethere) {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){ parent.document.body.innerHTML+=\"<style> body { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39) + newdus + String.fromCharCode(39) + \") !important;  } </style>\"; " . $opcd . "    }, 4000);  </scr" . "ipt></head>";
            //file_put_contents('xz.xz', $hdrstuff);
            return ''; //'"'" . str_replace('"', "\\" . '"', $newdus) . "'";
        } else {
            $hdrstuff="<head><scr" . "ipt type=text/javascript> var newdus='" . str_replace("'", "' + String.fromCharCode(39) + '",$newdus) . "'; " . $rearrangejs . " setTimeout(function(){  parent.document.body.innerHTML+=\"<style> body { background-image: linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(\" + String.fromCharCode(39)  + newdus + String.fromCharCode(39) + \") !important;  } </style>\";  " . $opcd . "    }, 4000);  </scr" . "ipt></head>";
            //file_put_contents('xzz.xzz', $hdrstuff);
            return ''; //'"" . str_replace('"', "\\" . '"', $newdus) . "";
        }
      } else {
        $dus=$newdus;
      }
    }
  } else if (strpos($dus, ' ') !== false) {
    if (!$squotethere) {
      return "'" . $dus . "'";
    }
  }
  return $dus;
}

if (isset($_POST['inwrite'])) {
  $prefixisin='';
  if (isset($_POST['inmode'])) {
    if (strlen($_POST['inmode']) > 0) {
      $prefixisin=' ';
    }
  }
  $exidea=explode('#', explode('?', $_SERVER['REQUEST_URI'])[0])[0];
  if (isset($_POST['inurl'])) {
    $exidea=str_replace('+', ' ', urldecode($_POST['inurl']));
  }
  if (file_exists('./bicollection.txt')) {
    file_put_contents('./bicollection.txt', file_get_contents('./bicollection.txt') . $prefixisin . csv_server_remote_addr() . ' --- ' . $exidea . ' ... ' . $_POST['inwrite'] . "\n");
  } else {
    file_put_contents('./bicollection.txt', $prefixisin . csv_server_remote_addr() . ' --- ' . $exidea . ' ... ' . $_POST['inwrite'] . "\n");
  }
  if (file_exists('./bicollection_backup.txt')) {
    file_put_contents('./bicollection_backup.txt', file_get_contents('./bicollection.txt'));
  }
  echo "<html><body></body></html>";
  exit;
}

if (isset($_GET['outread']) && isset($_GET['cleanup'])) {
    if (file_exists('./bicollection_backup.txt')) {
        sleep(3);
        if (file_exists('./bicollection_backup.txt')) {
           file_put_contents('./bicollection.txt', file_get_contents('./bicollection_backup.txt'));
           unlink('./bicollection_backup.txt');
        }
    }
    echo "<html><body></body></html>";
    exit;
} else if (isset($_POST['outread']) || isset($_GET['outread'])) {
  $prefixis='';
  $exidea=explode('#', explode('?', $_SERVER['REQUEST_URI'])[0])[0];
  if (isset($_POST['outread'])) {
   if (strlen($_POST['outread']) > 1) {
    $exidea=str_replace('+', ' ', urldecode($_POST['outread']));
   }
  } else if (isset($_GET['outread'])) {
   if (strlen($_GET['outread']) > 1) {
    $exidea=str_replace('+', ' ', urldecode($_GET['outread']));
   }
  }
  $secidea='';
  if (file_exists('./bicollection.txt')) {
    $filebicont=file_get_contents('./bicollection.txt');
    $origf=$filebicont;
    if (strpos($filebicont, csv_server_remote_addr() . ' --- ' . $exidea . ' ... ') !== false) {
      $relbi=explode("\n", explode(csv_server_remote_addr() . ' --- ' . $exidea . ' ... ', $filebicont)[-1 + sizeof(explode(csv_server_remote_addr() . ' --- ' . $exidea . ' ... ', $filebicont))])[0];
      if (strpos($filebicont, ' ' . csv_server_remote_addr() . ' --- ' . $exidea . ' ... ' . $relbi . "\n") !== false) {
        $prefixis=' ';
      }
      $filebicont=str_replace($prefixis . csv_server_remote_addr() . ' --- ' . $exidea . ' ... ' . $relbi . "\n","",$filebicont);
      if ($origf != $filebicont) {
        file_put_contents('./bicollection_backup.txt', $filebicont);
        $secidea=" setTimeout(function(){ location.href=\"/PHP/csv.php?outread=y&cleanup=y\";   }, 10000); ";
      } else if (file_exists('./bicollection_backup.txt')) {
        $secidea=" setTimeout(function(){ location.href=\"/PHP/csv.php?outread=y&cleanup=y\";   }, 9999); ";
      }
      if (strpos(('~' . $relbi), '~data') !== false) {
       if (isset($_GET['outread'])) {
        $ify=ifspacy(str_replace(' ','+',urldecode($relbi)), false, $prefixis);
        if ($ify == '') {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " parent." . $longbody . ".style.background" . $rearrangesize . "=\"" . $rearrangecover . "\"; " . $secidea . "   " . $rearrangests . "  '></body></html>";
        } else {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " parent." . $longbody . ".style.backgroundImage=\"linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(" . $ify . ")\";  parent." . $longbody . ".style.background" . $rearrangesize . "=\"" . $rearrangecover . "\"; " . $secidea . "   " . $rearrangests . "  '></body></html>";
        }
       } else {
        $ify=ifspacy(str_replace(' ','+',urldecode($relbi)), true, $prefixis);
        if ($ify == '') {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " " . $secidea . "  " . $rearrangests . "  '><p> done </p></body></html>";
        } else {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " " . $secidea . "  parent." . $longbody . ".style.backgroundImage=\"linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL('" . $ify . "')\";   " . $rearrangests . "  '></body><p> yes </p></html>";
        }
       }
      } else {
       if (isset($_GET['outread'])) {
        $ify=ifspacy(str_replace('+',' ',urldecode($relbi)), false, $prefixis);
        if ($ify == '') {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " " . $secidea . "  parent." . $longbody . ".style.background" . $rearrangesize . "=\"" . $rearrangecover . "\";  " . $rearrangests . "  '></body></html>";
        } else {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " " . $secidea . "  parent." . $longbody . ".style.backgroundImage=\"linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL(" . $ify . ")\";  parent." . $longbody . ".style.background" . $rearrangesize . "=\"" . $rearrangecover . "\";  " . $rearrangests . "  '></body></html>";
        }
       } else {
        echo "<html>" . $hdrstuff . "<body onload=' " . $rearrangestp . " " . $secidea . "  parent." . $longbody . ".style.backgroundImage=\"linear-gradient(rgba(255,255,255,0.4),rgba(255,255,255,0.4)),URL('" . str_replace('+',' ',urldecode($relbi)) . "')\";  " . $rearrangests . "  '></body><p> yes again</p></html>";
       }
      }
    } else {
      if (file_exists('./bicollection_backup.txt')) {
        sleep(3);
        if (file_exists('./bicollection_backup.txt')) {
           file_put_contents('./bicollection.txt', file_get_contents('./bicollection_backup.txt'));
           unlink('./bicollection_backup.txt');
        }
      }
      echo "<html><body></body></html>";
    }
  } else {
    if (file_exists('./bicollection_backup.txt')) {
        sleep(3);
        if (file_exists('./bicollection_backup.txt')) {
           file_put_contents('./bicollection.txt', file_get_contents('./bicollection_backup.txt'));
           unlink('./bicollection_backup.txt');
        }
    }
    echo "<html><body></body></html>";
  }
  exit;
}

$csv_file_content="";
$datais="";
if (isset($_GET['data'])) $datais=$_GET['data'];
if (isset($_POST['data'])) $datais=$_POST['data'];
if ($datais == '') {
    if (file_exists('./bicollection_backup.txt')) {
        sleep(3);
        if (file_exists('./bicollection_backup.txt')) {
           file_put_contents('./bicollection.txt', file_get_contents('./bicollection_backup.txt'));
           unlink('./bicollection_backup.txt');
        }
    }
}
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();
  }
}

?>
