rhythm/lib/validation.php

120 lines
2.9 KiB
PHP
Raw Normal View History

2020-03-05 20:46:08 +00:00
<?php
// https://stackoverflow.com/a/600306/9123061
function is_valid_note($x)
{
return ($x & ($x - 1)) == 0;
}
function is_valid_time($check_time)
{
if(!is_string($check_time))
{
return false;
}
$check_time = remove_whitespace($check_time);
$check_time_explode = explode("/", $check_time, 2);
$check_time_explode[0] = intval($check_time_explode[0]);
$check_time_explode[1] = intval($check_time_explode[1]);
if(count($check_time_explode) != 2 || $check_time_explode[0] < 1 || $check_time_explode[1] < 1)
{
return false;
}
if(!is_valid_note($check_time_explode[1]))
{
return false;
}
$ratio = $check_time_explode[0] / $check_time_explode[1];
$new_rhythm_length = intval(MAX_FRACTION * $ratio);
if(!is_int($new_rhythm_length) || $new_rhythm_length == 0)
{
return false;
}
return true;
}
function is_valid_tempo($check_tempo)
{
if(!is_string($check_tempo))
{
return false;
}
$check_tempo = remove_whitespace($check_tempo);
$check_tempo_explode = explode("=", $check_tempo, 2);
$check_tempo_explode[0] = intval($check_tempo_explode[0]);
$check_tempo_explode[1] = intval($check_tempo_explode[1]);
if(count($check_tempo_explode) != 2 || $check_tempo_explode[0] < 1 || $check_tempo_explode[1] < 1)
{
return false;
}
if(!is_valid_note($check_tempo_explode[0]))
{
return false;
}
return true;
}
function is_valid_bars($check_bars)
{
if(!intval($check_bars))
{
return false;
}
$check_bars = intval($check_bars);
if($check_bars < 1 || $check_bars > 64)
{
return false;
}
return true;
}
function is_valid_dynamic($check_dynamic)
{
if(!is_string($check_dynamic))
{
return false;
}
$allowed_dynamics_regex = "/^(p{1,5}|f{1,5}|m(p|f)|s(p{1,2}|f{1,2})|fp|(s|r)fz)$/";
if(!preg_match($allowed_dynamics_regex, $check_dynamic))
{
return false;
}
return true;
}
function validate_get_parameter()
{
if(!(isset($_GET["time"]) && is_valid_time($_GET["time"])))
{
$_GET["time"] = "4/4";
}
$_GET["time"] = remove_whitespace($_GET["time"]);
if(!(isset($_GET["tempo"]) && is_valid_tempo($_GET["tempo"])))
{
$_GET["tempo"] = "4=90";
}
$_GET["tempo"] = remove_whitespace($_GET["tempo"]);
if(!(isset($_GET["bars"]) && is_valid_bars($_GET["bars"])))
{
$_GET["bars"] = "2";
}
if(!(isset($_GET["dynamic_beat"]) && is_valid_dynamic($_GET["dynamic_beat"])))
{
$_GET["dynamic_beat"] = "pp";
}
if(!(isset($_GET["dynamic_rhythm"]) && is_valid_dynamic($_GET["dynamic_rhythm"])))
{
$_GET["dynamic_rhythm"] = "ff";
}
if(!(isset($_GET["id"]) && is_string($_GET["id"]) && strlen($_GET["id"]) > 1))
{
$_GET["id"] = md5(random_bytes(60));
}
}
?>