first commit; dx 1.0 beta

This commit is contained in:
2025-11-09 22:35:16 +03:00
commit 4d01725955
153 changed files with 6504 additions and 0 deletions
View File
+370
View File
@@ -0,0 +1,370 @@
<?php
include 'k-api.php';
function db()
{
$pdo = new PDO('sqlite:./data.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
};
function findClosestDateSort($array, $targetDate)
{
$targetTimestamp = DateTime::createFromFormat('d-m-y', $targetDate)->getTimestamp();
usort($array, function ($a, $b) use ($targetTimestamp) {
$aTimestamp = DateTime::createFromFormat('d-m-y', $a['fromDate'])->getTimestamp();
$bTimestamp = DateTime::createFromFormat('d-m-y', $b['fromDate'])->getTimestamp();
$aDiff = abs($aTimestamp - $targetTimestamp);
$bDiff = abs($bTimestamp - $targetTimestamp);
return $aDiff - $bDiff;
});
return $array[0];
}
function getDayOfWeek(string $date)
{
$p = explode('-', $date);
if (count($p) !== 3) throw new InvalidArgumentException('DD-MM-YY|YYYY');
[$d, $m, $y] = $p;
if (strlen($y) === 2) $y = '20' . $y;
$dt = DateTime::createFromFormat('Y-m-d', "$y-$m-$d");
if (!$dt) throw new InvalidArgumentException('Invalid date');
return (int)$dt->format('N') - 1; // 0=Mon ... 6=Sun
}
function joinArraysByKey(array $primaryArray, array $secondaryArray, bool $doNotOverwrite = false, string $key = 'num'): array
{
// Index secondary array once for O(1) lookups
$indexedArray = array_column($secondaryArray, null, $key);
$result = [];
foreach ($primaryArray as $item) {
if (!isset($item[$key])) {
$result[] = $item;
continue;
}
$currentKey = $item[$key];
if (isset($indexedArray[$currentKey])) {
// Merge based on $doNotOverwrite flag
$result[] = $doNotOverwrite
? array_merge($indexedArray[$currentKey], $item) // Primary values take precedence
: array_merge($item, $indexedArray[$currentKey]); // Secondary values take precedence
} else {
$result[] = $item;
}
}
return $result;
}
function FastDBReq(PDO $db, string $sql, array $params = []): array
{
// ivan
// pickme love
// <3 <3 <3 <3
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
CreateApi(function ($api) {
$api->on('/', 'GET', function () {
return 'dengi';
});
$api->on('/login', 'POST', function ($req) {
if (!isset($req->data['classId'])) {
$req->res->code(400);
return "class is empty";
}
$classId = substr(strtoupper($req->data['classId']), 0, 10);
// according docs (UPPERCASE, MIN 3 MAX 10)
$db = db();
$results = FastDBReq($db, "SELECT * FROM classes WHERE classid = ?", [$classId]);
$db = null;
if (count($results) != 0) {
return $results[0];
} else {
$req->res->code(400);
return "класс $classId не найден";
}
});
$api->on('/get_class_user_f', 'POST', function ($req) {
if (!isset($req->data['classId'])) {
$req->res->code(400);
return "";
}
$classId = substr(strtoupper($req->data['classId']), 0, 10);
// according docs (UPPERCASE, MIN 3 MAX 10)
$db = db();
$results = FastDBReq($db, "SELECT userclassname FROM classes WHERE classid = ?", [$classId]);
$db = null;
if (count($results) != 0) {
return $results[0];
} else {
$req->res->code(400);
return;
}
});
$api->on('/get_admin_user_f', 'POST', function ($req) {
if (!isset($req->data['adminId'])) {
$req->res->code(400);
return "";
}
$adminId = $req->data['adminId'];
$db = db();
$results = FastDBReq($db, "SELECT adminName FROM admins where adminid = ?", [$adminId]);
$db = null;
if (count($results) != 0) {
return $results[0];
} else {
$req->res->code(400);
return;
}
});
$api->on('/admin_login', 'POST', function ($req) {
if (!isset($req->data['adminId'])) {
$req->res->code(400);
return "admin is empty";
}
$adminId = $req->data['adminId'];
$db = db();
$results = FastDBReq($db, "SELECT * FROM admins WHERE adminid = ?", [$adminId]);
$db = null;
if (count($results) != 0) {
return $results[0];
} else {
$req->res->code(400);
return "админ не найден";
}
});
$api->on('/req_client_schedule', 'POST', function ($req) {
// NOTE: THIS IS SCHEDULE FOR USER (SHOULD BE WITH CHANGES AND CALLS)
// types = [0 - default schedule, 1 - with schedule changes, 2 - with schedule and rings]
if (!$req->hasData(['classId', 'day'])) {
$req->res->code(400);
return "net dannih";
}
$classId = substr(strtoupper($req->data['classId']), 0, 10);
$day = $req->data['day'];
$db = db();
$results = FastDBReq($db, "SELECT * FROM changes WHERE classId = ? AND forDay = ?", [$classId, $day]);
if (count($results) > 0) {
// return only changes
$content = json_decode($results[0]['content'], true);
$has_full_rings = true;
foreach ($content as $idx => $item) {
if (!isset($item['t-begin']) || !isset($item['t-end'])) {
$has_full_rings = false;
// optionally record $idx
break;
}
}
if ($has_full_rings) {
$db = null;
// with rings
return ['data' => $content, 'type' => 2];
} else {
// without rings
$results = FastDBReq($db, "SELECT * FROM RINGS WHERE classId = ?", [$classId]);
$rings = json_decode(findClosestDateSort($results, $day)['content'], true);
$out = joinArraysByKey($content, $rings, true);
$db = null;
return ['data' => $out, 'type' => 1];
}
} else {
// return shedules + calls
$dayOfWeek = getDayOfWeek($day);
$results = FastDBReq($db, "SELECT * FROM schedules WHERE classId = ? AND dayOfWeek = ?", [$classId, $dayOfWeek]);
if (count($results) > 0) {
$out = [];
$schedule = json_decode(findClosestDateSort($results, $day)['content'], true);
$results = FastDBReq($db, "SELECT * FROM RINGS WHERE classId = ?", [$classId]);
$rings = json_decode(findClosestDateSort($results, $day)['content'], true);
$out = joinArraysByKey($schedule, $rings);
$db = null;
return ['data' => $out, 'type' => 0];
} else {
$db = null;
return ['data' => []];
}
}
});
$api->on('/editor_data', "POST", function ($req) {
if (!$req->hasData(['tab', 'day', 'adminId'])) {
$req->res->code(400);
return "bad data";
}
$adminId = $req->data['adminId'];
$db = db();
$results = FastDBReq($db, "SELECT * FROM admins WHERE adminId=?", [$adminId]);
if (count($results) == 0) {
$db = null;
$req->res->code(400);
return "админ не найден";
# end
}
$classId = $results[0]['adminClass'];
$day = $req->data['day'];
$tab = intval($req->data['tab']);
$changes = null;
$schedule = [];
$rings = [];
if ($tab != 2) {
if ($tab == 0) {
$results = FastDBReq($db, "SELECT * FROM changes WHERE classId = ? AND forDay = ?", [$classId, $day]);
if (count($results) > 0) {
$changes = json_decode($results[0]['content'], true);
}
}
$dayOfWeek = getDayOfWeek($day);
$results = FastDBReq($db, "SELECT * FROM schedules WHERE classId = ? AND dayOfWeek = ?", [$classId, $dayOfWeek]);
if (count($results) > 0) {
$schedule = json_decode(findClosestDateSort($results, $day)['content'], true);
}
} else {
$results = FastDBReq($db, "SELECT * FROM RINGS WHERE classId = ?", [$classId]);
if (count($results) > 0) {
$rings = json_decode(findClosestDateSort($results, $day)['content'], true);
}
}
$db = null;
switch ($tab) {
case 0:
if ($changes === null) { // type check!!!
return $schedule;
} else {
return $changes;
}
case 1:
return $schedule;
case 2:
return $rings;
default:
return "tab not found dengi dengi";
}
});
$api->on(
"/editor_publish",
"POST",
function ($req) {
if (!$req->hasData(['adminId', 'tab', 'day', 'newData'])) {
$req->res->code(400);
return "bad data";
}
$adminId = $req->data['adminId'];
$db = db();
$results = FastDBReq($db, "SELECT * FROM admins WHERE adminId=?", [$adminId]);
if (count($results) == 0) {
$db = null;
$req->res->code(400);
return "админ не найден";
# end
}
$classId = $results[0]['adminClass'];
$day = $req->data['day'];
$tab = intval($req->data['tab']);
$newDataRaw = $req->data['newData'];
$newData = json_decode($newDataRaw, true);
// im too lazy to close db
switch ($tab) {
case 0: // changes
// first get rasp and compare
// if no chnages skip, else publish
$dayOfWeek = getDayOfWeek($day);
$results = FastDBReq($db, "SELECT * FROM schedules WHERE classId = ? AND dayOfWeek = ?", [$classId, $dayOfWeek]);
$publish = true;
if (count($results) > 0) {
$schedule = json_decode(findClosestDateSort($results, $day)['content'], true);
if ($newData === $schedule) { // position sentensive
$publish = false;
}
}
if ($publish) {
// removing changes for today if they are exists
$results = FastDBReq($db, "SELECT * FROM changes WHERE classId = ? AND forDay = ?", [$classId, $day]);
if (count($results) > 0) {
$changes = json_decode($results[0]['content'], true);
if ($newData === $changes) {
// already present
return true;
}
FastDBReq($db, "DELETE FROM changes WHERE forDay = ? AND classId = ?", [$day, $classId]); // SCARY 💀💀💀
}
// creating new
FastDBReq($db, 'INSERT INTO changes VALUES (?, ?, ?)', [$classId, $day, $newDataRaw]);
return true;
}
return false;
case 1: // rasp
$dayOfWeek = getDayOfWeek($day);
// FIXME: im to lazy to find if closest rasp are the same
FastDBReq($db, 'DELETE FROM schedules WHERE classId=? AND fromDate=?', [$classId, $day]);
FastDBReq($db, 'INSERT INTO schedules VALUES (?,?,?,?)', [$classId, $day, $dayOfWeek, $newDataRaw]);
return true;
case 2: // rigns
//same
FastDBReq($db, 'DELETE FROM rings WHERE classId=? AND fromDate=?', [$classId, $day]);
FastDBReq($db, 'INSERT INTO rings VALUES (?,?,?)', [$classId, $day, $newDataRaw]);
return true;
default:
return "tab not found dengi dengi";
}
}
);
$api->on('/editor_fullitems_del', "POST", function ($req) {
// SCARY!!!!!!
// LEVEL 10000000
// 💀💀💀💀💀
if (!$req->hasData(['tab', 'day', 'adminId'])) {
$req->res->code(400);
return "bad data";
}
$adminId = $req->data['adminId'];
$db = db();
$results = FastDBReq($db, "SELECT * FROM admins WHERE adminId=?", [$adminId]);
if (count($results) == 0) {
$db = null;
$req->res->code(400);
return "админ не найден";
# end
}
$classId = $results[0]['adminClass'];
$day = $req->data['day'];
$tab = intval($req->data['tab']);
switch ($tab) {
case 0:
FastDBReq($db, "DELETE FROM changes WHERE forDay = ? AND classId = ?", [$day, $classId]);
break;
case 1:
FastDBReq($db, 'DELETE FROM schedules WHERE classId=? AND fromDate=?', [$classId, $day]);
break;
case 2:
FastDBReq($db, 'DELETE FROM rings WHERE classId=? AND fromDate=?', [$classId, $day]);
break;
default:
return "you saved your live because you did'n know what tabs are here";
}
$db = null;
return true;
});
});
Binary file not shown.
+151
View File
@@ -0,0 +1,151 @@
# dx4 architecture
<p align='right'>dengi</p>
# fundamental types
## classes
#### db table
| name | meaning |
| ----------------- | ------------------------------------------------------ |
| **classid** | **unique** class id <u>_(uppercase, min 3 max 10)_</u> |
| **userclassname** | use friendly name |
| **caching** | `0 \| 1` toggles caching |
#### example
| classid | userclassname | caching |
| ----------- | ------------- | ------- |
| `9BPLETNEV` | 9б | `1` |
## admins
#### db table
| name | meaning |
| -------------- | ---------------------------------- |
| **adminId** | unique admin id, **it's secret** |
| **adminName** | user friendly admin name |
| **adminClass** | `classid`, that admin belongs to |
| **adminPerms** | admin permisions, look table below |
#### permissions
| val | meaning |
| ---- | ------------------------------------------------ |
| `-1` | **unlimited, full access** |
| `0` | _**preserved for users**_ |
| `1` | allowed to make change for _changes in schedule_ |
| `2` | _bells and permament schedule_ |
| `3` | _change class profile, and notes_ |
| `4` | _create and manage admins_ |
#### > Requests
You can **request** a change, if your level is lower, also you can **accept** those changes if your admin level can do this
#### example
| adminId | adminName | adminClass | adminPerms |
| -------------- | -------------- | ----------- | ---------- |
| `ivanpletnev4` | _Ivan Pletnev_ | `9BPLETNEV` | `-1` |
## schedule _(permanent)_
#### db table
| name | meaning |
| ------------- | ----------------------------------------- |
| **classId** | class belongs to |
| **fromDate** | active from date (DD-MM-YY) |
| **dayOfWeek** | day of week, _num_ **(**`0` **- monday)** |
| **content** | json **list** content, look table below |
#### json content
| key | meaning |
| ----------- | --------------------------------------- |
| **num** | n of lesson in schedule, start with `1` |
| **subject** | lesson subject |
| **cabinet** | lesson cabinet |
#### example
| **classId** | **raspId** | **dayOfWeek** | **content** |
| ----------- | ---------- | ------------- | ------------------------------------------------------- |
| `9BPLETNEV` | `3` | `0` | `[{"num":1, "subject":'физека🤬', "cabinet", 209},...]` |
## changes in schedule _(zameni)_
#### db table
| name | meaning |
| ----------- | ------------------------------------------------------------ |
| **classId** | class belongs to |
| **forDay** | day date `DD-MM-YY` _(i hope there wouldn't be y3k problem)_ |
| **content** | json list content, look table below |
#### json list content
| key | meaning |
| ------------- | ---------------------------------------------------- |
| **num** | n of lesson in schedule, start with `1` |
| **subject** | lesson subject, or `$function`, **look table below** |
| **cabinet** | lesson cabinet, if unused type `0` |
| **t-begin** ? | lesson begin time, if empty same as before |
| **t-end** ? | lesson end time, if empty same as before |
#### changes functions
| function | meaning |
| --------------------- | ---------------------------------------------------------------- |
| **`$rm-bef`** | remove all lessons **before**, _including this_, eq. to old `-3` |
| **`$rm-aft`** | remove all lessons **after**, _including this_, eq. to old `-2` |
| **`$no-lessons`** | permanently sets to no lessons today |
| ~~**`$no-changes`**~~ | ~~says that there is no changes today _(when 100% sure)_~~ |
#### example
ko v toromu
| **classId** | **forDay** | **forRaspId** | **content** |
| ----------- | ---------- | ------------- | ----------------------------------------------------------- |
| `9BPLETNEV` | `20-10-25` | `0` | `[{"num":1, "subject":"`**`$rm-bef`**`", "cabinet":0},...]` |
## rings _(zvonki)_
| name | meaning |
| ------------ | --------------------------------------- |
| **classId** | class belongs to |
| **fromDate** | active from date (DD-MM-YY) |
| **content** | json **list** content, look table below |
#### json list content
| key | meaning |
| ----------- | ----------------- |
| **num** | n of lesson |
| **t-begin** | lesson begin time |
| **t-end** | lesson end time |
#### example
| **classId** | **fromDay** | **content** |
| ----------- | ----------- | ----------------------------------------------- |
| `9BPLETNEV` | `20-10-25` | `[{"num":1, "t-begin:"9:00", t-end:"9:40"}...]` |
# api
## `/req_schedule` **POST**
returns ready to show schedule
#### req
`classId, date`
#### res
`{"num":1, "subject":'физека🤬', "cabinet": 209, "t-begin":"9:00", "t-begin": "9:40"}`
+88
View File
@@ -0,0 +1,88 @@
<?php
/** @param callable(_K_Api): void $apiFun */
function CreateApi(callable $apiFun)
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
$api = new _K_Api();
$apiFun($api);
$api->end();
}
class _K_Api
{
private $has_exec = false;
/** @param callable(_K_ApiRequest): string|array|int|float|bool $fun */
public function on(string $route, string $method, callable $fun)
{
$request_url = (count($_GET) > 0 ? array_keys($_GET)[0] : '');
$r = str_starts_with($route, '/') ? substr($route, 1) : $route;
if ($r != $request_url) {
return;
} else {
$this->has_exec = true;
if ($_SERVER['REQUEST_METHOD'] != $method) {
http_response_code(405);
die("ERROR: unsupported method ($method available)");
return;
}
$data = [];
if ($method == 'GET' && count($_GET) > 1) {
$data = array_slice(array_keys($_GET), 1);
} else if ($method == 'POST' && count($_POST) > 0) {
$data = $_POST;
}
$fun = $fun(new _K_ApiRequest($data));
if (is_string($fun) || is_numeric($fun)) {
if (json_validate($fun) && !is_numeric($fun)) {
Header('Content-Type: application/json');
}
echo $fun;
} else if (is_array($fun) || is_bool($fun)) {
Header('Content-Type: application/json');
echo json_encode($fun);
} else {
die("ERROR: unknown return type");
}
}
}
public function end()
{
if (!$this->has_exec) {
http_response_code(404);
echo '404';
}
}
}
class _K_ApiRequest
{
public array $data;
public _K_ApiResponse $res;
public function __construct(array $data)
{
$this->data = $data;
$this->res = new _K_ApiResponse($this);
}
public function hasData(array $dataArr)
{
foreach ($dataArr as $i) {
if (!isset($this->data[$i])) {
return false;
}
}
return true;
}
}
class _K_ApiResponse
{
public function __construct($req) {}
public function code(int $httpCode)
{
http_response_code($httpCode);
}
}
+1
View File
@@ -0,0 +1 @@
<?php phpinfo();