<?php
// macos_say_record.php
// Supervise and synchronize 'say [words]' (say) some text

if (isset($_GET['audiosize'])) {
//  if (file_exists('HTTP://www.rjmprogramming.com.au/MarkItUp/html/audio/audio.wav')) {
    if (isset($_GET['getmecontent'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'HTTP://www.rjmprogramming.com.au/MarkItUp/html/audio/audio.wav');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
    echo "<html><body onload=\" parent.document.getElementById('audioname').value='audiocapture.wav'; parent.document.getElementById('daudiolater').innerHTML='<audio id=thataudio controls autoplay><source type=audio/x-wav src=" . "data:audio/x-wav;base64," . base64_encode($output) . "></source></audio>&nbsp;<a style=display:inline-block;text-decoration:none;cursor:pointer;font-size:84px; onclick=emailit(); title=Email>&#128231;</a><div id=ifem style=display:inline-block;></div>';\"><p>" . strlen($output) . "</p><div>data:audio/x-wav;base64," . base64_encode($output) . "</div></body></html>";
    } else {
    //$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
    //$ct=file_get_contents('HTTP://www.rjmprogramming.com.au/MarkItUp/html/audio/audio.wav',false,$context);
    //file_put_contents("x.x",strlen($ct));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'HTTP://www.rjmprogramming.com.au/MarkItUp/html/audio/audio.wav');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
    echo "<html><body><p>" . strlen($output) . "</p><div></div></body></html>";
    }
//  } else {    
//    echo "<html><body><p>-1</p><div></div></body></html>";
//  }
  exit;
}

$hidden="hidden";
$sosw="";
 $thwords="Word Suggestion(s) for Voiceover Purposes"; 
if (PHP_OS == "Darwin") { $hidden="visible";  $sosw="Supervise and synchronize 'say [words]' or "; $thwords="Words";   }
$mms="My macOS say";
$aname="";
$precursur="";
$thecontent="";
$tastuff="";
$daudio="";
$audiois="";
$dcv="";
$langrest="";
$htmltop="<html>";
$sayprefix="";
$langsuffix="";
$voicecode="";
$voicesrest="";
$defvoice="";
$retdefvoice="";
$langcode="";
$bestext="aiff";

if (isset($_POST['mediais'])) {
  $audiois="<" . explode("/",explode("ata:", str_replace(" ","+",urldecode($_POST['mediais'])))[1])[0] . " id=thataudio controls autoplay><source type=" . explode(";",explode("ata:", str_replace(" ","+",urldecode($_POST['mediais'])))[1])[0] . " src=" . str_replace(" ","+",urldecode($_POST['mediais'])) . "></source></" . explode("/",explode("ata:", str_replace(" ","+",urldecode($_POST['mediais'])))[1])[0] . ">&nbsp;<a style=display:inline-block;text-decoration:none;cursor:pointer;font-size:84px; onclick=emailit(); title=Email>&#128231;</a><div id=ifem style=display:inline-block;></div>";
  $thecontent=str_replace(" ","+",urldecode($_POST['mediais']));
  $aname="\n document.getElementById('audioname').value='" . str_replace("+"," ",urldecode($_POST['audioname'])) . "'; \n";
  $mms="My media share";
}

if (isset($_GET['saythis'])) {
    $tastuff=str_replace("+"," ",urldecode($_GET['saythis']));
} else if (isset($_GET['saythis'])) {
    $tastuff=str_replace("+"," ",urldecode($_POST['saythis']));
}

$types = ["audio/x-m4r","audio/wav","audio/x-wav","audio/x-pn-realaudio","audio/x-mpegurl","audio/x-aiff","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"];
$exts = [".m4r",".wav",".wav",".ram",".m3u",".aiff",".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"];


$sayvoices="Alex                en_US    # Most people recognize me by my voice.
Alice               it_IT    # Salve, mi chiamo Alice e sono una voce italiana.
Alva                sv_SE    # Hej, jag heter Alva. Jag är en svensk röst.
Amelie              fr_CA    # Bonjour, je m’appelle Amelie. Je suis une voix canadienne.
Anna                de_DE    # Hallo, ich heiße Anna und ich bin eine deutsche Stimme.
Carmit              he_IL    # שלום. קוראים לי כרמית, ואני קול בשפה העברית.
Damayanti           id_ID    # Halo, nama saya Damayanti. Saya berbahasa Indonesia.
Daniel              en_GB    # Hello, my name is Daniel. I am a British-English voice.
Diego               es_AR    # Hola, me llamo Diego y soy una voz española.
Ellen               nl_BE    # Hallo, mijn naam is Ellen. Ik ben een Belgische stem.
Fiona               en_scotland # Hello, my name is Fiona. I am a Scottish-English voice.
Fred                en_US    # I sure like being inside this fancy computer
Ioana               ro_RO    # Bună, mă cheamă Ioana . Sunt o voce românească.
Joana               pt_PT    # Olá, chamo-me Joana e dou voz ao português falado em Portugal.
Jorge               es_ES    # Hola, me llamo Jorge y soy una voz española.
Juan                es_MX    # Hola, me llamo Juan y soy una voz mexicana.
Kanya               th_TH    # สวัสดีค่ะ ดิฉันชื่อKanya
Karen               en_AU    # Hello, my name is Karen. I am an Australian-English voice.
Kyoko               ja_JP    # こんにちは、私の名前はKyokoです。日本語の音声をお届けします。
Laura               sk_SK    # Ahoj. Volám sa Laura . Som hlas v slovenskom jazyku.
Lekha               hi_IN    # नमस्कार, मेरा नाम लेखा है. मैं हिन्दी में बोलने वाली आवाज़ हूँ.
Luca                it_IT    # Salve, mi chiamo Luca e sono una voce italiana.
Luciana             pt_BR    # Olá, o meu nome é Luciana e a minha voz corresponde ao português que é falado no Brasil
Maged               ar_SA    # مرحبًا اسمي Maged. أنا عربي من السعودية.
Mariska             hu_HU    # Üdvözlöm! Mariska vagyok. Én vagyok a magyar hang.
Mei-Jia             zh_TW    # 您好，我叫美佳。我說國語。
Melina              el_GR    # Γεια σας, ονομάζομαι Melina. Είμαι μια ελληνική φωνή.
Milena              ru_RU    # Здравствуйте, меня зовут Milena. Я – русский голос системы.
Moira               en_IE    # Hello, my name is Moira. I am an Irish-English voice.
Monica              es_ES    # Hola, me llamo Monica y soy una voz española.
Nora                nb_NO    # Hei, jeg heter Nora. Jeg er en norsk stemme.
Paulina             es_MX    # Hola, me llamo Paulina y soy una voz mexicana.
Samantha            en_US    # Hello, my name is Samantha. I am an American-English voice.
Sara                da_DK    # Hej, jeg hedder Sara. Jeg er en dansk stemme.
Satu                fi_FI    # Hei, minun nimeni on Satu. Olen suomalainen ääni.
Sin-ji              zh_HK    # 您好，我叫 Sin-ji。我講廣東話。
Tessa               en_ZA    # Hello, my name is Tessa. I am a South African-English voice.
Thomas              fr_FR    # Bonjour, je m’appelle Thomas. Je suis une voix française.
Ting-Ting           zh_CN    # 您好，我叫Ting-Ting。我讲中文普通话。
Veena               en_IN    # Hello, my name is Veena. I am an Indian-English voice.
Victoria            en_US    # Isn't it nice to have a computer that will talk to you?
Xander              nl_NL    # Hallo, mijn naam is Xander. Ik ben een Nederlandse stem.
Yelda               tr_TR    # Merhaba, benim adım Yelda. Ben Türkçe bir sesim.
Yuna                ko_KR    # 안녕하세요. 제 이름은 Yuna입니다. 저는 한국어 음성입니다.
Yuri                ru_RU    # Здравствуйте, меня зовут Yuri. Я – русский голос системы.
Zosia               pl_PL    # Witaj. Mam na imię Zosia, jestem głosem kobiecym dla języka polskiego.
Zuzana              cs_CZ    # Dobrý den, jmenuji se Zuzana. Jsem český hlas.
";

// Define default language.
$GLOBALS['_DLANG']='en';

// Define all available languages.
// WARNING: uncomment all available languages

$GLOBALS['_LANG'] = array(
'af-Afrikaans', // afrikaans.
'ar-Arabic', // arabic.
'bg-Bulgarian', // bulgarian.
'ca-Catalan', // catalan.
'cs-Czech', // czech.
'da-Danish', // danish.
'de-German', // german.
'el-Greek', // greek.
'en-English', // english.
'es-Spanish', // spanish.
'et-Estonian', // estonian.
'fi-Finnish', // finnish.
'fr-French', // french.
'gl-Galician', // galician.
'he-Hebrew', // hebrew.
'hi-Hindi', // hindi.
'hr-Croatian', // croatian.
'hu-Hungarian', // hungarian.
'id-Indonesian', // indonesian.
'it-Italian', // italian.
'ja-Japanese', // japanese.
'ko-Korean', // korean.
'ka-Georgian', // georgian.
'lt-Lituanian', // lithuanian.
'lv-Latvian', // latvian.
'ms-Malay', // malay.
'nl-Dutch', // dutch.
'no-Norwegian', // norwegian.
'pl-Polish', // polish.
'pt-Portuguese', // portuguese.
'ro-Romanian', // romanian.
'ru-Russian', // russian.
'sk-Slovak', // slovak.
'sl-Slovenian', // slovenian.
'sq-Albanian', // albanian.
'sr-Serbian', // serbian.
'sv-Swedish', // swedish.
'th-Thai', // thai.
'tr-Turkish', // turkish.
'uk-Ukrainian', // ukrainian.
'zh-Chinese' // chinese.
);

// Detect language from user agent browser ... thanks to https://stackoverflow.com/questions/3770513/detect-browser-language-in-php
function lixlpixel_get_env_var($Var) {
     global $GLOBALS, $langrest;
     if (empty($GLOBALS[$Var])) {
         $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
         $GLOBALS['_SERVER'][$Var] : (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var])) ? $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
     }
}

function lixlpixel_detect_lang($defl) {
     global $GLOBALS, $langrest, $sayvoices, $voicecode, $voicesrest, $tastuff, $defvoice, $retdefvoice;
     $voicesprefix="";
     $voicessuffix="";
     $selected=" selected";
     $M="";
     // Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
     lixlpixel_get_env_var('HTTP_ACCEPT_LANGUAGE');
     lixlpixel_get_env_var('HTTP_USER_AGENT');

     $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
     $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
     
     if ("$_AL" == "" && "$_UA" == "") {
     $_AL=strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);
     $_UA=strtolower($_SERVER['HTTP_USER_AGENT']);
     }
     
     if ($defl != "") {
     $_AL=strtolower($defl);
     $_UA=strtolower($defl);
     }
     
     // Try to detect Primary language if several languages are accepted.
     foreach ($GLOBALS['_LANG'] as $K) {
         $sayps=explode(" " . strtolower(explode("-", $K)[0]) . "_", $sayvoices);
         if (strpos($_AL, explode("-", $K)[0]) === 0) {  
           if (sizeof($sayps) > 1) {
             for ($ii=1; $ii<sizeof($sayps); $ii++) {
             $thisname=trim(explode("\n", $sayps[-1 + $ii])[-1 + sizeof(explode("\n", $sayps[-1 + $ii]))]);
             $thisnuance=strtolower(explode("-", $K)[0]) . "_" . explode(" ", $sayps[$ii])[0];
             $thisdefwords=trim(explode("#",explode("\n", $sayps[$ii])[0])[1]);
             $voicesprefix.="<option value='" . $thisnuance . " " . $thisname . "'" . $selected . ">" . $thisname . " " . $thisnuance . " " . $thisdefwords . "</option>";
             if ($defvoice == ($thisnuance . " " . $thisname)) {  $tastuff=$thisdefwords;  } 
             if ($voicecode == "") { if ($defvoice != "") { $voicecode=$defvoice;   } else { $voicecode=$thisnuance . " " . $thisname; $retdefvoice=$thisdefwords; }  } 
             $selected="";
             }
           }
           $langrest.="<option value='" . explode("-", $K)[0] . "' selected>" . explode("-", $K)[1] . "</option>"; 
           $M=$K; 
         } else { 
           if (sizeof($sayps) > 1) {
             for ($ii=1; $ii<sizeof($sayps); $ii++) {
             $thisname=trim(explode("\n", $sayps[-1 + $ii])[-1 + sizeof(explode("\n", $sayps[-1 + $ii]))]);
             $thisnuance=strtolower(explode("-", $K)[0]) . "_" . explode(" ", $sayps[$ii])[0];
             $thisdefwords=trim(explode("#",explode("\n", $sayps[$ii])[0])[1]);
             if ($defvoice == ($thisnuance . " " . $thisname)) {  $tastuff=$thisdefwords;  $voicecode=$defvoice;   } 
             $voicessuffix.="<option value='" . $thisnuance . " " . $thisname . "'>" . $thisname . " " . $thisnuance . " " . $thisdefwords . "</option>";
             }
           }
           $langrest.="<option value='" . explode("-", $K)[0] . "'>" . explode("-", $K)[1] . "</option>"; 
         }
     }
     
     $voicesrest=$voicesprefix . $voicessuffix;
     
     if ("$M" != "") { return $M; }

     // Try to detect any language if not yet detected.
     foreach ($GLOBALS['_LANG'] as $K) {
         if (strpos($_AL, explode("-", $K)[0]) !== false) { return $K; }
     }
     foreach ($GLOBALS['_LANG'] as $K) {
         //if(preg_match("/[[( ]{$K}[;,_-)]/",$_UA)) // matching other letters (create an error for seo spyder)
         return $K;
     }

     // Return default language if language is not yet detected.
     return $GLOBALS['_DLANG'];
}


function bestis() {
    global $bestext;
    $bestext = "aiff";
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    // you can add different browsers with the same way ..
    if (preg_match('/(chromium)[ \/]([\w.]+)/', $ua))
            $bestext = 'm4a';
    elseif(preg_match('/(chrome)[ \/]([\w.]+)/', $ua))
            $bestext = 'm4a';
    elseif(preg_match('/(safari)[ \/]([\w.]+)/', $ua))
            $bestext = 'aiff';
    elseif(preg_match('/(opera)[ \/]([\w.]+)/', $ua))
            $bestext = 'm4a';
    elseif(preg_match('/(msie)[ \/]([\w.]+)/', $ua))
            $bestext = 'm4a';
    elseif(preg_match('/(mozilla)[ \/]([\w.]+)/', $ua))
            $bestext = 'm4a';
    return $bestext;
}


if (isset($_GET['thevoice']) || isset($_POST['thevoice']) || isset($_GET['thelang']) || isset($_POST['thelang'])) {
  if (isset($_GET['thevoice'])) {
      $defvoice=str_replace("+"," ",urldecode($_GET['thevoice']));
  } else if (isset($_POST['thevoice'])) {
      $defvoice=str_replace("+"," ",urldecode($_POST['thevoice']));
  }
  if (isset($_GET['thelang'])) {
      $langcode=urldecode($_GET['thelang']);
  } else if (isset($_POST['thelang'])) {
      $langcode=urldecode($_POST['thelang']);
  } else if (isset($_GET['thevoice'])) {
      $langcode=explode("_",urldecode($_GET['thevoice']))[0];
  } else if (isset($_POST['thevoice'])) {
      $langcode=explode("_",urldecode($_POSTT['thevoice']))[0];
  }  
  $langcode = lixlpixel_detect_lang($langcode); //insert lang var system in a new var for conditional statement
  $langrest=str_replace(" selected", "", $langrest);
  if (isset($_GET['thelang'])) {
      $langcode=urldecode($_GET['thelang']);
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  } else if (isset($_POST['thelang'])) {
      $langcode=urldecode($_POST['thelang']);
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  } else if (isset($_GET['thevoice'])) {
      $langcode=explode("_",urldecode($_GET['thevoice']))[0];
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  } else if (isset($_POST['thevoice'])) {
      $langcode=explode("_",urldecode($_POSTT['thevoice']))[0];
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  }  
  if (isset($_GET['thevoice'])) {
      $voicesrest=str_replace(" selected", "", $voicesrest);
      $voicecode=str_replace("+"," ",urldecode($_GET['thevoice']));
      $voicesrest=str_replace("'" . $voicecode . "'", "'" . $voicecode . "' selected", $voicesrest);
      //echo $voicecode . " " . $voicesrest;
      //exit;
      $sayprefix=" -v " . trim(explode(" ",$voicecode)[1]) . "";
  } else if (isset($_POST['thevoice'])) {
      $voicesrest=str_replace(" selected", "", $voicesrest);
      $voicecode=str_replace("+"," ",urldecode($_POST['thevoice']));
      $voicesrest=str_replace("'" . $voicecode . "'", "'" . $voicecode . "' selected", $voicesrest);
      //echo $voicecode . " " . $voicesrest;
      //exit;
      $sayprefix=" -v " . trim(explode(" ",$voicecode)[1]) . "";
  }
  } else if (isset($_GET['thelang']) || isset($_POST['thelang'])) {
  $langcode = lixlpixel_detect_lang($langcode); //insert lang var system in a new var for conditional statement
  $langrest=str_replace(" selected", "", $langrest);
  if (isset($_GET['thelang'])) {
      $langcode=urldecode($_GET['thelang']);
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  } else {
      $langcode=urldecode($_POSTT['thelang']);
      $langrest=str_replace("'" . $langcode . "'", "'" . $langcode . "' selected", $langrest);
  }
} else { // Thanks to 

// Redirect to the correct location.
// Example Implementation aff var lang to name file
/*
echo 'The Language detected is: '.lixlpixel_detect_lang(); // For Demonstration
echo "<br />";    
*/
$langcode = lixlpixel_detect_lang($langcode); //insert lang var system in a new var for conditional statement

//echo "<br />";    

//echo $lang_var; // print var for trace

//echo "<br />";    
//exit;
}

$sayps=explode(" " . strtolower($langcode) . "_", $sayvoices);
if (sizeof($sayps) > 1) {
    if ($sayprefix == "") { $sayprefix=" -v " . trim(explode("#", $sayps[0])[-1 + sizeof(explode("#", $sayps[0]))]) . ""; }
}
$langsuffix='thelang=' . urlencode($langcode) . '&thevoice=' . urlencode($voicecode) . '&';
$htmltop="<!DOCTYPE html><html lang='" . urldecode($langcode) . "'>";
//$langchange=" lang='" . urldecode($langcode) . "'>";
if ($tastuff == "" && $retdefvoice != "") {
  $tastuff=$retdefvoice; 
}

bestis();

if (PHP_OS != "Darwin") {
$precursor=" if (two == twotwo) { alert('Sorry ... this only works with an underlying macOS or Mac OS X system that supports the say command.'); return false; } ";
}
if (PHP_OS == "Darwin" || 1 == 1) {
if (isset($_GET['saythis']) && isset($_GET['audioname'])) {
  if ($_GET['saythis'] != "") {
  //file_put_contents("xqx.xqx","say -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_GET['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  $thewords=str_replace("+"," ",urldecode($_GET['saythis']));
  //file_put_contents("xq.xq","say -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_GET['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  //file_put_contents("xq.xq",$sayprefix . " " . $voicecode . " " . $_POST['thevoice']);
  //exit;
  exec("say" . $sayprefix . " -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_GET['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  }
} else if (isset($_POST['saythis']) && isset($_POST['audioname'])) {
  if ($_POST['saythis'] != "") {
  //file_put_contents("xqqx.xqqx","say -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  $thewords=str_replace("+"," ",urldecode($_POST['saythis']));
  //echo "say -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords);
  //exit;
  //file_put_contents("xqq.xqq","say -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  //file_put_contents("xqv.xqv",$sayprefix . " " . $voicecode . " " . $_POST['thevoice']);
  //echo $sayprefix;
  //exit;
  exec("say" . $sayprefix . " -o " . dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname'])) . " " . str_replace("\n",",,,,,,",$thewords) . " > " . dirname(__FILE__) . "/sayout.out" . " 2> " . dirname(__FILE__) . "/sayerr.err");
  }
} else if (isset($_POST['mediais']) || ((!isset($_GET['saythis']) && !isset($_POST['saythis'])) || !isset($_GET['audioname']) || !isset($_POST['audioname']))) {
  if (!isset($_POST['mediais'])) { $audiois=""; }
  if (isset($_GET['audioname'])) {
    $ourmime="audio/x-aiff";
    $ourext=explode(".",str_replace("+"," ",urldecode($_GET['audioname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_GET['audioname']))))];
    for ($ib=0; $ib<sizeof($exts); $ib++) {
       if (strtolower("." . $ourext) == strtolower($exts[$ib])) $ourmime=$types[$ib];
    }
    $audiois="<audio id=thataudio controls autoplay><source type=" . $ourmime . " src=" . str_replace("+"," ",urldecode($_GET['audioname'])) . "?rand=" . rand(0,198765432) . "></source></audio>&nbsp;<a style='display:inline-block;text-decoration:none;cursor:pointer;font-size:84px;' onclick=emailit(); title=Email>&#128231;</a><div id=ifem style=display:inline-block;></div>";
    $thecontent="data:" . $ourmime . ";base64," . base64_encode(file_get_contents(dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_GET['audioname']))));
    $daudio="<audio id=thisaudio controls><source type=" . $ourmime . " src=" . $thecontent . "></source></audio>";
    //unlink(dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_GET['audioname'])));
  } else if (isset($_POST['audioname'])) {  
    $ourmime="audio/x-aiff";
    $ourext=explode(".",str_replace("+"," ",urldecode($_POST['audioname'])))[-1 + sizeof(explode(".",str_replace("+"," ",urldecode($_POST['audioname']))))];
    for ($ib=0; $ib<sizeof($exts); $ib++) {
       if (strtolower("." . $ourext) == strtolower($exts[$ib])) $ourmime=$types[$ib];
    }
    if ($audiois == "") {
    $audiois="<audio id=thataudio controls autoplay><source type=" . $ourmime . " src=" . str_replace("+"," ",urldecode($_POST['audioname'])) . "?rand=" . rand(0,198765432) . "></source></audio>";
    $thecontent="data:" . $ourmime . ";base64," . base64_encode(file_get_contents(dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname']))));
    }
    $daudio="<audio id=thisaudio controls><source type=" . $ourmime . " src=" . $thecontent . "></source></audio>";
    //unlink(dirname(__FILE__) . "/" . str_replace("+"," ",urldecode($_POST['audioname'])));
  }
  if (isset($_GET['saythis'])) {
    $tastuff=str_replace("+"," ",urldecode($_GET['saythis']));
  } else if (isset($_GET['saythis'])) {
    $tastuff=str_replace("+"," ",urldecode($_POST['saythis']));
  }
  if (isset($_GET['dummysaythis'])) {
    $dcv=str_replace("\n","&#10;",str_replace("+"," ",urldecode($_GET['dummysaythis'])));
    $dcv=str_replace("+"," ",urldecode($_GET['dummysaythis']));
    $tastuff=str_replace("+"," ",urldecode($_GET['dummysaythis']));
  } else if (isset($_GET['dummysaythis'])) {
    $dcv=str_replace("\n","&#10;",str_replace("+"," ",urldecode($_POST['dummysaythis'])));
    $dcv=str_replace("+"," ",urldecode($_POST['dummysaythis']));
    $tastuff=str_replace("+"," ",urldecode($_POST['dummysaythis']));
  }
  $xtastuff=$tastuff;
  if ($xtastuff == "") { $xtastuff="youllneverfindthis"; }
  echo $htmltop . "
<head>
<title>Voiceover ideas ... Supervise and synchronize 'say [words]' or Flash Player Record or Input audio/* capture</title>
<meta charset='utf-8'/>
<style>
textarea {
  white-space: pre-line;
}
</style>
<script type='text/javascript'>
  var two=2;
  var twotwo=2;
  var wasv='';
  var firstgo=true;
  var ewo=null;
  var ewf=null;
  var prevffs=-11;
  var ffs=-1;
  var vtrue=true;
  var twentythousand=20000;
  var altsubject='';
  
  function notwotwo() {
    twotwo=33;
    vtrue=false;
    twentythousand=200;
  }

  function copy_to_clipboard(containerid) {
    //var contentHolder = document.getElementById(containerid);
    document.getElementById(containerid).focus();
    // We will need a range object and a selection.
    var range = document.createRange(),
    selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    // Make the range select the entire content of the contentHolder paragraph.
    range.selectNodeContents(document.getElementById(containerid));

    // Add that range to the selection.
    selection.addRange(range);

    // Copy the selection to clipboard.
    document.execCommand('copy');

    // Clear selection if you want to.
    selection.removeAllRanges();
  }
  
  function thatencodeURIComponent(inz) {
    if (altsubject != '') { inz=altsubject; }
    return encodeURIComponent(inz);
  }
  
  function thisencodeURIComponent(inz) {
    if (altsubject != '') { inz=altsubject; }
    if (inz.indexOf('My media share') == 0) {
      return encodeURIComponent('My media share ... ')
    } 
    return encodeURIComponent(inz);
  }
  
  function emailit() {
  var selector;
  var audios=document.getElementsByTagName('audio');
  if (audios.length == 0) {  audios=document.getElementsByTagName('video');   }
  for (var iu=0; iu<audios.length; iu++) {
  if (iu == 0) {
  var tois=prompt('Who do you want to email to?  Optionally hashtag (#) separate your own personal subject line to the email (eg. theemail@theemailplace.com#Hello there, it is moi.)', '');
  if (tois == null) { tois=''; }
  if (tois.indexOf('@') != -1) {
  var alts=tois.split('#');
  if (alts.length > 1) { altsubject=alts[1]; tois=alts[0]; } 
  document.getElementById('result').focus();
  var text=document.getElementById('result').innerHTML;
  // Now copy whatever inside the textarea to clipboard ... vs copy_to_clipboard('result'); 
  if (navigator.clipboard != undefined) { //Chrome
        navigator.clipboard.writeText(text).then(function () {
            console.log('Async: Copying to clipboard was successful!');
        }, function (err) {
  selector = document.querySelector('#result');
  selector.select();
  document.execCommand('copy');
        });
    }
    else if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData('Text', text);
    } else {
  selector = document.querySelector('#result');
  selector.select();
  document.execCommand('copy');
    }
    var mms='" . $mms . "';
  //var zhr = new XMLHttpRequest();
  //var zform=new FormData();
  //zform.append('to', tois);
  //zform.append('subj', 'My macOS say ... ');
  //zform.append('tdhuhta', encodeURIComponent(audios[iu].outerHTML));
  //if (1 == 1) {
  if (document.getElementById('audioname').value.indexOf('audio') == 0 && (document.getElementById('audioname').value.indexOf('.wav') == -1 && document.getElementById('thewords').innerHTML.indexOf(('" . explode("'",explode("\n",$xtastuff)[0])[0] . "').trim()) == 0 && document.getElementById('slangcode').value != '' && document.getElementById('svoicecode').value != '')) {
  //ewo=window.open('//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php?to=' + encodeURIComponent(tois) + '&subj=' + thatencodeURIComponent('My macOS say ... ' + document.getElementById('slangcode').options[document.getElementById('slangcode').selectedIndex].text + ' ' + document.getElementById('svoicecode').value.replace(' ',' voice ') + ' saying ' + document.getElementById('thewords').value.split(String.fromCharCode(10))[0].replace(/\'/g,String.fromCharCode(39)) + ' ... ') + '&sliceminusten=' + encodeURIComponent(text.slice(-10)) + '&whatweneed7=qmpg6789','_blank','top=50,left=50,height=600,width=500');
  if (document.URL.indexOf('rjmprogramming.com.au/') != -1) {
  document.getElementById('ifem').innerHTML=\"<iframe onload=checkz(this); src='//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php?to=\" + encodeURIComponent(tois) + '&subj=' + thisencodeURIComponent(mms + ' ... ' + document.getElementById('slangcode').options[document.getElementById('slangcode').selectedIndex].text + ' ' + document.getElementById('svoicecode').value.replace(' ',' voice ') + ' saying ' + document.getElementById('thewords').value.split(String.fromCharCode(10))[0].replace(/\'/g,String.fromCharCode(39)) + ' ... ') + '&sliceminusten=' + encodeURIComponent(text.slice(-10)) + \"' style=width:500px;height:600px;></iframe>\"; 
  } else {
  ewo=window.open('//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php?to=' + encodeURIComponent(tois) + '&subj=' + thisencodeURIComponent(mms + ' ... ' + document.getElementById('slangcode').options[document.getElementById('slangcode').selectedIndex].text + ' ' + document.getElementById('svoicecode').value.replace(' ',' voice ') + ' saying ' + document.getElementById('thewords').value.split(String.fromCharCode(10))[0].replace(/\'/g,String.fromCharCode(39)) + ' ... ') + '&sliceminusten=' + encodeURIComponent(text.slice(-10)) + '','_blank','top=50,left=50,height=600,width=500');
  }
  } else {
  if (document.URL.indexOf('rjmprogramming.com.au/') != -1) {
  document.getElementById('ifem').innerHTML=\"<iframe onload=checkz(this); src='//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php?to=\" + encodeURIComponent(tois) + '&subj=' + thisencodeURIComponent(mms + ' ... ') + '&sliceminusten=' + encodeURIComponent(text.slice(-10)) + \"' style=width:500px;height:600px;></iframe>\"; 
  } else {
  ewo=window.open('//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php?to=' + encodeURIComponent(tois) + '&subj=' + thisencodeURIComponent(mms + ' ... ') + '&sliceminusten=' + encodeURIComponent(text.slice(-10)),'_blank','top=50,left=50,height=580,width=500');
  }
  }
  //} //else {
  //zhr.open('post', '//www.rjmprogramming.com.au/HTMLCSS/emailhtml.php', true);
  //zhr.setRequestHeader('Access-Control-Allow-Origin', '*');
  //zhr.setRequestHeader('Access-Control-Allow-Methods', 'POST');
  //zhr.send(zform);
  //}
  }
  }
  }
  }  

  function thenreload() {
    //alert('twotwo=' + twotwo);
    if (twotwo != 2) {
    //alert(4);
    document.getElementById('thewords').name='xsaythisx';
    document.getElementById('dtemp').innerHTML='<form target=_self style=display:none; action=./macos_say_record.php?rand=' + Math.floor(Math.random() * 198765432) + ' method=POST><input type=hidden name=mediais value=\"' + document.getElementById('result').innerHTML + '\"></input><input type=hidden name=audioname value=\"' + document.getElementById('audioname').value + '\"></input><input type=submit style=display:none; value=Submit id=mysb></input></form>';
    //alert(44);
    document.getElementById('mysb').click();
    //alert(444);
    } else {
    location.href=document.URL.split('?')[0].split('#')[0] + '?" . $langsuffix . "audioname=' + encodeURIComponent(document.getElementById('audioname').value) + '&dummysaythis=' + encodeURIComponent(document.getElementById('thewords').value) + '&rand=' + Math.floor(Math.random() * 198764764);
    }
  }
  
  function resultchange() {
    " . $aname . " 
    if (document.getElementById('result').value == '') {
    setTimeout(resultchange, 2000);
    } else if (firstgo) {
    document.getElementById('saysub').visibility='visible';
    firstgo=false;
    setTimeout(resultchange, 6000);
    } else if (window.opener) {
    document.getElementById('saysub').visibility='visible';
    if (document.getElementById('result').value.indexOf(':video/') != -1) {
    window.opener.document.getElementById('vurl').value=document.getElementById('result').value;
    } else {
    window.opener.document.getElementById('aurl').value=document.getElementById('result').value;
    }
    window.opener.document.getElementById('daudio').innerHTML='" . $daudio . "'; 
    window.opener.atab(window.opener.document.getElementById('aurl'));
    }
  }
  
  function saysubv() {
    //document.title='0';
    if (('' + document.getElementById('saysub').style.visibility).toLowerCase().indexOf('visible') == -1) {
    //document.title+='1';
      if (document.getElementById('result').innerHTML != '') {
    //document.title+='2';
      document.getElementById('saysub').style.visibility='visible';
      twotwo=31;
      } else {
    //document.title+='3';
      setTimeout(saysubv, 2000);
      }
    }
  }
  
  function anotherlook() {
      document.getElementById('checkflash').src=document.getElementById('checkflash').src.split('#')[0].split('?')[0] + '?audiosize=y&rand=' + Math.floor(Math.random() * 198765432);
      //anotherlook();
  }
  
  function openflash() {
    ewf=window.open('//www.rjmprogramming.com.au/MarkItUp/html/index.htm?interested=y','_blank','top=250,left=100,height=250,width=300');
  }
  
  function checkz(iois) {
  if (iois != null) {
    var aconto = (iois.contentWindow || iois.contentDocument);
    if (aconto != null) {
     if (aconto.document) { aconto = aconto.document; }
     if (aconto.body != null) {
      aconto.getElementById('status').innerHTML='Copy and Paste Done Below ...';
      aconto.getElementById('taready').value=document.getElementById('result').value;
      aconto.getElementById('sub').click();
     }
    }
  }
  }
  
  function checkff(iois) {
  if (iois != null) {
    var aconto = (iois.contentWindow || iois.contentDocument);
    if (aconto != null) {
     if (aconto.document) { aconto = aconto.document; }
     if (aconto.body != null) {
      if (iois.src.indexOf('getmecontent=') != -1) {
      document.getElementById('result').innerHTML=aconto.body.innerHTML.split('</div>')[0].split('>')[eval(-1 + aconto.body.innerHTML.split('</div>')[0].split('>').length)];
      if (ewf) { ewf.close(); ewf=null; } 
      } else if (eval('' + prevffs) < -1) {
      prevffs=eval('' + aconto.body.innerHTML.split('</p>')[0].split('>')[eval(-1 + aconto.body.innerHTML.split('</p>')[0].split('>').length)]);
      ffs=prevffs;
      //alert(ffs);
      //document.title='' + ffs;
      setTimeout(anotherlook, 5000);
      } else {
      ffs=eval('' + aconto.body.innerHTML.split('</p>')[0].split('>')[eval(-1 + aconto.body.innerHTML.split('</p>')[0].split('>').length)]);
      if (eval('' + ffs) != eval('' + prevffs)) {
      //document.title='' + ffs;
      iois.src=iois.src.split('#')[0].split('?')[0] + '?audiosize=y&getmecontent=y';
      } else {
      setTimeout(anotherlook, 5000);
      }
      }
     }
    }
  }
  }
</script>
</head>
<body onload='saysubv(); resultchange();'>
<h1>Voiceover Ideas</h1>
<h2>" . $sosw . "<a style=text-decoration:underline;cursor:pointer; onclick=openflash();>Flash Player Record</a> or <div style='display:inline-block;width:98px;height:30px;overflow:hidden;border-top:1px solid black;border-bottom:1px solid black;border-left:2px solid yellow;border-right:1px solid yellow;'><iframe style='width:173px;height:228px;margin-top:-194px;' src='HTMLCSS/client_browsing.htm?d=" . rand(0,18765432) . "'></iframe></div></h2>
<h3>RJM Programming - July, 2020</h3>
<div id=daudiolater>" . $audiois . "</div>
<form id=myform onsubmit=\"" . $precursor . " document.getElementById('myform').style.cursor='progress'; document.body.style.cursor='progress'; if (twotwo != 2) { thenreload(); } else { setTimeout(thenreload,twentythousand); } return vtrue;\" target=dothework action=./macos_say_record.php method=POST>
<input type=hidden name=thelang id=ilangcode value='" . $langcode . "'></input><input type=hidden name=thevoice id=ivoicecode value='" . $voicecode . "'></input>
<select style=display:inline-block; onchange=\"document.getElementById('ilangcode').value=this.value; if (document.getElementById('ivoicecode').value.indexOf(this.value) == 0) {  location.href=document.URL.split('?')[0].split('#')[0] + '?thelang=' + encodeURIComponent(this.value) + '&thevoice=' + encodeURIComponent(document.getElementById('ivoicecode').value);   } else { location.href=document.URL.split('?')[0].split('#')[0] + '?thelang=' + encodeURIComponent(this.value); }\" id=slangcode value='" . $langcode . "'><option value=''>Optionally select language code to match a voice to ...</option>
" . $langrest . "
</select>
<select style=display:inline-block; onchange=\"document.getElementById('ivoicecode').value=this.value; location.href=document.URL.split('?')[0].split('#')[0] + '?thelang=' + encodeURIComponent(this.value.split('_')[0]) + '&thevoice=' + encodeURIComponent(this.value);\" id=svoicecode value='" . $voicecode . "'><option value=''>Optionally select voice name to suit ...</option>
" . $voicesrest . "
</select><table border=20>
<tr><th>" . $thwords . "</th><th>Record to <input type=text name=audioname id=audioname value='audiocapture." . $bestext . "'></input></th></tr>
<tr><td style=vertical-align:top;><textarea onblur=\"document.getElementById('result').innerHTML='';\" placeholder=\"" . $dcv . "\" id=thewords name=saythis cols=80 rows=10 value=''>" . $tastuff . "</textarea></td><td style=vertical-align:top;><input style='width:100%;height:100px;background-color:yellow;visibility:" . $hidden . ";' id=saysub type=submit value='Record These Words'></input><br><br><textarea style='width:98%;background-color:lightgreen;' id=result cols=80 rows=10>" . $thecontent . "</textarea></td></tr>
</table>
</form>
<iframe name=dothework id=dothework style=display:none; src=macos_say_record.php></iframe>
<iframe onload=checkff(this); name=checkflash id=checkflash style=display:none; src='./macos_say_record.php?audiosize=y'></iframe>
<div id=dtemp></div>
</body>
</html>";
} 
} else {
 echo "<html><body><p>This PHP web application only works with macOS and its 'say [words]' command line Text to Speech and/or Audio functionality.</p></body><html>";
 exit;
}
?>
