<?php
// signature_signature.php
// RJM Programming
// May, 2017
// Help out signature_signature.html with large data set signatures

$oursubj="Signature's Signature";
$htmlis="";
$divcont="";
$data=[""];

function ourpremail($ris, $ssis, $tis, $his) {
    global $okay;
    $xsis = $ssis;
    try {
       //file_put_contents("aaaaa.00aaa", $ris . " " . $xsis);
       //mail("rmetcalfe15@gmail.com", $xsis, "My Body", $his);
       mail($ris, $xsis, $tis, $his);
    } catch (Exception $merr) {
      $okay = 0;
      if (file_exists(dirname(__FILE__) . "/mail.prob")) {
        file_put_contents(dirname(__FILE__) . "/mail.prob", file_get_contents(dirname(__FILE__) . "/mail.prob") . "\n\n" . date('l jS \of F Y h:i:s A') . " ... " . $merr->getMessage());
      } else {
        file_put_contents(dirname(__FILE__) . "/mail.prob", date('l jS \of F Y h:i:s A') . " ... " . $merr->getMessage());
      }
    }
}

function my_s_s_server_remote_addr() {
    $rma = $_SERVER['REMOTE_ADDR'];
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    // you can add different browsers with the same way ..
    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 $rma;
}

$eol = PHP_EOL;
if (isset($_POST['emailto']) && isset($_POST['contentto'])) {
        if (isset($_POST['htmlto'])) {
          if (strlen($_POST['htmlto']) > 0) {
          $htmlis=urldecode($_POST['htmlto']);
          //if (strpos($htmlis, "</head>") === false || 1 == 1) {
          //   $htmlis=str_replace("</body>", "<img style=\"position:absolute;top:0;left:0;\" src=\"" . $_POST['contentto'] . "\" title=\"User of Signature Signature\"></img></body>", $htmlis);
          //} else {
          //   $htmlis=str_replace("</head>", "<style> body {  background: #fff url(" . urldecode($_POST['contentto']) . "); } </style>\n</head>", $htmlis);
          //}
          }
        } else if (sizeof(explode('<',urldecode($_POST['emailto']))) > 1) {
          $htmlis=str_replace(explode('<',urldecode($_POST['emailto']))[0] . '<','<',urldecode($_POST['emailto']));
          //if (strpos($htmlis, "</head>") === false || 1 == 1) {
             //$htmlis=str_replace("<body", "<head><style> body {  background: #fff url(" . urldecode($_POST['contentto']) . "); } </style>\n</head><body", $htmlis);
          //   $htmlis=str_replace("</body>", "<img style=\"position:absolute;top:0;left:0\" src=\"" . $_POST['contentto'] . "\" title=\"User of Signature Signature\"></img></body>", $htmlis);
          //} else {
          //   $htmlis=str_replace("</head>", "<style> body {  background: #fff url(" . urldecode($_POST['contentto']) . "); } </style>\n</head>", $htmlis);
          //}
        }
        if (strlen($htmlis) > 0) {
           $oursubj="Congratulations. You have been sent a Postcard";
        }
        if (isset($_POST['subject'])) {
           if (strlen($_POST['subject']) > 0) {
            $oursubj=urldecode($_POST['subject']);
           }
        }
        if (isset($_POST['from'])) {
        if ($_POST['from'] != '') {
        $headers = 'From: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
        $headers .= 'Reply-To: ' . urldecode($_POST['from']) . $eol;
        } else {
        $headers = 'From: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
        $headers .= 'Reply-To: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
        }
        } else {
        $headers = 'From: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
        $headers .= 'Reply-To: ' . 'rmetcalfe@rjmprogramming.com.au' . $eol;
        }
        if (isset($_POST['cc'])) {
        if ($_POST['CC'] != '') {
        $headers .= 'CC: ' . urldecode($_POST['cc']) . $eol;
        }
        }
        if (isset($_POST['bcc'])) {
        if ($_POST['BCC'] != '') {
        $headers .= 'BCC: ' . urldecode($_POST['bcc']) . $eol;
        }
        }
                   //     'X-Mailer: PHP/' . phpversion();
        $contents = str_replace('data:image/png;base64,', '', str_replace('data:image/jpg;base64,', '', str_replace('data:image/jpeg;base64,', '', urldecode($_POST['contentto']))));
        if ($contents != "") {
          if ($contents != '') {

    		date_default_timezone_set('Australia/Perth');

            //$mysubject .= ' ... ' . $mybody;
    		//$fs = explode("/", $mybody);
    		//$filename = $fs[-1 + sizeof($fs)];
    		$content = chunk_split(base64_encode($contents));
    		if ($htmlis == "") {
    		$content = "<!doctype html><html><body><img src=\"" . $_POST['contentto'] . "\" title=\"User of Signature Signature\"></img></body></html>";
            } else {
            //$content=$htmlis;
            $hbits=explode("</head>", str_replace("<head>","</head>",$htmlis));
            $bbits=explode("</body", str_replace("<body","</body",$htmlis));
            $hdrbit="<head><style> img {  opacity:0.8; position:absolute; top:0; left:0; z-index:1;  } \n :not(img) { opacity:1.0; width:100; text-align:right; z-index:9; background-color: transparent; } </style></head>";
            $bodybit="<body>";
            $endbit="";
            if (sizeof($hbits) > 1) {
            $hdrbit=str_replace("<head><style>", "<head> " . $hbits[1] . "\n<style>", $hdrbit);
            }
            if (sizeof($bbits) > 1) {
            $bodybit="<body" . explode(">",$bbits[1])[0] . ">"; 
            $endbit = substr($bbits[1],strlen(explode(">",$bbits[1])[0] . ">"));
            }
    		$content = "<!doctype html><html>" . $hdrbit . $bodybit . "<img src=\"" . $_POST['contentto'] . "\" title=\"User of Signature Signature\"></img>" . $endbit . "</body></html>";
            }
  //file_put_contents("user_of_s_s.html", $bbits[1] . "..." . $endbit . ":::" . $htmlis);
  //file_put_contents("user_of_s_s.htm", $content);
    		//$uid = md5(uniqid(time()));

    		// a random hash will be necessary to send mixed content
    		$separator = md5(time());

    		$headers .= "MIME-Version: 1.0" . $eol;
    		
    		if (1 == 1 || strpos(strtolower(explode('<',urldecode($_POST['emailto']))[0]), "rmetcalfe15@gmail.com") !== false) {
    		$cont = chunk_split(base64_encode($content));
    		
    		$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
    		$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    		$headers .= "This is a MIME encoded message." . $eol . $eol;

    		// message
    		$headers .= "--" . $separator . $eol;
    		if (1 == 1) {
    		$headers .= "Content-Type: text/html; charset=utf-8" . $eol; //application/octet-stream; name=\"" . $filename . "\"" . $eol;
    		$headers .= $content . $eol . $eol;
            } else {
    		$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    		$headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
    		}

			//if ($cno != 0) {
    		//  $headers .= $defone . $eol . $eol;
    		//} else {
    		$headers .= "Please see attachment below:" . $eol . $eol;
    		//}
            //ourpremail($tem, $mysubject, "", $headers . "--" . $separator . "--");

    		// attachment
    		$filename="user_of_signature_signature_today.html";
    		$headers .= "--" . $separator . $eol;
    		$headers .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    		//$headers .= "Content-Type: application/html; name=\"" . $filename . "\"" . $eol;
    		$headers .= "Content-Transfer-Encoding: base64" . $eol;
    		$headers .= "Content-Disposition: attachment;filename=\"" . $filename . "\"" . $eol; //inline" . $eol; //attachment;filename=\"" . $filename . "\"" . $eol;
    		$headers .= $cont . $eol . $eol;
            $headers .= "--" . $separator . "--";
    		} else {
    		$headers .= "Content-Type: text/html; charset=utf-8" . $eol; //application/octet-stream; name=\"" . $filename . "\"" . $eol;
    		$headers .= $content . $eol . $eol;
    		}
          }
        }                      

        //$headers .= "--" . $separator . "--";
    
    		
    		//file_put_contents("aaa.aaa", $filename);
            
        ourpremail(explode('<',urldecode($_POST['emailto']))[0], $oursubj, "", $headers);
        //echo "<!doctype html><html><body><h1>Email sent to " . explode('<',urldecode($_POST['emailto']))[0] . "</h1></body></html>";
        //header("Location: ./signature_signature.html");        
        $thishcont=file_get_contents(dirname(__FILE__) . "/signature_signature.html");
        echo str_replace("<body", "<body onload=\" document.getElementById('animage').src='" . $_POST['contentto'] . "'; \" ", $thishcont);
        exit;
}

//if (!isset($_POST['emailto']) && !isset($_POST['contentto'])) {
$remove=0;
if (isset($_GET['pdf'])) {
    // Thanks to https://www.imagemagick.org/discourse-server/viewtopic.php?t=27974
    if (file_exists(dirname(__FILE__) . "/animage.wait")) {
     while (file_exists(dirname(__FILE__) . "/animage.wait")) {
       sleep(5);
     }
    }
    file_put_contents(dirname(__FILE__) . "/animage.wait", " ");
    $presufa="&pdfnickname=" . urlencode(explode("/", urldecode($_GET['pdf']))[-1 + sizeof(explode("/", urldecode($_GET['pdf'])))]);
    $presufa.="&pdfname=" . $_GET['pdf'];
    $sufa="&pno=1";
    $cpg="[0,-1]";
    if (isset($_GET['page'])) {
     if (strpos(urldecode($_GET['page']), "-") !== false || strpos(urldecode($_GET['page']), ",") !== false) {
      $sufa="";
      $cpg="[" . urldecode($_GET['page']) . "]";
     } else {
      $sufa="&pno=" . $_GET['page'];
      $cpg="[" . (-1 + $_GET['page']) . "]";
     }
    }
    if (file_exists(dirname(__FILE__) . "/animage.jpeg")) unlink(dirname(__FILE__) . "/animage.jpeg");
    foreach (glob(dirname(__FILE__) . "/animage-*.jpeg") as $filename) {
      unlink($filename);
    }
    exec("convert  " . explode('?',explode('#',urldecode($_GET['pdf']))[0])[0] . $cpg . " " . dirname(__FILE__) . "/animage.jpeg");
    //sleep(38);
    //$thishcont=file_get_contents(dirname(__FILE__) . "/signature_signature.html");
    //echo str_replace("<body", "<body onload=\" parent.document.location.href=parent.document.URL.split('#')[0].split('?')[0] + '?urlimage=' + encodeURIComponent('./animage.jpeg'); \" ", $thishcont);
    if (file_exists(dirname(__FILE__) . "/animage.jpeg")) {
    if (strpos($sufa, "&lno=") === false && isset($_GET['lastpage']))  $sufa .= "&lno=" . urldecode($_GET['lastpage']);
    if (file_exists(dirname(__FILE__) . "/animage.wait")) {
     unlink(dirname(__FILE__) . "/animage.wait");
    }
    if (isset($_GET['nameaimage'])) { // nametopcontext  nametopconvas
    echo "<!doctype html><html><head><script type='text/javascript'> parent.document.getElementById('" . $_GET['nameaimage'] . "').src='./animage.jpeg?rn=' + Math.floor(Math.random() * 23467894); </script></head><body></body></html>";
    } else {
    echo "<!doctype html><html><head><script type='text/javascript'> top.window.location = top.document.URL.split('#')[0].split('?')[0] + '?urlimage=' + encodeURIComponent('./animage.jpeg') + '" . $presufa . $sufa . "&rn=" . rand() . "'; </script></head><body></body></html>";
    }
    die;
    exit;
    } else {
    $sor=-1;
    $lor=-1;
    $sufa="";
    foreach (glob(dirname(__FILE__) . "/animage-*.jpeg") as $filename) {
      if ($sor < 0) {
        $sor=(1 + explode(".",explode("nimage-", $filename)[1])[0]);
        $sufa="&pno=" . $sor;
        $lor=$sor;
        //copy($filename, str_replace("-" . explode(".",explode("nimage-", $filename)[1])[0] . ".jpeg", ".jpeg", $filename));
        //unlink($filename);
        rename($filename, str_replace("-" . explode(".",explode("nimage-", $filename)[1])[0] . ".jpeg", ".jpeg", $filename));
      } else if ((1 + explode(".",explode("nimage-", $filename)[1])[0]) > $sor && (1 + explode(".",explode("nimage-", $filename)[1])[0]) > $lor) {
        $lor=(1 + explode(".",explode("nimage-", $filename)[1])[0]);
        unlink($filename);
      } else {
        unlink($filename);
      }
    }
    if ($sufa != "" && $lor > 0) $sufa .= "&lno=" . $lor;
    if (strpos($sufa, "&lno=") === false && isset($_GET['lastpage']))  $sufa .= "&lno=" . urldecode($_GET['lastpage']);
    if (file_exists(dirname(__FILE__) . "/animage.wait")) {
     unlink(dirname(__FILE__) . "/animage.wait");
    }
    if (isset($_GET['nameaimage'])) { // nametopcontext  nametopconvas
    echo "<!doctype html><html><head><script type='text/javascript'> parent.document.getElementById('" . $_GET['nameaimage'] . "').src='./animage.jpeg?rn=' + Math.floor(Math.random() * 23467894); </script></head><body></body></html>";
    } else {
    echo "<!doctype html><html><head><script type='text/javascript'> top.window.location = top.document.URL.split('#')[0].split('?')[0] + '?urlimage=' + encodeURIComponent('./animage.jpeg') + '" . $presufa . $sufa . "&rn=" . rand() . "'; </script></head><body></body></html>";
    }
    die;
    exit;
    }
} else if (isset($_GET['sscoords']) && isset($_GET['nonblankremove'])) {
    $pc=str_replace("+"," ",str_replace("@!@","",urldecode($_GET['sscoords'])));
    $remove=1;
    $thiscont=file_get_contents(dirname(__FILE__) . "/signature_signature.php");
    if (strpos($thiscont, ";" . my_s_s_server_remote_addr() . ";") !== false) {
      $predivcont=explode('|',explode(";" . my_s_s_server_remote_addr() . ";", $thiscont)[1])[0];
      $divcont=explode('"',explode(";" . my_s_s_server_remote_addr() . ";", $thiscont)[1])[0];
      //file_put_contents("xxx.z",substr(($pc . " "),0,1));
      if (substr(($pc . " "),0,1) == "|") {
      $ifthere="|" . explode("`", substr($pc,1))[0] . "`";
      //file_put_contents("xxx.zx",$remove . " " . $_GET['nonblankremove'] . "??" . $_SERVER['QUERY_STRING']);
      if ($remove > 0) {
      $jjustc=str_replace("``","`",str_replace($ifthere, "`", $pc)); 
      $justc=str_replace("``","`",str_replace($jjustc, "`", $divcont));
      //file_put_contents("xxx.zxc","\nifthere=" . $ifthere . "\njjustc=" . $jjustc . "\ndivcont=" . $divcont);
      if ($justc != $divcont) {
      //file_put_contents("xxx.zxcok","\nifthere=" . $ifthere . "\njjustc=" . $jjustc . "\ndivcont=" . $divcont);
      if (strpos(($justc . "|"), ($ifthere . "|")) !== false && strpos($divcont, ("|" . explode("`", substr($pc,1))[0] . $jjustc)) !== false) $jjustc="|" . explode("`", substr($pc,1))[0] . $jjustc;
      $thiscont=str_replace($divcont, str_replace($jjustc, "", $divcont), $thiscont);
      //file_put_contents("xxx.zxcokay","\nifthere=" . $ifthere . "\njjustc=" . $jjustc . "\ndivcont=" . str_replace($jjustc, "", $divcont));
      file_put_contents(dirname(__FILE__) . "/signature_signature.php", $thiscont);
      }
      }
      }
    }
} else if (isset($_POST['sscoords'])) {
    $pc=str_replace("@!@","",$_POST['sscoords']);
    $thiscont=file_get_contents(dirname(__FILE__) . "/signature_signature.php");
    if (strpos($thiscont, ";" . my_s_s_server_remote_addr() . ";") !== false) {
      $predivcont=explode('|',explode(";" . my_s_s_server_remote_addr() . ";", $thiscont)[1])[0];
      $divcont=explode('"',explode(";" . my_s_s_server_remote_addr() . ";", $thiscont)[1])[0];
      //file_put_contents("xx.z",substr(($pc . " "),0,1));
      if (substr(($pc . " "),0,1) == "|") {
      $ifthere="|" . explode("`", substr($pc,1))[0] . "`";

      if (strpos($divcont, $pc) === false) {
      if (strpos($divcont, $ifthere) !== false) {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";" . $divcont, ";" . my_s_s_server_remote_addr() . ";" . str_replace($ifthere,$pc . "`",$divcont), $thiscont);
      } else {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";" . $divcont, ";" . my_s_s_server_remote_addr() . ";" . $divcont . $pc, $thiscont);
      }
      } else if (strpos($divcont, $ifthere) !== false) {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";" . $divcont, ";" . my_s_s_server_remote_addr() . ";" . str_replace($ifthere,$pc . "`",$divcont), $thiscont);
      }
      
      } else if (strpos($divcont, "|") !== false && $predivcont != "") {
      if ($pc != $predivcont) {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";" . $predivcont, ";" . my_s_s_server_remote_addr() . ";" . $pc, $thiscont);
      }
      } else if (strpos($divcont, "|") !== false) {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";", ";" . my_s_s_server_remote_addr() . ";" . $pc, $thiscont);
      } else {
      $thiscont=str_replace(";" . my_s_s_server_remote_addr() . ";" . $divcont, ";" . my_s_s_server_remote_addr() . ";" . $pc, $thiscont);
      }
      
    } else {
      $thiscont=str_replace('"' . ']' . ';', '",' . "\n" . '"' . ";" . my_s_s_server_remote_addr() . ";" . $pc . '"' . ']' . ';', $thiscont);
    }
    file_put_contents(dirname(__FILE__) . "/signature_signature.php", $thiscont);
    $plusurl="";
    if (isset($_POST['url'])) $plusurl="?url=" . urldecode($_POST['url']);
    if (substr(($pc . " "),0,1) != "|") header("Location: ./signature_signature.html" . $plusurl);
} else {
    $thiscont=file_get_contents(dirname(__FILE__) . "/signature_signature.php");
    if (strpos($thiscont, ";" . my_s_s_server_remote_addr() . ";") !== false) {
      $divcont=explode('"',explode(";" . my_s_s_server_remote_addr() . ";", $thiscont)[1])[0];
      echo "<!doctype html><html><body onload=\" if (parent.document.getElementById('longsignature')) {  parent.document.getElementById('longsignature').innerHTML='" . $divcont . "'; }  \"></body></html>";
    }
}
//}
?>
