<?php
if(isset($_POST['jsfiddle_url'])) {
    $jsfiddle_url = $_POST['jsfiddle_url'];
    if(!preg_match("~^(?:f|ht)tps?://~i", $jsfiddle_url)) {
        $jsfiddle_url = "https://" . $jsfiddle_url;
    }
    $reformed_url = str_replace('jsfiddle.net', 'fiddle.jshell.net', $jsfiddle_url);
    $reformed_url = str_replace('/show', '', $reformed_url);
    // Fix the second jsfiddle url to also use fiddle.jshell
    $jsfiddle_url = str_replace('jsfiddle.net', 'fiddle.jshell.net', $jsfiddle_url);
    $curl_command = "curl '" . $reformed_url . "//show/' -H 'Referer: " . $jsfiddle_url . "//' --output 'fiddle.html'";
    echo "<pre>" . $curl_command . "</pre>";

exec ($curl_command);

//$url = reformed_url;
//$referer = jsfiddle_url;
//$outputFile = 'fiddle.html';
//$curl = curl_init();
//curl_setopt($curl, CURLOPT_URL, $url);
//curl_setopt($curl, CURLOPT_REFERER, $referer);
//$fileHandle = fopen($outputFile, 'w');
//curl_setopt($curl, CURLOPT_FILE, $fileHandle);
//curl_exec($curl);
//fclose($fileHandle);

if (curl_errno($curl)) {
    echo 'cURL error: ' . curl_error($curl);
} else {
    echo 'Request completed successfully.';
    echo '<a target="_blank" href="fiddle.html">link</a>';
}
curl_close($curl);
}


// Display the form
echo '<form method="post">';
echo '    <label for="jsfiddle_url">JSFiddle URL:</label>';
echo '    <input type="text" name="jsfiddle_url" value="https://jsfiddle.net/aoikurayami/745t8aeh/2">';
echo '    <input type="submit" value="Download">';
echo '</form>';

// Display the iframe with the content of the downloaded file
if (isset($outputFile)) {
    echo '<hr>';
    echo '<h2>Contents of fiddle.html:</h2>';
    echo '<iframe src="' . $outputFile . '" frameborder="0" width="100%" height="500"></iframe>';
}
?>

<?php
    // Allow or disallow source viewing
    define("ALLOW_SOURCE", TRUE);
    define("ALLOW_TITLE", TRUE);
    if(ALLOW_SOURCE && isset($_GET['source'])){
        highlight_file(__FILE__);
        exit(0);
    }
?>
<a target="_blank" href="?source">Source Code</a>
