/**
 * download http request recursive (If found HTTP 3xx)
 * @param string $url               to download
 * @param resource $toSource        to download
 * @return array                    retuns array
*/
function downloadSource($url, $toSource, $caller)
{
    $errno = 0;
    $errstr = '';
    ++$caller;
    if ($caller > MAX_LOOP) {
        return array('error' => 'Limit of ' . MAX_LOOP . ' redirects was exceeded, maybe there is a problem: ' . $url);
    }
    $uri = parse_url($url);
    $secure = strcasecmp($uri['scheme'], 'https') === 0;
    if ($secure) {
        $response = supportSSL();
        if ($response !== true) {
            return array('error' => $response);
        }
    }
    $port = isset($uri['port']) && strlen($uri['port']) > 0 ? (int) $uri['port'] : ($secure === true ? 443 : 80);
    $host = ($secure ? 'ssl://' : '') . $uri['host'];
    $fp = fsockopen($host, $port, $errno, $errstr, TIMEOUT);
    if ($fp === false) {
        return array('error' => 'SOCKET: ' . $errstr . '(' . (string) $errno . ')');
    } else {
        fwrite($fp, 'GET ' . (isset($uri['path']) && strlen($uri['path']) > 0 ? $uri['path'] : '/') . (isset($uri['query']) && strlen($uri['query']) > 0 ? '?' . $uri['query'] : '') . ' HTTP/1.0' . WOL . EOL);
        if (isset($uri['user'])) {
            $auth = base64_encode($uri['user'] . ':' . (isset($uri['pass']) ? $uri['pass'] : ''));
            fwrite($fp, 'Authorization: Basic ' . $auth . WOL . EOL);
        }
        if (isset($_SERVER['HTTP_ACCEPT']) && strlen($_SERVER['HTTP_ACCEPT']) > 0) {
            fwrite($fp, 'Accept: ' . $_SERVER['HTTP_ACCEPT'] . WOL . EOL);
        }
        if (isset($_SERVER['HTTP_USER_AGENT']) && strlen($_SERVER['HTTP_USER_AGENT']) > 0) {
            fwrite($fp, 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'] . WOL . EOL);
        }
        if (isset($_SERVER['HTTP_REFERER']) && strlen($_SERVER['HTTP_REFERER']) > 0) {
            fwrite($fp, 'Referer: ' . $_SERVER['HTTP_REFERER'] . WOL . EOL);
        }
        fwrite($fp, 'Host: ' . $uri['host'] . WOL . EOL);
        fwrite($fp, 'Connection: close' . WOL . EOL . WOL . EOL);
        $isRedirect = true;
        $isBody = false;
        $isHttp = false;
        $encode = null;
        $mime = null;
        $data = '';
        while (false === feof($fp)) {
            if (MAX_EXEC !== 0 && time() - INIT_EXEC >= MAX_EXEC) {
                return array('error' => 'Maximum execution time of ' . (string) (MAX_EXEC + 5) . ' seconds exceeded, configure this with ini_set/set_time_limit or "php.ini" (if safe_mode is enabled)');
            }
            $data = fgets($fp);
            if ($data === false) {
                continue;
            }
            if ($isHttp === false) {
                if (preg_match('#^HTTP[/]1[.]#i', $data) === 0) {
                    fclose($fp);
                    //Close connection
                    $data = '';
                    return array('error' => 'This request did not return a HTTP response valid');
                }
                $tmp = preg_replace('#(HTTP/1[.]\\d |[^0-9])#i', '', preg_replace('#^(HTTP/1[.]\\d \\d{3}) [\\w\\W]+$#i', '$1', $data));
                if ($tmp === '304') {
                    fclose($fp);
                    //Close connection
                    $data = '';
                    return array('error' => 'Request returned HTTP_304, this status code is incorrect because the html2canvas not send Etag');
                } else {
                    $isRedirect = preg_match('#^(301|302|303|307|308)$#', $tmp) !== 0;
                    if ($isRedirect === false && $tmp !== '200') {
                        fclose($fp);
                        $data = '';
                        return array('error' => 'Request returned HTTP_' . $tmp);
                    }
                    $isHttp = true;
                    continue;
                }
            }
            if ($isBody === false) {
                if (preg_match('#^location[:]#i', $data) !== 0) {
                    //200 force 302
                    fclose($fp);
                    //Close connection
                    $data = trim(preg_replace('#^location[:]#i', '', $data));
                    if ($data === '') {
                        return array('error' => '"Location:" header is blank');
                    }
                    $nextUri = $data;
                    $data = relativeToAbsolute($url, $data);
                    if ($data === '') {
                        return array('error' => 'Invalid scheme in url (' . $nextUri . ')');
                    }
                    if (isHttpUrl($data) === false) {
                        return array('error' => '"Location:" header redirected for a non-http url (' . $data . ')');
                    }
                    return downloadSource($data, $toSource, $caller);
                } else {
                    if (preg_match('#^content[-]length[:]( 0|0)$#i', $data) !== 0) {
                        fclose($fp);
                        $data = '';
                        return array('error' => 'source is blank (Content-length: 0)');
                    } else {
                        if (preg_match('#^content[-]type[:]#i', $data) !== 0) {
                            $data = strtolower($data);
                            if (preg_match('#[;](\\s|)+charset[=]#', $data) !== 0) {
                                $tmp2 = preg_split('#[;](\\s|)+charset[=]#', $data);
                                $encode = isset($tmp2[1]) ? trim($tmp2[1]) : null;
                            }
                            $mime = trim(preg_replace('/[;]([\\s\\S]|)+$/', '', str_replace('content-type:', '', str_replace('/x-', '/', $data))));
                            if (in_array($mime, array('image/bmp', 'image/windows-bmp', 'image/ms-bmp', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'text/html', 'application/xhtml', 'application/xhtml+xml', 'image/svg+xml', 'image/svg-xml')) === false) {
                                fclose($fp);
                                $data = '';
                                return array('error' => $mime . ' mimetype is invalid');
                            }
                        } else {
                            if ($isBody === false && trim($data) === '') {
                                $isBody = true;
                                continue;
                            }
                        }
                    }
                }
            } else {
                if ($isRedirect === true) {
                    fclose($fp);
                    $data = '';
                    return array('error' => 'The response should be a redirect "' . $url . '", but did not inform which header "Localtion:"');
                } else {
                    if ($mime === null) {
                        fclose($fp);
                        $data = '';
                        return array('error' => 'Not set the mimetype from "' . $url . '"');
                    } else {
                        fwrite($toSource, $data);
                        continue;
                    }
                }
            }
        }
        fclose($fp);
        $data = '';
        if ($isBody === false) {
            return array('error' => 'Content body is empty');
        } else {
            if ($mime === null) {
                return array('error' => 'Not set the mimetype from "' . $url . '"');
            }
        }
        return array('mime' => $mime, 'encode' => $encode);
    }
}
/**
 * Callback to for proxy page
 */
function ac_templates_proxy()
{
    drupal_add_http_header('Content-Type', 'application/javascript');
    if (isset($_GET['callback']) && strlen($_GET['callback']) > 0) {
        $param_callback = $_GET['callback'];
    }
    if (isset($_SERVER['HTTP_HOST']) === FALSE || strlen($_SERVER['HTTP_HOST']) === 0) {
        $response = array('error' => 'The client did not send the Host header');
    } else {
        if (isset($_SERVER['SERVER_PORT']) === FALSE) {
            $response = array('error' => 'The Server-proxy did not send the PORT (configure PHP)');
        } else {
            if (MAX_EXEC < 10) {
                $response = array('error' => 'Execution time is less 15 seconds, configure this with ini_set/set_time_limit or "php.ini" (if safe_mode is enabled), recommended time is 30 seconds or more');
            } else {
                if (MAX_EXEC <= TIMEOUT) {
                    $response = array('error' => 'The execution time is not configured enough to TIMEOUT in SOCKET, configure this with ini_set/set_time_limit or "php.ini" (if safe_mode is enabled), recommended that the "max_execution_time =;" be a minimum of 5 seconds longer or reduce the TIMEOUT in "define(\'TIMEOUT\', ' . TIMEOUT . ');"');
                } else {
                    if (isset($_GET['url']) === FALSE || strlen($_GET['url']) === 0) {
                        $response = array('error' => 'No such parameter "url"');
                    } else {
                        if (isHttpUrl($_GET['url']) === FALSE) {
                            $response = array('error' => 'Only http scheme and https scheme are allowed');
                        } else {
                            if (preg_match('#[^A-Za-z0-9_[.]\\[\\]]#', $param_callback) !== 0) {
                                $response = array('error' => 'Parameter "callback" contains invalid characters');
                                $param_callback = JSLOG;
                            } else {
                                if (createFolder() === FALSE) {
                                    $err = get_error();
                                    $response = array('error' => 'Can not create directory' . ($err !== NULL && isset($err['message']) && strlen($err['message']) > 0 ? ': ' . $err['message'] : ''));
                                    $err = NULL;
                                } else {
                                    $http_port = (int) $_SERVER['SERVER_PORT'];
                                    $tmp = createTmpFile($_GET['url'], FALSE);
                                    if ($tmp === FALSE) {
                                        $err = get_error();
                                        $response = array('error' => 'Can not create file' . ($err !== NULL && isset($err['message']) && strlen($err['message']) > 0 ? ': ' . $err['message'] : ''));
                                        $err = NULL;
                                    } else {
                                        $response = downloadSource($_GET['url'], $tmp['source'], 0);
                                        fclose($tmp['source']);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (is_array($response) && isset($response['mime']) && strlen($response['mime']) > 0) {
        clearstatcache();
        if (FALSE === file_exists($tmp['location'])) {
            $response = array('error' => 'Request was downloaded, but file can not be found, try again');
        } else {
            if (filesize($tmp['location']) < 1) {
                $response = array('error' => 'Request was downloaded, but there was some problem and now the file is empty, try again');
            } else {
                $extension = str_replace(array('image/', 'text/', 'application/'), '', $response['mime']);
                $extension = str_replace(array('windows-bmp', 'ms-bmp'), 'bmp', $extension);
                $extension = str_replace(array('svg+xml', 'svg-xml'), 'svg', $extension);
                $extension = str_replace('xhtml+xml', 'xhtml', $extension);
                $extension = str_replace('jpeg', 'jpg', $extension);
                $locationFile = preg_replace('#[.][0-9_]+$#', '.' . $extension, $tmp['location']);
                if (file_exists($locationFile)) {
                    unlink($locationFile);
                }
                if (rename($tmp['location'], $locationFile)) {
                    //set cache
                    setHeaders(FALSE);
                    remove_old_files();
                    if (CROSS_DOMAIN === 1) {
                        $mime = JsonEncodeString($response['mime'], TRUE);
                        $mime = $response['mime'];
                        if ($response['encode'] !== NULL) {
                            $mime .= ';charset=' . JsonEncodeString($response['encode'], TRUE);
                        }
                        $tmp = $response = NULL;
                        if (strpos($mime, 'image/svg') !== 0 && strpos($mime, 'image/') === 0) {
                            echo $param_callback, '("data:', $mime, ';base64,', base64_encode(file_get_contents($locationFile)), '");';
                        } else {
                            echo $param_callback, '("data:', $mime, ',', asciiToInline(file_get_contents($locationFile)), '");';
                        }
                    } else {
                        $tmp = $response = NULL;
                        $dir_name = dirname($_SERVER['SCRIPT_NAME']);
                        if ($dir_name === '\\/' || $dir_name === '\\') {
                            $dir_name = '';
                        }
                        if (strpos($locationFile, 'public://') === FALSE) {
                            $parse_file_location = explode('/', $locationFile);
                            $locationFile = sprintf('%s/%s', PATH, end($parse_file_location));
                        }
                        echo $param_callback, '(', JsonEncodeString(file_create_url($locationFile)), ');';
                    }
                    exit;
                } else {
                    $response = array('error' => 'Failed to rename the temporary file');
                }
            }
        }
    }
    if (is_array($tmp) && isset($tmp['location']) && file_exists($tmp['location'])) {
        //remove temporary file if an error occurred
        unlink($tmp['location']);
    }
    //errors
    setHeaders(TRUE);
    //no-cache
    remove_old_files();
    echo $param_callback, '(', JsonEncodeString('error: html2canvas-proxy-php: ' . $response['error']), ');';
}