diff options
Diffstat (limited to 'includes')
54 files changed, 98 insertions, 8902 deletions
diff --git a/includes/backup.inc b/includes/backup.inc deleted file mode 100644 index bed4637..0000000 --- a/includes/backup.inc +++ /dev/null @@ -1,95 +0,0 @@ -<?php - -echo(" Scanning...\n"); -$root = array_filter(scandir("data"), function ($i) { - return !str_starts_with($i, "."); -}); -$files = []; -$data = [ - "date" => date('c'), - "files" => [] -]; - -foreach ($root as $file) { - if ($file === "backup.poniesbackup" || $file === "backup.ponieskey" || $file === "encrypted" || str_ends_with($file, ".poniesbackup")) continue; - echo(" /$file\n"); - - if (is_dir("data/$file")) { - foreach (array_filter(scandir("data/$file"), function ($i) { - return !str_starts_with($i, "."); - }) as $dirfile) { - if ($dirfile === "backup.poniesbackup" || $dirfile === "backup.ponieskey" || $dirfile === "encrypted" || str_ends_with($dirfile, ".poniesbackup")) continue; - - echo(" /$dirfile/$file\n"); - $files[] = [ - "dir" => $file, - "file" => $dirfile - ]; - } - } else { - echo(" /$file\n"); - $files[] = [ - "dir" => "", - "file" => $file - ]; - } -} - -echo(" Reading files...\n"); -foreach ($files as $file) { - echo(" /$file[dir]/$file[file]\n"); - $file["mime"] = mime_content_type("data/$file[dir]/$file[file]"); - $file["checksum"] = [ - sha1_file("data/$file[dir]/$file[file]"), - md5_file("data/$file[dir]/$file[file]") - ]; - $file["content"] = base64_encode(file_get_contents("data/$file[dir]/$file[file]")); - - $data["files"][] = $file; -} - -function pkcs7_pad($data, $size) { - $length = $size - strlen($data) % $size; - return $data . str_repeat(chr($length), $length); -} - -if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.ponieskey")) { - echo(" Creating encryption key...\n"); - $key = openssl_random_pseudo_bytes(512); - $iv = openssl_random_pseudo_bytes(16); - file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.ponieskey", base64_encode(json_encode([ - "iv" => bin2hex($iv), - "key" => bin2hex($key) - ]))); -} else { - echo(" Reading encryption key...\n"); - $key_raw = json_decode(base64_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.ponieskey")), true); - $key = hex2bin($key_raw["key"]); - $iv = hex2bin($key_raw["iv"]); -} - -echo(" Encrypting...\n"); -$payload = json_encode($data); -$encrypted = openssl_encrypt(pkcs7_pad($payload, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); - -echo(" Writing backup...\n"); -file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.poniesbackup", $encrypted); -@mkdir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/encrypted"); - -$id = str_replace(":", "-", date('c')); -copy($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.poniesbackup", $_SERVER['DOCUMENT_ROOT'] . "/includes/data/encrypted/" . $id . ".poniesbackup"); - -echo(" Uploading to servers...\n"); - -echo(" zephyrheights... upload\n"); -exec("scp -P 2222 " . $_SERVER['DOCUMENT_ROOT'] . "/includes/data/encrypted/" . $id . ".poniesbackup root@zephyrheights.equestria.dev:/opt/ponies"); - -if (file_exists("/opt/ponies")) { - echo(" bridlewood... copy\n"); - copy($_SERVER['DOCUMENT_ROOT'] . "/includes/data/encrypted/" . $id . ".poniesbackup", "/opt/ponies/" . $id . ".poniesbackup"); - echo(" bridlewood... cleaning up\n"); - exec('bash -c "cd /opt/ponies; ls -tp | grep -v \'/$\' | tail -n +20 | xargs -I {} rm -- {}"'); -} - -echo(" Cleaning up...\n"); -unlink($_SERVER['DOCUMENT_ROOT'] . "/includes/data/encrypted/" . $id . ".poniesbackup");
\ No newline at end of file diff --git a/includes/components/2023ui.inc b/includes/components/2023ui.inc index 7b74395..4c1aa5b 100644 --- a/includes/components/2023ui.inc +++ b/includes/components/2023ui.inc @@ -102,17 +102,6 @@ <span style="margin-left: 5px; vertical-align: middle; position: relative; top: -1px; font-weight: bold;">Ponycule</span> </a> </div> - <div style="display: flex; align-items: center;"> - <?php global $isLowerLoggedIn; global $isLoggedIn; global $_PROFILE; if ($isLoggedIn || $isLowerLoggedIn): ?> - <div class="mobile-icon-container mobile-icon-container-left" style="margin-left: auto; margin-right: auto;"> - <a data-bs-toggle="tooltip" data-bs-placement="bottom" title="Alerts" class="ui2023-side-bar-item mobile-hide" href="/-/alerts" style="padding: 10px; height: 48px; width: 48px; display: inline-block; border-radius: 999px;"> - <img src="<?= icon("alerts") ?>" style="max-width: 28px; max-height: 28px;"> - </a><a data-bs-toggle="tooltip" data-bs-placement="bottom" title="Member lists" class="ui2023-side-bar-item mobile-hide" href="/-/lists" style="padding: 10px; height: 48px; width: 48px; display: inline-block; border-radius: 999px;"> - <img src="<?= icon("lists") ?>" style="max-width: 28px; max-height: 28px;"> - </a> - </div> - <?php endif; ?> - </div> </div> <div style="height: 52px; display: flex; align-items: center;"> <!--<form action="/-/search" style="width: 100%;"> @@ -125,24 +114,18 @@ <div style="margin-left: auto; margin-right: auto;" class="mobile-icon-container mobile-icon-container-right"> <a data-bs-toggle="tooltip" data-bs-placement="bottom" title="Jobs" class="ui2023-side-bar-item mobile-hide" href="/-/jobs" style="padding: 10px; height: 48px; width: 48px; display: inline-block; border-radius: 999px;"> <img src="<?= icon("jobs") ?>" style="max-width: 28px; max-height: 28px;"> - </a><a data-bs-toggle="tooltip" data-bs-placement="bottom" title="Account" class="ui2023-side-bar-item mobile-hide" href="/-/account" style="padding: 10px; height: 48px; width: 48px; display: inline-block; border-radius: 999px;"> - <img src="<?= icon("sessions") ?>" style="max-width: 28px; max-height: 28px;"> + </a><a data-bs-toggle="tooltip" data-bs-placement="bottom" title="Logout" class="ui2023-side-bar-item mobile-hide" href="/-/logout" style="padding: 10px; height: 48px; width: 48px; display: inline-block; border-radius: 999px;"> + <img src="<?= icon("logout") ?>" style="max-width: 28px; max-height: 28px;"> </a><div class="ui2023-side-bar-item mobile-show dropdown" style="padding: 10px; height: 48px; width: 48px; display: none; border-radius: 999px;"> <a data-bs-toggle="dropdown" href="#"> <img src="<?= icon("menu") ?>" style="max-width: 28px; max-height: 28px;"> </a> <ul class="dropdown-menu"> - <li><a class="dropdown-item" href="/-/alerts"> - <img src="<?= icon("alerts") ?>" style="vertical-align: middle; width: 24px; height: 24px;"><span style="vertical-align: middle; margin-left: 5px;">Alerts</span> - </a></li> - <li><a class="dropdown-item" href="/-/lists"> - <img src="<?= icon("lists") ?>" style="vertical-align: middle; width: 24px; height: 24px;"><span style="vertical-align: middle; margin-left: 5px;">Lists</span> - </a></li> <li><a class="dropdown-item" href="/-/jobs"> <img src="<?= icon("jobs") ?>" style="vertical-align: middle; width: 24px; height: 24px;"><span style="vertical-align: middle; margin-left: 5px;">Jobs</span> </a></li> - <li><a class="dropdown-item" href="/-/account"> - <img src="<?= icon("sessions") ?>" style="vertical-align: middle; width: 24px; height: 24px;"><span style="vertical-align: middle; margin-left: 5px;">Account</span> + <li><a class="dropdown-item" href="/-/logout"> + <img src="<?= icon("logout") ?>" style="vertical-align: middle; width: 24px; height: 24px;"><span style="vertical-align: middle; margin-left: 5px;">Logout</span> </a></li> </ul> </div> @@ -200,11 +183,5 @@ <img class="antialias" class="antialias" src="<?= getAsset("hrbom") ?>" style="max-width: 32px; max-height: 32px;"> </a> </div> - - <div id="side-bar-options" style="margin-top: 20px;"> - <a data-bs-toggle="tooltip" data-bs-placement="right" title="Relations" class="ui2023-side-bar-item" href="/-/relations" style="padding: 10px; height: 48px; width: 48px; display: block; border-radius: 999px;"> - <img src="<?= icon("relations") ?>" style="max-width: 28px; max-height: 28px;"> - </a> - </div> </div> -</div>
\ No newline at end of file +</div> diff --git a/includes/components/emergency.inc b/includes/components/emergency.inc deleted file mode 100644 index 67f4422..0000000 --- a/includes/components/emergency.inc +++ /dev/null @@ -1,156 +0,0 @@ -<h2>Emergency alert - <details style="display: inline-block;font-size:12px;"> - <summary class="text-muted" style="opacity:.5;"></summary> - <label><input id="test-mode" type="checkbox"> Test Mode</label> · <label><input id="fake-requests" type="checkbox"> Fake Requests</label> - </details> -</h2> - -<span data-bs-toggle="modal" data-bs-target="#turn-on" id="btn-on" style="background: #7f0000;font-size: 48px;padding: 10px 50px;border-radius: 10px;width: max-content;display: block;margin-left: auto;margin-right: auto;cursor: pointer;">Turn <b>ON</b></span> -<span data-bs-toggle="modal" onclick="disableAlert();" id="btn-off" style="display:none;background: #007f0b;font-size: 48px;padding: 10px 50px;border-radius: 10px;width: max-content;margin-left: auto;margin-right: auto;cursor: pointer;">Turn <b>OFF</b></span> -<p style="text-align:center;margin-top:10px;">Sending the next notification <b><span id="next-notification">never</span></b></p> - -<hr> - -<div style="margin-bottom: 10px;"> - <b>Targets:</b> -</div> - -<label style="display: block; margin-left: 10px;"> - <input type="checkbox" checked id="enable-raindrops"> Raindrops System -</label> -<label style="display: block; margin-left: 10px;"> - <input type="checkbox" id="enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>"> <?= $GLOBALS["ColdHazeApp"]["other"]["name"] ?> -</label> -<label style="display: block; margin-left: 10px;"> - <input type="checkbox" id="enable-moonglow"> Moonglow -</label> -<!--<label style="display: block; margin-left: 10px;"> - <input type="checkbox" id="enable-hailstorm"> Hailstorm -</label>--> - -<style> - <?php global $use2023UI; if (!$use2023UI): ?> - .modal-header { - border-bottom: 1px solid #353738; - } - - .modal-content { - border: 1px solid rgba(255, 255, 255, .2); - background-color: #111; - } - - .btn-close { - filter: invert(1); - } - <?php endif; ?> - - #btn-on.disabled, #btn-off.disabled { - opacity: .5; - pointer-events: none; - } -</style> - -<div class="modal fade" id="turn-on"> - <div class="modal-dialog"> - <div class="modal-content"> - - <div class="modal-header"> - <h4 class="modal-title">Important notice</h4> - <button type="button" class="btn-close" data-bs-dismiss="modal"></button> - </div> - - <div class="modal-body"> - <div class="alert alert-danger"> - Keep this page open until you receive help. If you close the page, alert notifications will not be sent. - </div> - - <button onclick="enableAlert();" data-bs-dismiss="modal" class="btn btn-danger" style="font-size:20px;font-weight:bold;display:block;width:100%;">Enable the alert now.</button> - - <div class="alert alert-light" style="margin-top: 20px;"> - <b>Disclaimer:</b> This alert should be used <b>if and only if</b> you are in a situation that requires immediate help from a loved one. If your life is at immediate risk, please do not use this emergency system and call your local emergency services. - </div> - </div> - </div> - </div> -</div> - -<script> - window.alertInterval = null; - window.alertInterval = null; - window.alertIntervalAmount = 15; - window.alertIntervalCounter = window.alertIntervalAmount; - - function buildTargets() { - let targets = [ - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").checked ? "<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>" : null, - document.getElementById("enable-raindrops").checked ? "raindrops" : null, - document.getElementById("enable-moonglow").checked ? "moonglow" : null, - //document.getElementById("enable-hailstorm").checked ? "hailstorm" : null, - ].filter(i => i); - return "?" + targets.join("&"); - } - - function sendNotification() { - window.alertIntervalCounter = -1; - - if (document.getElementById("test-mode").checked) { - document.getElementById("next-notification").innerText = "now"; - if (document.getElementById("fake-requests").checked) { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - } else { - window.fetch("/api/emergency" + buildTargets()).then(() => { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - }) - } - } else { - document.getElementById("next-notification").innerText = "now"; - if (document.getElementById("fake-requests").checked) { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - } else { - window.fetch("/api/emergency-real" + buildTargets()).then(() => { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - }) - } - } - } - - function enableAlert() { - sendNotification(); - document.getElementById("btn-on").style.display = "none"; - document.getElementById("btn-off").style.display = "block"; - document.getElementById("test-mode").disabled = true; - document.getElementById("fake-requests").disabled = true; - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").disabled = true; - document.getElementById("enable-raindrops").disabled = true; - document.getElementById("enable-moonglow").disabled = true; - //document.getElementById("enable-hailstorm").disabled = true; - - window.alertInterval = setInterval(() => { - window.alertIntervalCounter--; - - if (window.alertIntervalCounter === 0) { - sendNotification(); - } else if (window.alertIntervalCounter > -1) { - document.getElementById("next-notification").innerText = "in " + window.alertIntervalCounter + " second" + (window.alertIntervalCounter > 1 ? "s" : ""); - } - }, 1000); - } - - function disableAlert() { - clearInterval(window.alertInterval); - window.alertIntervalCounter = 15; - document.getElementById("next-notification").innerText = "never"; - document.getElementById("btn-on").style.display = "block"; - document.getElementById("btn-off").style.display = "none"; - document.getElementById("test-mode").disabled = false; - document.getElementById("fake-requests").disabled = false; - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").disabled = false; - document.getElementById("enable-raindrops").disabled = false; - document.getElementById("enable-moonglow").disabled = false; - //document.getElementById("enable-hailstorm").disabled = false; - } -</script>
\ No newline at end of file diff --git a/includes/components/footer.inc b/includes/components/footer.inc index c062436..00d74aa 100644 --- a/includes/components/footer.inc +++ b/includes/components/footer.inc @@ -14,8 +14,6 @@ $start = microtime(true); return new bootstrap.Tooltip(tooltipTriggerEl) }); - window.fetch("/api/rename?name=" + encodeURIComponent("Cold Haze Web (" + UAParser().browser.name + " on " + UAParser().os.name + ")")); - if (document.createElement("canvas").getContext("webgl") === null) { let style = document.createElement("style"); style.innerText = "* { backdrop-filter: none !important; }"; @@ -29,4 +27,4 @@ $start = microtime(true); <?php endif; ?> </body> -</html>
\ No newline at end of file +</html> diff --git a/includes/components/header.inc b/includes/components/header.inc index bd85761..7cf626e 100644 --- a/includes/components/header.inc +++ b/includes/components/header.inc @@ -25,7 +25,6 @@ $page = $pages[$toplevel] ?? [ "rail" => false ]; -require_once $_SERVER["DOCUMENT_ROOT"] . "/includes/util/travelling.inc"; global $travelling; require_once $_SERVER["DOCUMENT_ROOT"] . "/includes/util/score.inc"; require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/functions.inc"; require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/banner.inc"; @@ -473,4 +472,4 @@ require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/rainbow.inc"; <?php require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/components/2023ui.inc"; ?> <?php $GLOBALS["ColdHazePerformance"]["header"] = (microtime(true) - $start) * 1000; $start = microtime(true); ?> -<main id="app" style="background-color: var(--palette-0);">
\ No newline at end of file +<main id="app" style="background-color: var(--palette-0);"> diff --git a/includes/components/pleasure.inc b/includes/components/pleasure.inc deleted file mode 100644 index 6d5f4b1..0000000 --- a/includes/components/pleasure.inc +++ /dev/null @@ -1,201 +0,0 @@ -<?php global $app; global $_PROFILE; $front = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/gdapd/fronters.json"), true)["members"]; ?> - -<h2>Pleasure alert - <details style="display: inline-block;font-size:12px;"> - <summary class="text-muted" style="opacity:.5;"></summary> - <label><input id="test-mode" type="checkbox"> Test Mode</label> · <label><input id="fake-requests" type="checkbox"> Fake Requests</label> - </details> -</h2> - -<?php if (isset($front[0])): ?> - <?php if (!parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $front[0]["id"] . ".json"), true))["other"] && !parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $front[0]["id"] . ".json"), true))["other2"]): ?> - <div class="alert alert-warning"> - <?php - - if (count($front) === 1) { - echo("<b>" . ($front[0]["display_name"] ?? $front[0]["name"]) . "</b> is currently at front and you cannot have sex with this pony."); - } elseif (count($front) === 2) { - echo("<b>" . ($front[0]["display_name"] ?? $front[0]["name"]) . " and " . ($front[1]["display_name"] ?? $front[1]["name"]) . "</b> are currently at front and you cannot have sex with them."); - } else { - echo("Ponies are currently at front and you cannot have sex with them."); - } - - ?> However, if you wish, any of the ponies mentioned on this page can take control of the body for the amount of time required for sex. - </div> - <?php elseif (!parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $front[0]["id"] . ".json"), true))["other"]): ?> - <div class="alert alert-warning"> - <?php - - if (count($front) === 1) { - echo("<b>" . ($front[0]["display_name"] ?? $front[0]["name"]) . "</b> is currently at front and may not want to have sex with you."); - } elseif (count($front) === 2) { - echo("<b>" . ($front[0]["display_name"] ?? $front[0]["name"]) . " and " . ($front[1]["display_name"] ?? $front[1]["name"]) . "</b> are currently at front and may not want to have sex with you."); - } else { - echo("Ponies are currently at front and may not want to have sex with you."); - } - - ?> However, if this pony is not wanting to have sex with you, any of the ponies mentioned on this page can take control of the body for the amount of time required for sex. - </div> - <?php endif; ?> -<?php endif; ?> - -<span data-bs-toggle="modal" data-bs-target="#turn-on" id="btn-on" style="background: #7f0000;font-size: 48px;padding: 10px 50px;border-radius: 10px;width: max-content;display: block;margin-left: auto;margin-right: auto;cursor: pointer;">Turn <b>ON</b></span> -<span onclick="disableAlert()" id="btn-off" style="display:none;background: #007f0b;font-size: 48px;padding: 10px 50px;border-radius: 10px;width: max-content;margin-left: auto;margin-right: auto;cursor: pointer;">Turn <b>OFF</b></span> -<p style="text-align:center;margin-top:10px;">Sending the next notification <b><span id="next-notification">never</span></b> · Local time for Raindrops: <span id="raindrops-time">--:--</span></p> - -<hr> - -<div style="margin-bottom: 10px;"> - <b>Targets:</b> -</div> - -<label style="display: block; margin-left: 10px;"> - <input type="radio" name="target" checked id="enable-raindrops"> Raindrops System -</label> -<label style="display: block; margin-left: 10px;"> - <input type="radio" name="target" id="enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>"> <?= $GLOBALS["ColdHazeApp"]["other"]["name"] ?> -</label> -<label style="display: block; margin-left: 10px;"> - <input type="radio" name="target" id="enable-moonglow"> Moonglow -</label> - -<script> - function updateTime() { - let time = (new Intl.DateTimeFormat("en-US", { - timeZone: 'Europe/Paris', - hour: 'numeric', - minute: 'numeric', - hour12: true - })).format(new Date()); - - document.getElementById("raindrops-time").innerText = time; - } - - updateTime(); - - setInterval(() => { - updateTime(); - }, 10000); -</script> - -<style> - <?php global $use2023UI; if (!$use2023UI): ?> - .modal-header { - border-bottom: 1px solid #353738; - } - - .modal-content { - border: 1px solid rgba(255, 255, 255, .2); - background-color: #111; - } - - .btn-close { - filter: invert(1); - } - <?php endif; ?> - - #btn-on.disabled, #btn-off.disabled { - opacity: .5; - pointer-events: none; - } -</style> - -<div class="modal fade" id="turn-on"> - <div class="modal-dialog"> - <div class="modal-content"> - - <div class="modal-header"> - <h4 class="modal-title">Important notice</h4> - <button type="button" class="btn-close" data-bs-dismiss="modal"></button> - </div> - - <div class="modal-body"> - <div class="alert alert-danger"> - Keep this page open until your pony wakes up. If you close the page, alert notifications will not be sent. - </div> - - <button onclick="enableAlert();" data-bs-dismiss="modal" class="btn btn-danger" style="font-size:20px;font-weight:bold;display:block;width:100%;">Enable the alert now.</button> - - <div class="alert alert-light" style="margin-top: 20px;"> - <b>Disclaimer:</b> This alert is not to be used in an emergency. If you need immediate help, use the <a href="/-/emergency">Emergency alert</a> instead. - </div> - </div> - </div> - </div> -</div> - -<script> - window.alertInterval = null; - window.alertIntervalAmount = 5; - window.alertIntervalCounter = window.alertIntervalAmount; - - function buildTargets() { - let targets = [ - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").checked ? "<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>" : null, - document.getElementById("enable-raindrops").checked ? "raindrops" : null, - document.getElementById("enable-moonglow").checked ? "moonglow" : null, - ].filter(i => i); - return "?" + targets.join("&"); - } - - function sendNotification() { - window.alertIntervalCounter = -1; - - if (document.getElementById("test-mode").checked) { - document.getElementById("next-notification").innerText = "now"; - if (document.getElementById("fake-requests").checked) { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - } else { - window.fetch("/api/pleasure" + buildTargets()).then(() => { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - }) - } - } else { - document.getElementById("next-notification").innerText = "now"; - if (document.getElementById("fake-requests").checked) { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - } else { - window.fetch("/api/pleasure-real" + buildTargets()).then(() => { - window.alertIntervalCounter = window.alertIntervalAmount; - document.getElementById("next-notification").innerText = "in " + window.alertIntervalAmount + " seconds"; - }) - } - } - } - - function enableAlert() { - sendNotification(); - document.getElementById("btn-on").style.display = "none"; - document.getElementById("btn-off").style.display = "block"; - document.getElementById("test-mode").disabled = true; - document.getElementById("fake-requests").disabled = true; - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").disabled = true; - document.getElementById("enable-raindrops").disabled = true; - document.getElementById("enable-moonglow").disabled = true; - - window.alertInterval = setInterval(() => { - window.alertIntervalCounter--; - - if (window.alertIntervalCounter === 0) { - sendNotification(); - } else if (window.alertIntervalCounter > -1) { - document.getElementById("next-notification").innerText = "in " + window.alertIntervalCounter + " second" + (window.alertIntervalCounter > 1 ? "s" : ""); - } - }, 1000); - } - - function disableAlert() { - clearInterval(window.alertInterval); - document.getElementById("next-notification").innerText = "never"; - document.getElementById("btn-on").style.display = "block"; - document.getElementById("btn-off").style.display = "none"; - document.getElementById("test-mode").disabled = false; - document.getElementById("fake-requests").disabled = false; - document.getElementById("enable-<?= $GLOBALS["ColdHazeApp"]["other"]["slug"] ?>").disabled = false; - document.getElementById("enable-raindrops").disabled = false; - document.getElementById("enable-moonglow").disabled = false; - } -</script>
\ No newline at end of file diff --git a/includes/components/sysbanner.inc b/includes/components/sysbanner.inc index 6a66ab4..c6f9579 100644 --- a/includes/components/sysbanner.inc +++ b/includes/components/sysbanner.inc @@ -8,7 +8,7 @@ global $systemID; global $system; global $lang; global $pages; global $app; -$travelling = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/travelling/travelling.json"), true); +$travelling = []; $pages = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/pages.json"), true); ?> @@ -62,4 +62,4 @@ $pages = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/pa </a> <div></div> </div> -</div>
\ No newline at end of file +</div> diff --git a/includes/exchange.txt b/includes/exchange.txt deleted file mode 100644 index 309642e..0000000 --- a/includes/exchange.txt +++ /dev/null @@ -1 +0,0 @@ -0.87533867
\ No newline at end of file diff --git a/includes/external/next/index.php b/includes/external/next/index.php index 5e96fb7..f35a96f 100644 --- a/includes/external/next/index.php +++ b/includes/external/next/index.php @@ -69,16 +69,40 @@ $members = array_map(function ($i) { return $i["_system"] === "gdapd"; }))); -$requested = []; -foreach ([...$pairs, ...$pairs2] as $pair) { +$requested = []; foreach ([...$pairs, ...$pairs2] as $pair) { array_push($requested, ...$pair); -} +} $requested = array_unique($requested); + +usort($pairs2, function ($a, $b) use ($members) { + $times = []; + + foreach ($a as $id) { + if (getLastFronted($members, $id) > 0) $times[] = getLastFronted($members, $id); + } + + $timeA = time() - min($times); + $times = []; + + foreach ($b as $id) { + if (getLastFronted($members, $id) > 0) $times[] = getLastFronted($members, $id); + } + + $timeB = time() - min($times); + + if ($timeA < 5 || $timeB < 5) { + return -INF; + } else { + return $timeB - $timeA; + } +}); $pairsM = array_values($pairs2); + +$requested = array_map(function ($i) { return $i[0]; }, $pairsM); $fronters = array_map(function ($i) { return $i["id"]; }, json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/gdapd/fronters.json"), true)["members"]); -$requested = array_values(array_filter(array_reverse(array_unique($requested)), function ($i) use ($fronters) { +$requested = array_values(array_filter(array_unique($requested), function ($i) use ($fronters) { return !in_array($i, $fronters); })); diff --git a/includes/external/pair/index.js b/includes/external/pair/index.js deleted file mode 100644 index f933232..0000000 --- a/includes/external/pair/index.js +++ /dev/null @@ -1,117 +0,0 @@ -const { WebSocketServer } = require('ws'); -const crypto = require('crypto'); -const version = 1; - -const wss = new WebSocketServer({ port: 12378 }); -// wss://ponies.equestria.horse/_PairingServices-WebSocket-EntryPoint/socket - -let clients = {}; - -function generateCode() { - return crypto.randomBytes(32).toString("base64").replace(/[\/=+]/gm, "").substring(0, 5).toUpperCase(); -} - -wss.on('connection', (ws, req) => { - ws.code = generateCode(); - ws.ipAddress = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0].trim() : req.socket.remoteAddress; - - ws.on('error', (e) => { - console.error(e); - ws.close(); - }); - - ws.on('close', () => { - if (clients[ws.code]) { - delete clients[ws.code]; - } - }); - - ws.on('message', function message(raw) { - try { - let data = JSON.parse(raw.toString()); - - switch (data.type) { - case "fetch": - if (clients[data.code ?? ""] && clients[data.code ?? ""].socket) { - clients[data.code ?? ""].socket.send(JSON.stringify({ - type: "preflight", - identity: { - name: data.identity ? (data.identity.name ?? "<Unknown name>") : "<Unknown name>", - platform: data.identity ? (data.identity.platform ?? "<Unknown device>") : "<Unknown device>" - } - })); - ws.send(JSON.stringify({ - type: "device", - identity: { - name: clients[data.code ?? ""].name, - address: clients[data.code ?? ""].socket.ipAddress - } - })) - } else { - ws.send(JSON.stringify({ - type: "invalid" - })); - } - break; - - case "confirm": - if (clients[data.code ?? ""] && clients[data.code ?? ""].socket && data.token && ws.token) { - clients[data.code ?? ""].socket.send(JSON.stringify({ - type: "confirm", - token: data.token - })); - - delete clients[data.code ?? ""]; - } else { - ws.send(JSON.stringify({ - type: "invalid" - })); - } - break; - - case "reject": - if (clients[data.code ?? ""] && clients[data.code ?? ""].socket && ws.token) { - clients[data.code ?? ""].socket.send(JSON.stringify({ - type: "reject", - token: null - })); - - delete clients[data.code ?? ""]; - } else { - ws.send(JSON.stringify({ - type: "invalid" - })); - } - break; - - case "init": - if (data.token) { - ws.token = data.token; - } else { - clients[ws.code] = { - socket: ws, - name: (typeof data.name === "string" && data.name.length > 2 && data.name.length < 100) ? data.name : "<Unknown client>" - } - - ws.send(JSON.stringify({ - type: "waiting", - code: ws.code - })) - } - - break; - - default: - ws.close(); - } - } catch (e) { - console.error(e); - ws.close(); - } - }); - - ws.send(JSON.stringify({ - version, - type: "init" - })); -});
\ No newline at end of file diff --git a/includes/external/pair/node_modules/.package-lock.json b/includes/external/pair/node_modules/.package-lock.json deleted file mode 100644 index bd1f4fc..0000000 --- a/includes/external/pair/node_modules/.package-lock.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "pair", - "lockfileVersion": 2, - "requires": true, - "packages": { - "node_modules/ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/includes/external/pair/node_modules/ws/LICENSE b/includes/external/pair/node_modules/ws/LICENSE deleted file mode 100644 index 1da5b96..0000000 --- a/includes/external/pair/node_modules/ws/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com> -Copyright (c) 2013 Arnout Kazemier and contributors -Copyright (c) 2016 Luigi Pinca and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/includes/external/pair/node_modules/ws/README.md b/includes/external/pair/node_modules/ws/README.md deleted file mode 100644 index a550ca1..0000000 --- a/includes/external/pair/node_modules/ws/README.md +++ /dev/null @@ -1,536 +0,0 @@ -# ws: a Node.js WebSocket library - -[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) -[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) -[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) - -ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and -server implementation. - -Passes the quite extensive Autobahn test suite: [server][server-report], -[client][client-report]. - -**Note**: This module does not work in the browser. The client in the docs is a -reference to a back end with the role of a client in the WebSocket -communication. Browser clients must use the native -[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) -object. To make the same code work seamlessly on Node.js and the browser, you -can use one of the many wrappers available on npm, like -[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). - -## Table of Contents - -- [Protocol support](#protocol-support) -- [Installing](#installing) - - [Opt-in for performance](#opt-in-for-performance) -- [API docs](#api-docs) -- [WebSocket compression](#websocket-compression) -- [Usage examples](#usage-examples) - - [Sending and receiving text data](#sending-and-receiving-text-data) - - [Sending binary data](#sending-binary-data) - - [Simple server](#simple-server) - - [External HTTP/S server](#external-https-server) - - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) - - [Client authentication](#client-authentication) - - [Server broadcast](#server-broadcast) - - [Round-trip time](#round-trip-time) - - [Use the Node.js streams API](#use-the-nodejs-streams-api) - - [Other examples](#other-examples) -- [FAQ](#faq) - - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) - - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) - - [How to connect via a proxy?](#how-to-connect-via-a-proxy) -- [Changelog](#changelog) -- [License](#license) - -## Protocol support - -- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) -- **HyBi drafts 13-17** (Current default, alternatively option - `protocolVersion: 13`) - -## Installing - -``` -npm install ws -``` - -### Opt-in for performance - -There are 2 optional modules that can be installed along side with the ws -module. These modules are binary addons that improve the performance of certain -operations. Prebuilt binaries are available for the most popular platforms so -you don't necessarily need to have a C++ compiler installed on your machine. - -- `npm install --save-optional bufferutil`: Allows to efficiently perform - operations such as masking and unmasking the data payload of the WebSocket - frames. -- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a - message contains valid UTF-8. - -To not even try to require and use these modules, use the -[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) and -[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment -variables. These might be useful to enhance security in systems where a user can -put a package in the package search path of an application of another user, due -to how the Node.js resolver algorithm works. - -The `utf-8-validate` module is not needed and is not required, even if it is -already installed, regardless of the value of the `WS_NO_UTF_8_VALIDATE` -environment variable, if [`buffer.isUtf8()`][] is available. - -## API docs - -See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and -utility functions. - -## WebSocket compression - -ws supports the [permessage-deflate extension][permessage-deflate] which enables -the client and server to negotiate a compression algorithm and its parameters, -and then selectively apply it to the data payloads of each WebSocket message. - -The extension is disabled by default on the server and enabled by default on the -client. It adds a significant overhead in terms of performance and memory -consumption so we suggest to enable it only if it is really needed. - -Note that Node.js has a variety of issues with high-performance compression, -where increased concurrency, especially on Linux, can lead to [catastrophic -memory fragmentation][node-zlib-bug] and slow performance. If you intend to use -permessage-deflate in production, it is worthwhile to set up a test -representative of your workload and ensure Node.js/zlib will handle it with -acceptable performance and memory usage. - -Tuning of permessage-deflate can be done via the options defined below. You can -also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly -into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. - -See [the docs][ws-server-options] for more options. - -```js -import WebSocket, { WebSocketServer } from 'ws'; - -const wss = new WebSocketServer({ - port: 8080, - perMessageDeflate: { - zlibDeflateOptions: { - // See zlib defaults. - chunkSize: 1024, - memLevel: 7, - level: 3 - }, - zlibInflateOptions: { - chunkSize: 10 * 1024 - }, - // Other options settable: - clientNoContextTakeover: true, // Defaults to negotiated value. - serverNoContextTakeover: true, // Defaults to negotiated value. - serverMaxWindowBits: 10, // Defaults to negotiated value. - // Below options specified as default values. - concurrencyLimit: 10, // Limits zlib concurrency for perf. - threshold: 1024 // Size (in bytes) below which messages - // should not be compressed if context takeover is disabled. - } -}); -``` - -The client will only use the extension if it is supported and enabled on the -server. To always disable the extension on the client set the -`perMessageDeflate` option to `false`. - -```js -import WebSocket from 'ws'; - -const ws = new WebSocket('ws://www.host.com/path', { - perMessageDeflate: false -}); -``` - -## Usage examples - -### Sending and receiving text data - -```js -import WebSocket from 'ws'; - -const ws = new WebSocket('ws://www.host.com/path'); - -ws.on('error', console.error); - -ws.on('open', function open() { - ws.send('something'); -}); - -ws.on('message', function message(data) { - console.log('received: %s', data); -}); -``` - -### Sending binary data - -```js -import WebSocket from 'ws'; - -const ws = new WebSocket('ws://www.host.com/path'); - -ws.on('error', console.error); - -ws.on('open', function open() { - const array = new Float32Array(5); - - for (var i = 0; i < array.length; ++i) { - array[i] = i / 2; - } - - ws.send(array); -}); -``` - -### Simple server - -```js -import { WebSocketServer } from 'ws'; - -const wss = new WebSocketServer({ port: 8080 }); - -wss.on('connection', function connection(ws) { - ws.on('error', console.error); - - ws.on('message', function message(data) { - console.log('received: %s', data); - }); - - ws.send('something'); -}); -``` - -### External HTTP/S server - -```js -import { createServer } from 'https'; -import { readFileSync } from 'fs'; -import { WebSocketServer } from 'ws'; - -const server = createServer({ - cert: readFileSync('/path/to/cert.pem'), - key: readFileSync('/path/to/key.pem') -}); -const wss = new WebSocketServer({ server }); - -wss.on('connection', function connection(ws) { - ws.on('error', console.error); - - ws.on('message', function message(data) { - console.log('received: %s', data); - }); - - ws.send('something'); -}); - -server.listen(8080); -``` - -### Multiple servers sharing a single HTTP/S server - -```js -import { createServer } from 'http'; -import { parse } from 'url'; -import { WebSocketServer } from 'ws'; - -const server = createServer(); -const wss1 = new WebSocketServer({ noServer: true }); -const wss2 = new WebSocketServer({ noServer: true }); - -wss1.on('connection', function connection(ws) { - ws.on('error', console.error); - - // ... -}); - -wss2.on('connection', function connection(ws) { - ws.on('error', console.error); - - // ... -}); - -server.on('upgrade', function upgrade(request, socket, head) { - const { pathname } = parse(request.url); - - if (pathname === '/foo') { - wss1.handleUpgrade(request, socket, head, function done(ws) { - wss1.emit('connection', ws, request); - }); - } else if (pathname === '/bar') { - wss2.handleUpgrade(request, socket, head, function done(ws) { - wss2.emit('connection', ws, request); - }); - } else { - socket.destroy(); - } -}); - -server.listen(8080); -``` - -### Client authentication - -```js -import { createServer } from 'http'; -import { WebSocketServer } from 'ws'; - -function onSocketError(err) { - console.error(err); -} - -const server = createServer(); -const wss = new WebSocketServer({ noServer: true }); - -wss.on('connection', function connection(ws, request, client) { - ws.on('error', console.error); - - ws.on('message', function message(data) { - console.log(`Received message ${data} from user ${client}`); - }); -}); - -server.on('upgrade', function upgrade(request, socket, head) { - socket.on('error', onSocketError); - - // This function is not defined on purpose. Implement it with your own logic. - authenticate(request, function next(err, client) { - if (err || !client) { - socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); - socket.destroy(); - return; - } - - socket.removeListener('error', onSocketError); - - wss.handleUpgrade(request, socket, head, function done(ws) { - wss.emit('connection', ws, request, client); - }); - }); -}); - -server.listen(8080); -``` - -Also see the provided [example][session-parse-example] using `express-session`. - -### Server broadcast - -A client WebSocket broadcasting to all connected WebSocket clients, including -itself. - -```js -import WebSocket, { WebSocketServer } from 'ws'; - -const wss = new WebSocketServer({ port: 8080 }); - -wss.on('connection', function connection(ws) { - ws.on('error', console.error); - - ws.on('message', function message(data, isBinary) { - wss.clients.forEach(function each(client) { - if (client.readyState === WebSocket.OPEN) { - client.send(data, { binary: isBinary }); - } - }); - }); -}); -``` - -A client WebSocket broadcasting to every other connected WebSocket clients, -excluding itself. - -```js -import WebSocket, { WebSocketServer } from 'ws'; - -const wss = new WebSocketServer({ port: 8080 }); - -wss.on('connection', function connection(ws) { - ws.on('error', console.error); - - ws.on('message', function message(data, isBinary) { - wss.clients.forEach(function each(client) { - if (client !== ws && client.readyState === WebSocket.OPEN) { - client.send(data, { binary: isBinary }); - } - }); - }); -}); -``` - -### Round-trip time - -```js -import WebSocket from 'ws'; - -const ws = new WebSocket('wss://websocket-echo.com/'); - -ws.on('error', console.error); - -ws.on('open', function open() { - console.log('connected'); - ws.send(Date.now()); -}); - -ws.on('close', function close() { - console.log('disconnected'); -}); - -ws.on('message', function message(data) { - console.log(`Round-trip time: ${Date.now() - data} ms`); - - setTimeout(function timeout() { - ws.send(Date.now()); - }, 500); -}); -``` - -### Use the Node.js streams API - -```js -import WebSocket, { createWebSocketStream } from 'ws'; - -const ws = new WebSocket('wss://websocket-echo.com/'); - -const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); - -duplex.on('error', console.error); - -duplex.pipe(process.stdout); -process.stdin.pipe(duplex); -``` - -### Other examples - -For a full example with a browser client communicating with a ws server, see the -examples folder. - -Otherwise, see the test cases. - -## FAQ - -### How to get the IP address of the client? - -The remote IP address can be obtained from the raw socket. - -```js -import { WebSocketServer } from 'ws'; - -const wss = new WebSocketServer({ port: 8080 }); - -wss.on('connection', function connection(ws, req) { - const ip = req.socket.remoteAddress; - - ws.on('error', console.error); -}); -``` - -When the server runs behind a proxy like NGINX, the de-facto standard is to use -the `X-Forwarded-For` header. - -```js -wss.on('connection', function connection(ws, req) { - const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); - - ws.on('error', console.error); -}); -``` - -### How to detect and close broken connections? - -Sometimes the link between the server and the client can be interrupted in a way -that keeps both the server and the client unaware of the broken state of the -connection (e.g. when pulling the cord). - -In these cases ping messages can be used as a means to verify that the remote -endpoint is still responsive. - -```js -import { WebSocketServer } from 'ws'; - -function heartbeat() { - this.isAlive = true; -} - -const wss = new WebSocketServer({ port: 8080 }); - -wss.on('connection', function connection(ws) { - ws.isAlive = true; - ws.on('error', console.error); - ws.on('pong', heartbeat); -}); - -const interval = setInterval(function ping() { - wss.clients.forEach(function each(ws) { - if (ws.isAlive === false) return ws.terminate(); - - ws.isAlive = false; - ws.ping(); - }); -}, 30000); - -wss.on('close', function close() { - clearInterval(interval); -}); -``` - -Pong messages are automatically sent in response to ping messages as required by -the spec. - -Just like the server example above your clients might as well lose connection -without knowing it. You might want to add a ping listener on your clients to -prevent that. A simple implementation would be: - -```js -import WebSocket from 'ws'; - -function heartbeat() { - clearTimeout(this.pingTimeout); - - // Use `WebSocket#terminate()`, which immediately destroys the connection, - // instead of `WebSocket#close()`, which waits for the close timer. - // Delay should be equal to the interval at which your server - // sends out pings plus a conservative assumption of the latency. - this.pingTimeout = setTimeout(() => { - this.terminate(); - }, 30000 + 1000); -} - -const client = new WebSocket('wss://websocket-echo.com/'); - -client.on('error', console.error); -client.on('open', heartbeat); -client.on('ping', heartbeat); -client.on('close', function clear() { - clearTimeout(this.pingTimeout); -}); -``` - -### How to connect via a proxy? - -Use a custom `http.Agent` implementation like [https-proxy-agent][] or -[socks-proxy-agent][]. - -## Changelog - -We're using the GitHub [releases][changelog] for changelog entries. - -## License - -[MIT](LICENSE) - -[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input -[changelog]: https://github.com/websockets/ws/releases -[client-report]: http://websockets.github.io/ws/autobahn/clients/ -[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent -[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 -[node-zlib-deflaterawdocs]: - https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options -[permessage-deflate]: https://tools.ietf.org/html/rfc7692 -[server-report]: http://websockets.github.io/ws/autobahn/servers/ -[session-parse-example]: ./examples/express-session-parse -[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent -[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/includes/external/pair/node_modules/ws/browser.js b/includes/external/pair/node_modules/ws/browser.js deleted file mode 100644 index ca4f628..0000000 --- a/includes/external/pair/node_modules/ws/browser.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -module.exports = function () { - throw new Error( - 'ws does not work in the browser. Browser clients must use the native ' + - 'WebSocket object' - ); -}; diff --git a/includes/external/pair/node_modules/ws/index.js b/includes/external/pair/node_modules/ws/index.js deleted file mode 100644 index 41edb3b..0000000 --- a/includes/external/pair/node_modules/ws/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const WebSocket = require('./lib/websocket'); - -WebSocket.createWebSocketStream = require('./lib/stream'); -WebSocket.Server = require('./lib/websocket-server'); -WebSocket.Receiver = require('./lib/receiver'); -WebSocket.Sender = require('./lib/sender'); - -WebSocket.WebSocket = WebSocket; -WebSocket.WebSocketServer = WebSocket.Server; - -module.exports = WebSocket; diff --git a/includes/external/pair/node_modules/ws/lib/buffer-util.js b/includes/external/pair/node_modules/ws/lib/buffer-util.js deleted file mode 100644 index f7536e2..0000000 --- a/includes/external/pair/node_modules/ws/lib/buffer-util.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const { EMPTY_BUFFER } = require('./constants'); - -const FastBuffer = Buffer[Symbol.species]; - -/** - * Merges an array of buffers into a new buffer. - * - * @param {Buffer[]} list The array of buffers to concat - * @param {Number} totalLength The total length of buffers in the list - * @return {Buffer} The resulting buffer - * @public - */ -function concat(list, totalLength) { - if (list.length === 0) return EMPTY_BUFFER; - if (list.length === 1) return list[0]; - - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - - for (let i = 0; i < list.length; i++) { - const buf = list[i]; - target.set(buf, offset); - offset += buf.length; - } - - if (offset < totalLength) { - return new FastBuffer(target.buffer, target.byteOffset, offset); - } - - return target; -} - -/** - * Masks a buffer using the given mask. - * - * @param {Buffer} source The buffer to mask - * @param {Buffer} mask The mask to use - * @param {Buffer} output The buffer where to store the result - * @param {Number} offset The offset at which to start writing - * @param {Number} length The number of bytes to mask. - * @public - */ -function _mask(source, mask, output, offset, length) { - for (let i = 0; i < length; i++) { - output[offset + i] = source[i] ^ mask[i & 3]; - } -} - -/** - * Unmasks a buffer using the given mask. - * - * @param {Buffer} buffer The buffer to unmask - * @param {Buffer} mask The mask to use - * @public - */ -function _unmask(buffer, mask) { - for (let i = 0; i < buffer.length; i++) { - buffer[i] ^= mask[i & 3]; - } -} - -/** - * Converts a buffer to an `ArrayBuffer`. - * - * @param {Buffer} buf The buffer to convert - * @return {ArrayBuffer} Converted buffer - * @public - */ -function toArrayBuffer(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; - } - - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); -} - -/** - * Converts `data` to a `Buffer`. - * - * @param {*} data The data to convert - * @return {Buffer} The buffer - * @throws {TypeError} - * @public - */ -function toBuffer(data) { - toBuffer.readOnly = true; - - if (Buffer.isBuffer(data)) return data; - - let buf; - - if (data instanceof ArrayBuffer) { - buf = new FastBuffer(data); - } else if (ArrayBuffer.isView(data)) { - buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); - } else { - buf = Buffer.from(data); - toBuffer.readOnly = false; - } - - return buf; -} - -module.exports = { - concat, - mask: _mask, - toArrayBuffer, - toBuffer, - unmask: _unmask -}; - -/* istanbul ignore else */ -if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil = require('bufferutil'); - - module.exports.mask = function (source, mask, output, offset, length) { - if (length < 48) _mask(source, mask, output, offset, length); - else bufferUtil.mask(source, mask, output, offset, length); - }; - - module.exports.unmask = function (buffer, mask) { - if (buffer.length < 32) _unmask(buffer, mask); - else bufferUtil.unmask(buffer, mask); - }; - } catch (e) { - // Continue regardless of the error. - } -} diff --git a/includes/external/pair/node_modules/ws/lib/constants.js b/includes/external/pair/node_modules/ws/lib/constants.js deleted file mode 100644 index d691b30..0000000 --- a/includes/external/pair/node_modules/ws/lib/constants.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -module.exports = { - BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], - EMPTY_BUFFER: Buffer.alloc(0), - GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', - kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), - kListener: Symbol('kListener'), - kStatusCode: Symbol('status-code'), - kWebSocket: Symbol('websocket'), - NOOP: () => {} -}; diff --git a/includes/external/pair/node_modules/ws/lib/event-target.js b/includes/external/pair/node_modules/ws/lib/event-target.js deleted file mode 100644 index fea4cbc..0000000 --- a/includes/external/pair/node_modules/ws/lib/event-target.js +++ /dev/null @@ -1,292 +0,0 @@ -'use strict'; - -const { kForOnEventAttribute, kListener } = require('./constants'); - -const kCode = Symbol('kCode'); -const kData = Symbol('kData'); -const kError = Symbol('kError'); -const kMessage = Symbol('kMessage'); -const kReason = Symbol('kReason'); -const kTarget = Symbol('kTarget'); -const kType = Symbol('kType'); -const kWasClean = Symbol('kWasClean'); - -/** - * Class representing an event. - */ -class Event { - /** - * Create a new `Event`. - * - * @param {String} type The name of the event - * @throws {TypeError} If the `type` argument is not specified - */ - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - - /** - * @type {*} - */ - get target() { - return this[kTarget]; - } - - /** - * @type {String} - */ - get type() { - return this[kType]; - } -} - -Object.defineProperty(Event.prototype, 'target', { enumerable: true }); -Object.defineProperty(Event.prototype, 'type', { enumerable: true }); - -/** - * Class representing a close event. - * - * @extends Event - */ -class CloseEvent extends Event { - /** - * Create a new `CloseEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {Number} [options.code=0] The status code explaining why the - * connection was closed - * @param {String} [options.reason=''] A human-readable string explaining why - * the connection was closed - * @param {Boolean} [options.wasClean=false] Indicates whether or not the - * connection was cleanly closed - */ - constructor(type, options = {}) { - super(type); - - this[kCode] = options.code === undefined ? 0 : options.code; - this[kReason] = options.reason === undefined ? '' : options.reason; - this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; - } - - /** - * @type {Number} - */ - get code() { - return this[kCode]; - } - - /** - * @type {String} - */ - get reason() { - return this[kReason]; - } - - /** - * @type {Boolean} - */ - get wasClean() { - return this[kWasClean]; - } -} - -Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); -Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); -Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); - -/** - * Class representing an error event. - * - * @extends Event - */ -class ErrorEvent extends Event { - /** - * Create a new `ErrorEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.error=null] The error that generated this event - * @param {String} [options.message=''] The error message - */ - constructor(type, options = {}) { - super(type); - - this[kError] = options.error === undefined ? null : options.error; - this[kMessage] = options.message === undefined ? '' : options.message; - } - - /** - * @type {*} - */ - get error() { - return this[kError]; - } - - /** - * @type {String} - */ - get message() { - return this[kMessage]; - } -} - -Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); -Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); - -/** - * Class representing a message event. - * - * @extends Event - */ -class MessageEvent extends Event { - /** - * Create a new `MessageEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.data=null] The message content - */ - constructor(type, options = {}) { - super(type); - - this[kData] = options.data === undefined ? null : options.data; - } - - /** - * @type {*} - */ - get data() { - return this[kData]; - } -} - -Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); - -/** - * This provides methods for emulating the `EventTarget` interface. It's not - * meant to be used directly. - * - * @mixin - */ -const EventTarget = { - /** - * Register an event listener. - * - * @param {String} type A string representing the event type to listen for - * @param {(Function|Object)} handler The listener to add - * @param {Object} [options] An options object specifies characteristics about - * the event listener - * @param {Boolean} [options.once=false] A `Boolean` indicating that the - * listener should be invoked at most once after being added. If `true`, - * the listener would be automatically removed when invoked. - * @public - */ - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if ( - !options[kForOnEventAttribute] && - listener[kListener] === handler && - !listener[kForOnEventAttribute] - ) { - return; - } - } - - let wrapper; - - if (type === 'message') { - wrapper = function onMessage(data, isBinary) { - const event = new MessageEvent('message', { - data: isBinary ? data : data.toString() - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'close') { - wrapper = function onClose(code, message) { - const event = new CloseEvent('close', { - code, - reason: message.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'error') { - wrapper = function onError(error) { - const event = new ErrorEvent('error', { - error, - message: error.message - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'open') { - wrapper = function onOpen() { - const event = new Event('open'); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; - } - - wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; - wrapper[kListener] = handler; - - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); - } - }, - - /** - * Remove an event listener. - * - * @param {String} type A string representing the event type to remove - * @param {(Function|Object)} handler The listener to remove - * @public - */ - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { - this.removeListener(type, listener); - break; - } - } - } -}; - -module.exports = { - CloseEvent, - ErrorEvent, - Event, - EventTarget, - MessageEvent -}; - -/** - * Call an event listener - * - * @param {(Function|Object)} listener The listener to call - * @param {*} thisArg The value to use as `this`` when calling the listener - * @param {Event} event The event to pass to the listener - * @private - */ -function callListener(listener, thisArg, event) { - if (typeof listener === 'object' && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); - } -} diff --git a/includes/external/pair/node_modules/ws/lib/extension.js b/includes/external/pair/node_modules/ws/lib/extension.js deleted file mode 100644 index 3d7895c..0000000 --- a/includes/external/pair/node_modules/ws/lib/extension.js +++ /dev/null @@ -1,203 +0,0 @@ -'use strict'; - -const { tokenChars } = require('./validation'); - -/** - * Adds an offer to the map of extension offers or a parameter to the map of - * parameters. - * - * @param {Object} dest The map of extension offers or parameters - * @param {String} name The extension or parameter name - * @param {(Object|Boolean|String)} elem The extension parameters or the - * parameter value - * @private - */ -function push(dest, name, elem) { - if (dest[name] === undefined) dest[name] = [elem]; - else dest[name].push(elem); -} - -/** - * Parses the `Sec-WebSocket-Extensions` header into an object. - * - * @param {String} header The field value of the header - * @return {Object} The parsed object - * @public - */ -function parse(header) { - const offers = Object.create(null); - let params = Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i = 0; - - for (; i < header.length; i++) { - code = header.charCodeAt(i); - - if (extensionName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - const name = header.slice(start, end); - if (code === 0x2c) { - push(offers, name, params); - params = Object.create(null); - } else { - extensionName = name; - } - - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (paramName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x20 || code === 0x09) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - push(params, header.slice(start, end), true); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - - start = end = -1; - } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { - paramName = header.slice(start, i); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else { - // - // The value of a quoted-string after unescaping must conform to the - // token ABNF, so only token characters are valid. - // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 - // - if (isEscaping) { - if (tokenChars[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1) start = i; - else if (!mustUnescape) mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x22 /* '"' */ && start !== -1) { - inQuotes = false; - end = i; - } else if (code === 0x5c /* '\' */) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { - inQuotes = true; - } else if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (start !== -1 && (code === 0x20 || code === 0x09)) { - if (end === -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ''); - mustUnescape = false; - } - push(params, paramName, value); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - - paramName = undefined; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - } - - if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { - throw new SyntaxError('Unexpected end of input'); - } - - if (end === -1) end = i; - const token = header.slice(start, end); - if (extensionName === undefined) { - push(offers, token, params); - } else { - if (paramName === undefined) { - push(params, token, true); - } else if (mustUnescape) { - push(params, paramName, token.replace(/\\/g, '')); - } else { - push(params, paramName, token); - } - push(offers, extensionName, params); - } - - return offers; -} - -/** - * Builds the `Sec-WebSocket-Extensions` header field value. - * - * @param {Object} extensions The map of extensions and parameters to format - * @return {String} A string representing the given object - * @public - */ -function format(extensions) { - return Object.keys(extensions) - .map((extension) => { - let configurations = extensions[extension]; - if (!Array.isArray(configurations)) configurations = [configurations]; - return configurations - .map((params) => { - return [extension] - .concat( - Object.keys(params).map((k) => { - let values = params[k]; - if (!Array.isArray(values)) values = [values]; - return values - .map((v) => (v === true ? k : `${k}=${v}`)) - .join('; '); - }) - ) - .join('; '); - }) - .join(', '); - }) - .join(', '); -} - -module.exports = { format, parse }; diff --git a/includes/external/pair/node_modules/ws/lib/limiter.js b/includes/external/pair/node_modules/ws/lib/limiter.js deleted file mode 100644 index 3fd3578..0000000 --- a/includes/external/pair/node_modules/ws/lib/limiter.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const kDone = Symbol('kDone'); -const kRun = Symbol('kRun'); - -/** - * A very simple job queue with adjustable concurrency. Adapted from - * https://github.com/STRML/async-limiter - */ -class Limiter { - /** - * Creates a new `Limiter`. - * - * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed - * to run concurrently - */ - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; - } - - /** - * Adds a job to the queue. - * - * @param {Function} job The job to run - * @public - */ - add(job) { - this.jobs.push(job); - this[kRun](); - } - - /** - * Removes a job from the queue and runs it if possible. - * - * @private - */ - [kRun]() { - if (this.pending === this.concurrency) return; - - if (this.jobs.length) { - const job = this.jobs.shift(); - - this.pending++; - job(this[kDone]); - } - } -} - -module.exports = Limiter; diff --git a/includes/external/pair/node_modules/ws/lib/permessage-deflate.js b/includes/external/pair/node_modules/ws/lib/permessage-deflate.js deleted file mode 100644 index 77d918b..0000000 --- a/includes/external/pair/node_modules/ws/lib/permessage-deflate.js +++ /dev/null @@ -1,514 +0,0 @@ -'use strict'; - -const zlib = require('zlib'); - -const bufferUtil = require('./buffer-util'); -const Limiter = require('./limiter'); -const { kStatusCode } = require('./constants'); - -const FastBuffer = Buffer[Symbol.species]; -const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); -const kPerMessageDeflate = Symbol('permessage-deflate'); -const kTotalLength = Symbol('total-length'); -const kCallback = Symbol('callback'); -const kBuffers = Symbol('buffers'); -const kError = Symbol('error'); - -// -// We limit zlib concurrency, which prevents severe memory fragmentation -// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 -// and https://github.com/websockets/ws/issues/1202 -// -// Intentionally global; it's the global thread pool that's an issue. -// -let zlibLimiter; - -/** - * permessage-deflate implementation. - */ -class PerMessageDeflate { - /** - * Creates a PerMessageDeflate instance. - * - * @param {Object} [options] Configuration options - * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support - * for, or request, a custom client window size - * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ - * acknowledge disabling of client context takeover - * @param {Number} [options.concurrencyLimit=10] The number of concurrent - * calls to zlib - * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the - * use of a custom server window size - * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept - * disabling of server context takeover - * @param {Number} [options.threshold=1024] Size (in bytes) below which - * messages should not be compressed if context takeover is disabled - * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on - * deflate - * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on - * inflate - * @param {Boolean} [isServer=false] Create the instance in either server or - * client mode - * @param {Number} [maxPayload=0] The maximum allowed message length - */ - constructor(options, isServer, maxPayload) { - this._maxPayload = maxPayload | 0; - this._options = options || {}; - this._threshold = - this._options.threshold !== undefined ? this._options.threshold : 1024; - this._isServer = !!isServer; - this._deflate = null; - this._inflate = null; - - this.params = null; - - if (!zlibLimiter) { - const concurrency = - this._options.concurrencyLimit !== undefined - ? this._options.concurrencyLimit - : 10; - zlibLimiter = new Limiter(concurrency); - } - } - - /** - * @type {String} - */ - static get extensionName() { - return 'permessage-deflate'; - } - - /** - * Create an extension negotiation offer. - * - * @return {Object} Extension parameters - * @public - */ - offer() { - const params = {}; - - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - - return params; - } - - /** - * Accept an extension negotiation offer/response. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Object} Accepted configuration - * @public - */ - accept(configurations) { - configurations = this.normalizeParams(configurations); - - this.params = this._isServer - ? this.acceptAsServer(configurations) - : this.acceptAsClient(configurations); - - return this.params; - } - - /** - * Releases all resources used by the extension. - * - * @public - */ - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - - if (this._deflate) { - const callback = this._deflate[kCallback]; - - this._deflate.close(); - this._deflate = null; - - if (callback) { - callback( - new Error( - 'The deflate stream was closed while data was being processed' - ) - ); - } - } - } - - /** - * Accept an extension negotiation offer. - * - * @param {Array} offers The extension negotiation offers - * @return {Object} Accepted configuration - * @private - */ - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if ( - (opts.serverNoContextTakeover === false && - params.server_no_context_takeover) || - (params.server_max_window_bits && - (opts.serverMaxWindowBits === false || - (typeof opts.serverMaxWindowBits === 'number' && - opts.serverMaxWindowBits > params.server_max_window_bits))) || - (typeof opts.clientMaxWindowBits === 'number' && - !params.client_max_window_bits) - ) { - return false; - } - - return true; - }); - - if (!accepted) { - throw new Error('None of the extension offers can be accepted'); - } - - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; - } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; - } - if (typeof opts.serverMaxWindowBits === 'number') { - accepted.server_max_window_bits = opts.serverMaxWindowBits; - } - if (typeof opts.clientMaxWindowBits === 'number') { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if ( - accepted.client_max_window_bits === true || - opts.clientMaxWindowBits === false - ) { - delete accepted.client_max_window_bits; - } - - return accepted; - } - - /** - * Accept the extension negotiation response. - * - * @param {Array} response The extension negotiation response - * @return {Object} Accepted configuration - * @private - */ - acceptAsClient(response) { - const params = response[0]; - - if ( - this._options.clientNoContextTakeover === false && - params.client_no_context_takeover - ) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === 'number') { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if ( - this._options.clientMaxWindowBits === false || - (typeof this._options.clientMaxWindowBits === 'number' && - params.client_max_window_bits > this._options.clientMaxWindowBits) - ) { - throw new Error( - 'Unexpected or invalid parameter "client_max_window_bits"' - ); - } - - return params; - } - - /** - * Normalize parameters. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Array} The offers/response with normalized parameters - * @private - */ - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - - value = value[0]; - - if (key === 'client_max_window_bits') { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (!this._isServer) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else if (key === 'server_max_window_bits') { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if ( - key === 'client_no_context_takeover' || - key === 'server_no_context_takeover' - ) { - if (value !== true) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - - params[key] = value; - }); - }); - - return configurations; - } - - /** - * Decompress data. Concurrency limited. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - decompress(data, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - - /** - * Compress data. Concurrency limited. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - compress(data, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - - /** - * Decompress data. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _decompress(data, fin, callback) { - const endpoint = this._isServer ? 'client' : 'server'; - - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on('error', inflateOnError); - this._inflate.on('data', inflateOnData); - } - - this._inflate[kCallback] = callback; - - this._inflate.write(data); - if (fin) this._inflate.write(TRAILER); - - this._inflate.flush(() => { - const err = this._inflate[kError]; - - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - - const data = bufferUtil.concat( - this._inflate[kBuffers], - this._inflate[kTotalLength] - ); - - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - - callback(null, data); - }); - } - - /** - * Compress data. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _compress(data, fin, callback) { - const endpoint = this._isServer ? 'server' : 'client'; - - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - - this._deflate.on('data', deflateOnData); - } - - this._deflate[kCallback] = callback; - - this._deflate.write(data); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - // - // The deflate stream was closed while data was being processed. - // - return; - } - - let data = bufferUtil.concat( - this._deflate[kBuffers], - this._deflate[kTotalLength] - ); - - if (fin) { - data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); - } - - // - // Ensure that the callback will not be called again in - // `PerMessageDeflate#cleanup()`. - // - this._deflate[kCallback] = null; - - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - - callback(null, data); - }); - } -} - -module.exports = PerMessageDeflate; - -/** - * The listener of the `zlib.DeflateRaw` stream `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; -} - -/** - * The listener of the `zlib.InflateRaw` stream `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - - if ( - this[kPerMessageDeflate]._maxPayload < 1 || - this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload - ) { - this[kBuffers].push(chunk); - return; - } - - this[kError] = new RangeError('Max payload size exceeded'); - this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; - this[kError][kStatusCode] = 1009; - this.removeListener('data', inflateOnData); - this.reset(); -} - -/** - * The listener of the `zlib.InflateRaw` stream `'error'` event. - * - * @param {Error} err The emitted error - * @private - */ -function inflateOnError(err) { - // - // There is no need to call `Zlib#close()` as the handle is automatically - // closed when an error is emitted. - // - this[kPerMessageDeflate]._inflate = null; - err[kStatusCode] = 1007; - this[kCallback](err); -} diff --git a/includes/external/pair/node_modules/ws/lib/receiver.js b/includes/external/pair/node_modules/ws/lib/receiver.js deleted file mode 100644 index 96f572c..0000000 --- a/includes/external/pair/node_modules/ws/lib/receiver.js +++ /dev/null @@ -1,627 +0,0 @@ -'use strict'; - -const { Writable } = require('stream'); - -const PerMessageDeflate = require('./permessage-deflate'); -const { - BINARY_TYPES, - EMPTY_BUFFER, - kStatusCode, - kWebSocket -} = require('./constants'); -const { concat, toArrayBuffer, unmask } = require('./buffer-util'); -const { isValidStatusCode, isValidUTF8 } = require('./validation'); - -const FastBuffer = Buffer[Symbol.species]; -const GET_INFO = 0; -const GET_PAYLOAD_LENGTH_16 = 1; -const GET_PAYLOAD_LENGTH_64 = 2; -const GET_MASK = 3; -const GET_DATA = 4; -const INFLATING = 5; - -/** - * HyBi Receiver implementation. - * - * @extends Writable - */ -class Receiver extends Writable { - /** - * Creates a Receiver instance. - * - * @param {Object} [options] Options object - * @param {String} [options.binaryType=nodebuffer] The type for binary data - * @param {Object} [options.extensions] An object containing the negotiated - * extensions - * @param {Boolean} [options.isServer=false] Specifies whether to operate in - * client or server mode - * @param {Number} [options.maxPayload=0] The maximum allowed message length - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - */ - constructor(options = {}) { - super(); - - this._binaryType = options.binaryType || BINARY_TYPES[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket] = undefined; - - this._bufferedBytes = 0; - this._buffers = []; - - this._compressed = false; - this._payloadLength = 0; - this._mask = undefined; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - - this._state = GET_INFO; - this._loop = false; - } - - /** - * Implements `Writable.prototype._write()`. - * - * @param {Buffer} chunk The chunk of data to write - * @param {String} encoding The character encoding of `chunk` - * @param {Function} cb Callback - * @private - */ - _write(chunk, encoding, cb) { - if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); - - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); - } - - /** - * Consumes `n` bytes from the buffered data. - * - * @param {Number} n The number of bytes to consume - * @return {Buffer} The consumed bytes - * @private - */ - consume(n) { - this._bufferedBytes -= n; - - if (n === this._buffers[0].length) return this._buffers.shift(); - - if (n < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - - return new FastBuffer(buf.buffer, buf.byteOffset, n); - } - - const dst = Buffer.allocUnsafe(n); - - do { - const buf = this._buffers[0]; - const offset = dst.length - n; - - if (n >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - } - - n -= buf.length; - } while (n > 0); - - return dst; - } - - /** - * Starts the parsing loop. - * - * @param {Function} cb Callback - * @private - */ - startLoop(cb) { - let err; - this._loop = true; - - do { - switch (this._state) { - case GET_INFO: - err = this.getInfo(); - break; - case GET_PAYLOAD_LENGTH_16: - err = this.getPayloadLength16(); - break; - case GET_PAYLOAD_LENGTH_64: - err = this.getPayloadLength64(); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - err = this.getData(cb); - break; - default: - // `INFLATING` - this._loop = false; - return; - } - } while (this._loop); - - cb(err); - } - - /** - * Reads the first two bytes of a frame. - * - * @return {(RangeError|undefined)} A possible error - * @private - */ - getInfo() { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - - const buf = this.consume(2); - - if ((buf[0] & 0x30) !== 0x00) { - this._loop = false; - return error( - RangeError, - 'RSV2 and RSV3 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_2_3' - ); - } - - const compressed = (buf[0] & 0x40) === 0x40; - - if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { - this._loop = false; - return error( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - } - - this._fin = (buf[0] & 0x80) === 0x80; - this._opcode = buf[0] & 0x0f; - this._payloadLength = buf[1] & 0x7f; - - if (this._opcode === 0x00) { - if (compressed) { - this._loop = false; - return error( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - } - - if (!this._fragmented) { - this._loop = false; - return error( - RangeError, - 'invalid opcode 0', - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - } - - this._opcode = this._fragmented; - } else if (this._opcode === 0x01 || this._opcode === 0x02) { - if (this._fragmented) { - this._loop = false; - return error( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - } - - this._compressed = compressed; - } else if (this._opcode > 0x07 && this._opcode < 0x0b) { - if (!this._fin) { - this._loop = false; - return error( - RangeError, - 'FIN must be set', - true, - 1002, - 'WS_ERR_EXPECTED_FIN' - ); - } - - if (compressed) { - this._loop = false; - return error( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - } - - if ( - this._payloadLength > 0x7d || - (this._opcode === 0x08 && this._payloadLength === 1) - ) { - this._loop = false; - return error( - RangeError, - `invalid payload length ${this._payloadLength}`, - true, - 1002, - 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' - ); - } - } else { - this._loop = false; - return error( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - } - - if (!this._fin && !this._fragmented) this._fragmented = this._opcode; - this._masked = (buf[1] & 0x80) === 0x80; - - if (this._isServer) { - if (!this._masked) { - this._loop = false; - return error( - RangeError, - 'MASK must be set', - true, - 1002, - 'WS_ERR_EXPECTED_MASK' - ); - } - } else if (this._masked) { - this._loop = false; - return error( - RangeError, - 'MASK must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_MASK' - ); - } - - if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; - else return this.haveLength(); - } - - /** - * Gets extended payload length (7+16). - * - * @return {(RangeError|undefined)} A possible error - * @private - */ - getPayloadLength16() { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - - this._payloadLength = this.consume(2).readUInt16BE(0); - return this.haveLength(); - } - - /** - * Gets extended payload length (7+64). - * - * @return {(RangeError|undefined)} A possible error - * @private - */ - getPayloadLength64() { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - - // - // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned - // if payload length is greater than this number. - // - if (num > Math.pow(2, 53 - 32) - 1) { - this._loop = false; - return error( - RangeError, - 'Unsupported WebSocket frame: payload length > 2^53 - 1', - false, - 1009, - 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' - ); - } - - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - return this.haveLength(); - } - - /** - * Payload length has been read. - * - * @return {(RangeError|undefined)} A possible error - * @private - */ - haveLength() { - if (this._payloadLength && this._opcode < 0x08) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - this._loop = false; - return error( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ); - } - } - - if (this._masked) this._state = GET_MASK; - else this._state = GET_DATA; - } - - /** - * Reads mask bytes. - * - * @private - */ - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - - this._mask = this.consume(4); - this._state = GET_DATA; - } - - /** - * Reads data bytes. - * - * @param {Function} cb Callback - * @return {(Error|RangeError|undefined)} A possible error - * @private - */ - getData(cb) { - let data = EMPTY_BUFFER; - - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - - data = this.consume(this._payloadLength); - - if ( - this._masked && - (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 - ) { - unmask(data, this._mask); - } - } - - if (this._opcode > 0x07) return this.controlMessage(data); - - if (this._compressed) { - this._state = INFLATING; - this.decompress(data, cb); - return; - } - - if (data.length) { - // - // This message is not compressed so its length is the sum of the payload - // length of all fragments. - // - this._messageLength = this._totalPayloadLength; - this._fragments.push(data); - } - - return this.dataMessage(); - } - - /** - * Decompresses data. - * - * @param {Buffer} data Compressed data - * @param {Function} cb Callback - * @private - */ - decompress(data, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - - perMessageDeflate.decompress(data, this._fin, (err, buf) => { - if (err) return cb(err); - - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - return cb( - error( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ) - ); - } - - this._fragments.push(buf); - } - - const er = this.dataMessage(); - if (er) return cb(er); - - this.startLoop(cb); - }); - } - - /** - * Handles a data message. - * - * @return {(Error|undefined)} A possible error - * @private - */ - dataMessage() { - if (this._fin) { - const messageLength = this._messageLength; - const fragments = this._fragments; - - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - - if (this._opcode === 2) { - let data; - - if (this._binaryType === 'nodebuffer') { - data = concat(fragments, messageLength); - } else if (this._binaryType === 'arraybuffer') { - data = toArrayBuffer(concat(fragments, messageLength)); - } else { - data = fragments; - } - - this.emit('message', data, true); - } else { - const buf = concat(fragments, messageLength); - - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - this._loop = false; - return error( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - } - - this.emit('message', buf, false); - } - } - - this._state = GET_INFO; - } - - /** - * Handles a control message. - * - * @param {Buffer} data Data to handle - * @return {(Error|RangeError|undefined)} A possible error - * @private - */ - controlMessage(data) { - if (this._opcode === 0x08) { - this._loop = false; - - if (data.length === 0) { - this.emit('conclude', 1005, EMPTY_BUFFER); - this.end(); - } else { - const code = data.readUInt16BE(0); - - if (!isValidStatusCode(code)) { - return error( - RangeError, - `invalid status code ${code}`, - true, - 1002, - 'WS_ERR_INVALID_CLOSE_CODE' - ); - } - - const buf = new FastBuffer( - data.buffer, - data.byteOffset + 2, - data.length - 2 - ); - - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - return error( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - } - - this.emit('conclude', code, buf); - this.end(); - } - } else if (this._opcode === 0x09) { - this.emit('ping', data); - } else { - this.emit('pong', data); - } - - this._state = GET_INFO; - } -} - -module.exports = Receiver; - -/** - * Builds an error object. - * - * @param {function(new:Error|RangeError)} ErrorCtor The error constructor - * @param {String} message The error message - * @param {Boolean} prefix Specifies whether or not to add a default prefix to - * `message` - * @param {Number} statusCode The status code - * @param {String} errorCode The exposed error code - * @return {(Error|RangeError)} The error - * @private - */ -function error(ErrorCtor, message, prefix, statusCode, errorCode) { - const err = new ErrorCtor( - prefix ? `Invalid WebSocket frame: ${message}` : message - ); - - Error.captureStackTrace(err, error); - err.code = errorCode; - err[kStatusCode] = statusCode; - return err; -} diff --git a/includes/external/pair/node_modules/ws/lib/sender.js b/includes/external/pair/node_modules/ws/lib/sender.js deleted file mode 100644 index c848853..0000000 --- a/includes/external/pair/node_modules/ws/lib/sender.js +++ /dev/null @@ -1,478 +0,0 @@ -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ - -'use strict'; - -const net = require('net'); -const tls = require('tls'); -const { randomFillSync } = require('crypto'); - -const PerMessageDeflate = require('./permessage-deflate'); -const { EMPTY_BUFFER } = require('./constants'); -const { isValidStatusCode } = require('./validation'); -const { mask: applyMask, toBuffer } = require('./buffer-util'); - -const kByteLength = Symbol('kByteLength'); -const maskBuffer = Buffer.alloc(4); - -/** - * HyBi Sender implementation. - */ -class Sender { - /** - * Creates a Sender instance. - * - * @param {(net.Socket|tls.Socket)} socket The connection socket - * @param {Object} [extensions] An object containing the negotiated extensions - * @param {Function} [generateMask] The function used to generate the masking - * key - */ - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - - this._socket = socket; - - this._firstFragment = true; - this._compress = false; - - this._bufferedBytes = 0; - this._deflating = false; - this._queue = []; - } - - /** - * Frames a piece of data according to the HyBi WebSocket protocol. - * - * @param {(Buffer|String)} data The data to frame - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @return {(Buffer|String)[]} The framed data - * @public - */ - static frame(data, options) { - let mask; - let merge = false; - let offset = 2; - let skipMasking = false; - - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - - if (options.generateMask) { - options.generateMask(mask); - } else { - randomFillSync(mask, 0, 4); - } - - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - - let dataLength; - - if (typeof data === 'string') { - if ( - (!options.mask || skipMasking) && - options[kByteLength] !== undefined - ) { - dataLength = options[kByteLength]; - } else { - data = Buffer.from(data); - dataLength = data.length; - } - } else { - dataLength = data.length; - merge = options.mask && options.readOnly && !skipMasking; - } - - let payloadLength = dataLength; - - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - - const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); - - target[0] = options.fin ? options.opcode | 0x80 : options.opcode; - if (options.rsv1) target[0] |= 0x40; - - target[1] = payloadLength; - - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - - if (!options.mask) return [target, data]; - - target[1] |= 0x80; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - - if (skipMasking) return [target, data]; - - if (merge) { - applyMask(data, mask, target, offset, dataLength); - return [target]; - } - - applyMask(data, mask, data, 0, dataLength); - return [target, data]; - } - - /** - * Sends a close message to the other peer. - * - * @param {Number} [code] The status code component of the body - * @param {(String|Buffer)} [data] The message component of the body - * @param {Boolean} [mask=false] Specifies whether or not to mask the message - * @param {Function} [cb] Callback - * @public - */ - close(code, data, mask, cb) { - let buf; - - if (code === undefined) { - buf = EMPTY_BUFFER; - } else if (typeof code !== 'number' || !isValidStatusCode(code)) { - throw new TypeError('First argument must be a valid error code number'); - } else if (data === undefined || !data.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data); - - if (length > 123) { - throw new RangeError('The message must not be greater than 123 bytes'); - } - - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - - if (typeof data === 'string') { - buf.write(data, 2); - } else { - buf.set(data, 2); - } - } - - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x08, - readOnly: false, - rsv1: false - }; - - if (this._deflating) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(Sender.frame(buf, options), cb); - } - } - - /** - * Sends a ping message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - ping(data, mask, cb) { - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x09, - readOnly, - rsv1: false - }; - - if (this._deflating) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - - /** - * Sends a pong message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - pong(data, mask, cb) { - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x0a, - readOnly, - rsv1: false - }; - - if (this._deflating) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - - /** - * Sends a data message to the other peer. - * - * @param {*} data The message to send - * @param {Object} options Options object - * @param {Boolean} [options.binary=false] Specifies whether `data` is binary - * or text - * @param {Boolean} [options.compress=false] Specifies whether or not to - * compress `data` - * @param {Boolean} [options.fin=false] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Function} [cb] Callback - * @public - */ - send(data, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - - if (this._firstFragment) { - this._firstFragment = false; - if ( - rsv1 && - perMessageDeflate && - perMessageDeflate.params[ - perMessageDeflate._isServer - ? 'server_no_context_takeover' - : 'client_no_context_takeover' - ] - ) { - rsv1 = byteLength >= perMessageDeflate._threshold; - } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - - if (options.fin) this._firstFragment = true; - - if (perMessageDeflate) { - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 - }; - - if (this._deflating) { - this.enqueue([this.dispatch, data, this._compress, opts, cb]); - } else { - this.dispatch(data, this._compress, opts, cb); - } - } else { - this.sendFrame( - Sender.frame(data, { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1: false - }), - cb - ); - } - } - - /** - * Dispatches a message. - * - * @param {(Buffer|String)} data The message to send - * @param {Boolean} [compress=false] Specifies whether or not to compress - * `data` - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - dispatch(data, compress, options, cb) { - if (!compress) { - this.sendFrame(Sender.frame(data, options), cb); - return; - } - - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - - this._bufferedBytes += options[kByteLength]; - this._deflating = true; - perMessageDeflate.compress(data, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error( - 'The socket was closed while data was being compressed' - ); - - if (typeof cb === 'function') cb(err); - - for (let i = 0; i < this._queue.length; i++) { - const params = this._queue[i]; - const callback = params[params.length - 1]; - - if (typeof callback === 'function') callback(err); - } - - return; - } - - this._bufferedBytes -= options[kByteLength]; - this._deflating = false; - options.readOnly = false; - this.sendFrame(Sender.frame(buf, options), cb); - this.dequeue(); - }); - } - - /** - * Executes queued send operations. - * - * @private - */ - dequeue() { - while (!this._deflating && this._queue.length) { - const params = this._queue.shift(); - - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - - /** - * Enqueues a send operation. - * - * @param {Array} params Send operation parameters. - * @private - */ - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); - } - - /** - * Sends a frame. - * - * @param {Buffer[]} list The frame to send - * @param {Function} [cb] Callback - * @private - */ - sendFrame(list, cb) { - if (list.length === 2) { - this._socket.cork(); - this._socket.write(list[0]); - this._socket.write(list[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list[0], cb); - } - } -} - -module.exports = Sender; diff --git a/includes/external/pair/node_modules/ws/lib/stream.js b/includes/external/pair/node_modules/ws/lib/stream.js deleted file mode 100644 index 230734b..0000000 --- a/includes/external/pair/node_modules/ws/lib/stream.js +++ /dev/null @@ -1,159 +0,0 @@ -'use strict'; - -const { Duplex } = require('stream'); - -/** - * Emits the `'close'` event on a stream. - * - * @param {Duplex} stream The stream. - * @private - */ -function emitClose(stream) { - stream.emit('close'); -} - -/** - * The listener of the `'end'` event. - * - * @private - */ -function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } -} - -/** - * The listener of the `'error'` event. - * - * @param {Error} err The error - * @private - */ -function duplexOnError(err) { - this.removeListener('error', duplexOnError); - this.destroy(); - if (this.listenerCount('error') === 0) { - // Do not suppress the throwing behavior. - this.emit('error', err); - } -} - -/** - * Wraps a `WebSocket` in a duplex stream. - * - * @param {WebSocket} ws The `WebSocket` to wrap - * @param {Object} [options] The options for the `Duplex` constructor - * @return {Duplex} The duplex stream - * @public - */ -function createWebSocketStream(ws, options) { - let terminateOnDestroy = true; - - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - - ws.on('message', function message(msg, isBinary) { - const data = - !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; - - if (!duplex.push(data)) ws.pause(); - }); - - ws.once('error', function error(err) { - if (duplex.destroyed) return; - - // Prevent `ws.terminate()` from being called by `duplex._destroy()`. - // - // - If the `'error'` event is emitted before the `'open'` event, then - // `ws.terminate()` is a noop as no socket is assigned. - // - Otherwise, the error is re-emitted by the listener of the `'error'` - // event of the `Receiver` object. The listener already closes the - // connection by calling `ws.close()`. This allows a close frame to be - // sent to the other peer. If `ws.terminate()` is called right after this, - // then the close frame might not be sent. - terminateOnDestroy = false; - duplex.destroy(err); - }); - - ws.once('close', function close() { - if (duplex.destroyed) return; - - duplex.push(null); - }); - - duplex._destroy = function (err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose, duplex); - return; - } - - let called = false; - - ws.once('error', function error(err) { - called = true; - callback(err); - }); - - ws.once('close', function close() { - if (!called) callback(err); - process.nextTick(emitClose, duplex); - }); - - if (terminateOnDestroy) ws.terminate(); - }; - - duplex._final = function (callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._final(callback); - }); - return; - } - - // If the value of the `_socket` property is `null` it means that `ws` is a - // client websocket and the handshake failed. In fact, when this happens, a - // socket is never assigned to the websocket. Wait for the `'error'` event - // that will be emitted by the websocket. - if (ws._socket === null) return; - - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) duplex.destroy(); - } else { - ws._socket.once('finish', function finish() { - // `duplex` is not destroyed here because the `'end'` event will be - // emitted on `duplex` after this `'finish'` event. The EOF signaling - // `null` chunk is, in fact, pushed when the websocket emits `'close'`. - callback(); - }); - ws.close(); - } - }; - - duplex._read = function () { - if (ws.isPaused) ws.resume(); - }; - - duplex._write = function (chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._write(chunk, encoding, callback); - }); - return; - } - - ws.send(chunk, callback); - }; - - duplex.on('end', duplexOnEnd); - duplex.on('error', duplexOnError); - return duplex; -} - -module.exports = createWebSocketStream; diff --git a/includes/external/pair/node_modules/ws/lib/subprotocol.js b/includes/external/pair/node_modules/ws/lib/subprotocol.js deleted file mode 100644 index d4381e8..0000000 --- a/includes/external/pair/node_modules/ws/lib/subprotocol.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const { tokenChars } = require('./validation'); - -/** - * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. - * - * @param {String} header The field value of the header - * @return {Set} The subprotocol names - * @public - */ -function parse(header) { - const protocols = new Set(); - let start = -1; - let end = -1; - let i = 0; - - for (i; i < header.length; i++) { - const code = header.charCodeAt(i); - - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x2c /* ',' */) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - - const protocol = header.slice(start, end); - - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - - protocols.add(protocol); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - - if (start === -1 || end !== -1) { - throw new SyntaxError('Unexpected end of input'); - } - - const protocol = header.slice(start, i); - - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - - protocols.add(protocol); - return protocols; -} - -module.exports = { parse }; diff --git a/includes/external/pair/node_modules/ws/lib/validation.js b/includes/external/pair/node_modules/ws/lib/validation.js deleted file mode 100644 index c352e6e..0000000 --- a/includes/external/pair/node_modules/ws/lib/validation.js +++ /dev/null @@ -1,130 +0,0 @@ -'use strict'; - -const { isUtf8 } = require('buffer'); - -// -// Allowed token characters: -// -// '!', '#', '$', '%', '&', ''', '*', '+', '-', -// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' -// -// tokenChars[32] === 0 // ' ' -// tokenChars[33] === 1 // '!' -// tokenChars[34] === 0 // '"' -// ... -// -// prettier-ignore -const tokenChars = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 - 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 -]; - -/** - * Checks if a status code is allowed in a close frame. - * - * @param {Number} code The status code - * @return {Boolean} `true` if the status code is valid, else `false` - * @public - */ -function isValidStatusCode(code) { - return ( - (code >= 1000 && - code <= 1014 && - code !== 1004 && - code !== 1005 && - code !== 1006) || - (code >= 3000 && code <= 4999) - ); -} - -/** - * Checks if a given buffer contains only correct UTF-8. - * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by - * Markus Kuhn. - * - * @param {Buffer} buf The buffer to check - * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` - * @public - */ -function _isValidUTF8(buf) { - const len = buf.length; - let i = 0; - - while (i < len) { - if ((buf[i] & 0x80) === 0) { - // 0xxxxxxx - i++; - } else if ((buf[i] & 0xe0) === 0xc0) { - // 110xxxxx 10xxxxxx - if ( - i + 1 === len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i] & 0xfe) === 0xc0 // Overlong - ) { - return false; - } - - i += 2; - } else if ((buf[i] & 0xf0) === 0xe0) { - // 1110xxxx 10xxxxxx 10xxxxxx - if ( - i + 2 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong - (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) - ) { - return false; - } - - i += 3; - } else if ((buf[i] & 0xf8) === 0xf0) { - // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - if ( - i + 3 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i + 3] & 0xc0) !== 0x80 || - (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong - (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || - buf[i] > 0xf4 // > U+10FFFF - ) { - return false; - } - - i += 4; - } else { - return false; - } - } - - return true; -} - -module.exports = { - isValidStatusCode, - isValidUTF8: _isValidUTF8, - tokenChars -}; - -if (isUtf8) { - module.exports.isValidUTF8 = function (buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); - }; -} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = require('utf-8-validate'); - - module.exports.isValidUTF8 = function (buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); - }; - } catch (e) { - // Continue regardless of the error. - } -} diff --git a/includes/external/pair/node_modules/ws/lib/websocket-server.js b/includes/external/pair/node_modules/ws/lib/websocket-server.js deleted file mode 100644 index bac30eb..0000000 --- a/includes/external/pair/node_modules/ws/lib/websocket-server.js +++ /dev/null @@ -1,535 +0,0 @@ -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ - -'use strict'; - -const EventEmitter = require('events'); -const http = require('http'); -const https = require('https'); -const net = require('net'); -const tls = require('tls'); -const { createHash } = require('crypto'); - -const extension = require('./extension'); -const PerMessageDeflate = require('./permessage-deflate'); -const subprotocol = require('./subprotocol'); -const WebSocket = require('./websocket'); -const { GUID, kWebSocket } = require('./constants'); - -const keyRegex = /^[+/0-9A-Za-z]{22}==$/; - -const RUNNING = 0; -const CLOSING = 1; -const CLOSED = 2; - -/** - * Class representing a WebSocket server. - * - * @extends EventEmitter - */ -class WebSocketServer extends EventEmitter { - /** - * Create a `WebSocketServer` instance. - * - * @param {Object} options Configuration options - * @param {Number} [options.backlog=511] The maximum length of the queue of - * pending connections - * @param {Boolean} [options.clientTracking=true] Specifies whether or not to - * track clients - * @param {Function} [options.handleProtocols] A hook to handle protocols - * @param {String} [options.host] The hostname where to bind the server - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.noServer=false] Enable no server mode - * @param {String} [options.path] Accept only connections matching this path - * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable - * permessage-deflate - * @param {Number} [options.port] The port where to bind the server - * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S - * server to use - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @param {Function} [options.verifyClient] A hook to reject connections - * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` - * class to use. It must be the `WebSocket` class or class that extends it - * @param {Function} [callback] A listener for the `listening` event - */ - constructor(options, callback) { - super(); - - options = { - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - verifyClient: null, - noServer: false, - backlog: null, // use default (511 as implemented in net.js) - server: null, - host: null, - path: null, - port: null, - WebSocket, - ...options - }; - - if ( - (options.port == null && !options.server && !options.noServer) || - (options.port != null && (options.server || options.noServer)) || - (options.server && options.noServer) - ) { - throw new TypeError( - 'One and only one of the "port", "server", or "noServer" options ' + - 'must be specified' - ); - } - - if (options.port != null) { - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - - res.writeHead(426, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - - if (this._server) { - const emitConnection = this.emit.bind(this, 'connection'); - - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, 'listening'), - error: this.emit.bind(this, 'error'), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = new Set(); - this._shouldEmitClose = false; - } - - this.options = options; - this._state = RUNNING; - } - - /** - * Returns the bound address, the address family name, and port of the server - * as reported by the operating system if listening on an IP socket. - * If the server is listening on a pipe or UNIX domain socket, the name is - * returned as a string. - * - * @return {(Object|String|null)} The address of the server - * @public - */ - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - - if (!this._server) return null; - return this._server.address(); - } - - /** - * Stop the server from accepting new connections and emit the `'close'` event - * when all existing connections are closed. - * - * @param {Function} [cb] A one-time listener for the `'close'` event - * @public - */ - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once('close', () => { - cb(new Error('The server is not running')); - }); - } - - process.nextTick(emitClose, this); - return; - } - - if (cb) this.once('close', cb); - - if (this._state === CLOSING) return; - this._state = CLOSING; - - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - - this._removeListeners(); - this._removeListeners = this._server = null; - - // - // The HTTP/S server was created internally. Close it, and rely on its - // `'close'` event. - // - server.close(() => { - emitClose(this); - }); - } - } - - /** - * See if a given request should be handled by this server instance. - * - * @param {http.IncomingMessage} req Request object to inspect - * @return {Boolean} `true` if the request is valid, else `false` - * @public - */ - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf('?'); - const pathname = index !== -1 ? req.url.slice(0, index) : req.url; - - if (pathname !== this.options.path) return false; - } - - return true; - } - - /** - * Handle a HTTP Upgrade request. - * - * @param {http.IncomingMessage} req The request object - * @param {(net.Socket|tls.Socket)} socket The network socket between the - * server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @public - */ - handleUpgrade(req, socket, head, cb) { - socket.on('error', socketOnError); - - const key = req.headers['sec-websocket-key']; - const version = +req.headers['sec-websocket-version']; - - if (req.method !== 'GET') { - const message = 'Invalid HTTP method'; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); - return; - } - - if (req.headers.upgrade.toLowerCase() !== 'websocket') { - const message = 'Invalid Upgrade header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (!key || !keyRegex.test(key)) { - const message = 'Missing or invalid Sec-WebSocket-Key header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (version !== 8 && version !== 13) { - const message = 'Missing or invalid Sec-WebSocket-Version header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - - const secWebSocketProtocol = req.headers['sec-websocket-protocol']; - let protocols = new Set(); - - if (secWebSocketProtocol !== undefined) { - try { - protocols = subprotocol.parse(secWebSocketProtocol); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Protocol header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - - const secWebSocketExtensions = req.headers['sec-websocket-extensions']; - const extensions = {}; - - if ( - this.options.perMessageDeflate && - secWebSocketExtensions !== undefined - ) { - const perMessageDeflate = new PerMessageDeflate( - this.options.perMessageDeflate, - true, - this.options.maxPayload - ); - - try { - const offers = extension.parse(secWebSocketExtensions); - - if (offers[PerMessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); - extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - const message = - 'Invalid or unacceptable Sec-WebSocket-Extensions header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - - // - // Optionally call external client verification handler. - // - if (this.options.verifyClient) { - const info = { - origin: - req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - - this.completeUpgrade( - extensions, - key, - protocols, - req, - socket, - head, - cb - ); - }); - return; - } - - if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); - } - - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } - - /** - * Upgrade the connection to WebSocket. - * - * @param {Object} extensions The accepted extensions - * @param {String} key The value of the `Sec-WebSocket-Key` header - * @param {Set} protocols The subprotocols - * @param {http.IncomingMessage} req The request object - * @param {(net.Socket|tls.Socket)} socket The network socket between the - * server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @throws {Error} If called more than once with the same socket - * @private - */ - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - // - // Destroy the socket if the client has already sent a FIN packet. - // - if (!socket.readable || !socket.writable) return socket.destroy(); - - if (socket[kWebSocket]) { - throw new Error( - 'server.handleUpgrade() was called more than once with the same ' + - 'socket, possibly due to a misconfiguration' - ); - } - - if (this._state > RUNNING) return abortHandshake(socket, 503); - - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - - const headers = [ - 'HTTP/1.1 101 Switching Protocols', - 'Upgrade: websocket', - 'Connection: Upgrade', - `Sec-WebSocket-Accept: ${digest}` - ]; - - const ws = new this.options.WebSocket(null); - - if (protocols.size) { - // - // Optionally call external protocol selection handler. - // - const protocol = this.options.handleProtocols - ? this.options.handleProtocols(protocols, req) - : protocols.values().next().value; - - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - - if (extensions[PerMessageDeflate.extensionName]) { - const params = extensions[PerMessageDeflate.extensionName].params; - const value = extension.format({ - [PerMessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - - // - // Allow external modification/inspection of handshake headers. - // - this.emit('headers', headers, req); - - socket.write(headers.concat('\r\n').join('\r\n')); - socket.removeListener('error', socketOnError); - - ws.setSocket(socket, head, { - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - - if (this.clients) { - this.clients.add(ws); - ws.on('close', () => { - this.clients.delete(ws); - - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - - cb(ws, req); - } -} - -module.exports = WebSocketServer; - -/** - * Add event listeners on an `EventEmitter` using a map of <event, listener> - * pairs. - * - * @param {EventEmitter} server The event emitter - * @param {Object.<String, Function>} map The listeners to add - * @return {Function} A function that will remove the added listeners when - * called - * @private - */ -function addListeners(server, map) { - for (const event of Object.keys(map)) server.on(event, map[event]); - - return function removeListeners() { - for (const event of Object.keys(map)) { - server.removeListener(event, map[event]); - } - }; -} - -/** - * Emit a `'close'` event on an `EventEmitter`. - * - * @param {EventEmitter} server The event emitter - * @private - */ -function emitClose(server) { - server._state = CLOSED; - server.emit('close'); -} - -/** - * Handle socket errors. - * - * @private - */ -function socketOnError() { - this.destroy(); -} - -/** - * Close the connection when preconditions are not fulfilled. - * - * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request - * @param {Number} code The HTTP response status code - * @param {String} [message] The HTTP response body - * @param {Object} [headers] Additional HTTP response headers - * @private - */ -function abortHandshake(socket, code, message, headers) { - // - // The socket is writable unless the user destroyed or ended it before calling - // `server.handleUpgrade()` or in the `verifyClient` function, which is a user - // error. Handling this does not make much sense as the worst that can happen - // is that some of the data written by the user might be discarded due to the - // call to `socket.end()` below, which triggers an `'error'` event that in - // turn causes the socket to be destroyed. - // - message = message || http.STATUS_CODES[code]; - headers = { - Connection: 'close', - 'Content-Type': 'text/html', - 'Content-Length': Buffer.byteLength(message), - ...headers - }; - - socket.once('finish', socket.destroy); - - socket.end( - `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + - Object.keys(headers) - .map((h) => `${h}: ${headers[h]}`) - .join('\r\n') + - '\r\n\r\n' + - message - ); -} - -/** - * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least - * one listener for it, otherwise call `abortHandshake()`. - * - * @param {WebSocketServer} server The WebSocket server - * @param {http.IncomingMessage} req The request object - * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request - * @param {Number} code The HTTP response status code - * @param {String} message The HTTP response body - * @private - */ -function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { - if (server.listenerCount('wsClientError')) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - - server.emit('wsClientError', err, socket, req); - } else { - abortHandshake(socket, code, message); - } -} diff --git a/includes/external/pair/node_modules/ws/lib/websocket.js b/includes/external/pair/node_modules/ws/lib/websocket.js deleted file mode 100644 index b2b2b09..0000000 --- a/includes/external/pair/node_modules/ws/lib/websocket.js +++ /dev/null @@ -1,1311 +0,0 @@ -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */ - -'use strict'; - -const EventEmitter = require('events'); -const https = require('https'); -const http = require('http'); -const net = require('net'); -const tls = require('tls'); -const { randomBytes, createHash } = require('crypto'); -const { Readable } = require('stream'); -const { URL } = require('url'); - -const PerMessageDeflate = require('./permessage-deflate'); -const Receiver = require('./receiver'); -const Sender = require('./sender'); -const { - BINARY_TYPES, - EMPTY_BUFFER, - GUID, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket, - NOOP -} = require('./constants'); -const { - EventTarget: { addEventListener, removeEventListener } -} = require('./event-target'); -const { format, parse } = require('./extension'); -const { toBuffer } = require('./buffer-util'); - -const closeTimeout = 30 * 1000; -const kAborted = Symbol('kAborted'); -const protocolVersions = [8, 13]; -const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; -const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - -/** - * Class representing a WebSocket. - * - * @extends EventEmitter - */ -class WebSocket extends EventEmitter { - /** - * Create a new `WebSocket`. - * - * @param {(String|URL)} address The URL to which to connect - * @param {(String|String[])} [protocols] The subprotocols - * @param {Object} [options] Connection options - */ - constructor(address, protocols, options) { - super(); - - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER; - this._closeTimer = null; - this._extensions = {}; - this._paused = false; - this._protocol = ''; - this._readyState = WebSocket.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - - if (protocols === undefined) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === 'object' && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - - initAsClient(this, address, protocols, options); - } else { - this._isServer = true; - } - } - - /** - * This deviates from the WHATWG interface since ws doesn't support the - * required default "blob" type (instead we define a custom "nodebuffer" - * type). - * - * @type {String} - */ - get binaryType() { - return this._binaryType; - } - - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) return; - - this._binaryType = type; - - // - // Allow to change `binaryType` on the fly. - // - if (this._receiver) this._receiver._binaryType = type; - } - - /** - * @type {Number} - */ - get bufferedAmount() { - if (!this._socket) return this._bufferedAmount; - - return this._socket._writableState.length + this._sender._bufferedBytes; - } - - /** - * @type {String} - */ - get extensions() { - return Object.keys(this._extensions).join(); - } - - /** - * @type {Boolean} - */ - get isPaused() { - return this._paused; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onclose() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onerror() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onopen() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onmessage() { - return null; - } - - /** - * @type {String} - */ - get protocol() { - return this._protocol; - } - - /** - * @type {Number} - */ - get readyState() { - return this._readyState; - } - - /** - * @type {String} - */ - get url() { - return this._url; - } - - /** - * Set up the socket and the internal resources. - * - * @param {(net.Socket|tls.Socket)} socket The network socket between the - * server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Object} options Options object - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.maxPayload=0] The maximum allowed message size - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ - setSocket(socket, head, options) { - const receiver = new Receiver({ - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation - }); - - this._sender = new Sender(socket, this._extensions, options.generateMask); - this._receiver = receiver; - this._socket = socket; - - receiver[kWebSocket] = this; - socket[kWebSocket] = this; - - receiver.on('conclude', receiverOnConclude); - receiver.on('drain', receiverOnDrain); - receiver.on('error', receiverOnError); - receiver.on('message', receiverOnMessage); - receiver.on('ping', receiverOnPing); - receiver.on('pong', receiverOnPong); - - socket.setTimeout(0); - socket.setNoDelay(); - - if (head.length > 0) socket.unshift(head); - - socket.on('close', socketOnClose); - socket.on('data', socketOnData); - socket.on('end', socketOnEnd); - socket.on('error', socketOnError); - - this._readyState = WebSocket.OPEN; - this.emit('open'); - } - - /** - * Emit the `'close'` event. - * - * @private - */ - emitClose() { - if (!this._socket) { - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - return; - } - - if (this._extensions[PerMessageDeflate.extensionName]) { - this._extensions[PerMessageDeflate.extensionName].cleanup(); - } - - this._receiver.removeAllListeners(); - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - } - - /** - * Start a closing handshake. - * - * +----------+ +-----------+ +----------+ - * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - - * | +----------+ +-----------+ +----------+ | - * +----------+ +-----------+ | - * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING - * +----------+ +-----------+ | - * | | | +---+ | - * +------------------------+-->|fin| - - - - - * | +---+ | +---+ - * - - - - -|fin|<---------------------+ - * +---+ - * - * @param {Number} [code] Status code explaining why the connection is closing - * @param {(String|Buffer)} [data] The reason why the connection is - * closing - * @public - */ - close(code, data) { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake(this, this._req, msg); - return; - } - - if (this.readyState === WebSocket.CLOSING) { - if ( - this._closeFrameSent && - (this._closeFrameReceived || this._receiver._writableState.errorEmitted) - ) { - this._socket.end(); - } - - return; - } - - this._readyState = WebSocket.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - // - // This error is handled by the `'error'` listener on the socket. We only - // want to know if the close frame has been sent here. - // - if (err) return; - - this._closeFrameSent = true; - - if ( - this._closeFrameReceived || - this._receiver._writableState.errorEmitted - ) { - this._socket.end(); - } - }); - - // - // Specify a timeout for the closing handshake to complete. - // - this._closeTimer = setTimeout( - this._socket.destroy.bind(this._socket), - closeTimeout - ); - } - - /** - * Pause the socket. - * - * @public - */ - pause() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - - this._paused = true; - this._socket.pause(); - } - - /** - * Send a ping. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the ping is sent - * @public - */ - ping(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Send a pong. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the pong is sent - * @public - */ - pong(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Resume the socket. - * - * @public - */ - resume() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - - this._paused = false; - if (!this._receiver._writableState.needDrain) this._socket.resume(); - } - - /** - * Send a data message. - * - * @param {*} data The message to send - * @param {Object} [options] Options object - * @param {Boolean} [options.binary] Specifies whether `data` is binary or - * text - * @param {Boolean} [options.compress] Specifies whether or not to compress - * `data` - * @param {Boolean} [options.fin=true] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when data is written out - * @public - */ - send(data, options, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - const opts = { - binary: typeof data !== 'string', - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - - if (!this._extensions[PerMessageDeflate.extensionName]) { - opts.compress = false; - } - - this._sender.send(data || EMPTY_BUFFER, opts, cb); - } - - /** - * Forcibly close the connection. - * - * @public - */ - terminate() { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake(this, this._req, msg); - return; - } - - if (this._socket) { - this._readyState = WebSocket.CLOSING; - this._socket.destroy(); - } - } -} - -/** - * @constant {Number} CONNECTING - * @memberof WebSocket - */ -Object.defineProperty(WebSocket, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') -}); - -/** - * @constant {Number} CONNECTING - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket.prototype, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') -}); - -/** - * @constant {Number} OPEN - * @memberof WebSocket - */ -Object.defineProperty(WebSocket, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') -}); - -/** - * @constant {Number} OPEN - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket.prototype, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') -}); - -/** - * @constant {Number} CLOSING - * @memberof WebSocket - */ -Object.defineProperty(WebSocket, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') -}); - -/** - * @constant {Number} CLOSING - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket.prototype, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') -}); - -/** - * @constant {Number} CLOSED - * @memberof WebSocket - */ -Object.defineProperty(WebSocket, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') -}); - -/** - * @constant {Number} CLOSED - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket.prototype, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') -}); - -[ - 'binaryType', - 'bufferedAmount', - 'extensions', - 'isPaused', - 'protocol', - 'readyState', - 'url' -].forEach((property) => { - Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); -}); - -// -// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. -// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface -// -['open', 'error', 'close', 'message'].forEach((method) => { - Object.defineProperty(WebSocket.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) return listener[kListener]; - } - - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; - } - } - - if (typeof handler !== 'function') return; - - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); -}); - -WebSocket.prototype.addEventListener = addEventListener; -WebSocket.prototype.removeEventListener = removeEventListener; - -module.exports = WebSocket; - -/** - * Initialize a WebSocket client. - * - * @param {WebSocket} websocket The client to initialize - * @param {(String|URL)} address The URL to which to connect - * @param {Array} protocols The subprotocols - * @param {Object} [options] Connection options - * @param {Boolean} [options.followRedirects=false] Whether or not to follow - * redirects - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the - * handshake request - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Number} [options.maxRedirects=10] The maximum number of redirects - * allowed - * @param {String} [options.origin] Value of the `Origin` or - * `Sec-WebSocket-Origin` header - * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable - * permessage-deflate - * @param {Number} [options.protocolVersion=13] Value of the - * `Sec-WebSocket-Version` header - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ -function initAsClient(websocket, address, protocols, options) { - const opts = { - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - createConnection: undefined, - socketPath: undefined, - hostname: undefined, - protocol: undefined, - timeout: undefined, - method: 'GET', - host: undefined, - path: undefined, - port: undefined - }; - - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} ` + - `(supported versions: ${protocolVersions.join(', ')})` - ); - } - - let parsedUrl; - - if (address instanceof URL) { - parsedUrl = address; - websocket._url = address.href; - } else { - try { - parsedUrl = new URL(address); - } catch (e) { - throw new SyntaxError(`Invalid URL: ${address}`); - } - - websocket._url = address; - } - - const isSecure = parsedUrl.protocol === 'wss:'; - const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; - let invalidUrlMessage; - - if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { - invalidUrlMessage = - 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = 'The URL contains a fragment identifier'; - } - - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - - if (websocket._redirects === 0) { - throw err; - } else { - emitErrorAndClose(websocket, err); - return; - } - } - - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString('base64'); - const request = isSecure ? https.request : http.request; - const protocolSet = new Set(); - let perMessageDeflate; - - opts.createConnection = isSecure ? tlsConnect : netConnect; - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith('[') - ? parsedUrl.hostname.slice(1, -1) - : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - 'Sec-WebSocket-Version': opts.protocolVersion, - 'Sec-WebSocket-Key': key, - Connection: 'Upgrade', - Upgrade: 'websocket' - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate( - opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, - false, - opts.maxPayload - ); - opts.headers['Sec-WebSocket-Extensions'] = format({ - [PerMessageDeflate.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols.length) { - for (const protocol of protocols) { - if ( - typeof protocol !== 'string' || - !subprotocolRegex.test(protocol) || - protocolSet.has(protocol) - ) { - throw new SyntaxError( - 'An invalid or duplicated subprotocol was specified' - ); - } - - protocolSet.add(protocol); - } - - opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers['Sec-WebSocket-Origin'] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - - if (isIpcUrl) { - const parts = opts.path.split(':'); - - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - - let req; - - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl - ? opts.socketPath - : parsedUrl.host; - - const headers = options && options.headers; - - // - // Shallow copy the user provided options so that headers can be changed - // without mutating the original object. - // - options = { ...options, headers: {} }; - - if (headers) { - for (const [key, value] of Object.entries(headers)) { - options.headers[key.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount('redirect') === 0) { - const isSameHost = isIpcUrl - ? websocket._originalIpc - ? opts.socketPath === websocket._originalHostOrSocketPath - : false - : websocket._originalIpc - ? false - : parsedUrl.host === websocket._originalHostOrSocketPath; - - if (!isSameHost || (websocket._originalSecure && !isSecure)) { - // - // Match curl 7.77.0 behavior and drop the following headers. These - // headers are also dropped when following a redirect to a subdomain. - // - delete opts.headers.authorization; - delete opts.headers.cookie; - - if (!isSameHost) delete opts.headers.host; - - opts.auth = undefined; - } - } - - // - // Match curl 7.77.0 behavior and make the first `Authorization` header win. - // If the `Authorization` header is set, then there is nothing to do as it - // will take precedence. - // - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = - 'Basic ' + Buffer.from(opts.auth).toString('base64'); - } - - req = websocket._req = request(opts); - - if (websocket._redirects) { - // - // Unlike what is done for the `'upgrade'` event, no early exit is - // triggered here if the user calls `websocket.close()` or - // `websocket.terminate()` from a listener of the `'redirect'` event. This - // is because the user can also call `request.destroy()` with an error - // before calling `websocket.close()` or `websocket.terminate()` and this - // would result in an error being emitted on the `request` object with no - // `'error'` event listeners attached. - // - websocket.emit('redirect', websocket.url, req); - } - } else { - req = websocket._req = request(opts); - } - - if (opts.timeout) { - req.on('timeout', () => { - abortHandshake(websocket, req, 'Opening handshake has timed out'); - }); - } - - req.on('error', (err) => { - if (req === null || req[kAborted]) return; - - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - - req.on('response', (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - - if ( - location && - opts.followRedirects && - statusCode >= 300 && - statusCode < 400 - ) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake(websocket, req, 'Maximum redirects exceeded'); - return; - } - - req.abort(); - - let addr; - - try { - addr = new URL(location, address); - } catch (e) { - const err = new SyntaxError(`Invalid URL: ${location}`); - emitErrorAndClose(websocket, err); - return; - } - - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit('unexpected-response', req, res)) { - abortHandshake( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - - req.on('upgrade', (res, socket, head) => { - websocket.emit('upgrade', res); - - // - // The user may have closed the connection from a listener of the - // `'upgrade'` event. - // - if (websocket.readyState !== WebSocket.CONNECTING) return; - - req = websocket._req = null; - - if (res.headers.upgrade.toLowerCase() !== 'websocket') { - abortHandshake(websocket, socket, 'Invalid Upgrade header'); - return; - } - - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - - if (res.headers['sec-websocket-accept'] !== digest) { - abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); - return; - } - - const serverProt = res.headers['sec-websocket-protocol']; - let protError; - - if (serverProt !== undefined) { - if (!protocolSet.size) { - protError = 'Server sent a subprotocol but none was requested'; - } else if (!protocolSet.has(serverProt)) { - protError = 'Server sent an invalid subprotocol'; - } - } else if (protocolSet.size) { - protError = 'Server sent no subprotocol'; - } - - if (protError) { - abortHandshake(websocket, socket, protError); - return; - } - - if (serverProt) websocket._protocol = serverProt; - - const secWebSocketExtensions = res.headers['sec-websocket-extensions']; - - if (secWebSocketExtensions !== undefined) { - if (!perMessageDeflate) { - const message = - 'Server sent a Sec-WebSocket-Extensions header but no extension ' + - 'was requested'; - abortHandshake(websocket, socket, message); - return; - } - - let extensions; - - try { - extensions = parse(secWebSocketExtensions); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake(websocket, socket, message); - return; - } - - const extensionNames = Object.keys(extensions); - - if ( - extensionNames.length !== 1 || - extensionNames[0] !== PerMessageDeflate.extensionName - ) { - const message = 'Server indicated an extension that was not requested'; - abortHandshake(websocket, socket, message); - return; - } - - try { - perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake(websocket, socket, message); - return; - } - - websocket._extensions[PerMessageDeflate.extensionName] = - perMessageDeflate; - } - - websocket.setSocket(socket, head, { - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } -} - -/** - * Emit the `'error'` and `'close'` events. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {Error} The error to emit - * @private - */ -function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket.CLOSING; - websocket.emit('error', err); - websocket.emitClose(); -} - -/** - * Create a `net.Socket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {net.Socket} The newly created socket used to start the connection - * @private - */ -function netConnect(options) { - options.path = options.socketPath; - return net.connect(options); -} - -/** - * Create a `tls.TLSSocket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {tls.TLSSocket} The newly created socket used to start the connection - * @private - */ -function tlsConnect(options) { - options.path = undefined; - - if (!options.servername && options.servername !== '') { - options.servername = net.isIP(options.host) ? '' : options.host; - } - - return tls.connect(options); -} - -/** - * Abort the handshake and emit an error. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to - * abort or the socket to destroy - * @param {String} message The error message - * @private - */ -function abortHandshake(websocket, stream, message) { - websocket._readyState = WebSocket.CLOSING; - - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake); - - if (stream.setHeader) { - stream[kAborted] = true; - stream.abort(); - - if (stream.socket && !stream.socket.destroyed) { - // - // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if - // called after the request completed. See - // https://github.com/websockets/ws/issues/1869. - // - stream.socket.destroy(); - } - - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream.destroy(err); - stream.once('error', websocket.emit.bind(websocket, 'error')); - stream.once('close', websocket.emitClose.bind(websocket)); - } -} - -/** - * Handle cases where the `ping()`, `pong()`, or `send()` methods are called - * when the `readyState` attribute is `CLOSING` or `CLOSED`. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {*} [data] The data to send - * @param {Function} [cb] Callback - * @private - */ -function sendAfterClose(websocket, data, cb) { - if (data) { - const length = toBuffer(data).length; - - // - // The `_bufferedAmount` property is used only when the peer is a client and - // the opening handshake fails. Under these circumstances, in fact, the - // `setSocket()` method is not called, so the `_socket` and `_sender` - // properties are set to `null`. - // - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} ` + - `(${readyStates[websocket.readyState]})` - ); - process.nextTick(cb, err); - } -} - -/** - * The listener of the `Receiver` `'conclude'` event. - * - * @param {Number} code The status code - * @param {Buffer} reason The reason for closing - * @private - */ -function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket]; - - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - - if (websocket._socket[kWebSocket] === undefined) return; - - websocket._socket.removeListener('data', socketOnData); - process.nextTick(resume, websocket._socket); - - if (code === 1005) websocket.close(); - else websocket.close(code, reason); -} - -/** - * The listener of the `Receiver` `'drain'` event. - * - * @private - */ -function receiverOnDrain() { - const websocket = this[kWebSocket]; - - if (!websocket.isPaused) websocket._socket.resume(); -} - -/** - * The listener of the `Receiver` `'error'` event. - * - * @param {(RangeError|Error)} err The emitted error - * @private - */ -function receiverOnError(err) { - const websocket = this[kWebSocket]; - - if (websocket._socket[kWebSocket] !== undefined) { - websocket._socket.removeListener('data', socketOnData); - - // - // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See - // https://github.com/websockets/ws/issues/1940. - // - process.nextTick(resume, websocket._socket); - - websocket.close(err[kStatusCode]); - } - - websocket.emit('error', err); -} - -/** - * The listener of the `Receiver` `'finish'` event. - * - * @private - */ -function receiverOnFinish() { - this[kWebSocket].emitClose(); -} - -/** - * The listener of the `Receiver` `'message'` event. - * - * @param {Buffer|ArrayBuffer|Buffer[])} data The message - * @param {Boolean} isBinary Specifies whether the message is binary or not - * @private - */ -function receiverOnMessage(data, isBinary) { - this[kWebSocket].emit('message', data, isBinary); -} - -/** - * The listener of the `Receiver` `'ping'` event. - * - * @param {Buffer} data The data included in the ping frame - * @private - */ -function receiverOnPing(data) { - const websocket = this[kWebSocket]; - - websocket.pong(data, !websocket._isServer, NOOP); - websocket.emit('ping', data); -} - -/** - * The listener of the `Receiver` `'pong'` event. - * - * @param {Buffer} data The data included in the pong frame - * @private - */ -function receiverOnPong(data) { - this[kWebSocket].emit('pong', data); -} - -/** - * Resume a readable stream - * - * @param {Readable} stream The readable stream - * @private - */ -function resume(stream) { - stream.resume(); -} - -/** - * The listener of the `net.Socket` `'close'` event. - * - * @private - */ -function socketOnClose() { - const websocket = this[kWebSocket]; - - this.removeListener('close', socketOnClose); - this.removeListener('data', socketOnData); - this.removeListener('end', socketOnEnd); - - websocket._readyState = WebSocket.CLOSING; - - let chunk; - - // - // The close frame might not have been received or the `'end'` event emitted, - // for example, if the socket was destroyed due to an error. Ensure that the - // `receiver` stream is closed after writing any remaining buffered data to - // it. If the readable side of the socket is in flowing mode then there is no - // buffered data as everything has been already written and `readable.read()` - // will return `null`. If instead, the socket is paused, any possible buffered - // data will be read as a single chunk. - // - if ( - !this._readableState.endEmitted && - !websocket._closeFrameReceived && - !websocket._receiver._writableState.errorEmitted && - (chunk = websocket._socket.read()) !== null - ) { - websocket._receiver.write(chunk); - } - - websocket._receiver.end(); - - this[kWebSocket] = undefined; - - clearTimeout(websocket._closeTimer); - - if ( - websocket._receiver._writableState.finished || - websocket._receiver._writableState.errorEmitted - ) { - websocket.emitClose(); - } else { - websocket._receiver.on('error', receiverOnFinish); - websocket._receiver.on('finish', receiverOnFinish); - } -} - -/** - * The listener of the `net.Socket` `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function socketOnData(chunk) { - if (!this[kWebSocket]._receiver.write(chunk)) { - this.pause(); - } -} - -/** - * The listener of the `net.Socket` `'end'` event. - * - * @private - */ -function socketOnEnd() { - const websocket = this[kWebSocket]; - - websocket._readyState = WebSocket.CLOSING; - websocket._receiver.end(); - this.end(); -} - -/** - * The listener of the `net.Socket` `'error'` event. - * - * @private - */ -function socketOnError() { - const websocket = this[kWebSocket]; - - this.removeListener('error', socketOnError); - this.on('error', NOOP); - - if (websocket) { - websocket._readyState = WebSocket.CLOSING; - this.destroy(); - } -} diff --git a/includes/external/pair/node_modules/ws/package.json b/includes/external/pair/node_modules/ws/package.json deleted file mode 100644 index 4b5d92b..0000000 --- a/includes/external/pair/node_modules/ws/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "ws", - "version": "8.13.0", - "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", - "keywords": [ - "HyBi", - "Push", - "RFC-6455", - "WebSocket", - "WebSockets", - "real-time" - ], - "homepage": "https://github.com/websockets/ws", - "bugs": "https://github.com/websockets/ws/issues", - "repository": "websockets/ws", - "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)", - "license": "MIT", - "main": "index.js", - "exports": { - ".": { - "browser": "./browser.js", - "import": "./wrapper.mjs", - "require": "./index.js" - }, - "./package.json": "./package.json" - }, - "browser": "browser.js", - "engines": { - "node": ">=10.0.0" - }, - "files": [ - "browser.js", - "index.js", - "lib/*.js", - "wrapper.mjs" - ], - "scripts": { - "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", - "integration": "mocha --throw-deprecation test/*.integration.js", - "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - }, - "devDependencies": { - "benchmark": "^2.1.4", - "bufferutil": "^4.0.1", - "eslint": "^8.0.0", - "eslint-config-prettier": "^8.1.0", - "eslint-plugin-prettier": "^4.0.0", - "mocha": "^8.4.0", - "nyc": "^15.0.0", - "prettier": "^2.0.5", - "utf-8-validate": "^6.0.0" - } -} diff --git a/includes/external/pair/node_modules/ws/wrapper.mjs b/includes/external/pair/node_modules/ws/wrapper.mjs deleted file mode 100644 index 7245ad1..0000000 --- a/includes/external/pair/node_modules/ws/wrapper.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import createWebSocketStream from './lib/stream.js'; -import Receiver from './lib/receiver.js'; -import Sender from './lib/sender.js'; -import WebSocket from './lib/websocket.js'; -import WebSocketServer from './lib/websocket-server.js'; - -export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; -export default WebSocket; diff --git a/includes/external/pair/package-lock.json b/includes/external/pair/package-lock.json deleted file mode 100644 index da57184..0000000 --- a/includes/external/pair/package-lock.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "pair", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "dependencies": { - "ws": "^8.13.0" - } - }, - "node_modules/ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - }, - "dependencies": { - "ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "requires": {} - } - } -} diff --git a/includes/external/pair/package.json b/includes/external/pair/package.json deleted file mode 100644 index f19286e..0000000 --- a/includes/external/pair/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "dependencies": { - "ws": "^8.13.0" - } -} diff --git a/includes/external/pair/reference.js b/includes/external/pair/reference.js deleted file mode 100644 index 9b7b61e..0000000 --- a/includes/external/pair/reference.js +++ /dev/null @@ -1,78 +0,0 @@ -"use strict"; - -const { WebSocket } = require('ws'); - -// Create a WebSocket to the pairing endpoint -const ws = new WebSocket("wss://ponies.equestria.horse/_PairingServices-WebSocket-EntryPoint/socket"); - -// In case there is an error, the connection should be reset and the pairing process will have to be initiated again -ws.on('error', (e) => { - console.error(e); -}); - -ws.on('message', (raw) => { - // The server always sends JSON data - let data = JSON.parse(raw.toString()); - - // All data objects have a "type" value - switch (data.type) { - case "init": - // The 'init' event is the first event sent after the connection is established - // Note: future implementations can read 'data.version' to get the protocol version (as an integer) - ws.send(JSON.stringify({ - type: "init", - name: "Ponycule pairing reference client" // Replace this with the name of your application - // The 'name' value must be a string between 2 and 50 characters, additional requirements might get - // added in future protocol versions. - })); - break; - - case "preflight": - // The 'preflight' event is sent before the user confirms the request. It contains identifiable information. - // On a real implementation, this should make a sound/show a message to let the user know they are working - // with the right device. - console.log(`Attempting to pair with: '${data.identity.name}' using '${data.identity.platform}'`); - // 'data.identity.name' contains the display name of the user doing the pairing process. - // 'data.identity.platform' contains the platform (browser + OS) the pairing process is being done from. - break; - - case "confirm": - // The 'confirm' event is sent once the user has accepted the request. At this point, the paired device is - // in possession of a valid authentication token (a different one than the one used by the pairing device). - // The paired device should now store this authentication token in a safe place and send it back to the - // server as the 'PEH2_SESSION_TOKEN' cookie when making an authenticated request. - console.log(`Token: ${data.token.substring(0, 10)}${"*".repeat(data.token.length - 10)}`); - // The token is stored in 'data.token', the code above censors all but the first 10 characters. - // Once you have the token, you can make authenticated requests: - fetch("https://ponies.equestria.horse/api/session", { - // The 'session' endpoint returns information about the current session (name, IPs, dates, ...) - headers: { - Cookie: "PEH2_SESSION_TOKEN=" + data.token // Passing the token as a cookie - } - }).then((res) => { - res.json().then((data) => { // Most (if not all) endpoints return JSON data - console.log(data); - process.exit(); - }); - }); - break; - - case "reject": - // The 'reject' event is sent if the user has rejected the request. This should be considered an error by - // a client implementation, and the pairing process should not attempt to continue any further after this - // event occurs. No token is sent. - console.log(`Pairing rejected`); - process.exit(); - break; - - case "waiting": - // The 'waiting' event is sent after the connection has been initialized. It's at this point that you can - // consider the connection to be established and the device to be ready. - console.log(`Pairing code: ${data.code}`); // 'data.code' contains the 5-character pairing code. - break; - - default: - // An unrecognised type should be considered to be an error - throw new Error("Invalid type"); - } -});
\ No newline at end of file diff --git a/includes/external/signal/index.js b/includes/external/signal/index.js index 31de8a7..bcbb2b8 100644 --- a/includes/external/signal/index.js +++ b/includes/external/signal/index.js @@ -12,7 +12,6 @@ const child_process = require("child_process"); let system = require('../../data/' + (user === "raindrops" ? "gdapd" : (user === "Moonglow" ? "hrbom" : "other")) + "/general.json"); let fronters = require('../../data/' + (user === "raindrops" ? "gdapd" : (user === "Moonglow" ? "hrbom" : "other")) + "/fronters.json"); - let members = require('../../data/' + (user === "raindrops" ? "gdapd" : (user === "Moonglow" ? "hrbom" : "other")) + "/members.json"); console.log(system.name); console.log(fronters.members.length + " member(s) at front"); @@ -21,13 +20,10 @@ const child_process = require("child_process"); let avatar1 = system.avatar_url; let avatar2 = null; - let fronter1 = null; - let fronter2 = null; - - if (fronters.members.length === 1 || (fronters.members.length === 2 && (fronters.members[0].name === "scootaloo" && fronters.members[1].name === "rainbowdash"))) { + if (fronters.members.length === 1) { name = fronters.members[0].display_name ?? fronters.members[0].name; avatar1 = fronters.members[0].avatar_url ?? avatar1; - } else if (fronters.members.length >= 2 && !(fronters.members[0].name === "scootaloo" && fronters.members[1].name === "rainbowdash")) { + } else if (fronters.members.length >= 2) { name = (fronters.members[0].display_name ?? fronters.members[0].name) + " and " + (fronters.members[1].display_name ?? fronters.members[1].name); avatar1 = fronters.members[0].avatar_url ?? avatar1; avatar2 = fronters.members[1].avatar_url ?? avatar2; @@ -63,4 +59,4 @@ const child_process = require("child_process"); child_process.execFileSync("signal-cli", [ "-a", number, "updateAccount", "--device-name", "Ponycule to Signal integration (v" + new Date().toISOString().split("T")[0].replaceAll("-", ".") + ")" ]); child_process.execFileSync("signal-cli", [ "-a", number, "sendSyncRequest" ]); fs.unlinkSync("/tmp/chm-" + user + "-pfp-final"); -})();
\ No newline at end of file +})(); diff --git a/includes/flags.json b/includes/flags.json deleted file mode 100644 index e1702c6..0000000 --- a/includes/flags.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "age_regressor": null, - "age_spells": null, - "leader": null, - "not_talking": null, - "median": null, - "sexual_features": null, - "sexually_active": null, - "polyamorous": { - "romantic": null, - "sexual": null - }, - "less_frequent": null, - "not_fronting": null, - "punished": null, - "alcohol": null, - "pacifier": null, - "sleep_plush": null, - - "host": "Host", - "protector": "!!Protector", - "leader2": "Leader", - "fictive": "!!Equestrian", - "fictive2": "Fictive (Celeste)", - "robot": "!!Robot", - "plush": "!!Plush", - "non_verbal": "!!Non verbal in real life", - "persecutor": "!!Persecutor", - "private": "Hide from public listings", - "other": "Having sex with %other%", - "other2": "Potentially having sex with %other%", - "other3": "#Having sex with Raindrops", - "other4": "#Potentially having sex with Raindrops", - "show_gender": "Display Gender on page" -} diff --git a/includes/fragments/dashboard.inc b/includes/fragments/dashboard.inc index 29b5b84..9ad9372 100644 --- a/includes/fragments/dashboard.inc +++ b/includes/fragments/dashboard.inc @@ -25,7 +25,8 @@ global $use2023UI; </div> <div class="alert alert-warning"> - <b>Ponycule's user-space pages are going away.</b> Starting in April 2024, we will be discontinuing all the Ponycule public pages to better focus on making Ponycule a central hub for plural integrations with other services. If you need access to all your content, you may request a backup to the administrators. + <p><b>Ponycule's user-space pages are going away.</b> Starting in April 2024, we will be discontinuing all the Ponycule public pages to better focus on making Ponycule a central hub for plural integrations with other services. If you need access to all your content, you may request a backup to the administrators.</p> + <div>Emergency features are not guaranteed to work anymore and have been removed. If you need a trusted one to respond within a short amount of time, you can try sending a lot of messages on instant messaging apps (e.g. Signal); if there is an immediate risk for your or someone else's life, please call <?= $_PROFILE["login"] === "Moonglow" || $_PROFILE["login"] === "raindrops" ? "112" : "991" ?> immediately.</div> </div> <style> @@ -222,15 +223,6 @@ global $use2023UI; <a href="/moonglow" class="list-group-item list-group-item-action" style="display: flex; align-items: center;"> <img src="/assets/avatars/d1cd97eb9c924e4294cd4397a5074ff9.webp" style="margin-right: 5px; width: 24px;"><div style="vertical-align: middle; display: flex; align-items: center; color: var(--bs-body-color);">Moonglow</div> </a> - <a href="/-/emergency" class="list-group-item list-group-item-action" style="display: grid; grid-template-columns: max-content 1fr;"> - <img src="<?= icon("emergency") ?>" style="margin-right: 5px; height: 24px; width: 24px;"><div style="display: flex; align-items: center; color: var(--bs-body-color);">Emergency alert</div> - </a> - <a href="/-/byfront" class="list-group-item list-group-item-action" style="display: grid; grid-template-columns: max-content 1fr;"> - <img src="<?= icon("front") ?>" style="margin-right: 5px; height: 24px; width: 24px;"><div style="display: flex; align-items: center; color: var(--bs-body-color);">By last fronted date</div> - </a> - <a href="/-/schedule" class="list-group-item list-group-item-action" style="display: grid; grid-template-columns: max-content 1fr;"> - <img src="<?= icon("schedule") ?>" style="margin-right: 5px; height: 24px; width: 24px;"><div style="display: flex; align-items: center; color: var(--bs-body-color);">Raindrops schedule</div> - </a> <a href="https://plex.p.equestria.dev" target="_blank" class="list-group-item list-group-item-action" style="display: grid; grid-template-columns: max-content 1fr;"> <img src="https://plex.p.equestria.dev/web/favicon.ico" style="margin-right: 5px; height: 24px; width: 24px;"><div style="display: flex; align-items: center; color: var(--bs-body-color);">Plex</div> </a> diff --git a/includes/fragments/member.inc b/includes/fragments/member.inc index 0b1ce03..c621bc3 100644 --- a/includes/fragments/member.inc +++ b/includes/fragments/member.inc @@ -1,4 +1,4 @@ -<?php global $system; global $systemCommonName; global $systemID; global $member; global $memberData; global $memberCommonName; global $memberID; global $lang; global $pages; global $app; global $isLoggedIn; global $isLowerLoggedIn; +<?php global $system; global $defaultMember; global $systemCommonName; global $systemID; global $member; global $memberData; global $memberCommonName; global $memberID; global $lang; global $pages; global $app; global $isLoggedIn; global $isLowerLoggedIn; require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/session.inc"; @@ -11,7 +11,7 @@ if ($memberData["name"] === "fusion") { } if ($memberData["name"] !== "unknown" && $memberData["name"] !== "fusion") { - $metadata = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json"), true)); + $metadata = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json", $defaultMember), true)); if (isset($metadata["private"]) && $metadata["private"] && !$isLoggedIn && !$isLowerLoggedIn) { peh_error("Page not found: " . strip_tags($member), 404); @@ -20,10 +20,10 @@ if ($memberData["name"] !== "unknown" && $memberData["name"] !== "fusion") { require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/header.inc'; -$travelling = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/travelling/travelling.json"), true); +$travelling = []; if ($memberData["name"] !== "unknown" && $memberData["name"] !== "fusion") { - $metadata = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json"), true)); + $metadata = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json", $defaultMember), true)); } global $isLoggedIn; @@ -105,7 +105,7 @@ if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/ponies/" . $memberID . ".pn <details> <summary style="list-style: none;"> - <small style="opacity:.5;display:block;"><a href="/-/metadata/<?= $system ?>/<?= $memberData['name'] ?>">Edit metadata</a> · <a href="/-/ponytown/<?= $memberData['id'] ?>">Upload Pony Town character</a></small> + <small style="opacity:.5;display:block;">Click here for technical details.</small> </summary> <div class="alert alert-dark"> <ul style="margin-bottom:0;"> @@ -124,7 +124,7 @@ if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/ponies/" . $memberID . ".pn <li> <b>Metadata:</b> <ul> - <?php foreach (parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$memberID.json"), true)) as $name => $value): ?> + <?php foreach (parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json", $defaultMember), true)) as $name => $value): ?> <li> <b><?= $name ?></b>: <?php @@ -201,4 +201,4 @@ if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/assets/ponies/" . $memberID . ".pn <?php endif; ?> </div> -<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/footer.inc'; ?>
\ No newline at end of file +<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/footer.inc'; ?> diff --git a/includes/fragments/metadata.inc b/includes/fragments/metadata.inc deleted file mode 100644 index 6449dc0..0000000 --- a/includes/fragments/metadata.inc +++ /dev/null @@ -1,308 +0,0 @@ -<?php global $system; global $app; global $systemCommonName; global $systemID; global $member; global $memberData; global $memberCommonName; global $memberID; $title = "Editing metadata for " . $memberCommonName . " · " . $systemCommonName; require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/header.inc'; - -if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json")) { - $metadata = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json"), true)); -} - -?> - -<style> - .modal-header { - border-bottom: 1px solid #353738; - } - - .modal-content { - border: 1px solid rgba(255, 255, 255, .2); - background-color: #111; - } - - .btn-close { - filter: invert(1); - } - - .list-group-item { - color: #fff; - background-color: #222; - border: 1px solid rgba(255, 255, 255, .125); - } - - .list-group-item.disabled { - color: #fff; - background-color: #222; - border-color: rgba(255, 255, 255, .125); - opacity: .75; - } - - .list-group-item:hover { - background-color: #252525; - color: #ddd; - } - - .list-group-item:active, .list-group-item:focus { - background-color: #272727; - color: #bbb; - } - - .member-link, .list-group-item-action { - cursor: pointer !important; - } -</style> - -<br> -<div class="container"> - <h2 id="page-content"><a href="/<?= $memberData["name"] ?>"><?= $memberData["display_name"] ?? $memberData["name"] ?></a></h2> - <?php if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json")): ?> - <form> - <input name="submit" type="hidden"> - <p> - <b>File</b><br> - <?= $_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $memberID . ".json" ?> - </p> - - <hr> - - <h3>Species</h3> - - <div style="margin-bottom: 1rem;"> - <div style="display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px;"> - <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23000000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");' name="species[0]"> - <option <?= !isset($metadata["species"][0]) || $metadata["species"][0] === "" ? "selected" : "" ?> value="">None</option> - <option <?= $metadata["species"][0] === "earth" ? "selected" : "" ?> value="earth">Earth pony</option> - <option <?= $metadata["species"][0] === "unicorn" ? "selected" : "" ?> value="unicorn">Unicorn</option> - <option <?= $metadata["species"][0] === "pegasus" ? "selected" : "" ?> value="pegasus">Pegasus</option> - <option <?= $metadata["species"][0] === "alicorn" ? "selected" : "" ?> value="alicorn">Alicorn</option> - <option <?= $metadata["species"][0] === "batpony" ? "selected" : "" ?> value="batpony">Bat pony</option> - <option <?= $metadata["species"][0] === "crystal" ? "selected" : "" ?> value="crystal">Crystal pony</option> - <option <?= $metadata["species"][0] === "changeling" ? "selected" : "" ?> value="changeling">Changeling</option> - <option <?= $metadata["species"][0] === "merpony" ? "selected" : "" ?> value="merpony">Merpony</option> - <option <?= $metadata["species"][0] === "deer" ? "selected" : "" ?> value="deer">Deer</option> - <option <?= $metadata["species"][0] === "kirin" ? "selected" : "" ?> value="kirin">Kirin</option> - <option <?= $metadata["species"][0] === "human" ? "selected" : "" ?> value="human">Human</option> - </select> - <select class="tooltip-nohelp form-select" style='display:inline-block;filter:invert(1) hue-rotate(180deg);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23000000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");' name="species[1]"> - <option <?= !isset($metadata["species"][1]) || $metadata["species"][1] === "" ? "selected" : "" ?> value="">None</option> - <option <?= ($metadata["species"][1] ?? "") === "earth" ? "selected" : "" ?> value="earth">Earth pony</option> - <option <?= ($metadata["species"][1] ?? "") === "unicorn" ? "selected" : "" ?> value="unicorn">Unicorn</option> - <option <?= ($metadata["species"][1] ?? "") === "pegasus" ? "selected" : "" ?> value="pegasus">Pegasus</option> - <option <?= ($metadata["species"][1] ?? "") === "alicorn" ? "selected" : "" ?> value="alicorn">Alicorn</option> - <option <?= ($metadata["species"][1] ?? "") === "batpony" ? "selected" : "" ?> value="batpony">Bat pony</option> - <option <?= ($metadata["species"][1] ?? "") === "crystal" ? "selected" : "" ?> value="crystal">Crystal pony</option> - <option <?= ($metadata["species"][1] ?? "") === "changeling" ? "selected" : "" ?> value="changeling">Changeling</option> - <option <?= ($metadata["species"][1] ?? "") === "merpony" ? "selected" : "" ?> value="merpony">Merpony</option> - <option <?= ($metadata["species"][1] ?? "") === "deer" ? "selected" : "" ?> value="deer">Deer</option> - <option <?= ($metadata["species"][1] ?? "") === "kirin" ? "selected" : "" ?> value="kirin">Kirin</option> - <option <?= ($metadata["species"][1] ?? "") === "human" ? "selected" : "" ?> value="human">Human</option> - </select> - </div> - </div> - - <hr> - - <h3>Relationships</h3> - - <div class="modal" id="new-relation" data-bs-backdrop="static" data-bs-keyboard="false"> - <div class="modal-dialog"> - <div class="modal-content"> - - <div class="modal-header"> - <h4 class="modal-title">Add a new <span id="new-relation-type">-</span> for <?= $memberData["display_name"] ?? $memberData["name"] ?></h4> - <button id="new-fronter-close" type="button" class="btn-close" data-bs-dismiss="modal"></button> - </div> - - <div class="modal-body"> - <input type="text" placeholder="Search for a pony..." class="form-control" style="margin-bottom:15px;color:white;background:#111;border-color:#222;" id="search"> - - <div id="list"> - <div class="list-group"> - <?php foreach (scoreOrderGlobal() as $member): ?> - <a id="list-pony-<?= $member['id'] ?>" onclick="confirmAdd('<?= $member['system'] ?>/<?= $member['id'] ?>');" class="new-fronter-link list-group-item list-group-item-action"><img src="<?= getAsset($member["system"], $member["id"], "heads") ?>" style="width:24px;"> <?= $member["display_name"] ?? $member["name"] ?></a> - <?php endforeach; ?> - </div> - </div> - - <div id="search-results" class="list-group"></div> - </div> - - </div> - </div> - </div> - - <script src="/assets/editor/fuse.js"></script> - <script> - window.modal = new bootstrap.Modal(document.getElementById("new-relation")); - window.currentSelectedValue = null; - - function openAddDialog(value, text) { - modal.show(); - window.currentSelectedValue = value; - document.getElementById("new-relation-type").innerText = text; - document.getElementById("search").value = ""; search({}); - document.getElementById("search").focus(); - } - - window.poniesList = JSON.parse(atob(`<?= base64_encode(json_encode(array_values(scoreOrderGlobal()))) ?>`)); - window.avatars = JSON.parse(atob(`<?php - - $avatars = []; - - foreach (scoreOrderGlobal() as $pony) { - $avatars[$pony["system"] . "/" . $pony["id"]] = getAsset($pony["system"], $pony["id"]); - } - - echo(base64_encode(json_encode($avatars))); ?>`)) - - const fuse = new Fuse(window.poniesList, { - includeScore: true, - keys: [ - { - name: 'name', - weight: 1 - }, - { - name: 'display_name', - weight: 1 - }, - { - name: 'id', - weight: 0.7 - }, - { - name: 'species', - weight: 0.5 - } - ] - }) - - function search(event) { - if (event.key === "Enter") { - return; - } - - let query = document.getElementById("search").value; - let results = fuse.search(query).map((i) => { - return { - id: i.item.id, - score: i.score - }; - }); - - let unfiltered = results; - - results = results.filter((i) => { - return i.score < 0.7; - }); - - console.log("Before:", unfiltered, "After:", results); - - document.getElementById("list").style.display = "none"; - document.getElementById("search-results").style.display = "block"; - document.getElementById("search-results").innerHTML = ""; - - for (let result of results) { - if (document.getElementById("list-pony-" + result.id)) document.getElementById("search-results").innerHTML += document.getElementById("list-pony-" + result.id).outerHTML; - } - - console.log(results); - - if (query.trim() === "") { - document.getElementById("list").style.display = "block"; - document.getElementById("search-results").style.display = "none"; - } - } - - document.getElementById("search").onchange = document.getElementById("search").onkeyup = document.getElementById("search").onkeydown = search; - - document.getElementById("search").addEventListener("keydown", (event) => { - if (event.key === "Enter") { - document.querySelector("#search-results .new-fronter-link").click(); - event.preventDefault(); - } - }); - - function update(type) { - document.getElementById(type + "-list").innerHTML = document.getElementsByName(type)[0].value.split(",").map(i => i.trim()).filter(i => i && i.trim() !== "").map(i => ` - <a style="margin-top: 4px;" class="btn btn-dark" onclick="deleteRelation('${type}', '${i}');"> - <img src="${window.avatars[i]}" style="width: 24px; vertical-align: middle; border-radius: 999px;"> - <span style="vertical-align: middle; margin-left: 5px;">${window.poniesList.filter(j => j.id === i.split("/")[1])[0]['display_name'] ?? window.poniesList.filter(j => j.id === i.split("/")[1])[0]['name']}</span> - </a> - `).join(""); - } - - function confirmAdd(item) { - document.getElementsByName(window.currentSelectedValue)[0].value += ", " + item; - update(window.currentSelectedValue); - window.currentSelectedValue = null; - modal.hide(); - } - - function deleteRelation(type, relation) { - let relations = document.getElementsByName(type)[0].value.split(",").map(i => i.trim()).filter(i => i && i !== ""); - relations = relations.filter(i => i !== relation); - document.getElementsByName(type)[0].value = relations.join(", "); - update(type); - } - </script> - - <?php foreach ([ - $systemID !== $app["other"]["id"] ? [ "sexfriends", "Sexfriends" ] : null, - [ "marefriends", "Marefriends", "marefriend" ], - [ "sisters", "Sisters", "sister" ], - [ "caretakers", "Caretakers", "caretaker" ], - [ "friends", "Friends", "friend" ], - ] as $relations): if (isset($relations)): ?> - <p> - <b><?= $relations[1] ?></b><br> - <input name="<?= $relations[0] ?>" type="hidden" value="<?= implode(", ", $metadata[$relations[0]] ?? []) ?>"> - <span id="<?= $relations[0] ?>-list"></span> - <a style="margin-top: 4px;" class="btn btn-secondary" onclick="openAddDialog('<?= $relations[0] ?>', '<?= $relations[2] ?? '' ?>')">+</a> - <script> - update('<?= $relations[0] ?>'); - </script> - </p> - <?php endif; endforeach; ?> - - <hr> - - <h3>Age and birth</h3> - - <p> - <b>Birthdate (use January 1<sup>st</sup> for none, fixed age takes priority over birth year if applicable)</b><br> - <input name="birth" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="date" value="<?= $metadata["birth"]["year"] ?? "" ?>-<?= $metadata["birth"]["date"] ?? "" ?>"> - </p> - <p> - <b>Age (for ponies with fixed age, takes priority over birth year)</b><br> - <input name="age" class="form-control" style="filter: invert(1) hue-rotate(180deg);" type="text" pattern="^(-\d{1,2}|\d{1,2}(-\d{1,2}|))$" value="<?= $metadata["birth"]["age"] ?? "" ?>"> - </p> - - <hr> - - <h3>Toggleable flags</h3> - - <?php - - $flags = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/flags.json"), true); - - foreach ($flags as $id => $name): if (!is_array($name) && !is_null($name)): if (($systemID === $app["other"]["id"] && str_starts_with($name, "!!")) || ($systemID === $app["other"]["id"] && str_starts_with($name, "#")) || ($systemID !== $app["other"]["id"] && !str_starts_with($name, "#"))): ?> - <label style="margin-bottom:5px;"> - <input <?= (isset($metadata[$id]) && $metadata[$id]) ? "checked" : "" ?> class="form-check-input" type="checkbox" name="flags[<?= $id ?>]"> - <?= str_replace("%other%", $app["other"]["name"], str_starts_with($name, "!!") ? substr($name, 2) : (str_starts_with($name, "#") ? substr($name, 1) : $name)) ?> - </label><br> - <?php endif; else: foreach ($name ?? [] as $id2 => $name2): if (!is_array($name2) && !is_null($name2)): if (($systemID === $app["other"]["id"] && str_starts_with($name2, "!!")) || ($systemID !== $app["other"]["id"] && !str_starts_with($name2, "#"))): ?> - <label style="margin-bottom:5px;"> - <input <?= $metadata[$id][$id2] ? "checked" : "" ?> class="form-check-input" type="checkbox" name="flags[<?= $id ?>][<?= $id2 ?>]"> - <?= str_replace("%other%", $app["other"]["name"], str_starts_with($name2, "!!") ? substr($name2, 2) : $name2) ?> - </label><br> - <?php endif; endif; endforeach; endif; endforeach; ?> - - <hr> - - <input name="submit" class="btn btn-outline-primary" value="Save and refresh" type="submit"> - </form> - <?php else: ?> - <div class="alert alert-warning"> - This member does not have a metadata file. This file needs to be initially created by an administrator before it can be edited using this page. - </div> - <?php endif; ?> -</div> - -<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/footer.inc'; ?>
\ No newline at end of file diff --git a/includes/init.inc b/includes/init.inc index 8773ba4..52c9ee2 100644 --- a/includes/init.inc +++ b/includes/init.inc @@ -11,27 +11,6 @@ require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/session.inc"; global $i if (in_array($toplevel, array_keys($pages))) { $title = $pages[$toplevel]["name"][$lang["_name"]]; - - if ($pages[$toplevel]["admin"]) { - $readOnly = false; - @file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/.test", "hello"); - - if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/.test")) { - unlink($_SERVER['DOCUMENT_ROOT'] . "/includes/data/.test"); - } else { - $readOnly = true; - } - - if (!isset($emergencyHeader)) { - $emergencyHeader = false; - } - - if ($pages[$toplevel]["limited"]) { - if ((!$isLoggedIn && !$isLowerLoggedIn) || ($readOnly && !$emergencyHeader)) header("Location: /-/login/?return=/-/$toplevel") and die(); - } else { - if (!$isLoggedIn || ($readOnly && !$emergencyHeader)) header("Location: /-/login/?return=/-/$toplevel") and die(); - } - } } else { $title = $toplevel; -}
\ No newline at end of file +} diff --git a/includes/jobs/FrontersNotification.php b/includes/jobs/FrontersNotification.php index 888b640..b4b8ae2 100644 --- a/includes/jobs/FrontersNotification.php +++ b/includes/jobs/FrontersNotification.php @@ -34,28 +34,6 @@ file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/$system/last.json" $ntfy = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/app.json"), true)["ntfy"]; -if (count($fronters["members"]) > 0 && ($system !== $app["other"]["id"] || !isset($app["other"]))) { - foreach ($fronters["members"] as $member) { - if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $member["id"] . ".json")) { - $metadata = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . $member["id"] . ".json"), true); - - if (!isset($metadata["birth"])) { - echo("Showing age warning\n"); - showWarning($member["display_name"] ?? $member["name"], $member["name"], $system); - } else if (isset($metadata['birth']["age"]) && $metadata["birth"]["age"] === 0 && (!isset($metadata['birth']["year"]) || $metadata["birth"]["year"] < 1900)) { - echo("Showing age warning\n"); - showWarning($member["display_name"] ?? $member["name"], $member["name"], $system); - } else if (isset($metadata['birth']["year"]) && $metadata["birth"]["year"] < 1900) { - echo("Showing age warning\n"); - showWarning($member["display_name"] ?? $member["name"], $member["name"], $system); - } else if (!isset($metadata['birth']["year"]) && !isset($metadata['birth']["age"])) { - echo("Showing age warning\n"); - showWarning($member["display_name"] ?? $member["name"], $member["name"], $system); - } - } - } -} - if (count($fronters["members"]) > 1) { echo("Creating context for 2 members\n"); $context = stream_context_create([ @@ -115,4 +93,4 @@ if ($system === "gdapd") { } echo("Sending to specific channel ($topic)\n"); -file_get_contents('https://' . $ntfy["server"] . '/' . $topic, false, $context);
\ No newline at end of file +file_get_contents('https://' . $ntfy["server"] . '/' . $topic, false, $context); diff --git a/includes/maintenance/clearUnused.php b/includes/maintenance/clearUnused.php deleted file mode 100644 index 499375b..0000000 --- a/includes/maintenance/clearUnused.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -$_SERVER['DOCUMENT_ROOT'] = "../.."; - -foreach (array_filter(scandir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata"), function ($i) { return !str_starts_with($i, "."); }) as $file) { - $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$file"), true); - echo("$file\n"); - - if (!isset($data["bitset"])) { - die(" No bitset?? wtf\n"); - } else { - $bits = str_split(substr(str_repeat("0", 48), 0, 48 - strlen(decbin($data["bitset"]))) . decbin($data["bitset"])); - echo(" Old:\n"); - echo(" " . str_replace("+", "\e[92m1\e[39m", str_replace("-", "\e[31m0\e[39m", implode("", str_replace("0", "-", str_replace("1", "+", $bits))))) . "\n"); - echo(" XX \n"); - - $bitsOld = implode("", $bits); - foreach ([27, 28] as $bit) { - $bits[$bit] = "0"; - } - - echo(" New:\n"); - echo(" " . str_replace("+", "\e[92m1\e[39m", str_replace("-", "\e[31m0\e[39m", implode("", str_replace("0", "-", str_replace("1", "+", $bits))))) . "\n"); - echo(" XX \n"); - echo(" Changed " . levenshtein($bitsOld, implode("", $bits)) . " bit(s)\n"); - - echo(" Backup made in " . substr($file, 0, -5) . "-old.json\n"); - copy($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$file", $_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/" . substr($file, 0, -5) . "-old.json"); - - $data["bitset"] = bindec(implode("", $bits)); - echo(" Saved to " . $file . "\n"); - file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$file", json_encode($data)); - } -}
\ No newline at end of file diff --git a/includes/maintenance/deleteUnusedAssets.php b/includes/maintenance/deleteUnusedAssets.php index bd7cd38..0c195a2 100644 --- a/includes/maintenance/deleteUnusedAssets.php +++ b/includes/maintenance/deleteUnusedAssets.php @@ -1,7 +1,7 @@ <?php global $action; -if (!isset($_SERVER['DOCUMENT_ROOT'])) $_SERVER['DOCUMENT_ROOT'] = "../.."; +if (!isset($_SERVER['DOCUMENT_ROOT']) || $_SERVER['DOCUMENT_ROOT'] === "") $_SERVER['DOCUMENT_ROOT'] = "../.."; if (!isset($action)) $action = "list"; if (isset($_SERVER["argv"][1])) { @@ -66,4 +66,4 @@ foreach (["heads", "bodies", "banners", "avatars"] as $t) { } } -echo($count . " file(s), leaving " . $left . " file(s), action: " . $action . "\n");
\ No newline at end of file +echo($count . " file(s), leaving " . $left . " file(s), action: " . $action . "\n"); diff --git a/includes/refresh.php b/includes/refresh.php deleted file mode 100644 index cac1fb1..0000000 --- a/includes/refresh.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php - -$_SERVER['DOCUMENT_ROOT'] = ".."; - -$app = json_decode(file_get_contents("./app.json"), true); -@mkdir("./data"); - - -$version = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/version.json"), true); - -$ignore = [ - $_SERVER['DOCUMENT_ROOT'] . "/includes/data", - $_SERVER['DOCUMENT_ROOT'] . "/includes/tokens", - $_SERVER['DOCUMENT_ROOT'] . "/app", - $_SERVER['DOCUMENT_ROOT'] . "/assets", -]; - -$documents = array_map(function ($i) { - return [ - "id" => substr($i, 0, -5), - ...(json_decode(file_get_contents("./data/docs/" . $i), true) ?? []) - ]; -}, array_filter(scandir("./data/docs"), function ($i) { - return !str_starts_with($i, ".") && str_ends_with($i, ".json"); -})); - -$deletable = array_values(array_filter($documents, function ($i) { - return str_starts_with(strip_tags($i["contents"]), "/delete"); -})); - -foreach ($deletable as $item) { - if (time() - $item["last"]["date"] > 86400) { - unlink("./data/docs/" . $item["id"] . ".json"); - } -} - -function rscandir($dir) { - global $ignore; - $files = []; - - foreach (array_filter(scandir($dir), function ($i) { - return !str_starts_with($i, "."); - }) as $file) { - if (in_array($dir . "/" . $file, $ignore)) continue; - - if (is_dir($dir . "/" . $file)) { - array_push($files, ...rscandir($dir . "/" . $file)); - } else { - $files[] = $dir . "/" . $file; - } - } - - return array_unique($files); -} - -function calculateVersionNumber() { - $files = rscandir($_SERVER['DOCUMENT_ROOT']); - $hashes = []; - - foreach ($files as $file) { - $hashes[] = md5_file($file); - } - - $hash = md5(implode("", $hashes)); - return [$hash, $hashes]; -} - -$versionHash = calculateVersionNumber(); - -if ($versionHash[0] !== $version["hash"]) { - $version["hash"] = $versionHash[0]; - $version["timestamp"] = time(); - $version["revision"] = 0; - $version["list"] = [ - "current" => $versionHash[1], - "old" => isset($version["list"]) ? $version["list"]["current"] ?? null : null - ]; - $version["build"]++; -} else { - $version["revision"]++; -} - -file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/version.json", json_encode($version)); - -if (!is_link($_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $app["other"]["id"])) { - link($_SERVER['DOCUMENT_ROOT'] . "/includes/data/other", $_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $app["other"]["id"]); -} - -echo("Backing up...\n"); - -$lastBackup = (int)trim(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.txt")); - -if (time() - $lastBackup >= 3600) { - require_once "./backup.inc"; - file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/backup.txt", time()); - echo("Backup completed\n"); -} else { - echo("Backup skipped\n"); -} - -echo("Completed.\n");
\ No newline at end of file diff --git a/includes/reminder.php b/includes/reminder.php deleted file mode 100644 index e69de29..0000000 --- a/includes/reminder.php +++ /dev/null diff --git a/includes/restore.php b/includes/restore.php deleted file mode 100644 index 72748ab..0000000 --- a/includes/restore.php +++ /dev/null @@ -1,130 +0,0 @@ -<?php - -function isJson($string): bool { - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); -} - -function pkcs7_unpad($data) { - return substr($data, 0, -ord($data[strlen($data) - 1])); -} - -function timeAgo($time): string { - if (!is_numeric($time)) { - $time = strtotime($time); - } - - $periods = ["second", "minute", "hour", "day", "week", "month", "year", "age"]; - $lengths = array("60", "60", "24", "7", "4.35", "12", "100"); - - $now = time(); - - $difference = $now - $time; - if ($difference <= 10 && $difference >= 0) { - return $tense = "now"; - } elseif ($difference > 0) { - $tense = "ago"; - } else { - $tense = "later"; - } - - for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { - $difference /= $lengths[$j]; - } - - $difference = round($difference); - - $period = $periods[$j] . ($difference >1 ? "s" :''); - return "{$difference} {$period} {$tense}"; -} - -if (!isset($_SERVER['argv'][1]) || !isset($_SERVER['argv'][2])) { - echo("Usage: php " . $_SERVER['argv'][0] . " <file> <key>\n"); - die(); -} else { - $file = @file_get_contents($_SERVER['argv'][1]); - $raw = @file_get_contents($_SERVER['argv'][2]); - - if ($file === false) { - echo("Unable to open backup file\n"); - die(); - } - - if ($raw === false) { - echo("Unable to open key file\n"); - die(); - } - - $raw2 = base64_decode($raw); - - if (!isJson($raw2)) { - echo("Key file is corrupt\n"); - die(); - } - - $keydata = json_decode($raw2, true); - - if (!is_array($keydata) || !isset($keydata["iv"]) || !isset($keydata["key"])) { - echo("Key file is invalid\n"); - die(); - } - - $iv = hex2bin($keydata["iv"]); - $key = hex2bin($keydata["key"]); - - $decrypted = openssl_decrypt($file, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); - - if ($decrypted === false) { - echo("Unable to decrypt backup\n"); - die(); - } - - $unpadded = pkcs7_unpad($decrypted); - - if (!is_string($unpadded)) { - echo("Unable to decrypt backup\n"); - die(); - } - - if (!isJson($unpadded)) { - echo("Backup is corrupt\n"); - die(); - } - - $data = json_decode($unpadded, true); - - if (!is_array($data) || !isset($data["date"]) || !isset($data["files"])) { - echo("Backup is invalid\n"); - die(); - } - - echo(realpath($_SERVER['argv'][1]) . "\n Key: " . $_SERVER['argv'][2] . "\n Date: " . date('r', strtotime($data["date"])) . " (" . timeAgo($data["date"]) . ")" . "\n Contents: " . count($data["files"]) . " files\n"); - - @mkdir("./_restored"); - - $index = 0; - foreach ($data["files"] as $file) { - if ($file["dir"] === "") { - print("[$index] /" . $file["file"] . "\n"); - } else { - print("[$index] /" . $file["dir"] . "/" . $file["file"] . "\n"); - } - - $content = base64_decode($file["content"]); - if (sha1($content) !== $file["checksum"][0]) { - print(" Backed up file is corrupted (SHA1 mismatch)\n Expected: " . $file["checksum"][0] . "\n Got: " . sha1($content) . "\n"); - die("Backup aborted.\n"); - } - if (md5($content) !== $file["checksum"][1]) { - print(" Backed up file is corrupted (MD5 mismatch)\n Expected: " . $file["checksum"][1] . "\n Got: " . md5($content) . "\n"); - die("Backup aborted.\n"); - } - - @mkdir("./_restored/" . $file["dir"], 0777, true); - file_put_contents("./_restored/" . $file["dir"] . "/" . $file["file"], $content); - - $index++; - } - - print("Restored backup to ./_restored; review files before restoring to production\n"); -}
\ No newline at end of file diff --git a/includes/system/history.inc b/includes/system/history.inc deleted file mode 100644 index ddf49bb..0000000 --- a/includes/system/history.inc +++ /dev/null @@ -1,174 +0,0 @@ -<?php global $system; global $lang; global $pages; global $systemCommonName; $pages = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/pages.json"), true); $title = $pages["s:history"]["name"][$lang["_name"]] . " · " . $systemCommonName; global $systemID; global $app; require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/header.inc'; global $isLoggedIn; global $isLowerLoggedIn; - -function frenchIfRequired($original) { - return $original; -} - -function getSwitchesForDay(int $day) { - global $switches; - - $filtered = array_values(array_filter($switches, function ($i) use ($day) { - $diff = strtotime(date("Y-m-d")) - strtotime(explode("T", $i["timestamp"])[0]); - return $diff <= (86400 * $day) && $diff > (86400 * ($day - 1)); - })); - - uksort($filtered, function ($a, $b) { - if (isset($b["timestamp"]) && isset($a["timestamp"])) { - return strtotime($b["timestamp"]) - strtotime($a["timestamp"]); - } else { - return null; - } - }); - - return $filtered; -} - -function getSwitchBefore(string $id) { - global $switches; - - $currentPassed = false; - $before = null; - - foreach ($switches as $switch) { - if ($currentPassed) { - $before = $switch; - break; - } else { - if ($switch["id"] === $id) { - $currentPassed = true; - } - } - } - - return $before; -} - -function isNotToday(int $timestamp, int $offset) { - if (date('Y-m-d', $timestamp) !== date('Y-m-d', time() - (86400 * $offset))) { - return true; - } else { - return false; - } -} - -if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/history.json")) file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/history.json", "{}"); - -$cache = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/history.json"), true); - -function page() { global $lang; global $systemCommonName; global $systemID; global $app; global $switches; global $isLoggedIn; global $isLowerLoggedIn; ?> - <br> - <div class="container" id="page-content"> - <?php - - $switches = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/$systemID/switches.json"), true); - - uksort($switches, function ($a, $b) { - if (isset($b["timestamp"]) && isset($a["timestamp"])) { - return strtotime($b["timestamp"]) - strtotime($a["timestamp"]); - } else { - return null; - } - }); - - ?> - <h2><?= $systemID === $app["other"]["id"] ? "Front history in " . $app["other"]["name"] : $lang["history"]["title"] . " " . $systemCommonName ?></h2> - <div class="alert alert-warning" id="timezone" style="display: none;"> - <?= str_replace("%1", '<span id="timezone-name">-</span>', str_replace("%2", '<span id="day-start">-</span>', $lang["history"]["timezone"])) ?> - <script> - document.getElementById("day-start").innerText = new Date(<?= strtotime(date('Y-m-d')) ?> * 1000).toTimeString().substring(0, 5); - document.getElementById("timezone-name").innerText = new Date().toTimeString().split("(")[1].split(")")[0]; - </script> - </div> - <?php foreach ([ - [ "Today", 0 ], - [ "Yesterday", 1 ], - [ date('D j M', time() - (86400 * 2)), 2 ], - [ date('D j M', time() - (86400 * 3)), 3 ], - [ date('D j M', time() - (86400 * 4)), 4 ], - [ date('D j M', time() - (86400 * 5)), 5 ], - [ date('D j M', time() - (86400 * 6)), 6 ], - [ date('D j M', time() - (86400 * 7)), 7 ], - [ date('D j M', time() - (86400 * 8)), 8 ], - [ date('D j M', time() - (86400 * 9)), 9 ], - ] as $day): - $switchesDay = getSwitchesForDay($day[1]); - if (isset($switchesDay[count($switchesDay) - 1])) { - $switchesDay[] = getSwitchBefore($switchesDay[count($switchesDay) - 1]["id"]); - } - ?> - <h4 style="margin-top:15px;"><?= frenchIfRequired($day[0]) ?></h4> - <?php if (count($switchesDay) === 0): ?> - <p class="text-muted">No switches happened on that day</p> - <?php endif; ?> - <?php foreach ($switchesDay as $switch): $switch["timestamp"] = strtotime($switch["timestamp"]); ?> - <?php if (isset($switch["members"][0])): $member = getMemberWithoutSystem($switch["members"][0]); ?> - <div class="fronter"> - <span class="fronter-date" data-date-time="<?= isNotToday($switch["timestamp"], $day[1]) ? strtotime(date('Y-m-d', $switch["timestamp"])) : $switch["timestamp"] ?>" style="opacity:.5;font-family: monospace;font-size:14px;vertical-align: middle;"> - <?= isNotToday($switch["timestamp"], $day[1]) ? "00:00" : date('H:i', $switch["timestamp"]) ?> - </span> - <span class="fronter-profile" style="vertical-align: middle;"> - <a class="member-link" href="/<?= (isset($member) && $member["name"] === "unknown") ? ($systemID === "gdapd" ? "unknown-rd" : $app["other"]["unknown"]) : $member["name"] ?>"> - <img src="<?= getAsset($systemID, $member["id"], "heads") ?>" style="width:24px;"> <?= $member["display_name"] ?? $member["name"] ?> - </a> - <?php if (count($switch["members"]) > 1): ?> - and - <?php if (isset($switch["members"][1])): $member2 = getMember($switch["members"][1]); ?><a class="member-link" href="/<?= $member2["name"] ?>"><img src="<?= getAsset($systemID, $member2["id"], "heads") ?>" style="width:24px;"> <?= $member2["display_name"] ?? $member2["name"] ?></a><?php endif; ?><?php if (isset($switch["members"][2])): $member2 = getMember($switch["members"][2]); ?>, <a class="member-link" href="/<?= $member2["name"] ?>"><img src="<?= getAsset($systemID, $member2["id"], "heads") ?>" style="width:24px;"> <?= $member2["display_name"] ?? $member2["name"] ?></a><?php endif; ?><?php if (isset($switch["members"][3])): $member2 = getMember($switch["members"][3]); ?>, <a class="member-link" href="/<?= $member2["name"] ?>"><img src="<?= getAsset($systemID, $member2["id"], "heads") ?>" style="width:24px;"> <?= $member2["display_name"] ?? $member2["name"] ?></a><?php endif; ?> - <?php endif; ?> - </span> - </div> - <?php else: ?> - <div class="fronter"> - <span class="fronter-date" data-date-time="<?= isNotToday($switch["timestamp"], $day[1]) ? strtotime(date('Y-m-d', $switch["timestamp"])) : $switch["timestamp"] ?>" style="opacity:.5;font-family: monospace;font-size:14px;vertical-align: middle;"> - <?= isNotToday($switch["timestamp"], $day[1]) ? "00:00" : date('H:i', $switch["timestamp"]) ?> - </span> - <span class="fronter-profile" style="vertical-align: middle;"> - <span class="text-muted"><?= $lang["history"]["fallback"] ?></span> - </span> - </div> - <?php endif; ?> - <?php endforeach; ?> - <?php endforeach; ?> - </div> - <script> - Array.from(document.getElementsByClassName("fronter-date")).forEach((i) => { i.innerText = new Date(parseInt(i.getAttribute("data-date-time").trim()) * 1000).toTimeString().split(" ")[0].substring(0, 5) + " " }); - document.getElementById("timezone").style.display = ""; - </script> -<?php } - -?> - -<?php - -if (!isset($cache[$systemID])) $cache[$systemID] = []; - -if (!isset($cache[$systemID]["private"]) || !isset($cache[$systemID]["public"])) { - ob_start(); - $isLoggedInOldState = $isLoggedIn; - $isLowerLoggedInOldState = $isLowerLoggedIn; - $isLoggedIn = true; - $isLowerLoggedIn = true; - page(); - $isLoggedIn = $isLoggedInOldState; - $isLowerLoggedIn = $isLowerLoggedInOldState; - $cache[$systemID]["private"] = ob_get_contents(); - ob_end_clean(); - - if ($systemID !== $app["other"]["id"]) { - ob_start(); - $isLoggedInOldState = $isLoggedIn; - $isLowerLoggedInOldState = $isLowerLoggedIn; - $isLoggedIn = false; - $isLowerLoggedIn = false; - page(); - $isLoggedIn = $isLoggedInOldState; - $isLowerLoggedIn = $isLowerLoggedInOldState; - $cache[$systemID]["public"] = ob_get_contents(); - ob_end_clean(); - } else { - $cache[$systemID]["public"] = ""; - } -} - -echo($isLoggedIn ? $cache[$systemID]["private"] : $cache[$systemID]["public"]); file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/cache/history.json", json_encode($cache)); ?> - -<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/components/footer.inc'; ?>
\ No newline at end of file diff --git a/includes/util/Parsedown.php b/includes/util/Parsedown.php deleted file mode 100644 index 3e29589..0000000 --- a/includes/util/Parsedown.php +++ /dev/null @@ -1,1994 +0,0 @@ -<?php - -# -# -# Parsedown -# http://parsedown.org -# -# (c) Emanuil Rusev -# http://erusev.com -# -# For the full license information, view the LICENSE file that was distributed -# with this source code. -# -# - -class Parsedown -{ - # ~ - - const version = '1.8.0-beta-7'; - - # ~ - - function text($text) - { - $Elements = $this->textElements($text); - - # convert to markup - $markup = $this->elements($Elements); - - # trim line breaks - $markup = trim($markup, "\n"); - - return $markup; - } - - protected function textElements($text) - { - # make sure no definitions are set - $this->DefinitionData = array(); - - # standardize line breaks - $text = str_replace(array("\r\n", "\r"), "\n", $text); - - # remove surrounding line breaks - $text = trim($text, "\n"); - - # split text into lines - $lines = explode("\n", $text); - - # iterate through lines to identify blocks - return $this->linesElements($lines); - } - - # - # Setters - # - - function setBreaksEnabled($breaksEnabled) - { - $this->breaksEnabled = $breaksEnabled; - - return $this; - } - - protected $breaksEnabled; - - function setMarkupEscaped($markupEscaped) - { - $this->markupEscaped = $markupEscaped; - - return $this; - } - - protected $markupEscaped; - - function setUrlsLinked($urlsLinked) - { - $this->urlsLinked = $urlsLinked; - - return $this; - } - - protected $urlsLinked = true; - - function setSafeMode($safeMode) - { - $this->safeMode = (bool) $safeMode; - - return $this; - } - - protected $safeMode; - - function setStrictMode($strictMode) - { - $this->strictMode = (bool) $strictMode; - - return $this; - } - - protected $strictMode; - - protected $safeLinksWhitelist = array( - 'http://', - 'https://', - 'ftp://', - 'ftps://', - 'mailto:', - 'tel:', - 'data:image/png;base64,', - 'data:image/gif;base64,', - 'data:image/jpeg;base64,', - 'irc:', - 'ircs:', - 'git:', - 'ssh:', - 'news:', - 'steam:', - ); - - # - # Lines - # - - protected $BlockTypes = array( - '#' => array('Header'), - '*' => array('Rule', 'List'), - '+' => array('List'), - '-' => array('SetextHeader', 'Table', 'Rule', 'List'), - '0' => array('List'), - '1' => array('List'), - '2' => array('List'), - '3' => array('List'), - '4' => array('List'), - '5' => array('List'), - '6' => array('List'), - '7' => array('List'), - '8' => array('List'), - '9' => array('List'), - ':' => array('Table'), - '<' => array('Comment', 'Markup'), - '=' => array('SetextHeader'), - '>' => array('Quote'), - '[' => array('Reference'), - '_' => array('Rule'), - '`' => array('FencedCode'), - '|' => array('Table'), - '~' => array('FencedCode'), - ); - - # ~ - - protected $unmarkedBlockTypes = array( - 'Code', - ); - - # - # Blocks - # - - protected function lines(array $lines) - { - return $this->elements($this->linesElements($lines)); - } - - protected function linesElements(array $lines) - { - $Elements = array(); - $CurrentBlock = null; - - foreach ($lines as $line) - { - if (chop($line) === '') - { - if (isset($CurrentBlock)) - { - $CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted']) - ? $CurrentBlock['interrupted'] + 1 : 1 - ); - } - - continue; - } - - while (($beforeTab = strstr($line, "\t", true)) !== false) - { - $shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4; - - $line = $beforeTab - . str_repeat(' ', $shortage) - . substr($line, strlen($beforeTab) + 1) - ; - } - - $indent = strspn($line, ' '); - - $text = $indent > 0 ? substr($line, $indent) : $line; - - # ~ - - $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); - - # ~ - - if (isset($CurrentBlock['continuable'])) - { - $methodName = 'block' . $CurrentBlock['type'] . 'Continue'; - $Block = $this->$methodName($Line, $CurrentBlock); - - if (isset($Block)) - { - $CurrentBlock = $Block; - - continue; - } - else - { - if ($this->isBlockCompletable($CurrentBlock['type'])) - { - $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; - $CurrentBlock = $this->$methodName($CurrentBlock); - } - } - } - - # ~ - - $marker = $text[0]; - - # ~ - - $blockTypes = $this->unmarkedBlockTypes; - - if (isset($this->BlockTypes[$marker])) - { - foreach ($this->BlockTypes[$marker] as $blockType) - { - $blockTypes []= $blockType; - } - } - - # - # ~ - - foreach ($blockTypes as $blockType) - { - $Block = $this->{"block$blockType"}($Line, $CurrentBlock); - - if (isset($Block)) - { - $Block['type'] = $blockType; - - if ( ! isset($Block['identified'])) - { - if (isset($CurrentBlock)) - { - $Elements[] = $this->extractElement($CurrentBlock); - } - - $Block['identified'] = true; - } - - if ($this->isBlockContinuable($blockType)) - { - $Block['continuable'] = true; - } - - $CurrentBlock = $Block; - - continue 2; - } - } - - # ~ - - if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph') - { - $Block = $this->paragraphContinue($Line, $CurrentBlock); - } - - if (isset($Block)) - { - $CurrentBlock = $Block; - } - else - { - if (isset($CurrentBlock)) - { - $Elements[] = $this->extractElement($CurrentBlock); - } - - $CurrentBlock = $this->paragraph($Line); - - $CurrentBlock['identified'] = true; - } - } - - # ~ - - if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) - { - $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; - $CurrentBlock = $this->$methodName($CurrentBlock); - } - - # ~ - - if (isset($CurrentBlock)) - { - $Elements[] = $this->extractElement($CurrentBlock); - } - - # ~ - - return $Elements; - } - - protected function extractElement(array $Component) - { - if ( ! isset($Component['element'])) - { - if (isset($Component['markup'])) - { - $Component['element'] = array('rawHtml' => $Component['markup']); - } - elseif (isset($Component['hidden'])) - { - $Component['element'] = array(); - } - } - - return $Component['element']; - } - - protected function isBlockContinuable($Type) - { - return method_exists($this, 'block' . $Type . 'Continue'); - } - - protected function isBlockCompletable($Type) - { - return method_exists($this, 'block' . $Type . 'Complete'); - } - - # - # Code - - protected function blockCode($Line, $Block = null) - { - if (isset($Block) and $Block['type'] === 'Paragraph' and ! isset($Block['interrupted'])) - { - return; - } - - if ($Line['indent'] >= 4) - { - $text = substr($Line['body'], 4); - - $Block = array( - 'element' => array( - 'name' => 'pre', - 'element' => array( - 'name' => 'code', - 'text' => $text, - ), - ), - ); - - return $Block; - } - } - - protected function blockCodeContinue($Line, $Block) - { - if ($Line['indent'] >= 4) - { - if (isset($Block['interrupted'])) - { - $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); - - unset($Block['interrupted']); - } - - $Block['element']['element']['text'] .= "\n"; - - $text = substr($Line['body'], 4); - - $Block['element']['element']['text'] .= $text; - - return $Block; - } - } - - protected function blockCodeComplete($Block) - { - return $Block; - } - - # - # Comment - - protected function blockComment($Line) - { - if ($this->markupEscaped or $this->safeMode) - { - return; - } - - if (strpos($Line['text'], '<!--') === 0) - { - $Block = array( - 'element' => array( - 'rawHtml' => $Line['body'], - 'autobreak' => true, - ), - ); - - if (strpos($Line['text'], '-->') !== false) - { - $Block['closed'] = true; - } - - return $Block; - } - } - - protected function blockCommentContinue($Line, array $Block) - { - if (isset($Block['closed'])) - { - return; - } - - $Block['element']['rawHtml'] .= "\n" . $Line['body']; - - if (strpos($Line['text'], '-->') !== false) - { - $Block['closed'] = true; - } - - return $Block; - } - - # - # Fenced Code - - protected function blockFencedCode($Line) - { - $marker = $Line['text'][0]; - - $openerLength = strspn($Line['text'], $marker); - - if ($openerLength < 3) - { - return; - } - - $infostring = trim(substr($Line['text'], $openerLength), "\t "); - - if (strpos($infostring, '`') !== false) - { - return; - } - - $Element = array( - 'name' => 'code', - 'text' => '', - ); - - if ($infostring !== '') - { - /** - * https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * Every HTML element may have a class attribute specified. - * The attribute, if specified, must have a value that is a set - * of space-separated tokens representing the various classes - * that the element belongs to. - * [...] - * The space characters, for the purposes of this specification, - * are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), - * U+000A LINE FEED (LF), U+000C FORM FEED (FF), and - * U+000D CARRIAGE RETURN (CR). - */ - $language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r")); - - $Element['attributes'] = array('class' => "language-$language"); - } - - $Block = array( - 'char' => $marker, - 'openerLength' => $openerLength, - 'element' => array( - 'name' => 'pre', - 'element' => $Element, - ), - ); - - return $Block; - } - - protected function blockFencedCodeContinue($Line, $Block) - { - if (isset($Block['complete'])) - { - return; - } - - if (isset($Block['interrupted'])) - { - $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); - - unset($Block['interrupted']); - } - - if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength'] - and chop(substr($Line['text'], $len), ' ') === '' - ) { - $Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1); - - $Block['complete'] = true; - - return $Block; - } - - $Block['element']['element']['text'] .= "\n" . $Line['body']; - - return $Block; - } - - protected function blockFencedCodeComplete($Block) - { - return $Block; - } - - # - # Header - - protected function blockHeader($Line) - { - $level = strspn($Line['text'], '#'); - - if ($level > 6) - { - return; - } - - $text = trim($Line['text'], '#'); - - if ($this->strictMode and isset($text[0]) and $text[0] !== ' ') - { - return; - } - - $text = trim($text, ' '); - - $Block = array( - 'element' => array( - 'name' => 'h' . $level, - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $text, - 'destination' => 'elements', - ) - ), - ); - - return $Block; - } - - # - # List - - protected function blockList($Line, array $CurrentBlock = null) - { - list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]'); - - if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches)) - { - $contentIndent = strlen($matches[2]); - - if ($contentIndent >= 5) - { - $contentIndent -= 1; - $matches[1] = substr($matches[1], 0, -$contentIndent); - $matches[3] = str_repeat(' ', $contentIndent) . $matches[3]; - } - elseif ($contentIndent === 0) - { - $matches[1] .= ' '; - } - - $markerWithoutWhitespace = strstr($matches[1], ' ', true); - - $Block = array( - 'indent' => $Line['indent'], - 'pattern' => $pattern, - 'data' => array( - 'type' => $name, - 'marker' => $matches[1], - 'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1)), - ), - 'element' => array( - 'name' => $name, - 'elements' => array(), - ), - ); - $Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/'); - - if ($name === 'ol') - { - $listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0'; - - if ($listStart !== '1') - { - if ( - isset($CurrentBlock) - and $CurrentBlock['type'] === 'Paragraph' - and ! isset($CurrentBlock['interrupted']) - ) { - return; - } - - $Block['element']['attributes'] = array('start' => $listStart); - } - } - - $Block['li'] = array( - 'name' => 'li', - 'handler' => array( - 'function' => 'li', - 'argument' => !empty($matches[3]) ? array($matches[3]) : array(), - 'destination' => 'elements' - ) - ); - - $Block['element']['elements'] []= & $Block['li']; - - return $Block; - } - } - - protected function blockListContinue($Line, array $Block) - { - if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument'])) - { - return null; - } - - $requiredIndent = ($Block['indent'] + strlen($Block['data']['marker'])); - - if ($Line['indent'] < $requiredIndent - and ( - ( - $Block['data']['type'] === 'ol' - and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) - ) or ( - $Block['data']['type'] === 'ul' - and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) - ) - ) - ) { - if (isset($Block['interrupted'])) - { - $Block['li']['handler']['argument'] []= ''; - - $Block['loose'] = true; - - unset($Block['interrupted']); - } - - unset($Block['li']); - - $text = isset($matches[1]) ? $matches[1] : ''; - - $Block['indent'] = $Line['indent']; - - $Block['li'] = array( - 'name' => 'li', - 'handler' => array( - 'function' => 'li', - 'argument' => array($text), - 'destination' => 'elements' - ) - ); - - $Block['element']['elements'] []= & $Block['li']; - - return $Block; - } - elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line)) - { - return null; - } - - if ($Line['text'][0] === '[' and $this->blockReference($Line)) - { - return $Block; - } - - if ($Line['indent'] >= $requiredIndent) - { - if (isset($Block['interrupted'])) - { - $Block['li']['handler']['argument'] []= ''; - - $Block['loose'] = true; - - unset($Block['interrupted']); - } - - $text = substr($Line['body'], $requiredIndent); - - $Block['li']['handler']['argument'] []= $text; - - return $Block; - } - - if ( ! isset($Block['interrupted'])) - { - $text = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']); - - $Block['li']['handler']['argument'] []= $text; - - return $Block; - } - } - - protected function blockListComplete(array $Block) - { - if (isset($Block['loose'])) - { - foreach ($Block['element']['elements'] as &$li) - { - if (end($li['handler']['argument']) !== '') - { - $li['handler']['argument'] []= ''; - } - } - } - - return $Block; - } - - # - # Quote - - protected function blockQuote($Line) - { - if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) - { - $Block = array( - 'element' => array( - 'name' => 'blockquote', - 'handler' => array( - 'function' => 'linesElements', - 'argument' => (array) $matches[1], - 'destination' => 'elements', - ) - ), - ); - - return $Block; - } - } - - protected function blockQuoteContinue($Line, array $Block) - { - if (isset($Block['interrupted'])) - { - return; - } - - if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) - { - $Block['element']['handler']['argument'] []= $matches[1]; - - return $Block; - } - - if ( ! isset($Block['interrupted'])) - { - $Block['element']['handler']['argument'] []= $Line['text']; - - return $Block; - } - } - - # - # Rule - - protected function blockRule($Line) - { - $marker = $Line['text'][0]; - - if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '') - { - $Block = array( - 'element' => array( - 'name' => 'hr', - ), - ); - - return $Block; - } - } - - # - # Setext - - protected function blockSetextHeader($Line, array $Block = null) - { - if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) - { - return; - } - - if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '') - { - $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; - - return $Block; - } - } - - # - # Markup - - protected function blockMarkup($Line) - { - if ($this->markupEscaped or $this->safeMode) - { - return; - } - - if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches)) - { - $element = strtolower($matches[1]); - - if (in_array($element, $this->textLevelElements)) - { - return; - } - - $Block = array( - 'name' => $matches[1], - 'element' => array( - 'rawHtml' => $Line['text'], - 'autobreak' => true, - ), - ); - - return $Block; - } - } - - protected function blockMarkupContinue($Line, array $Block) - { - if (isset($Block['closed']) or isset($Block['interrupted'])) - { - return; - } - - $Block['element']['rawHtml'] .= "\n" . $Line['body']; - - return $Block; - } - - # - # Reference - - protected function blockReference($Line) - { - if (strpos($Line['text'], ']') !== false - and preg_match('/^\[(.+?)\]:[ ]*+<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches) - ) { - $id = strtolower($matches[1]); - - $Data = array( - 'url' => $matches[2], - 'title' => isset($matches[3]) ? $matches[3] : null, - ); - - $this->DefinitionData['Reference'][$id] = $Data; - - $Block = array( - 'element' => array(), - ); - - return $Block; - } - } - - # - # Table - - protected function blockTable($Line, array $Block = null) - { - if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) - { - return; - } - - if ( - strpos($Block['element']['handler']['argument'], '|') === false - and strpos($Line['text'], '|') === false - and strpos($Line['text'], ':') === false - or strpos($Block['element']['handler']['argument'], "\n") !== false - ) { - return; - } - - if (chop($Line['text'], ' -:|') !== '') - { - return; - } - - $alignments = array(); - - $divider = $Line['text']; - - $divider = trim($divider); - $divider = trim($divider, '|'); - - $dividerCells = explode('|', $divider); - - foreach ($dividerCells as $dividerCell) - { - $dividerCell = trim($dividerCell); - - if ($dividerCell === '') - { - return; - } - - $alignment = null; - - if ($dividerCell[0] === ':') - { - $alignment = 'left'; - } - - if (substr($dividerCell, - 1) === ':') - { - $alignment = $alignment === 'left' ? 'center' : 'right'; - } - - $alignments []= $alignment; - } - - # ~ - - $HeaderElements = array(); - - $header = $Block['element']['handler']['argument']; - - $header = trim($header); - $header = trim($header, '|'); - - $headerCells = explode('|', $header); - - if (count($headerCells) !== count($alignments)) - { - return; - } - - foreach ($headerCells as $index => $headerCell) - { - $headerCell = trim($headerCell); - - $HeaderElement = array( - 'name' => 'th', - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $headerCell, - 'destination' => 'elements', - ) - ); - - if (isset($alignments[$index])) - { - $alignment = $alignments[$index]; - - $HeaderElement['attributes'] = array( - 'style' => "text-align: $alignment;", - ); - } - - $HeaderElements []= $HeaderElement; - } - - # ~ - - $Block = array( - 'alignments' => $alignments, - 'identified' => true, - 'element' => array( - 'name' => 'table', - 'elements' => array(), - ), - ); - - $Block['element']['elements'] []= array( - 'name' => 'thead', - ); - - $Block['element']['elements'] []= array( - 'name' => 'tbody', - 'elements' => array(), - ); - - $Block['element']['elements'][0]['elements'] []= array( - 'name' => 'tr', - 'elements' => $HeaderElements, - ); - - return $Block; - } - - protected function blockTableContinue($Line, array $Block) - { - if (isset($Block['interrupted'])) - { - return; - } - - if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|')) - { - $Elements = array(); - - $row = $Line['text']; - - $row = trim($row); - $row = trim($row, '|'); - - preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches); - - $cells = array_slice($matches[0], 0, count($Block['alignments'])); - - foreach ($cells as $index => $cell) - { - $cell = trim($cell); - - $Element = array( - 'name' => 'td', - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $cell, - 'destination' => 'elements', - ) - ); - - if (isset($Block['alignments'][$index])) - { - $Element['attributes'] = array( - 'style' => 'text-align: ' . $Block['alignments'][$index] . ';', - ); - } - - $Elements []= $Element; - } - - $Element = array( - 'name' => 'tr', - 'elements' => $Elements, - ); - - $Block['element']['elements'][1]['elements'] []= $Element; - - return $Block; - } - } - - # - # ~ - # - - protected function paragraph($Line) - { - return array( - 'type' => 'Paragraph', - 'element' => array( - 'name' => 'p', - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $Line['text'], - 'destination' => 'elements', - ), - ), - ); - } - - protected function paragraphContinue($Line, array $Block) - { - if (isset($Block['interrupted'])) - { - return; - } - - $Block['element']['handler']['argument'] .= "\n".$Line['text']; - - return $Block; - } - - # - # Inline Elements - # - - protected $InlineTypes = array( - '!' => array('Image'), - '&' => array('SpecialCharacter'), - '*' => array('Emphasis'), - ':' => array('Url'), - '<' => array('UrlTag', 'EmailTag', 'Markup'), - '[' => array('Link'), - '_' => array('Emphasis'), - '`' => array('Code'), - '~' => array('Strikethrough'), - '\\' => array('EscapeSequence'), - ); - - # ~ - - protected $inlineMarkerList = '!*_&[:<`~\\'; - - # - # ~ - # - - public function line($text, $nonNestables = array()) - { - return $this->elements($this->lineElements($text, $nonNestables)); - } - - protected function lineElements($text, $nonNestables = array()) - { - # standardize line breaks - $text = str_replace(array("\r\n", "\r"), "\n", $text); - - $Elements = array(); - - $nonNestables = (empty($nonNestables) - ? array() - : array_combine($nonNestables, $nonNestables) - ); - - # $excerpt is based on the first occurrence of a marker - - while ($excerpt = strpbrk($text, $this->inlineMarkerList)) - { - $marker = $excerpt[0]; - - $markerPosition = strlen($text) - strlen($excerpt); - - $Excerpt = array('text' => $excerpt, 'context' => $text); - - foreach ($this->InlineTypes[$marker] as $inlineType) - { - # check to see if the current inline type is nestable in the current context - - if (isset($nonNestables[$inlineType])) - { - continue; - } - - $Inline = $this->{"inline$inlineType"}($Excerpt); - - if ( ! isset($Inline)) - { - continue; - } - - # makes sure that the inline belongs to "our" marker - - if (isset($Inline['position']) and $Inline['position'] > $markerPosition) - { - continue; - } - - # sets a default inline position - - if ( ! isset($Inline['position'])) - { - $Inline['position'] = $markerPosition; - } - - # cause the new element to 'inherit' our non nestables - - - $Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables']) - ? array_merge($Inline['element']['nonNestables'], $nonNestables) - : $nonNestables - ; - - # the text that comes before the inline - $unmarkedText = substr($text, 0, $Inline['position']); - - # compile the unmarked text - $InlineText = $this->inlineText($unmarkedText); - $Elements[] = $InlineText['element']; - - # compile the inline - $Elements[] = $this->extractElement($Inline); - - # remove the examined text - $text = substr($text, $Inline['position'] + $Inline['extent']); - - continue 2; - } - - # the marker does not belong to an inline - - $unmarkedText = substr($text, 0, $markerPosition + 1); - - $InlineText = $this->inlineText($unmarkedText); - $Elements[] = $InlineText['element']; - - $text = substr($text, $markerPosition + 1); - } - - $InlineText = $this->inlineText($text); - $Elements[] = $InlineText['element']; - - foreach ($Elements as &$Element) - { - if ( ! isset($Element['autobreak'])) - { - $Element['autobreak'] = false; - } - } - - return $Elements; - } - - # - # ~ - # - - protected function inlineText($text) - { - $Inline = array( - 'extent' => strlen($text), - 'element' => array(), - ); - - $Inline['element']['elements'] = self::pregReplaceElements( - $this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/', - array( - array('name' => 'br'), - array('text' => "\n"), - ), - $text - ); - - return $Inline; - } - - protected function inlineCode($Excerpt) - { - $marker = $Excerpt['text'][0]; - - if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(?<!['.$marker.'])\1(?!'.$marker.')/s', $Excerpt['text'], $matches)) - { - $text = $matches[2]; - $text = preg_replace('/[ ]*+\n/', ' ', $text); - - return array( - 'extent' => strlen($matches[0]), - 'element' => array( - 'name' => 'code', - 'text' => $text, - ), - ); - } - } - - protected function inlineEmailTag($Excerpt) - { - $hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'; - - $commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@' - . $hostnameLabel . '(?:\.' . $hostnameLabel . ')*'; - - if (strpos($Excerpt['text'], '>') !== false - and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches) - ){ - $url = $matches[1]; - - if ( ! isset($matches[2])) - { - $url = "mailto:$url"; - } - - return array( - 'extent' => strlen($matches[0]), - 'element' => array( - 'name' => 'a', - 'text' => $matches[1], - 'attributes' => array( - 'href' => $url, - ), - ), - ); - } - } - - protected function inlineEmphasis($Excerpt) - { - if ( ! isset($Excerpt['text'][1])) - { - return; - } - - $marker = $Excerpt['text'][0]; - - if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) - { - $emphasis = 'strong'; - } - elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) - { - $emphasis = 'em'; - } - else - { - return; - } - - return array( - 'extent' => strlen($matches[0]), - 'element' => array( - 'name' => $emphasis, - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $matches[1], - 'destination' => 'elements', - ) - ), - ); - } - - protected function inlineEscapeSequence($Excerpt) - { - if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) - { - return array( - 'element' => array('rawHtml' => $Excerpt['text'][1]), - 'extent' => 2, - ); - } - } - - protected function inlineImage($Excerpt) - { - if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') - { - return; - } - - $Excerpt['text']= substr($Excerpt['text'], 1); - - $Link = $this->inlineLink($Excerpt); - - if ($Link === null) - { - return; - } - - $Inline = array( - 'extent' => $Link['extent'] + 1, - 'element' => array( - 'name' => 'img', - 'attributes' => array( - 'src' => $Link['element']['attributes']['href'], - 'alt' => $Link['element']['handler']['argument'], - ), - 'autobreak' => true, - ), - ); - - $Inline['element']['attributes'] += $Link['element']['attributes']; - - unset($Inline['element']['attributes']['href']); - - return $Inline; - } - - protected function inlineLink($Excerpt) - { - $Element = array( - 'name' => 'a', - 'handler' => array( - 'function' => 'lineElements', - 'argument' => null, - 'destination' => 'elements', - ), - 'nonNestables' => array('Url', 'Link'), - 'attributes' => array( - 'href' => null, - 'title' => null, - ), - ); - - $extent = 0; - - $remainder = $Excerpt['text']; - - if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) - { - $Element['handler']['argument'] = $matches[1]; - - $extent += strlen($matches[0]); - - $remainder = substr($remainder, $extent); - } - else - { - return; - } - - if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*+"|\'[^\']*+\'))?\s*+[)]/', $remainder, $matches)) - { - $Element['attributes']['href'] = $matches[1]; - - if (isset($matches[2])) - { - $Element['attributes']['title'] = substr($matches[2], 1, - 1); - } - - $extent += strlen($matches[0]); - } - else - { - if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) - { - $definition = strlen($matches[1]) ? $matches[1] : $Element['handler']['argument']; - $definition = strtolower($definition); - - $extent += strlen($matches[0]); - } - else - { - $definition = strtolower($Element['handler']['argument']); - } - - if ( ! isset($this->DefinitionData['Reference'][$definition])) - { - return; - } - - $Definition = $this->DefinitionData['Reference'][$definition]; - - $Element['attributes']['href'] = $Definition['url']; - $Element['attributes']['title'] = $Definition['title']; - } - - return array( - 'extent' => $extent, - 'element' => $Element, - ); - } - - protected function inlineMarkup($Excerpt) - { - if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false) - { - return; - } - - if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches)) - { - return array( - 'element' => array('rawHtml' => $matches[0]), - 'extent' => strlen($matches[0]), - ); - } - - if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?+[^-])*-->/s', $Excerpt['text'], $matches)) - { - return array( - 'element' => array('rawHtml' => $matches[0]), - 'extent' => strlen($matches[0]), - ); - } - - if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w[\w-]*+(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+\/?>/s', $Excerpt['text'], $matches)) - { - return array( - 'element' => array('rawHtml' => $matches[0]), - 'extent' => strlen($matches[0]), - ); - } - } - - protected function inlineSpecialCharacter($Excerpt) - { - if (substr($Excerpt['text'], 1, 1) !== ' ' and strpos($Excerpt['text'], ';') !== false - and preg_match('/^&(#?+[0-9a-zA-Z]++);/', $Excerpt['text'], $matches) - ) { - return array( - 'element' => array('rawHtml' => '&' . $matches[1] . ';'), - 'extent' => strlen($matches[0]), - ); - } - - return; - } - - protected function inlineStrikethrough($Excerpt) - { - if ( ! isset($Excerpt['text'][1])) - { - return; - } - - if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) - { - return array( - 'extent' => strlen($matches[0]), - 'element' => array( - 'name' => 'del', - 'handler' => array( - 'function' => 'lineElements', - 'argument' => $matches[1], - 'destination' => 'elements', - ) - ), - ); - } - } - - protected function inlineUrl($Excerpt) - { - if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') - { - return; - } - - if (strpos($Excerpt['context'], 'http') !== false - and preg_match('/\bhttps?+:[\/]{2}[^\s<]+\b\/*+/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE) - ) { - $url = $matches[0][0]; - - $Inline = array( - 'extent' => strlen($matches[0][0]), - 'position' => $matches[0][1], - 'element' => array( - 'name' => 'a', - 'text' => $url, - 'attributes' => array( - 'href' => $url, - ), - ), - ); - - return $Inline; - } - } - - protected function inlineUrlTag($Excerpt) - { - if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w++:\/{2}[^ >]++)>/i', $Excerpt['text'], $matches)) - { - $url = $matches[1]; - - return array( - 'extent' => strlen($matches[0]), - 'element' => array( - 'name' => 'a', - 'text' => $url, - 'attributes' => array( - 'href' => $url, - ), - ), - ); - } - } - - # ~ - - protected function unmarkedText($text) - { - $Inline = $this->inlineText($text); - return $this->element($Inline['element']); - } - - # - # Handlers - # - - protected function handle(array $Element) - { - if (isset($Element['handler'])) - { - if (!isset($Element['nonNestables'])) - { - $Element['nonNestables'] = array(); - } - - if (is_string($Element['handler'])) - { - $function = $Element['handler']; - $argument = $Element['text']; - unset($Element['text']); - $destination = 'rawHtml'; - } - else - { - $function = $Element['handler']['function']; - $argument = $Element['handler']['argument']; - $destination = $Element['handler']['destination']; - } - - $Element[$destination] = $this->{$function}($argument, $Element['nonNestables']); - - if ($destination === 'handler') - { - $Element = $this->handle($Element); - } - - unset($Element['handler']); - } - - return $Element; - } - - protected function handleElementRecursive(array $Element) - { - return $this->elementApplyRecursive(array($this, 'handle'), $Element); - } - - protected function handleElementsRecursive(array $Elements) - { - return $this->elementsApplyRecursive(array($this, 'handle'), $Elements); - } - - protected function elementApplyRecursive($closure, array $Element) - { - $Element = call_user_func($closure, $Element); - - if (isset($Element['elements'])) - { - $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']); - } - elseif (isset($Element['element'])) - { - $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']); - } - - return $Element; - } - - protected function elementApplyRecursiveDepthFirst($closure, array $Element) - { - if (isset($Element['elements'])) - { - $Element['elements'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['elements']); - } - elseif (isset($Element['element'])) - { - $Element['element'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['element']); - } - - $Element = call_user_func($closure, $Element); - - return $Element; - } - - protected function elementsApplyRecursive($closure, array $Elements) - { - foreach ($Elements as &$Element) - { - $Element = $this->elementApplyRecursive($closure, $Element); - } - - return $Elements; - } - - protected function elementsApplyRecursiveDepthFirst($closure, array $Elements) - { - foreach ($Elements as &$Element) - { - $Element = $this->elementApplyRecursiveDepthFirst($closure, $Element); - } - - return $Elements; - } - - protected function element(array $Element) - { - if ($this->safeMode) - { - $Element = $this->sanitiseElement($Element); - } - - # identity map if element has no handler - $Element = $this->handle($Element); - - $hasName = isset($Element['name']); - - $markup = ''; - - if ($hasName) - { - $markup .= '<' . $Element['name']; - - if (isset($Element['attributes'])) - { - foreach ($Element['attributes'] as $name => $value) - { - if ($value === null) - { - continue; - } - - $markup .= " $name=\"".self::escape($value).'"'; - } - } - } - - $permitRawHtml = false; - - if (isset($Element['text'])) - { - $text = $Element['text']; - } - // very strongly consider an alternative if you're writing an - // extension - elseif (isset($Element['rawHtml'])) - { - $text = $Element['rawHtml']; - - $allowRawHtmlInSafeMode = isset($Element['allowRawHtmlInSafeMode']) && $Element['allowRawHtmlInSafeMode']; - $permitRawHtml = !$this->safeMode || $allowRawHtmlInSafeMode; - } - - $hasContent = isset($text) || isset($Element['element']) || isset($Element['elements']); - - if ($hasContent) - { - $markup .= $hasName ? '>' : ''; - - if (isset($Element['elements'])) - { - $markup .= $this->elements($Element['elements']); - } - elseif (isset($Element['element'])) - { - $markup .= $this->element($Element['element']); - } - else - { - if (!$permitRawHtml) - { - $markup .= self::escape($text, true); - } - else - { - $markup .= $text; - } - } - - $markup .= $hasName ? '</' . $Element['name'] . '>' : ''; - } - elseif ($hasName) - { - $markup .= ' />'; - } - - return $markup; - } - - protected function elements(array $Elements) - { - $markup = ''; - - $autoBreak = true; - - foreach ($Elements as $Element) - { - if (empty($Element)) - { - continue; - } - - $autoBreakNext = (isset($Element['autobreak']) - ? $Element['autobreak'] : isset($Element['name']) - ); - // (autobreak === false) covers both sides of an element - $autoBreak = !$autoBreak ? $autoBreak : $autoBreakNext; - - $markup .= ($autoBreak ? "\n" : '') . $this->element($Element); - $autoBreak = $autoBreakNext; - } - - $markup .= $autoBreak ? "\n" : ''; - - return $markup; - } - - # ~ - - protected function li($lines) - { - $Elements = $this->linesElements($lines); - - if ( ! in_array('', $lines) - and isset($Elements[0]) and isset($Elements[0]['name']) - and $Elements[0]['name'] === 'p' - ) { - unset($Elements[0]['name']); - } - - return $Elements; - } - - # - # AST Convenience - # - - /** - * Replace occurrences $regexp with $Elements in $text. Return an array of - * elements representing the replacement. - */ - protected static function pregReplaceElements($regexp, $Elements, $text) - { - $newElements = array(); - - while (preg_match($regexp, $text, $matches, PREG_OFFSET_CAPTURE)) - { - $offset = $matches[0][1]; - $before = substr($text, 0, $offset); - $after = substr($text, $offset + strlen($matches[0][0])); - - $newElements[] = array('text' => $before); - - foreach ($Elements as $Element) - { - $newElements[] = $Element; - } - - $text = $after; - } - - $newElements[] = array('text' => $text); - - return $newElements; - } - - # - # Deprecated Methods - # - - function parse($text) - { - $markup = $this->text($text); - - return $markup; - } - - protected function sanitiseElement(array $Element) - { - static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/'; - static $safeUrlNameToAtt = array( - 'a' => 'href', - 'img' => 'src', - ); - - if ( ! isset($Element['name'])) - { - unset($Element['attributes']); - return $Element; - } - - if (isset($safeUrlNameToAtt[$Element['name']])) - { - $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]); - } - - if ( ! empty($Element['attributes'])) - { - foreach ($Element['attributes'] as $att => $val) - { - # filter out badly parsed attribute - if ( ! preg_match($goodAttribute, $att)) - { - unset($Element['attributes'][$att]); - } - # dump onevent attribute - elseif (self::striAtStart($att, 'on')) - { - unset($Element['attributes'][$att]); - } - } - } - - return $Element; - } - - protected function filterUnsafeUrlInAttribute(array $Element, $attribute) - { - foreach ($this->safeLinksWhitelist as $scheme) - { - if (self::striAtStart($Element['attributes'][$attribute], $scheme)) - { - return $Element; - } - } - - $Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]); - - return $Element; - } - - # - # Static Methods - # - - protected static function escape($text, $allowQuotes = false) - { - return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8'); - } - - protected static function striAtStart($string, $needle) - { - $len = strlen($needle); - - if ($len > strlen($string)) - { - return false; - } - else - { - return strtolower(substr($string, 0, $len)) === strtolower($needle); - } - } - - static function instance($name = 'default') - { - if (isset(self::$instances[$name])) - { - return self::$instances[$name]; - } - - $instance = new static(); - - self::$instances[$name] = $instance; - - return $instance; - } - - private static $instances = array(); - - # - # Fields - # - - protected $DefinitionData; - - # - # Read-Only - - protected $specialCharacters = array( - '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', '~' - ); - - protected $StrongRegex = array( - '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s', - '_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us', - ); - - protected $EmRegex = array( - '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', - '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', - ); - - protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+'; - - protected $voidElements = array( - 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', - ); - - protected $textLevelElements = array( - 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', - 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', - 'i', 'rp', 'del', 'code', 'strike', 'marquee', - 'q', 'rt', 'ins', 'font', 'strong', - 's', 'tt', 'kbd', 'mark', - 'u', 'xm', 'sub', 'nobr', - 'sup', 'ruby', - 'var', 'span', - 'wbr', 'time', - ); -}
\ No newline at end of file diff --git a/includes/util/agewarning.inc b/includes/util/agewarning.inc deleted file mode 100644 index 06a5e4d..0000000 --- a/includes/util/agewarning.inc +++ /dev/null @@ -1,35 +0,0 @@ -<?php - -function showWarning($name, $id, $system) { - $ntfy = $GLOBALS["ColdHazeApp"]["ntfy"]; - - if (time() > 1677628800) { - file_get_contents('https://' . $ntfy["server"] . '/' . $ntfy['topic'], false, stream_context_create([ - 'http' => [ - 'method' => 'POST', - 'header' => - "Content-Type: text/plain\r\n" . - "Title: " . formatPonypush("⚠️ $name does not have an age or birth year set") . "\r\n" . - "Priority: max\r\n" . - "Tags: switch\r\n" . - "Actions: view, Edit on Ponycule, https://ponycule.p.equestria.dev/-/metadata/" . ($system === "gdapd" ? "raindrops" : ($system === "hrbom" ? "moonglow" : $GLOBALS["ColdHazeApp"]["other"]["slug"])) . "/" . $id . "/, clear=true\r\n" . - "Authorization: Basic " . base64_encode($ntfy["user"] . ":" . $ntfy["password"]), - 'content' => formatPonypush("To make sure they appear on the fronting schedule (and to make sure they can front again), they need to set an age or birth year now.") - ] - ])); - } else { - file_get_contents('https://' . $ntfy["server"] . '/' . $ntfy['topic'], false, stream_context_create([ - 'http' => [ - 'method' => 'POST', - 'header' => - "Content-Type: text/plain\r\n" . - "Title: " . formatPonypush("⚠️ $name does not have an age or birth year set") . "\r\n" . - "Priority: max\r\n" . - "Tags: switch\r\n" . - "Actions: view, Edit on Ponycule, https://ponycule.p.equestria.dev/-/metadata/" . ($system === "gdapd" ? "raindrops" : ($system === "hrbom" ? "moonglow" : $GLOBALS["ColdHazeApp"]["other"]["slug"])) . "/" . $id . "/, clear=true\r\n" . - "Authorization: Basic " . base64_encode($ntfy["user"] . ":" . $ntfy["password"]), - 'content' => formatPonypush("To make sure they still appear on the fronting schedule after March 1st, they need to set an age or birth year now.") - ] - ])); - } -}
\ No newline at end of file diff --git a/includes/util/banner.inc b/includes/util/banner.inc index ea8a1eb..72656ca 100644 --- a/includes/util/banner.inc +++ b/includes/util/banner.inc @@ -1,31 +1,9 @@ <?php -function getAge($metadata) { - if (!isset($metadata["birth"]["year"]) || $metadata["birth"]["age"] > 0 || $metadata["birth"]["age"] === -1) { - if ($metadata["birth"]["age"] === -1) { - return "Eternal"; - } elseif ($metadata["birth"]["age"] <= 0) { - return "-"; - } elseif (is_numeric($metadata["birth"]["age"])) { - return $metadata["birth"]["age"] . "* years old"; - } - } else { - if ($metadata["birth"]["year"] <= 1900) { - return "-"; - } else { - $age = (int)date('Y') - $metadata["birth"]["year"] + (strtotime(date('Y') . "-" . $metadata["birth"]["date"]) <= time() ? 0 : -1); - return $age . " years old"; - } - } - - return "-"; -} - require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/session.inc"; global $isLoggedIn; global $lang; global $pages; global $isLowerLoggedIn; require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/functions.inc"; -require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/Parsedown.php"; $Parsedown = new Parsedown(); -$travelling = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/travelling/travelling.json"), true); +$travelling = []; function _header_getMember(string $id, $system) { $members = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/$system/members.json"), true); @@ -43,7 +21,6 @@ function getMemberBannerData(string $id, string $system, bool $french = false) { global $isLoggedIn; global $isLowerLoggedIn; global $lang; - global $Parsedown; global $use2023UI; $french = $lang["_french"]; @@ -404,7 +381,7 @@ function getMemberBannerData(string $id, string $system, bool $french = false) { 'median' => $metadata["median"], 'little' => $metadata["little"] >= 2, 'name' => $member["display_name"] ?? $member["name"], - 'gender' => isset($metadata["show_gender"]) && $metadata["show_gender"] ? (isset($metadata["gender"]) && trim($metadata["gender"]) !== "" ? $Parsedown->text($metadata["gender"]) : "Agender") : null, + 'gender' => "Agender", 'badges' => $badges, 'prefixes' => $prefixes, 'pronouns' => isset($member["pronouns"]) && trim($member["pronouns"]) !== "" ? $member["pronouns"] : "<i>they/them</i>", @@ -412,7 +389,7 @@ function getMemberBannerData(string $id, string $system, bool $french = false) { 'last_fronted' => $lastFronted, 'species' => $speciesList, 'system' => $systemData, - 'age' => getAge($metadata), + 'age' => -1, 'relations' => [ 'marefriends' => $marefriends ?? [], 'sexfriends' => $sexfriends ?? null, diff --git a/includes/util/functions.inc b/includes/util/functions.inc index 87954ea..b01476f 100644 --- a/includes/util/functions.inc +++ b/includes/util/functions.inc @@ -23,6 +23,16 @@ if (!function_exists("getMemberPronouns")) { } } +if (!function_exists("file_get_contents_or_defaults")) { + function file_get_contents_or_defaults($file, $default) { + if (file_exists($file)) { + return file_get_contents($file); + } else { + return $default; + } + } +} + if (!function_exists("parseMetadata")) { function parseMetadata ($metadata) { $metadata["little"] = 0; @@ -106,6 +116,24 @@ if (!function_exists("peh_error")) { if (!function_exists("getAsset")) { function getAsset($systemID, $memberID = null, $type = "avatars"): string { + if ($systemID === "gdapd") { + if (isset($memberID)) { + if ($type === "avatars" || $type === "heads") { + return getSystemMember($systemID, $memberID)["avatar_url"]; + } else { + return getSystemMember($systemID, $memberID)["banner"]; + } + } else { + $system = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $systemID . "/general.json"), true); + + if ($type === "avatars" || $type === "heads") { + return $system["avatar_url"]; + } else { + return $system["banner"]; + } + } + } + $app = $GLOBALS["ColdHazeApp"] ?? json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/app.json"), true); $systemFile = (isset($app["other"]) && $systemID === $app["other"]["id"]) ? "other" : $systemID; @@ -660,4 +688,4 @@ if (!function_exists("calculateFullAmount")) { return number_format($total, 2, '.', ','); } } -}
\ No newline at end of file +} diff --git a/includes/util/homepage.inc b/includes/util/homepage.inc index 45f91b6..df6679f 100644 --- a/includes/util/homepage.inc +++ b/includes/util/homepage.inc @@ -18,7 +18,7 @@ function newHomepage($id, $page, $title) { <?php endif; ?> <div class="new-homepage-system-list" id="new-homepage-system-<?= $id ?>-list"> - <?php $list = array_values(scoreOrder(withTravelers(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $id . "/members.json"), true), $id), $id)); foreach ($list as $index => $member): ?> + <?php $list = array_values(scoreOrder(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/" . $id . "/members.json"), true), $id)); foreach ($list as $index => $member): ?> <a href="/<?= $member["name"] ?>" class="new-homepage-link <?= $index === count($list) - 1 ? "new-homepage-link-last" : "" ?>" style="color: white; text-decoration: none !important; display: block; background-color: #<?= $member["color"] ?>22; padding: 5px 10px;"> <img src="<?= getAsset($id, $member["id"]) ?>" style="width: 32px; height: 32px; vertical-align: middle; background-color: rgba(0, 0, 0, .25); border-radius: 999px;"> <span style="width: calc(100% - 37px); vertical-align: middle; margin-left: 5px;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;"><?= $member["display_name"] ?? $member["name"] ?></span> @@ -26,4 +26,4 @@ function newHomepage($id, $page, $title) { <?php endforeach; ?> </div> </div> -<?php }
\ No newline at end of file +<?php } diff --git a/includes/util/score.inc b/includes/util/score.inc index 622f057..c7d47de 100644 --- a/includes/util/score.inc +++ b/includes/util/score.inc @@ -1,12 +1,13 @@ <?php function scoreOrder($members, $system, $useDominant = false) { + global $defaultMember; global $isLowerLoggedIn; global $isLoggedIn; $ordered = []; foreach ($members as $member) { - if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling") && file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json")) { + if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling")) { if (isset($member["color"])) { if ($useDominant) { $rgb = [ @@ -28,14 +29,13 @@ function scoreOrder($members, $system, $useDominant = false) { $rgb[2] ); } else { - $rgb = [255, 255, 255]; $hsl = rgbToHsl(255, 255, 255); } $systemID = $member["system"] ?? $system; $member["_system"] = $member["system"] = $systemID; - $member["_metadata"] = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json"), true)); + $member["_metadata"] = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json", $defaultMember), true)); $member["_score"] = $hsl[0]; if (!isset($member["_metadata"]["private"]) || !$member["_metadata"]["private"] || $isLoggedIn || $isLowerLoggedIn) { @@ -52,13 +52,14 @@ function scoreOrder($members, $system, $useDominant = false) { } function scoreOrderGlobal() { + global $defaultMember; global $isLowerLoggedIn; global $isLoggedIn; $ordered = []; foreach (json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/hrbom/members.json"), true) as $member) { - if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling") && file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json")) { + if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling")) { if (isset($member["color"])) { $rgb = [ hexdec(substr($member["color"], 0, 2)), @@ -71,13 +72,12 @@ function scoreOrderGlobal() { $rgb[2] ); } else { - $rgb = [255, 255, 255]; $hsl = rgbToHsl(255, 255, 255); } $member["_score"] = $hsl[0]; $member["_system"] = "hrbom"; $member["system"] = "hrbom"; - $member["_metadata"] = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json"), true)); + $member["_metadata"] = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json", $defaultMember), true)); if (!isset($member["_metadata"]["private"]) || !$member["_metadata"]["private"] || $isLoggedIn || $isLowerLoggedIn) { $ordered[] = $member; @@ -86,7 +86,7 @@ function scoreOrderGlobal() { } foreach (json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/gdapd/members.json"), true) as $member) { - if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling") && file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json")) { + if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling")) { if (isset($member["color"])) { $rgb = [ hexdec(substr($member["color"], 0, 2)), @@ -99,13 +99,12 @@ function scoreOrderGlobal() { $rgb[2] ); } else { - $rgb = [255, 255, 255]; $hsl = rgbToHsl(255, 255, 255); } $member["_score"] = $hsl[0]; $member["_system"] = "gdapd"; $member["system"] = "gdapd"; - $member["_metadata"] = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json"), true)); + $member["_metadata"] = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json", $defaultMember), true)); if (!isset($member["_metadata"]["private"]) || !$member["_metadata"]["private"] || $isLoggedIn || $isLowerLoggedIn) { $ordered[] = $member; @@ -116,7 +115,7 @@ function scoreOrderGlobal() { if ($isLowerLoggedIn || $isLoggedIn) { $app = $GLOBALS["ColdHazeApp"] ?? json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/app.json"), true); foreach (json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/other/members.json"), true) as $member) { - if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling") && file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json")) { + if ($member["name"] !== "unknown" && $member["name"] !== "fusion" && $member["name"] !== "new" && !str_starts_with($member["name"], "smol") && !str_ends_with($member["name"], "-travelling")) { if (isset($member["color"])) { $rgb = [ hexdec(substr($member["color"], 0, 2)), @@ -129,13 +128,12 @@ function scoreOrderGlobal() { $rgb[2] ); } else { - $rgb = [255, 255, 255]; $hsl = rgbToHsl(255, 255, 255); } $member["_score"] = $hsl[0]; $member["_system"] = $app["other"]["id"]; $member["system"] = $app["other"]["id"]; - $member["_metadata"] = parseMetadata(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json"), true)); + $member["_metadata"] = parseMetadata(json_decode(file_get_contents_or_defaults($_SERVER['DOCUMENT_ROOT'] . "/includes/data/metadata/$member[id].json", $defaultMember), true)); $ordered[] = $member; } } @@ -146,4 +144,4 @@ function scoreOrderGlobal() { }); return array_values($ordered); -}
\ No newline at end of file +} diff --git a/includes/util/short.inc b/includes/util/short.inc deleted file mode 100644 index 1654d93..0000000 --- a/includes/util/short.inc +++ /dev/null @@ -1,55 +0,0 @@ -<?php - -require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/functions.inc"; -require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/util/score.inc"; - -global $toplevel; global $lang; global $pages; - -header("Content-Type: text/plain"); -$members = scoreOrderGlobal(); -$list = [ - "rd" => "/raindrops", - "minty" => "/cloudydreams", - "violetdawn" => "/sandydawn", - "cloudy" => "/cloudydreams", - "zipp" => "/zippstorm", - "babs" => "/fleurheartseed", - "frost" => "/frostcrystals", - "violet" => "/sandydawn", - "scootaloo" => "/scoots", - "babsseed" => "/fleurheartseed", - "flurryheart" => "/fleurheartseed" -]; - -foreach ($members as $member) { - for ($i = 1; $i < strlen($member["name"]); $i++) { - $part = substr($member["name"], 0, $i); - - if (in_array($part, array_keys($list))) { - $list[$part] = false; - } else { - $list[$part] = "/" . $member["name"]; - } - } - - foreach ($member["proxy_tags"] as $proxy) { - $system = $member["_system"] === "gdapd" ? "rd" : "cb"; - $list[$system . preg_replace("/[^a-z]/m", "", $proxy["prefix"])] = "/" . $member["name"]; - } - - $list[$member["id"]] = "/" . $member["name"]; - $list[$member["uuid"]] = "/" . $member["name"]; -} - -$list["minty"] = "/cloudydreams"; -$list["twilight"] = "/twi"; - -if (in_array($toplevel, array_keys($list)) && $list[$toplevel]) { - if ($toplevel !== "unknown") { - header("Location: " . $list[$toplevel]); - } else { - peh_error("Page not found: " . strip_tags($toplevel), 404); - } -} else { - peh_error("Page not found: " . strip_tags($toplevel), 404); -}
\ No newline at end of file diff --git a/includes/util/travelling.inc b/includes/util/travelling.inc deleted file mode 100644 index b1479fb..0000000 --- a/includes/util/travelling.inc +++ /dev/null @@ -1,5 +0,0 @@ -<?php - -function withTravelers(array $members): array { - return $members; -}
\ No newline at end of file |