fixed conflict in header.php

This commit is contained in:
sørenpeter 2024-02-02 20:16:50 +01:00
commit 86e386b412
10 changed files with 359 additions and 71 deletions

View file

@ -30,7 +30,8 @@ $routes = [
'/new' => 'new_twt.php',
'/add' => 'add_feed.php',
'/following' => 'following.php',
'/refresh' => 'load_twt_files.php',
//'/refresh' => 'load_twt_files.php',
'/refresh' => 'refresh.php',
'/login' => 'login.php',
'/logout' => 'logout.php',
'/profile' => 'profile.php',

166
libs/TOTP.php Normal file
View file

@ -0,0 +1,166 @@
<?php
function verifyTOTP($secret, $enteredCode, $digits = 10, $window = 1) {
$windowTime = 30;
$timeSlice = floor(time() / $windowTime);
$enteredCode = trim($enteredCode);
$enteredCode = str_replace(' ', '', trim($enteredCode));
$enteredCodeInt = intval($enteredCode);
#var_dump($enteredCodeInt);
#echo "<br>\n";
for ($currentWindow = -$window; $currentWindow <= $window; $currentWindow++) {
$time = $timeSlice + $currentWindow;
$generatedCode = generateTOTP($secret, $digits, $time);
#echo "$time $generatedCode<br>\n";
if ($generatedCode === $enteredCodeInt) {
return true; // Code is valid within the window
}
}
return false; // Code is not valid
}
function generateTOTP($secret, $digits = 6, $timeSlice = null) {
if ($timeSlice === null) {
$timeSlice = floor(time() / 30);
}
$secret = base32Decode($secret);
$timeSlice = pack('N*', 0) . pack('N*', $timeSlice);
$hash = hash_hmac('sha1', $timeSlice, $secret, true);
$offset = ord($hash[19]) & 0xf;
$otp = (
(ord($hash[$offset + 0]) & 0x7f) << 24 |
(ord($hash[$offset + 1]) & 0xff) << 16 |
(ord($hash[$offset + 2]) & 0xff) << 8 |
(ord($hash[$offset + 3]) & 0xff)
);
#var_dump($otp);
#echo "<br>\n";
// When digits is 10, the padding was giving a wrong OTP
// Just return the calculated value
if ($digits === 10) {
return $otp;
}
$otp = $otp % pow(10, $digits);
return str_pad($otp, $digits, '0', STR_PAD_LEFT);
}
function base32Decode($base32) {
$base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$base32charsFlipped = array_flip(str_split($base32chars));
$paddingChar = '=';
$paddingCharCount = 0;
if (strpos($base32, $paddingChar) !== false) {
$paddingCharCount = substr_count($base32, $paddingChar);
}
$allowedValues = array(6, 4, 3, 1, 0);
if (!in_array($paddingCharCount, $allowedValues)) {
return false;
}
for ($i = 0; $i < 4; ++$i) {
if ($paddingCharCount == $allowedValues[$i] &&
substr($base32, -$allowedValues[$i]) != str_repeat($paddingChar, $allowedValues[$i])
) {
return false;
}
}
$base32 = str_replace($paddingChar, '', $base32);
$base32 = str_split($base32);
$binaryString = '';
foreach ($base32 as $char) {
if (!isset($base32charsFlipped[$char])) {
return false; // Invalid character found
}
$binaryString .= sprintf('%05b', $base32charsFlipped[$char]);
}
$length = strlen($binaryString);
$offset = 0;
$binaryData = '';
while ($offset < $length) {
$binaryChunk = substr($binaryString, $offset, 8);
if (strlen($binaryChunk) < 8) {
$binaryChunk = str_pad($binaryChunk, 8, '0', STR_PAD_RIGHT);
}
$decimalChunk = bindec($binaryChunk);
$binaryData .= pack('C', $decimalChunk);
$offset += 8;
}
return $binaryData;
}
function base32Encode($input) {
$base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$base32String = '';
$position = 0;
$carry = 0;
foreach (str_split($input) as $byte) {
$carry |= ord($byte) << $position;
$position += 8;
while ($position >= 5) {
$base32String .= $base32Chars[$carry & 31];
$carry >>= 5;
$position -= 5;
}
}
if ($position > 0) {
if ($carry & 31) {
$base32String .= $base32Chars[$carry & 31];
}
}
return $base32String;
}
function generateRandomSecret($length = 32) {
// https://medium.com/@nicola88/two-factor-authentication-with-totp-ccc5f828b6df
$bytes = random_bytes($length);
$base32 = base32Encode($bytes);
return substr($base32, 0, $length);
}
# Examples of usage (To move somewhere else)
/*
$randomSecret = generateRandomSecret();
echo "Random Secret Key: $randomSecret<br>\n";
$secret = 'K3OBZ7XPR6T4PTNXSNCQ';
$enteredCode = '123456';
$digits = 6;
if (isset($_GET['c']) && isset($_GET['s'])) {
$enteredCode = $_GET['c'];
$secret = $_GET['s'];
$isCodeValid = verifyTOTP($secret, $digits, $enteredCode);
if ($isCodeValid) {
echo "Code $enteredCode is valid!<br>";
} else {
echo "Code $enteredCode is invalid!<br>";
}
}
$code = generateTOTP($secret);
echo "TOTP code: $code<br>\n";
$code = generateTOTP($secret, 8);
echo "TOTP code: $code<br>\n";
*/

View file

@ -1,18 +1,30 @@
<?php
require_once('libs/TOTP.php');
$config = parse_ini_file('private/config.ini');
$password = $config['password'];
session_start();
if(isset($_POST['submit_pass']) && $_POST['pass'])
if (isset($_POST['submit_pass']) && $_POST['pass'])
{
$pass=$_POST['pass'];
if($pass=="$password")
$pass = $_POST['pass'];
// @eapl.me 2023-11-23 - I'm trying to add support to passwords
// and TOTP (passwordless). So, in the Pwd field you can enter
// the password, or the current TOTP
if ($pass == $password)
{
$_SESSION['password']=$pass;
$_SESSION['password'] = $pass;
}
elseif ($isCodeValid = verifyTOTP(
$config['totp_secret'], $pass, intval($config['totp_digits']))
)
{
// If TOTP is valid, assume that we entered the Password
$_SESSION['password'] = $password;
}
else
{
$error="Incorrect Password";
$error = "Incorrect Password";
}
}

View file

@ -238,6 +238,26 @@ nav.pagnation {
padding: 0.5rem 0;
}
/* === REFRESH === */
#refreshLabel {
}
#refreshInfo {
font-weight: bold;
/* display: block;*/
}
#refreshURL {
}
#refreshCounter {
float: right;
}
/* === FOOTER === */
footer {
border-top: thin solid grey;
margin-top: 1rem;

View file

@ -17,7 +17,7 @@ declare(strict_types=1);
# hash(string) =
#
require_once("libs/session.php");
require_once('libs/session.php');
require_once('libs/twtxt.php');
require_once('libs/hash.php');
require_once('libs/Slimdown.php');
@ -32,7 +32,7 @@ $config = parse_ini_file('private/config.ini');
// TODO: Take the title from the config.ini
$title = "Timeline"; // Fallback, should be set in all views
// HACKED by sp@darch.dk
// HACKED by sp@darch.dk
if(!empty($_GET['list'])) {
$url = "https://darch.dk/twtxt-lists/".$_GET['list'];
}

View file

@ -4,13 +4,15 @@ $profile = getTwtsFromTwtxtString($config['public_txt_url']);
?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="webmention" href="<?= $baseURL ?>/webmention" />
<link rel="stylesheet" href="<?= $baseURL ?>/libs/simple.css">
<link rel="stylesheet" type="text/css" href="<?= $baseURL ?>/style.css">
<link rel="stylesheet" type="text/css" href="<?= $baseURL ?>/libs/simple.css">
<link rel="stylesheet" type="text/css" href="<?= $baseURL ?>/libs/timeline.css">
<link rel="stylesheet" type="text/css" href="<?= $baseURL ?>/custom_style.css">
<title><?= $title ?></title>
</head>
<body>
@ -43,5 +45,3 @@ $profile = getTwtsFromTwtxtString($config['public_txt_url']);
</header>
<main>

View file

@ -1,34 +0,0 @@
# | |___ _| |___ _| |_
# | __\ \ /\ / / __\ \/ / __|
# | |_ \ V V /| |_ > <| |_
# \__| \_/\_/ \__/_/\_\\__|
#
# Twtxt is an open, distributed and decentralized microblogging platform
# for hackers and friends that uses raw text files, easy to read by humans,
# and with common protocols and free and open.
#
# Using twtxt-php from: https://github.com/eapl-gemugami/twtxt-php
# Know more about twtxt here: https://github.com/buckket/twtxt
# Using the following extensions:
# https://github.com/eapl-gemugami/twtxt-php/blob/master/docs/02-metadata-extension.md
#
# nick = timeline
# url = http://example.com/timeline/twtxt.txt
# avatar = http://example.com/timeline/avatar.png
# emoji = 👾
# link =
# lang =
# description =
# discovery =
#
# following = 123
# follow = eapl.me https://eapl.me/twtxt.txt
# follow = eapl.mx https://eapl.mx/twtxt.txt
# follow = lyse https://lyse.isobeef.org/twtxt.txt
# follow = prologic https://twtxt.net/user/prologic/twtxt.txt
# follow = sorenpeter http://darch.dk/twtxt.txt
# follow = stigatle https://yarn.stigatle.no/user/stigatle/twtxt.txt
# follow = thecanine https://twtxt.net/user/thecanine/twtxt.txt
#~~~#
2023-09-10T18:55:27+02:00 Hello twtxt world!

View file

@ -2,9 +2,13 @@
# Gets the followers from an URL and then gets all the Followers twtxt.txt files
# Intended to be run in the background
/*
require_once("libs/session.php"); // TODO: Move all to base.php
require_once('libs/twtxt.php');
require_once('libs/hash.php');
*/
require_once("partials/base.php");
$config = parse_ini_file('private/config.ini');
@ -13,6 +17,7 @@ if (!isset($_SESSION['password'])) {
exit();
}
$max_execution_time = intval($config['max_execution_time']);
if ($max_execution_time < 1) {
$max_execution_time = 1;
@ -20,9 +25,13 @@ if ($max_execution_time < 1) {
ini_set('max_execution_time', $max_execution_time);
#ob_start();
//ob_start();
$config = parse_ini_file('private/config.ini');
//require_once 'partials/header.php';
//ob_flush();
//$config = parse_ini_file('private/config.ini');
$url = $config['public_txt_url'];
if (!empty($_GET['url'])) {
@ -33,17 +42,20 @@ if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
die('Not a valid URL');
}
echo "Loading URL: $url<br>\n<br>\n";
#ob_flush();
echo '<label id="refreshLabel" for="refreshProgress">Loading feeds followed by: '.$url.'</label><br>';
echo '<progress id="refreshProgress" value=""></progress>';
ob_flush();
const DEBUG_TIME_SECS = 300;
const PRODUCTION_TIME_SECS = 5;
$fileContent = getCachedFileContentsOrUpdate($url, PRODUCTION_TIME_SECS);
$fileContent = mb_convert_encoding($fileContent, 'UTF-8');
$fileLines = explode("\n", $fileContent);
// Build Following List
$twtFollowingList = [];
foreach ($fileLines as $currentLine) {
if (str_starts_with($currentLine, '#')) {
if (!is_null(getDoubleParameter('follow', $currentLine))) {
@ -52,15 +64,32 @@ foreach ($fileLines as $currentLine) {
}
}
# Load all the files
# Save a flag to know it's loading files in the background
foreach ($twtFollowingList as $following) {
echo "Updating: $following[1]<br>\n";
#ob_flush();
updateCachedFile($following[1]);
}
echo 'Finished';
#ob_flush();
header('Location: /');
/* Progress bar based on: https://github.com/w3shaman/php-progress-bar */
$i = 1;
$total = count($twtFollowingList);
foreach ($twtFollowingList as $following) {
$float = $i/$total;
$percent = intval($float * 100)."%";
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("refreshLabel").innerHTML = "Updating: '.$following[1].' ('.$i.'/'.$total.')";
document.getElementById("refreshProgress").value = "'.$float.'";
document.getElementById("refreshProgress").innerHTML = "'.$percent.'";
</script>';
updateCachedFile($following[1]);
ob_flush(); // Send output to browser immediately
$i++;
}
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("refreshLabel").innerHTML="Refreshed '.$total.' feeds"</script>';
//header('Location: /');
exit();

View file

@ -5,23 +5,21 @@ $title = "Login - ".$title;
include 'partials/header.php';
?>
<?php
//$config = parse_ini_file('private/config.ini');
//$password = $config['password'];
if( isset($_SESSION['password'])) {
if($_SESSION['password']=="$password") {
header("Location: .");
die();
// Password comes from libs/session.php
if (isset($_SESSION['password'])) {
if ($_SESSION['password'] == $password) {
header("Location: .");
die();
}
}
else { ?>
<center>
<h2>Enter password:</h2>
<h2>Enter password or TOTP</h2>
<form method="post" action="" id="login_form">
<input type="password" name="pass"><br>
<input type="password" name="pass" placeholder="Password" autofocus><br>
<input type="submit" name="submit_pass" value="Login">
<p><font style="color:red;"><?php if(isset($error)) {echo $error;}?></font></p>
</form>

96
views/refresh.php Normal file
View file

@ -0,0 +1,96 @@
<?php
require_once("partials/base.php");
if (!isset($_SESSION['password'])) {
header('Location: ./login');
exit();
}
//ob_start();
$title = "Refresh - ".$title;
ob_end_flush();
include 'partials/header.php';
?>
<p id="refreshLabel">
<strong id="refreshInfo">Loading feeds followed by:</strong>
<span id="refreshURL"><?= preg_replace('(^https?://)', '', $url) ?></span>
<span id="refreshCounter"></span>
</p>
<progress id="refreshProgress" value=""></progress>
<?php
include 'partials/footer.php';
ob_start();
flush();
// Get URL from query
$url = $config['public_txt_url'];
if (!empty($_GET['url'])) {
$url = $_GET['url'];
}
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
die('Not a valid URL');
}
// Build Following List
$twtFollowingList = [];
foreach ($fileLines as $currentLine) {
if (str_starts_with($currentLine, '#')) {
if (!is_null(getDoubleParameter('follow', $currentLine))) {
$twtFollowingList[] = getDoubleParameter('follow', $currentLine);
}
}
}
// Loop over feeds followed
/* Progress bar based on: https://github.com/w3shaman/php-progress-bar */
$i = 1;
$total = count($twtFollowingList);
echo '<script language="javascript">document.getElementById("refreshInfo").innerHTML = "Updating feed from:"</script>';
foreach ($twtFollowingList as $following) {
//ob_start();
$float = $i/$total;
$percent = intval($float * 100)."%";
$feed = $following[1];
//$feed = preg_replace('(^https?://)', '', $feed);
//$feed = $following[0].'@'. parse_url($following[1], PHP_URL_HOST);
$feed = $following[0].' ('.$following[1].')';
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("refreshURL").innerHTML = "'.$feed.'";
document.getElementById("refreshCounter").innerHTML = "('.$i.' of '.$total.')";
document.getElementById("refreshProgress").value = "'.$float.'";
document.getElementById("refreshProgress").innerHTML = "'.$percent.'";
</script>';
updateCachedFile($following[1]);
ob_flush(); // Send output to browser immediately
flush();
$i++;
}
// Tell user that the process is completed
echo '<script language="javascript">
document.getElementById("refreshInfo").innerHTML="Refreshed '.$total.' feeds from:";
document.getElementById("refreshURL").innerHTML = "'.preg_replace('(^https?://)', '', $url).'";
document.getElementById("refreshCounter").innerHTML = "";
history.back();
</script>';