Attempt to rewrite the code

This commit is contained in:
Yehuda Eisenberg
2020-12-09 18:33:00 +02:00
parent eb6cf93a6b
commit e028617c4e
23 changed files with 132 additions and 1738 deletions

View File

@@ -1,3 +0,0 @@
php_value display_errors 1
php_flag log_errors on
php_value error_log /var/www/speedtest/php.error.log

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -1,8 +0,0 @@
<?php
$site_name = 'Internet Speed Test | בדיקת מהירות אינטרנט';
$site_descr = 'Check the speed of your Internet connection | בדוק מה המהירות אינטרנט שלך';
$copyrights = 'Yehuda Eisenberg © 2020';
$website_url = 'https://speedtest.yehudae.ga/';
?>

View File

@@ -1,14 +0,0 @@
<html>
<?php require_once ('inc/head.php')?>
<body>
<?php require_once ('inc/menu.php')?>
<div class="container">
<div class="pages">
<h1>Contact Us | צור קשר</h1>
<span dir="rtl" style="float:right;">זקוק לעזרה? צור קשר דרך <a href="mailto:yehuda.telegram@gmail.com?subject=speed-test">yehuda.telegram@gmail.com</a></span>
<span>Need help? contact in <a href="mailto:yehuda.telegram@gmail.com?subject=speed-test">yehuda.telegram@gmail.com</a></span>
</div>
</div>
<?php require_once ('inc/footer.php')?>
</body>
</html>

View File

@@ -1,416 +0,0 @@
@import url('https://fonts.googleapis.com/css?family=Lato:100,100i,300,300i,400,400i,700,700i,900,900i');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Lato', sans-serif;
font-size: 14px;
color: #999999;
word-wrap:break-word;
background: #231f20;
}
.topnav {
overflow: hidden;
background-color: #fff;
max-width: 80%;
margin: 1em auto;
}
.topnav a {
float: left;
display: block;
color: #333;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #231f20;
color: #fff;
}
.topnav .selected {
background-color: #f2f2f2;
color: #0085c9;
box-shadow: 0px -2px 0px #0085c9 inset;
box-shadow: 0px 2px 0px #0085c9 inset;
}
.topnav .home {
background-color: #0085c9;
color: #fff;
font-size: 1.5em;
}
.topnav .home:hover {
background-color: #0085c9;
color: #fff;
}
.topnav .icon {
display: none;
font-size: 1.5em;
}
@media (min-width: 181px) and (max-width: 868px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
@media (min-width: 181px) and (max-width: 868px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
.container {
background: #fff;
max-width: 80%;
margin: 1em auto;
border-radius: 4px;
padding: 1em;
}
.pages {
padding: 1.3em;
font-size: 1.3em;
line-height: 1.8em;
color: #333;
}
.pages h2 {
padding-bottom: 1em;
text-align: center;
font-size: 2em;
color: #333;
}
.pages ul{
padding: 1em 2em;
color: #666;
}
h1 {
font-size:2em;
color:#0085c9;
font-weight: 900;
letter-spacing: 2px;
padding: 0.5em;
text-align: center;
}
h2 {
font-size:1em;
color:#0085c9;
letter-spacing: 2px;
padding: 0.5em;
text-align: center;
margin: 0.5em;
}
h3 {
font-size:1em;
color:#0085c9;
letter-spacing: 2px;
padding: 0.5em;
text-align: center;
margin: 0.5em;
}
h3 span{
font-size:0.8em;
color:#333;
font-weight: 900;
letter-spacing: 2px;
padding: 0.5em;
text-align: center;
}
.intro {
text-align:center;
}
.intro p {
font-size:1em;
letter-spacing: 2px;
padding:1em;
}
.outro {
display: grid;
grid-template-columns: 29% auto;
grid-gap: 10px;
background-color: #fff;
border-top: 1px solid #c6c6c6;
padding-top: 1em;
color: #444;
margin-top:1em;
margin-bottom:1em;
border-radius: 4px;
}
/* 868 */
@media (min-width: 181px) and (max-width: 868px) {
.outro {
display: grid;
grid-template-columns: 90%;
}
}
.partone img{
text-align:right;
}
.outro p {
font-size:1em;
letter-spacing: 2px;
padding:1em;
text-align: justify;
}
#startStopBtn{
background-color: #0085c9;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 100%;
border-radius: 4px;
}
#startStopBtn:hover{
background-color: #0576af;
}
#startStopBtn.running{
background-color:#c63b1f;
border-color:#c63b1f;
color:#FFFFFF;
}
#startStopBtn:before{
content:"Start Test Now | התחל בדיקה";
}
#startStopBtn.running:before{
content:"Cancel Test | ביטול";
}
#test{
margin-top:6em;
margin-bottom:2em;
text-align: center;
}
div.testArea{
display:inline-block;
width:16em;
height:12.5em;
position:relative;
box-sizing:border-box;
}
div.testName{
position:absolute;
top:-5em; left:0;
width:100%;
font-size:1em;
background:#eeeeee;
border-radius:0.3em;
padding: 0.3em;
letter-spacing: 2px;
color: #666;
z-index:9;
}
div.icontest {
position:absolute;
top:-0.7em; left:0;
width:100%;
font-size:3em;
color:#eeeeee;
z-index:9;
}
div.meterText{
position:absolute;
bottom:4em; left:30%;
width:40%;
font-size:1em;
z-index:9;
color:#fff;
background-color: #55be00;
border-radius:0.3em;
padding:0.2em;
}
div.meterText:empty:before{
content:"0.00";
}
div.unit{
position:absolute;
bottom:2em; left:0;
width:100%;
z-index:9;
}
div.testArea canvas{
position:absolute;
top:0; left:0; width:100%; height:100%;
z-index:1;
}
div.testGroup{
display:inline-block;
height:12.5em;
}
@media (min-width: 560px) and (max-width: 1224px) {
body{
font-size:0.8em;
}
#test{
margin-top:6em;
margin-bottom:1em;
text-align: center;
}
div.testArea {
width:16em;
height:12.5em;
}
div.testGroup{
display:inline-block;
height:12.5em;
position:relative;
box-sizing:border-box;
margin-bottom:6em;
}
}
@media (min-width: 10px) and (max-width: 560px) {
body{
font-size:0.8em;
}
#test{
margin-top:6em;
margin-bottom:1em;
text-align: center;
}
div.testArea {
width:16em;
height:12.5em;
margin-bottom:8em;
}
div.testGroup{
display:inline-block;
height:32em;
position:relative;
box-sizing:border-box;
}
#nomob{
display:none;
}
}
.fbdiv a {
background-color: rgb(60, 90, 153);
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 100%;
border-radius: 4px;
}
.fbdiv .fblink:hover {
background:rgb(43, 68, 121);
color: #fff;
}
.fa-facebook-square{
font-size: 1.3em;
padding: 0px 10px;
}
footer {
width:100%;
text-align:center;
padding:1em;
margin: 1em 0em;
}
.footer a {
color: #fff;
font-size: 1em;
text-decoration: none;
padding:0 1em;
}
.footer p {
color: #fff;
font-size: 1em;
text-decoration: none;
padding:1em 0em;
}
.footer p a {
color: #fff;
padding: 0em;
}
.footer p span {
color: #2d0100;
}
.footer a:hover {
color: #0f75bc;
font-size: 1em;
text-decoration: none;
}
#counter-area {
padding: 2px;
background-color: rgba(205, 204, 204, 0.19);
border-radius: 2px;
width: 300px;
height: 30px;
line-height: 30px;
text-align: center;
width: 100%;
}
#counter-winkey {
color: white;
background-color: #db8002;
padding: 3px 9px;
border-radius: 5px;
}

View File

@@ -1,41 +0,0 @@
<?php
include_once('settings.php');
require 'idObfuscation.php';
$ip = ($_SERVER['REMOTE_ADDR'] ?? "");
$ispinfo = ($_POST["ispinfo"] ?? "");
$extra = ($_POST["extra"] ?? "");
$ua = ($_SERVER['HTTP_USER_AGENT'] ?? "");
$lang=""; if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = ($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? "");
$dl = ($_POST["dl"] ?? "");
$ul = ($_POST["ul"] ?? "");
$ping = ($_POST["ping"] ?? "");
$jitter = ($_POST["jitter"] ?? "");
$log = ($_POST["log"] ?? "");
if($db_type=="sqlite"){
$conn = new PDO("sqlite:$Sqlite_db_file") or die("1");
$conn->exec("
CREATE TABLE IF NOT EXISTS `speedtest_users` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`ispinfo` text,
`extra` text,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip` text NOT NULL,
`ua` text NOT NULL,
`lang` text NOT NULL,
`dl` text,
`ul` text,
`ping` text,
`jitter` text,
`log` longtext
);
");
$stmt = $conn->prepare("INSERT INTO speedtest_users (ip,ispinfo,extra,ua,lang,dl,ul,ping,jitter,log) VALUES (?,?,?,?,?,?,?,?,?,?)") or die("2");
$stmt->execute(array($ip,$ispinfo,$extra,$ua,$lang,$dl,$ul,$ping,$jitter,$log)) or die("3");
$id=$conn->lastInsertId();
echo "id ".($enable_id_obfuscation?obfuscateId($id):$id);
$conn = null;
}
else die("-1");
?>

View File

@@ -1,43 +0,0 @@
<?php
function getObfuscationSalt(){
$saltFile=dirname(__FILE__)."/idObfuscation_salt.php";
if(file_exists($saltFile)){
require $saltFile;
}else{
$bytes=openssl_random_pseudo_bytes(4);
$sf=fopen($saltFile,"w");
fwrite($sf,chr(60)."?php\n");
fwrite($sf,'$OBFUSCATION_SALT=0x'.bin2hex($bytes).";\n");
fwrite($sf,"?".chr(62));
fclose($sf);
require $saltFile;
}
return isset($OBFUSCATION_SALT)?$OBFUSCATION_SALT:0;
}
/*
This is a simple reversible hash function I made for encoding and decoding test IDs.
It is not cryptographically secure, don't use it to hash passwords or something!
*/
function obfdeobf($id,$dec){
$salt=getObfuscationSalt()&0xFFFFFFFF;
$id=$id&0xFFFFFFFF;
if($dec){
$id=$id^$salt;
$id=(($id&0xAAAAAAAA)>>1)|($id&0x55555555)<<1;
$id=(($id&0x0000FFFF)<<16)|(($id&0xFFFF0000)>>16);
return $id;
}else{
$id=(($id&0x0000FFFF)<<16)|(($id&0xFFFF0000)>>16);
$id=(($id&0xAAAAAAAA)>>1)|($id&0x55555555)<<1;
return $id^$salt;
}
}
function obfuscateId($id){
return str_pad(base_convert(obfdeobf($id+1,false),10,36),7,0,STR_PAD_LEFT);
}
function deobfuscateId($id){
return obfdeobf(base_convert($id,36,10),true)-1;
}
//IMPORTANT: DO NOT ADD ANYTHING BELOW THE PHP CLOSING TAG, NOT EVEN EMPTY LINES!
?>

View File

@@ -1,157 +0,0 @@
<?php
session_start();
error_reporting(0);
header('Content-Type: text/html; charset=utf-8');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Speedtest - Stats</title>
<style type="text/css">
html,body{
margin:0;
padding:0;
border:none;
width:100%; min-height:100%;
}
html{
background-color: hsl(198,72%,35%);
font-family: "Segoe UI","Roboto",sans-serif;
}
body{
background-color:#FFFFFF;
box-sizing:border-box;
width:100%;
max-width:70em;
margin:4em auto;
box-shadow:0 1em 6em #00000080;
padding:1em 1em 4em 1em;
border-radius:0.4em;
}
h1,h2,h3,h4,h5,h6{
font-weight:300;
margin-bottom: 0.1em;
}
h1{
text-align:center;
}
table{
margin:2em 0;
width:100%;
}
table, tr, th, td {
border: 1px solid #AAAAAA;
}
th {
width: 6em;
}
td {
word-break: break-all;
}
</style>
</head>
<body>
<h1>HTML5 Speedtest - Stats</h1>
<?php
include_once("settings.php");
require "idObfuscation.php";
if($stats_password == "default"){
?>
change password in settings.php
<?php
}else if($_SESSION["logged"]===true){
if($_GET["op"]=="logout"){
$_SESSION["logged"]=false;
?><script type="text/javascript">window.location=location.protocol+"//"+location.host+location.pathname;</script><?php
}else{
$conn=null;
if($db_type=="mysql"){
$conn = new mysqli($MySql_hostname, $MySql_username, $MySql_password, $MySql_databasename);
}else if($db_type=="sqlite"){
$conn = new PDO("sqlite:$Sqlite_db_file");
} else if($db_type=="postgresql"){
$conn_host = "host=$PostgreSql_hostname";
$conn_db = "dbname=$PostgreSql_databasename";
$conn_user = "user=$PostgreSql_username";
$conn_password = "password=$PostgreSql_password";
$conn = new PDO("pgsql:$conn_host;$conn_db;$conn_user;$conn_password");
}else die();
?>
<form action="index.php" method="GET"><input type="hidden" name="op" value="logout" /><input type="submit" value="Logout" /></form>
<form action="index.php" method="GET">
<h3>Search test results</h6>
<input type="hidden" name="op" value="id" />
<input type="text" name="id" id="id" placeholder="Test ID" value=""/>
<input type="submit" value="Find" />
<input type="submit" onclick="document.getElementById('id').value=''" value="Show last 100 tests" />
</form>
<?php
$q=null;
if($_GET["op"]=="id"&&!empty($_GET["id"])){
$id=$_GET["id"];
if($enable_id_obfuscation) $id=deobfuscateId($id);
if($db_type=="sqlite"){
$q=$conn->prepare("select id,timestamp,ip,ispinfo,ua,lang,dl,ul,ping,jitter,log,extra from speedtest_users where id=?");
$q->execute(array($id));
}
else die();
}else{
if($db_type=="sqlite"){
$q=$conn->prepare("select id,timestamp,ip,ispinfo,ua,lang,dl,ul,ping,jitter,log,extra from speedtest_users order by timestamp desc limit 0,100");
$q->execute();
}
else die();
}
while(true){
$id=null; $timestamp=null; $ip=null; $ispinfo=null; $ua=null; $lang=null; $dl=null; $ul=null; $ping=null; $jitter=null; $log=null; $extra=null;
if($db_type=="sqlite"){
if(!($row=$q->fetch())) break;
$id=$row["id"];
$timestamp=$row["timestamp"];
$ip=$row["ip"];
$ispinfo=$row["ispinfo"];
$ua=$row["ua"];
$lang=$row["lang"];
$dl=$row["dl"];
$ul=$row["ul"];
$ping=$row["ping"];
$jitter=$row["jitter"];
$log=$row["log"];
}else die();
?>
<table>
<tr><th>Test ID</th><td><?=htmlspecialchars(($enable_id_obfuscation?obfuscateId($id):$id), ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Date and time</th><td><?=htmlspecialchars($timestamp, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>IP and ISP Info</th><td><?=$ip ?><br/><?=htmlspecialchars($ispinfo, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>User agent and locale</th><td><?=$ua ?><br/><?=htmlspecialchars($lang, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Download speed</th><td><?=htmlspecialchars($dl, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Upload speed</th><td><?=htmlspecialchars($ul, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Ping</th><td><?=htmlspecialchars($ping, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Jitter</th><td><?=htmlspecialchars($jitter, ENT_HTML5, 'UTF-8') ?></td></tr>
<tr><th>Log</th><td><?=htmlspecialchars($log, ENT_HTML5, 'UTF-8') ?></td></tr>
</table>
<?php
}
?>
<?php
}
}else{
if($_GET["op"]=="login"&&$_POST["password"]===$stats_password){
$_SESSION["logged"]=true;
?><script type="text/javascript">window.location=location.protocol+"//"+location.host+location.pathname;</script><?php
}else{
?>
<form action="index.php?op=login" method="POST">
<h3>Login</h3>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
<?php
}
}
?>
</body>
</html>

View File

@@ -1,11 +0,0 @@
<?php
$db_type = "sqlite";
$stats_password = "default";
$enable_id_obfuscation = false;
$Sqlite_db_file = "../../data.sql";
?>

7
e.php Normal file
View File

@@ -0,0 +1,7 @@
<?php
header( "HTTP/1.1 200 OK" );
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: keep-alive");
?>

View File

@@ -11,9 +11,7 @@
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
$data = openssl_random_pseudo_bytes(1048576);
$chunks=isset($_GET['ckSize']) ? intval($_GET['ckSize']) : 4;
if(empty($chunks)){$chunks = 4;}
if($chunks>1024){$chunks = 1024;}
$chunks = 4;
for($i = 0; $i < $chunks; $i++){
echo $data;
flush();

View File

@@ -1,12 +0,0 @@
<footer>
<div class="footer">
<a href="./">Home | דף הבית</a>
<a href="contact.php">Contact | צור קשר</a>
</div>
<div class="footer">
<p><?php echo "$copyrights" ;?></p>
</div>
</footer>

View File

@@ -1,19 +0,0 @@
<head>
<?php require_once ('config.php')?>
<meta charset="UTF-8">
<title><?php echo $site_name ;?></title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="description" content="<?php echo "$site_descr"; ?>" />
<meta property="og:type" content="article" />
<meta property="og:title" content="<?php echo "$site_name"; ?>" />
<meta property="og:description" content="<?php echo "$site_descr"; ?>" />
<meta property="og:image" content="assets/fbbanner.png" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" >
<link rel="icon" type="image/png" href="assets/logo-w.png" />
<link rel="stylesheet" href="css/style.css">
</head>
<div class="intro">
<a href="./"><img width="120px" src="assets/logo-b.png" /></a>
<h1><?php echo $site_name; ?></h1>
<p><?php echo "$site_descr"; ?></p>
</div>

View File

@@ -1,2 +0,0 @@
<?php
header('Location: ../');

View File

@@ -1,106 +0,0 @@
<script type="text/javascript">
function I(id){return document.getElementById(id);}
var meterBk="#E0E0E0";
var dlColor="#0085c9",
ulColor="#0085c9",
pingColor="#0085c9",
jitColor="#0085c9";
var progColor="#55be00";
function drawMeter(c,amount,bk,fg,progress,prog){
var ctx=c.getContext("2d");
var dp=window.devicePixelRatio||1;
var cw=c.clientWidth*dp, ch=c.clientHeight*dp;
var sizScale=ch*0.0055;
if(c.width==cw&&c.height==ch){
ctx.clearRect(0,0,cw,ch);
}else{
c.width=cw;
c.height=ch;
}
ctx.beginPath();
ctx.strokeStyle=bk;
ctx.lineWidth=16*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,Math.PI*0.1);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle=fg;
ctx.lineWidth=16*sizScale;
ctx.arc(c.width/2,c.height-58*sizScale,c.height/1.8-ctx.lineWidth,-Math.PI*1.1,amount*Math.PI*1.2-Math.PI*1.1);
ctx.stroke();
if(typeof progress !== "undefined"){
ctx.fillStyle=prog;
ctx.fillRect(c.width*0.3,c.height-16*sizScale,c.width*0.4*progress,4*sizScale);
}
}
function mbpsToAmount(s){
return 1-(1/(Math.pow(1.3,Math.sqrt(s))));
}
function msToAmount(s){
return 1-(1/(Math.pow(1.08,Math.sqrt(s))));
}
var w=null;
var data=null;
function startStop(){
if(w!=null){
w.postMessage('abort');
w=null;
data=null;
I("startStopBtn").className="";
initUI();
}else{
w=new Worker('netspeed/speedtest_worker.min.js');
w.postMessage('start');
I("startStopBtn").className="running";
w.onmessage=function(e){
data=JSON.parse(e.data);
var status=data.testState;
if(status>=4){
I("startStopBtn").className="";
w=null;
updateUI(true);
}
};
}
}
function updateUI(forced){
if(!forced&&(!data||!w)) return;
var status=data.testState;
I("ip").textContent=data.clientIp;
I("ipArea").style.display="block";
I("dlText").textContent=(status==1&&data.dlStatus==0)?"...":data.dlStatus;
drawMeter(I("dlMeter"),mbpsToAmount(Number(data.dlStatus*(status==1?oscillate():1))),meterBk,dlColor,Number(data.dlProgress),progColor);
I("ulText").textContent=(status==3&&data.ulStatus==0)?"...":data.ulStatus;
drawMeter(I("ulMeter"),mbpsToAmount(Number(data.ulStatus*(status==3?oscillate():1))),meterBk,ulColor,Number(data.ulProgress),progColor);
I("pingText").textContent=data.pingStatus;
drawMeter(I("pingMeter"),msToAmount(Number(data.pingStatus*(status==2?oscillate():1))),meterBk,pingColor,Number(data.pingProgress),progColor);
I("jitText").textContent=data.jitterStatus;
drawMeter(I("jitMeter"),msToAmount(Number(data.jitterStatus*(status==2?oscillate():1))),meterBk,jitColor,Number(data.pingProgress),progColor);
}
function oscillate(){
return 1+0.02*Math.sin(Date.now()/100);
}
setInterval(function(){
if(w) w.postMessage('status');
},200);
window.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||(function(callback,element){setTimeout(callback,1000/60);});
function frame(){
requestAnimationFrame(frame);
updateUI();
}
frame();
function initUI(){
drawMeter(I("dlMeter"),0,meterBk,dlColor,0);
drawMeter(I("ulMeter"),0,meterBk,ulColor,0);
drawMeter(I("pingMeter"),0,meterBk,pingColor,0);
drawMeter(I("jitMeter"),0,meterBk,jitColor,0);
I("dlText").textContent="";
I("ulText").textContent="";
I("pingText").textContent="";
I("jitText").textContent="";
I("ip").textContent="";
}
</script>
<div class="topnav" id="myTopnav">
<a href="./" class="home"><i class="fas fa-house-damage"></i></a>
<a href="contact.php" class="<?php if (basename($_SERVER['PHP_SELF']) == "contact.php") { ?> selected <?php } ?>">Contact | צור קשר</a>
</div>

View File

@@ -1,52 +1,14 @@
<html>
<?php require_once ('inc/head.php')?>
<head>
<meta charset="UTF-8">
<title>Speedtest | beta</title>
<script src="service.js"></script>
</head>
<body>
<?php require_once ('inc/menu.php')?>
<div class="container">
<div id="test">
<div class="testGroup" id="nomob">
<div class="testArea">
<div class="icontest"><i class="fas fa-unlink"></i></div>
<div class="testName">Jitter | דילאי</div>
<canvas id="jitMeter" class="meter"></canvas>
<div id="jitText" class="meterText"></div>
<div class="unit">ms</div>
</div>
<div class="testArea">
<div class="icontest"><i class="fas fa-link"></i></div>
<div class="testName">Ping | פינג</div>
<canvas id="pingMeter" class="meter"></canvas>
<div id="pingText" class="meterText"></div>
<div class="unit">ms</div>
</div>
</div>
<div class="testGroup">
<div class="testArea">
<div class="testAreastyle">
<div class="icontest"><i class="fas fa-download"></i></div>
<div class="testName">Download | הורדה</div>
</div>
<canvas id="dlMeter" class="meter"></canvas>
<div id="dlText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
<div class="testArea">
<div class="icontest"><i class="fas fa-upload"></i></div>
<div class="testName">Upload | העלאה</div>
<canvas id="ulMeter" class="meter"></canvas>
<div id="ulText" class="meterText"></div>
<div class="unit">Mbps</div>
</div>
</div>
<div style="display: none;" id="ipArea">
IP Address: <span id="ip"></span> :כתובת אייפי
</div>
</div>
<center>
<div id="startStopBtn" onclick="startStop()"></div>
</center>
<script type="text/javascript">setTimeout(initUI,100);</script>
</div>
<?php require_once ('inc/footer.php')?>
<p>Ping: <span id="ping"></span></p>
<p>Download: <span id="down"></span></p>
<p>Upload: <span id="up"></span></p>
<p>Status: <span id="status"></span></p>
<button onclick="startTest()" id="button">Start Test</button>
</body>
</html>

View File

@@ -1,7 +0,0 @@
<?php
header( "HTTP/1.1 200 OK" );
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Connection: keep-alive");
?>

View File

@@ -1,142 +0,0 @@
<?php
error_reporting(0);
$ip = "";
header('Content-Type: application/json; charset=utf-8');
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['X-Real-IP'])) {
$ip = $_SERVER['X-Real-IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = preg_replace("/,.*/", "", $ip); # hosts are comma-separated, client is first
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$ip = preg_replace("/^::ffff:/", "", $ip);
if ($ip == "::1") { // ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
echo json_encode(['processedString' => $ip . " - localhost IPv6 access", 'rawIspInfo' => ""]);
die();
}
if (stripos($ip, 'fe80:') === 0) { // simplified IPv6 link-local address (should match fe80::/10)
echo json_encode(['processedString' => $ip . " - link-local IPv6 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '127.') === 0) { //anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
echo json_encode(['processedString' => $ip . " - localhost IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '10.') === 0) { // 10/8 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) { // 172.16/12 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '192.168.') === 0) { // 192.168/16 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '169.254.') === 0) { // IPv4 link-local
echo json_encode(['processedString' => $ip . " - link-local IPv4 access", 'rawIspInfo' => ""]);
die();
}
/**
* Optimized algorithm from http://www.codexworld.com
*
* @param float $latitudeFrom
* @param float $longitudeFrom
* @param float $latitudeTo
* @param float $longitudeTo
*
* @return float [km]
*/
function distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) {
$rad = M_PI / 180;
$theta = $longitudeFrom - $longitudeTo;
$dist = sin($latitudeFrom * $rad) * sin($latitudeTo * $rad) + cos($latitudeFrom * $rad) * cos($latitudeTo * $rad) * cos($theta * $rad);
return acos($dist) / $rad * 60 * 1.853;
}
function getIpInfoTokenString(){
$apikeyFile="getIP_ipInfo_apikey.php";
if(!file_exists($apikeyFile)) return "";
require $apikeyFile;
if(empty($IPINFO_APIKEY)) return "";
return "?token=".$IPINFO_APIKEY;
}
if (isset($_GET["isp"])) {
$isp = "";
$rawIspInfo=null;
try {
$json = file_get_contents("https://ipinfo.io/" . $ip . "/json".getIpInfoTokenString());
$details = json_decode($json, true);
$rawIspInfo=$details;
if (array_key_exists("org", $details)){
$isp .= $details["org"];
$isp=preg_replace("/AS\d{1,}\s/","",$isp); //Remove AS##### from ISP name, if present
}else{
$isp .= "Unknown ISP";
}
if (array_key_exists("country", $details)){
$isp .= ", " . $details["country"];
}
$clientLoc = NULL;
$serverLoc = NULL;
if (array_key_exists("loc", $details)){
$clientLoc = $details["loc"];
}
if (isset($_GET["distance"])) {
if ($clientLoc) {
$locFile="getIP_serverLocation.php";
$serverLoc=null;
if(file_exists($locFile)){
require $locFile;
}else{
$json = file_get_contents("https://ipinfo.io/json".getIpInfoTokenString());
$details = json_decode($json, true);
if (array_key_exists("loc", $details)){
$serverLoc = $details["loc"];
}
if($serverLoc){
$lf=fopen($locFile,"w");
fwrite($lf,chr(60)."?php\n");
fwrite($lf,'$serverLoc="'.addslashes($serverLoc).'";');
fwrite($lf,"\n");
fwrite($lf,"?".chr(62));
fclose($lf);
}
}
if ($serverLoc) {
try {
$clientLoc = explode(",", $clientLoc);
$serverLoc = explode(",", $serverLoc);
$dist = distance($clientLoc[0], $clientLoc[1], $serverLoc[0], $serverLoc[1]);
if ($_GET["distance"] == "mi") {
$dist /= 1.609344;
$dist = round($dist, -1);
if ($dist < 15)
$dist = "<15";
$isp .= " (" . $dist . " mi)";
}else if ($_GET["distance"] == "km") {
$dist = round($dist, -1);
if ($dist < 20)
$dist = "<20";
$isp .= " (" . $dist . " km)";
}
} catch (Exception $e) {
}
}
}
}
} catch (Exception $ex) {
$isp = "Unknown ISP";
}
echo json_encode(['processedString' => $ip . " - " . $isp, 'rawIspInfo' => $rawIspInfo]);
} else {
echo json_encode(['processedString' => $ip, 'rawIspInfo' => ""]);
}
?>

View File

@@ -1,701 +0,0 @@
var testStatus = -1; // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort/error
var dlStatus = ""; // download speed in megabit/s with 2 decimal digits
var ulStatus = ""; // upload speed in megabit/s with 2 decimal digits
var pingStatus = ""; // ping in milliseconds with 2 decimal digits
var jitterStatus = ""; // jitter in milliseconds with 2 decimal digits
var clientIp = ""; // client's IP address as reported by getIP.php
var dlProgress = 0; //progress of download test 0-1
var ulProgress = 0; //progress of upload test 0-1
var pingProgress = 0; //progress of ping+jitter test 0-1
var testId = null; //test ID (sent back by telemetry if used, null otherwise)
var log = ""; //telemetry log
function tlog(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + ": " + s + "\n";
}
}
function tverb(s) {
if (settings.telemetry_level >= 3) {
log += Date.now() + ": " + s + "\n";
}
}
function twarn(s) {
if (settings.telemetry_level >= 2) {
log += Date.now() + " WARN: " + s + "\n";
}
console.warn(s);
}
// test settings. can be overridden by sending specific values with the start command
var settings = {
test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
time_ul_max: 15, // max duration of upload test in seconds
time_dl_max: 15, // max duration of download test in seconds
time_auto: true, // if set to true, tests will take less time on faster connections
time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
count_ping: 10, // number of pings to perform in ping test
url_dl: "garbage.php", // path to a large file or garbage.php, used for download test. must be relative to this js file
url_ul: "empty.php", // path to an empty file, used for upload test. must be relative to this js file
url_ping: "empty.php", // path to an empty file, used for ping test. must be relative to this js file
url_getIp: "getIP.php", // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
getIp_ispInfo_distance: "km", //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
xhr_dlMultistream: 6, // number of download streams to use (can be different if enable_quirks is active)
xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
garbagePhp_chunkSize: 100, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
telemetry_level: 2, // 0=disabled, 1=basic (results only), 2=full (results and timing) 3=debug (results+log)
url_telemetry: "../data/data.php", // path to the script that adds telemetry data to the database
telemetry_extra: "" //extra data that can be passed to the telemetry through the settings
};
var xhr = null; // array of currently active xhr requests
var interval = null; // timer used in tests
var test_pointer = 0; //pointer to the next test to run inside settings.test_order
/*
this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
*/
function url_sep(url) {
return url.match(/\?/) ? "&" : "?";
}
/*
listener for commands from main thread to this worker.
commands:
-status: returns the current status as a JSON string containing testStatus, dlStatus, ulStatus, pingStatus, clientIp, jitterStatus, dlProgress, ulProgress, pingProgress
-abort: aborts the current test
-start: starts the test. optionally, settings can be passed as JSON.
example: start {"time_ul_max":"10", "time_dl_max":"10", "count_ping":"50"}
*/
this.addEventListener("message", function(e) {
var params = e.data.split(" ");
if (params[0] === "status") {
// return status
postMessage(
JSON.stringify({
testState: testStatus,
dlStatus: dlStatus,
ulStatus: ulStatus,
pingStatus: pingStatus,
clientIp: clientIp,
jitterStatus: jitterStatus,
dlProgress: dlProgress,
ulProgress: ulProgress,
pingProgress: pingProgress,
testId: testId
})
);
}
if (params[0] === "start" && testStatus === -1) {
// start new test
testStatus = 0;
try {
// parse settings, if present
var s = {};
try {
var ss = e.data.substring(5);
if (ss) s = JSON.parse(ss);
} catch (e) {
twarn("Error parsing custom settings JSON. Please check your syntax");
}
//copy custom settings
for (var key in s) {
if (typeof settings[key] !== "undefined") settings[key] = s[key];
else twarn("Unknown setting ignored: " + key);
}
// quirks for specific browsers. apply only if not overridden. more may be added in future releases
if (settings.enable_quirks || (typeof s.enable_quirks !== "undefined" && s.enable_quirks)) {
var ua = navigator.userAgent;
if (/Firefox.(\d+\.\d+)/i.test(ua)) {
if (typeof s.xhr_ulMultistream === "undefined") {
// ff more precise with 1 upload stream
settings.xhr_ulMultistream = 1;
}
if (typeof s.xhr_ulMultistream === "undefined") {
// ff performance API sucks
settings.ping_allowPerformanceApi = false;
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
if (typeof s.xhr_dlMultistream === "undefined") {
// edge more precise with 3 download streams
settings.xhr_dlMultistream = 3;
}
}
if (/Chrome.(\d+)/i.test(ua) && !!self.fetch) {
if (typeof s.xhr_dlMultistream === "undefined") {
// chrome more precise with 5 streams
settings.xhr_dlMultistream = 5;
}
}
}
if (/Edge.(\d+\.\d+)/i.test(ua)) {
//Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
settings.forceIE11Workaround = true;
}
if (/PlayStation 4.(\d+\.\d+)/i.test(ua)) {
//PS4 browser has the same bug as IE11/Edge
settings.forceIE11Workaround = true;
}
if (/Chrome.(\d+)/i.test(ua) && /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)) {
//cheap af
//Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
settings.xhr_ul_blob_megabytes = 4;
}
//telemetry_level has to be parsed and not just copied
if (typeof s.telemetry_level !== "undefined") settings.telemetry_level = s.telemetry_level === "basic" ? 1 : s.telemetry_level === "full" ? 2 : s.telemetry_level === "debug" ? 3 : 0; // telemetry level
//transform test_order to uppercase, just in case
settings.test_order = settings.test_order.toUpperCase();
} catch (e) {
twarn("Possible error in custom test settings. Some settings may not be applied. Exception: " + e);
}
// run the tests
tverb(JSON.stringify(settings));
test_pointer = 0;
var iRun = false,
dRun = false,
uRun = false,
pRun = false;
var runNextTest = function() {
if (testStatus == 5) return;
if (test_pointer >= settings.test_order.length) {
//test is finished
if (settings.telemetry_level > 0)
sendTelemetry(function(id) {
testStatus = 4;
if (id != null) testId = id;
});
else testStatus = 4;
return;
}
switch (settings.test_order.charAt(test_pointer)) {
case "I":
{
test_pointer++;
if (iRun) {
runNextTest();
return;
} else iRun = true;
getIp(runNextTest);
}
break;
case "D":
{
test_pointer++;
if (dRun) {
runNextTest();
return;
} else dRun = true;
testStatus = 1;
dlTest(runNextTest);
}
break;
case "U":
{
test_pointer++;
if (uRun) {
runNextTest();
return;
} else uRun = true;
testStatus = 3;
ulTest(runNextTest);
}
break;
case "P":
{
test_pointer++;
if (pRun) {
runNextTest();
return;
} else pRun = true;
testStatus = 2;
pingTest(runNextTest);
}
break;
case "_":
{
test_pointer++;
setTimeout(runNextTest, 1000);
}
break;
default:
test_pointer++;
}
};
runNextTest();
}
if (params[0] === "abort") {
// abort command
tlog("manually aborted");
clearRequests(); // stop all xhr activity
runNextTest = null;
if (interval) clearInterval(interval); // clear timer if present
if (settings.telemetry_level > 1) sendTelemetry(function() {});
testStatus = 5;
dlStatus = "";
ulStatus = "";
pingStatus = "";
jitterStatus = ""; // set test as aborted
}
});
// stops all XHR activity, aggressively
function clearRequests() {
tverb("stopping pending XHRs");
if (xhr) {
for (var i = 0; i < xhr.length; i++) {
try {
xhr[i].onprogress = null;
xhr[i].onload = null;
xhr[i].onerror = null;
} catch (e) {}
try {
xhr[i].upload.onprogress = null;
xhr[i].upload.onload = null;
xhr[i].upload.onerror = null;
} catch (e) {}
try {
xhr[i].abort();
} catch (e) {}
try {
delete xhr[i];
} catch (e) {}
}
xhr = null;
}
}
// gets client's IP using url_getIp, then calls the done function
var ipCalled = false; // used to prevent multiple accidental calls to getIp
var ispInfo = ""; //used for telemetry
function getIp(done) {
tverb("getIp");
if (ipCalled) return;
else ipCalled = true; // getIp already called?
var startT = new Date().getTime();
xhr = new XMLHttpRequest();
xhr.onload = function() {
tlog("IP: " + xhr.responseText + ", took " + (new Date().getTime() - startT) + "ms");
try {
var data = JSON.parse(xhr.responseText);
clientIp = data.processedString;
ispInfo = data.rawIspInfo;
} catch (e) {
clientIp = xhr.responseText;
ispInfo = "";
}
done();
};
xhr.onerror = function() {
tlog("getIp failed, took " + (new Date().getTime() - startT) + "ms");
done();
};
xhr.open("GET", settings.url_getIp + url_sep(settings.url_getIp) + (settings.getIp_ispInfo ? "isp=true" + (settings.getIp_ispInfo_distance ? "&distance=" + settings.getIp_ispInfo_distance + "&" : "&") : "&") + "r=" + Math.random(), true);
xhr.send();
}
// download test, calls done function when it's over
var dlCalled = false; // used to prevent multiple accidental calls to dlTest
function dlTest(done) {
tverb("dlTest");
if (dlCalled) return;
else dlCalled = true; // dlTest already called?
var totLoaded = 0.0, // total number of loaded bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create a download stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testStatus !== 1) return; // delayed stream ended up starting after the end of the download test
tverb("dl test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes loaded last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
xhr[i].onprogress = function(event) {
tverb("dl stream progress event " + i + " " + event.loaded);
if (testStatus !== 1) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the download test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].onload = function() {
// the large file has been loaded entirely, start again
tverb("dl stream finished " + i);
try {
xhr[i].abort();
} catch (e) {} // reset the stream data to empty ram
testStream(i, 0);
}.bind(this);
xhr[i].onerror = function() {
// error
tverb("dl stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
try {
if (settings.xhr_dlUseBlob) xhr[i].responseType = "blob";
else xhr[i].responseType = "arraybuffer";
} catch (e) {}
xhr[i].open("GET", settings.url_dl + url_sep(settings.url_dl) + "r=" + Math.random() + "&ckSize=" + settings.garbagePhp_chunkSize, true); // random string to prevent caching
xhr[i].send();
}.bind(this),
1 + delay
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_dlMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update dlStatus
interval = setInterval(
function() {
tverb("DL: " + dlStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) dlProgress = (t + bonusT) / (settings.time_dl_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_dlGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (6.4 * speed) / 100000;
bonusT += bonus > 800 ? 800 : bonus;
}
//update status
dlStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
if ((t + bonusT) / 1000.0 > settings.time_dl_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(dlStatus)) dlStatus = "Fail";
clearRequests();
clearInterval(interval);
dlProgress = 1;
tlog("dlTest: " + dlStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}
// upload test, calls done function whent it's over
var ulCalled = false; // used to prevent multiple accidental calls to ulTest
function ulTest(done) {
tverb("ulTest");
if (ulCalled) return;
else ulCalled = true; // ulTest already called?
// garbage data for upload test
var r = new ArrayBuffer(1048576);
var maxInt = Math.pow(2, 32) - 1;
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
var req = [];
var reqsmall = [];
for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r);
req = new Blob(req);
r = new ArrayBuffer(262144);
try {
r = new Uint32Array(r);
for (var i = 0; i < r.length; i++) r[i] = Math.random() * maxInt;
} catch (e) {}
reqsmall.push(r);
reqsmall = new Blob(reqsmall);
var totLoaded = 0.0, // total number of transmitted bytes
startT = new Date().getTime(), // timestamp when test was started
bonusT = 0, //how many milliseconds the test has been shortened by (higher on faster connections)
graceTimeDone = false, //set to true after the grace time is past
failed = false; // set to true if a stream fails
xhr = [];
// function to create an upload stream. streams are slightly delayed so that they will not end at the same time
var testStream = function(i, delay) {
setTimeout(
function() {
if (testStatus !== 3) return; // delayed stream ended up starting after the end of the upload test
tverb("ul test stream started " + i + " " + delay);
var prevLoaded = 0; // number of bytes transmitted last time onprogress was called
var x = new XMLHttpRequest();
xhr[i] = x;
var ie11workaround;
if (settings.forceIE11Workaround) ie11workaround = true;
else {
try {
xhr[i].upload.onprogress;
ie11workaround = false;
} catch (e) {
ie11workaround = true;
}
}
if (ie11workaround) {
// IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
xhr[i].onload = xhr[i].onerror = function() {
tverb("ul stream progress event (ie11wa)");
totLoaded += reqsmall.size;
testStream(i, 0);
};
xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
try{
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
}catch(e){}
try{
xhr[i].setRequestHeader("Content-Type", "application/octet-stream"); //force content-type to application/octet-stream in case the server misinterprets it
}catch(e){}
xhr[i].send(reqsmall);
} else {
// REGULAR version, no workaround
xhr[i].upload.onprogress = function(event) {
tverb("ul stream progress event " + i + " " + event.loaded);
if (testStatus !== 3) {
try {
x.abort();
} catch (e) {}
} // just in case this XHR is still running after the upload test
// progress event, add number of new loaded bytes to totLoaded
var loadDiff = event.loaded <= 0 ? 0 : event.loaded - prevLoaded;
if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return; // just in case
totLoaded += loadDiff;
prevLoaded = event.loaded;
}.bind(this);
xhr[i].upload.onload = function() {
// this stream sent all the garbage data, start again
tverb("ul stream finished " + i);
testStream(i, 0);
}.bind(this);
xhr[i].upload.onerror = function() {
tverb("ul stream failed " + i);
if (settings.xhr_ignoreErrors === 0) failed = true; //abort
try {
xhr[i].abort();
} catch (e) {}
delete xhr[i];
if (settings.xhr_ignoreErrors === 1) testStream(i, 0); //restart stream
}.bind(this);
// send xhr
xhr[i].open("POST", settings.url_ul + url_sep(settings.url_ul) + "r=" + Math.random(), true); // random string to prevent caching
try{
xhr[i].setRequestHeader("Content-Encoding", "identity"); // disable compression (some browsers may refuse it, but data is incompressible anyway)
}catch(e){}
try{
xhr[i].setRequestHeader("Content-Type", "application/octet-stream"); //force content-type to application/octet-stream in case the server misinterprets it
}catch(e){}
xhr[i].send(req);
}
}.bind(this),
1
);
}.bind(this);
// open streams
for (var i = 0; i < settings.xhr_ulMultistream; i++) {
testStream(i, settings.xhr_multistreamDelay * i);
}
// every 200ms, update ulStatus
interval = setInterval(
function() {
tverb("UL: " + ulStatus + (graceTimeDone ? "" : " (in grace time)"));
var t = new Date().getTime() - startT;
if (graceTimeDone) ulProgress = (t + bonusT) / (settings.time_ul_max * 1000);
if (t < 200) return;
if (!graceTimeDone) {
if (t > 1000 * settings.time_ulGraceTime) {
if (totLoaded > 0) {
// if the connection is so slow that we didn't get a single chunk yet, do not reset
startT = new Date().getTime();
bonusT = 0;
totLoaded = 0.0;
}
graceTimeDone = true;
}
} else {
var speed = totLoaded / (t / 1000.0);
if (settings.time_auto) {
//decide how much to shorten the test. Every 200ms, the test is shortened by the bonusT calculated here
var bonus = (6.4 * speed) / 100000;
bonusT += bonus > 800 ? 800 : bonus;
}
//update status
ulStatus = ((speed * 8 * settings.overheadCompensationFactor) / (settings.useMebibits ? 1048576 : 1000000)).toFixed(2); // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
if ((t + bonusT) / 1000.0 > settings.time_ul_max || failed) {
// test is over, stop streams and timer
if (failed || isNaN(ulStatus)) ulStatus = "Fail";
clearRequests();
clearInterval(interval);
ulProgress = 1;
tlog("ulTest: " + ulStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this),
200
);
}
// ping+jitter test, function done is called when it's over
var ptCalled = false; // used to prevent multiple accidental calls to pingTest
function pingTest(done) {
tverb("pingTest");
if (ptCalled) return;
else ptCalled = true; // pingTest already called?
var startT = new Date().getTime(); //when the test was started
var prevT = null; // last time a pong was received
var ping = 0.0; // current ping value
var jitter = 0.0; // current jitter value
var i = 0; // counter of pongs received
var prevInstspd = 0; // last ping time, used for jitter calculation
xhr = [];
// ping function
var doPing = function() {
tverb("ping");
pingProgress = i / settings.count_ping;
prevT = new Date().getTime();
xhr[0] = new XMLHttpRequest();
xhr[0].onload = function() {
// pong
tverb("pong");
if (i === 0) {
prevT = new Date().getTime(); // first pong
} else {
var instspd = new Date().getTime() - prevT;
if (settings.ping_allowPerformanceApi) {
try {
//try to get accurate performance timing using performance api
var p = performance.getEntries();
p = p[p.length - 1];
var d = p.responseStart - p.requestStart;
if (d <= 0) d = p.duration;
if (d > 0 && d < instspd) instspd = d;
} catch (e) {
//if not possible, keep the estimate
tverb("Performance API not supported, using estimate");
}
}
//noticed that some browsers randomly have 0ms ping
if(instspd<1) instspd=prevInstspd;
if(instspd<1) instspd=1;
var instjitter = Math.abs(instspd - prevInstspd);
if (i === 1) ping = instspd;
/* first ping, can't tell jitter yet*/ else {
ping = instspd < ping ? instspd : ping * 0.8 + instspd * 0.2; // update ping, weighted average. if the instant ping is lower than the current average, it is set to that value instead of averaging
if (i === 2) jitter = instjitter;
//discard the first jitter measurement because it might be much higher than it should be
else jitter = instjitter > jitter ? jitter * 0.3 + instjitter * 0.7 : jitter * 0.8 + instjitter * 0.2; // update jitter, weighted average. spikes in ping values are given more weight.
}
prevInstspd = instspd;
}
pingStatus = ping.toFixed(2);
jitterStatus = jitter.toFixed(2);
i++;
tverb("ping: " + pingStatus + " jitter: " + jitterStatus);
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}.bind(this);
xhr[0].onerror = function() {
// a ping failed, cancel test
tverb("ping failed");
if (settings.xhr_ignoreErrors === 0) {
//abort
pingStatus = "Fail";
jitterStatus = "Fail";
clearRequests();
tlog("ping test failed, took " + (new Date().getTime() - startT) + "ms");
pingProgress = 1;
done();
}
if (settings.xhr_ignoreErrors === 1) doPing(); //retry ping
if (settings.xhr_ignoreErrors === 2) {
//ignore failed ping
i++;
if (i < settings.count_ping) doPing();
else {
// more pings to do?
pingProgress = 1;
tlog("ping: " + pingStatus + " jitter: " + jitterStatus + ", took " + (new Date().getTime() - startT) + "ms");
done();
}
}
}.bind(this);
// send xhr
xhr[0].open("GET", settings.url_ping + url_sep(settings.url_ping) + "r=" + Math.random(), true); // random string to prevent caching
xhr[0].send();
}.bind(this);
doPing(); // start first ping
}
// telemetry
function sendTelemetry(done) {
if (settings.telemetry_level < 1) return;
xhr = new XMLHttpRequest();
xhr.onload = function() {
try {
var parts = xhr.responseText.split(" ");
if (parts[0] == "id") {
try {
var id = parts[1];
done(id);
} catch (e) {
done(null);
}
} else done(null);
} catch (e) {
done(null);
}
};
xhr.onerror = function() {
console.log("TELEMETRY ERROR " + xhr.status);
done(null);
};
xhr.open("POST", settings.url_telemetry + url_sep(settings.url_telemetry) + "r=" + Math.random(), true);
var telemetryIspInfo = {
processedString: clientIp,
rawIspInfo: typeof ispInfo === "object" ? ispInfo : ""
};
try {
var fd = new FormData();
fd.append("ispinfo", JSON.stringify(telemetryIspInfo));
fd.append("dl", dlStatus);
fd.append("ul", ulStatus);
fd.append("ping", pingStatus);
fd.append("jitter", jitterStatus);
fd.append("log", settings.telemetry_level > 1 ? log : "");
fd.append("extra", settings.telemetry_extra);
xhr.send(fd);
} catch (ex) {
var postData = "extra=" + encodeURIComponent(settings.telemetry_extra) + "&ispinfo=" + encodeURIComponent(JSON.stringify(telemetryIspInfo)) + "&dl=" + encodeURIComponent(dlStatus) + "&ul=" + encodeURIComponent(ulStatus) + "&ping=" + encodeURIComponent(pingStatus) + "&jitter=" + encodeURIComponent(jitterStatus) + "&log=" + encodeURIComponent(settings.telemetry_level > 1 ? log : "");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postData);
}
}

File diff suppressed because one or more lines are too long

110
service.js Normal file
View File

@@ -0,0 +1,110 @@
let serverEUrl = "http://localhost/speedtest/e.php";
let serverGUrl = "http://localhost/speedtest/g.php";
let status = "";
function startTest(){
if(status == "" || status == "stop"){
status = "start";
setText("button", "Stop Test");
}
else if(status == "start"){
status = "stop";
setText("status", "stoping...");
return;
}
setText("status", "checking ping...");
ping((ms) => {
setText("ping", ms);
if(status == "stoped"){stopTest();return;}
setText("status", "checking download...");
download((mb) => {
setText("down", mb);
if(status == "stoped"){stopTest();return;}
setText("status", "checking upload...");
upload((mb) => {
setText("up", mb);
if(status == "stoped"){stopTest();return;}
setText("status", "done.");
setText("button", "Start Test");
});
});
});
}
function stopTest(){
setText("button", "Start Test");
setText("status", "stoped.");
}
function setText(elm, text){
document.getElementById(elm).innerText = text;
}
function ping(callback) {
var startTime = 0;
var request = new XMLHttpRequest();
request.open("HEAD", serverEUrl + "?_=" + Math.random(), true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var endTime = new Date().getTime();
callback(endTime - startTime);
}
};
try {
startTime = new Date().getTime();
request.send(null);
} catch(exception) {
alert("Your internet connection is unavelible...");
}
}
function download(callback){
var startTime = 0;
var request = new XMLHttpRequest();
request.open("GET", serverGUrl, true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status === 200) {
var endTime = new Date().getTime();
var reqLength = request.responseText.length * 8;
var sumTime = (endTime - startTime) / 1000;
var speed = (((reqLength / sumTime) / 1024 /* Kbps */) / 1024 /* Mbps */).toFixed(2);
callback(speed + " Mbps");
}
};
try {
startTime = new Date().getTime();
request.send(null);
} catch(exception) {
alert("Your internet connection is unavelible...");
}
}
function junkData(length){
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()`[]\\{}|:"<>?,./;\'', result = '';
for (var i = 0; i < length; i++) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
function upload(callback){
var startTime = 0;
var junkLength = 2500000;
var junk = junkData(junkLength); //=2.5 Mb
var request = new XMLHttpRequest();
request.open("POST", serverEUrl + "?_=" + Math.random(), true);
request.setRequestHeader("Content-Type", "application/octet-stream");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status === 200) {
var endTime = new Date().getTime();
var sumTime = (endTime - startTime) / 1000;
var speed = (((junkLength / sumTime) / 1024 /* Kbps */) / 1024 /* Mbps */).toFixed(2);
callback(speed + " Mbps");
}
};
try {
startTime = new Date().getTime();
request.send(junk);
} catch(exception) {
alert("Your internet connection is unavelible...");
}
}