Пример #1
0
function AbsoluteUrl($baseUrl, $url)
{
    if (!isHttpUrl($url)) {
        $url = JoinUrl($baseUrl, $url);
    }
    return NormalizePath($url);
}
Пример #2
0
 function DownloadFragments($cc, $manifest, $opt = array())
 {
     $start = 0;
     extract($opt, EXTR_IF_EXISTS);
     $this->ParseManifest($cc, $manifest);
     $segNum = $this->segStart;
     $fragNum = $this->fragStart;
     if ($start) {
         if ($segNum > 1) {
             if ($start % $this->fragsPerSeg) {
                 $segNum = (int) ($start / $this->fragsPerSeg + 1);
             } else {
                 $segNum = (int) ($start / $this->fragsPerSeg);
             }
         }
         $fragNum = $start - 1;
         $this->segStart = $segNum;
         $this->fragStart = $fragNum;
     }
     $this->lastFrag = $fragNum;
     $opt['cc'] = $cc;
     $opt['duration'] = 0;
     // Extract baseFilename
     $this->baseFilename = $this->media['url'];
     if (substr($this->baseFilename, -1) == '/') {
         $this->baseFilename = substr($this->baseFilename, 0, -1);
     }
     $this->baseFilename = RemoveExtension($this->baseFilename);
     if (strrpos($this->baseFilename, '/')) {
         $this->baseFilename = substr($this->baseFilename, strrpos($this->baseFilename, '/') + 1);
     }
     if (strpos($manifest, "?")) {
         $this->baseFilename = md5(substr($manifest, 0, strpos($manifest, "?"))) . "_" . $this->baseFilename;
     } else {
         $this->baseFilename = md5($manifest) . "_" . $this->baseFilename;
     }
     $this->baseFilename .= "Seg" . $segNum . "-Frag";
     if ($fragNum >= $this->fragCount) {
         LogError("No fragment available for downloading");
     }
     if (isHttpUrl($this->media['url'])) {
         $this->fragUrl = $this->media['url'];
     } else {
         $this->fragUrl = $this->baseUrl . "/" . $this->media['url'];
     }
     $this->fragUrl = NormalizePath($this->fragUrl);
     LogDebug("Base Fragment Url:\n" . $this->fragUrl . "\n");
     LogDebug("Downloading Fragments:\n");
     while ($fragNum < $this->fragCount or $cc->active) {
         while (count($cc->ch) < $this->parallel and $fragNum < $this->fragCount) {
             $frag = array();
             $fragNum = $fragNum + 1;
             $frag['id'] = $fragNum;
             LogInfo("Downloading {$fragNum}/{$this->fragCount} fragments", true);
             if (in_array_field($fragNum, "firstFragment", $this->fragTable, true)) {
                 $this->discontinuity = value_in_array_field($fragNum, "firstFragment", "discontinuityIndicator", $this->fragTable, true);
             } else {
                 $closest = 1;
                 foreach ($this->fragTable as $item) {
                     if ($item['firstFragment'] < $fragNum) {
                         $closest = $item['firstFragment'];
                     } else {
                         break;
                     }
                 }
                 $this->discontinuity = value_in_array_field($closest, "firstFragment", "discontinuityIndicator", $this->fragTable, true);
             }
             if ($this->discontinuity == 1 or $this->discontinuity == 3) {
                 LogDebug("Skipping fragment {$fragNum} due to discontinuity");
                 $frag['response'] = false;
                 $this->rename = true;
             } else {
                 if (file_exists($this->baseFilename . $fragNum)) {
                     LogDebug("Fragment {$fragNum} is already downloaded");
                     $frag['response'] = file_get_contents($this->baseFilename . $fragNum);
                 }
             }
             if (isset($frag['response'])) {
                 if ($this->WriteFragment($frag, $opt) === 2) {
                     break 2;
                 } else {
                     continue;
                 }
             }
             /* Increase or decrease segment number if current fragment is not available */
             /* in selected segment range                                                */
             if (count($this->segTable) > 1) {
                 if ($fragNum > $segNum * $this->fragsPerSeg) {
                     $segNum++;
                 } else {
                     if ($fragNum <= ($segNum - 1) * $this->fragsPerSeg) {
                         $segNum--;
                     }
                 }
             }
             LogDebug("Adding fragment {$fragNum} to download queue");
             $cc->addDownload($this->fragUrl . "Seg" . $segNum . "-Frag" . $fragNum . $this->auth, $fragNum);
         }
         $downloads = $cc->checkDownloads();
         if ($downloads !== false) {
             for ($i = 0; $i < count($downloads); $i++) {
                 $frag = array();
                 $download = $downloads[$i];
                 $frag['id'] = $download['id'];
                 if ($download['status'] == 200) {
                     if ($this->VerifyFragment($download['response'])) {
                         LogDebug("Fragment " . $this->baseFilename . $download['id'] . " successfully downloaded");
                         if (!($this->live or $this->play)) {
                             file_put_contents($this->baseFilename . $download['id'], $download['response']);
                         }
                         $frag['response'] = $download['response'];
                     } else {
                         LogDebug("Fragment " . $download['id'] . " failed to verify");
                         LogDebug("Adding fragment " . $download['id'] . " to download queue");
                         $cc->addDownload($download['url'], $download['id']);
                     }
                 } else {
                     if ($download['status'] === false) {
                         LogDebug("Fragment " . $download['id'] . " failed to download");
                         LogDebug("Adding fragment " . $download['id'] . " to download queue");
                         $cc->addDownload($download['url'], $download['id']);
                     } else {
                         if ($download['status'] == 403) {
                             LogError("Access Denied! Unable to download fragments.");
                         } else {
                             LogDebug("Fragment " . $download['id'] . " doesn't exist, Status: " . $download['status']);
                             $frag['response'] = false;
                             $this->rename = true;
                             /* Resync with latest available fragment when we are left behind due to */
                             /* slow connection and short live window on streaming server. make sure */
                             /* to reset the last written fragment.                                  */
                             if ($this->live and $i + 1 == count($downloads) and !$cc->active) {
                                 LogDebug("Trying to resync with latest available fragment");
                                 if ($this->WriteFragment($frag, $opt) === 2) {
                                     break 2;
                                 }
                                 unset($frag['response']);
                                 $this->UpdateBootstrapInfo($cc, $this->bootstrapUrl);
                                 $fragNum = $this->fragCount - 1;
                                 $this->lastFrag = $fragNum;
                             }
                         }
                     }
                 }
                 if (isset($frag['response'])) {
                     if ($this->WriteFragment($frag, $opt) === 2) {
                         break 2;
                     }
                 }
             }
             unset($downloads, $download);
         }
         if ($this->live and $fragNum >= $this->fragCount and !$cc->active) {
             $this->UpdateBootstrapInfo($cc, $this->bootstrapUrl);
         }
     }
     LogInfo("");
     LogDebug("\nAll fragments downloaded successfully\n");
     $cc->stopDownloads();
     $this->processed = true;
 }
Пример #3
0
 public function loadAssets($assets, $isAdmin = false)
 {
     $prefix = $isAdmin ? 'admin-' : '';
     if (isset($this->_loadedThemes[$prefix])) {
         return $this;
     }
     $this->_loadedThemes[$prefix] = true;
     $assetsOptions = $this->config['options']['assets_options'];
     $applyFilter = $assetsOptions['apply_filter'];
     // The base path, usually the public directory
     $basePath = $assetsOptions['base_path'];
     // The assets dir inside base path
     $resourcePath = '/' . $assetsOptions['assets_dir'] . '/';
     $compiledPath = '/' . $assetsOptions['compiled_dir'] . '/';
     foreach ($assets as $collectionName => $resources) {
         $resourceType = substr($collectionName, strrpos($collectionName, '-') + 1);
         $collectionName = $prefix . $collectionName;
         $collection = $this->assets->collection($collectionName);
         $collection->setSourcePath($basePath);
         $contentHash = '';
         switch ($resourceType) {
             case 'css':
                 foreach ($resources as $item) {
                     $isLocal = !isHttpUrl($item);
                     $resource = new Css($isLocal ? $resourcePath . $item : $item, $isLocal);
                     $applyFilter and $contentHash = $resource->concatenateHash($contentHash);
                     $collection->add($resource);
                 }
                 $applyFilter and $collection->addFilter(new Cssmin());
                 break;
             case 'js':
                 foreach ($resources as $item) {
                     $isLocal = !isHttpUrl($item);
                     $resource = new Js($isLocal ? $resourcePath . $item : $item, $isLocal);
                     $applyFilter and $contentHash = $resource->concatenateHash($contentHash);
                     $collection->add($resource);
                 }
                 $applyFilter and $collection->addFilter(new Jsmin());
                 break;
         }
         $targetUri = $compiledPath . substr($collectionName, 0, -1 - strlen($resourceType));
         $contentHash and $targetUri .= '.' . $contentHash;
         $targetUri .= '.' . $resourceType;
         $collection->setTargetPath($basePath . $targetUri)->setTargetUri(url($targetUri));
     }
     return $this;
 }
Пример #4
0
/**
 * 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);
    }
}
Пример #5
0
/**
 * 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']), ');';
}
Пример #6
0
function url($path, $queries = [], $secure = null)
{
    if (isHttpUrl($path)) {
        return $path;
    }
    $path = trim($path, '/');
    if (Config::get('app.enable_https')) {
        Text::startsWith($path, 'admin', false) and $secure = true;
        $secure === null && null !== ($configValue = Config::get('app.secure_routes.' . $path)) and $secure = $configValue;
        // TODO Detection https via proxy
        $secure === null and $secure = Di::getDefault()['request']->getScheme() === 'https';
    } else {
        $secure = false;
    }
    $protocol = $secure ? 'https://' : 'http://';
    $host = fnGet($_SERVER, 'HTTP_HOST') ?: parse_url(Config::get('app.url'), PHP_URL_HOST);
    $base = $_SERVER['SCRIPT_NAME'];
    $base = trim(dirname($base), '/');
    $base and $base .= '/';
    $url = $protocol . $host . '/' . $base;
    $url .= $path;
    if ($queries && is_array($queries)) {
        $queries = http_build_query($queries);
    }
    $queries && is_string($queries) and $url .= '?' . str_replace('?', '', $queries);
    return $url;
}