final update

This commit is contained in:
themohooks 2024-10-16 17:16:21 +03:00
parent 42730bac08
commit 63b5c43ba4
11 changed files with 324 additions and 224 deletions

View file

@ -15,15 +15,19 @@ class GetVehicleInputs
$id = explode('/', $_SERVER['REQUEST_URI'])[4]; $id = explode('/', $_SERVER['REQUEST_URI'])[4];
$vehicle = DB::query('SELECT * FROM entities WHERE id=:id', array(':id' => $id))[0]; $vehicle = DB::query('SELECT * FROM entities WHERE id=:id', array(':id' => $id))[0];
$data = json_decode($vehicle['sampledata'], true); $data = json_decode($vehicle['sampledata'], true);
$count = 1;
foreach ($data as $d) { foreach ($data as $d) {
if ($d['important'] === "1") { if ($d['important'] === "1") {
$imp = 'required'; $imp = 'required';
} }
echo ' echo '
<div class="mb-3"> <div class="mt-3">
<label for="exampleFormControlInput1" class="form-label">' . $d['name'] . '</label> <label for="exampleFormControlInput1" class="form-label">' . $d['name'] . '</label>
<input type="text" name="title" class="form-control" id="exampleFormControlInput1" placeholder="'.$d['name'].'" '.$imp.'> <input type="text" name="modelinput_'.$count.'" class="form-control" id="exampleFormControlInput1" placeholder="'.$d['name'].'" '.$imp.'>
</div>'; </div>';
} $count++;
}
} }
} }

View file

@ -21,6 +21,9 @@ class Upload
static $showtop = 'allowed'; static $showtop = 'allowed';
static $subsnotify = 'allowed'; static $subsnotify = 'allowed';
static $exif = 'exif'; static $exif = 'exif';
static $entitydata_id = 0;
static $entityroute = NULL;
static $entitycomment = NULL;
public static function create($postbody, $content, $exif) public static function create($postbody, $content, $exif)
{ {
@ -34,7 +37,7 @@ class Upload
} else { } else {
$moderated = 1; $moderated = 1;
} }
DB::query('INSERT INTO photos VALUES (\'0\', :userid, :postbody, :photourl, :time, :timeup, :exif, 0, :moderated, :place, 0, :gallery, :content)', array(':postbody' => $postbody, ':userid' => Auth::userid(), ':time' => mktime(0, 0, 0, $_POST['month'], $_POST['day'], $_POST['year']), ':content' => $content, ':photourl' => self::$photourl, ':exif' => $exif, ':place' => $_POST['place'], ':timeup' => time(), ':moderated' => $moderated, ':gallery'=>$_POST['gallery'])); DB::query('INSERT INTO photos VALUES (\'0\', :userid, :postbody, :photourl, :time, :timeup, :exif, 0, :moderated, :place, 0, :gallery, :entityid, :content)', array(':postbody' => $postbody, ':userid' => Auth::userid(), ':time' => mktime(0, 0, 0, $_POST['month'], $_POST['day'], $_POST['year']), ':content' => $content, ':photourl' => self::$photourl, ':exif' => $exif, ':place' => $_POST['place'], ':timeup' => time(), ':moderated' => $moderated, ':gallery'=>$_POST['gallery'], ':entityid'=>self::$entitydata_id));
if (($moderated === 1) && (self::$subsnotify != 'disabled')) { if (($moderated === 1) && (self::$subsnotify != 'disabled')) {
$followers = DB::query('SELECT * FROM followers WHERE user_id=:uid', array(':uid' => Auth::userid())); $followers = DB::query('SELECT * FROM followers WHERE user_id=:uid', array(':uid' => Auth::userid()));
foreach ($followers as $f) { foreach ($followers as $f) {
@ -150,6 +153,15 @@ class Upload
if ((int)$_POST['disableexif'] === 1) { if ((int)$_POST['disableexif'] === 1) {
self::$exif = 'disabled'; self::$exif = 'disabled';
} }
if ((int)$_POST['nid'] >= 1) {
if (DB::query('SELECT id FROM entities_data WHERE id=:id', array(':id'=>$_POST['nid']))[0]['id']) {
self::$entitydata_id = $_POST['nid'];
self::$entityroute = $_POST["route[".$_POST['nid']."]"];
self::$entitycomment = $_POST["notes[".$_POST['nid']."]"];
} else {
return;
}
}
if ($upload->getType() !== null) { if ($upload->getType() !== null) {
$content = Json::return( $content = Json::return(
array( array(
@ -162,6 +174,8 @@ class Upload
'comments' => self::$comments, 'comments' => self::$comments,
'rating' => self::$rating, 'rating' => self::$rating,
'showtop' => self::$showtop, 'showtop' => self::$showtop,
'entityroute' => self::$entityroute,
'entitycomment' => self::$entitycomment
) )
); );
if (explode('/', $type)[0] === 'video') { if (explode('/', $type)[0] === 'video') {

View file

@ -27,7 +27,7 @@ class Load
<tr> <tr>
<td style="padding:10px"><a href="/vehicle/'.$e['id'].'" target="_blank" class="num pcnt">'.$e['id'].'</a> <td style="padding:10px"><a href="/vehicle/'.$e['id'].'" target="_blank" class="num pcnt">'.$e['id'].'</a>
</td> </td>
<td style="padding:10px; font-size:16px" class="mname">hhhhh</td> <td style="padding:10px; font-size:16px" class="mname">'.$e['title'].'</td>
<td style="padding:10px" class="d"> <td style="padding:10px" class="d">
'.$e['comment'].' '.$e['comment'].'
</td> </td>

View file

@ -9,7 +9,7 @@ class Vehicle {
$this->userid = $user_id; $this->userid = $user_id;
} }
public function i($table) { public function i($table) {
return DB::query("SELECT * FROM entities_data WHERE id=:id", array(':id'=>$this->userid))[0][$table]; return DB::query("SELECT * FROM entities WHERE id=:id", array(':id'=>$this->userid))[0][$table];
} }
public function getvehicle($table) { public function getvehicle($table) {
return DB::query("SELECT * FROM entities WHERE id=:id", array(':id'=>self::i('entityid')))[0][$table]; return DB::query("SELECT * FROM entities WHERE id=:id", array(':id'=>self::i('entityid')))[0][$table];

View file

@ -77,26 +77,18 @@ class Upload
} }
else else
{ {
echo $tmpname; $location = "your-location";
$location = "your-location"; // Название локации $folder = "{$location}/" . basename($tmpname);
$folder = "{$location}/" . basename($tmpname); // Создаем корректное имя для папки с файлом
$uploadDir = "{$_SERVER['DOCUMENT_ROOT']}/uploads/{$location}"; // Полный путь к директории $uploadDir = "{$_SERVER['DOCUMENT_ROOT']}/uploads/{$location}";
// Создание директории, если она не существует
if (!is_dir($uploadDir)) { if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true); mkdir($uploadDir, 0777, true);
} }
// Путь к файлу, куда он должен быть перемещен
$destination = "{$uploadDir}/" . basename($tmpname); $destination = "{$uploadDir}/" . basename($tmpname);
// Перемещение файла
if (move_uploaded_file($tmpname, $destination)) {
echo "Файл успешно перемещен!";
} else {
echo "Ошибка при перемещении файла.";
}
$this->type = $type; $this->type = $type;
$this->src = "/uploads/{$folder}"; $this->src = "/uploads/{$folder}";

View file

@ -121,10 +121,10 @@ $(document).ready(function()
var html = '<tbody data-nid="' + nid + '" data-vid="' + vid + '" data-twoside="' + $(this).data('twoside') + '" class="s' + $(this).data('state') + '">\n'; var html = '<tbody data-nid="' + nid + '" data-vid="' + vid + '" data-twoside="' + $(this).data('twoside') + '" class="s' + $(this).data('state') + '">\n';
html += '<tr>\n'; html += '<tr>\n';
html += '<td style="padding:3px 10px 5px"><input type="hidden" name="nids[]" value="' + nid + '"><input type="hidden" name="cids[]" value="' + cid + '"><a href="' + (nid > 0 ? '/vehicle/' + vid : '/lk/vehicles.php?action=edit&amp;vid=' + (-nid)) + '" target="_blank" class="num pcnt">' + $('.num', this).html() + '</a></td>\n'; html += '<td style="padding:3px 10px 5px"><input type="hidden" name="nid" value="' + vid + '"><input type="hidden" name="cids[]" value="' + cid + '"><a href="' + (nid > 0 ? '/vehicle/' + vid : '/lk/vehicles.php?action=edit&amp;vid=' + (-nid)) + '" target="_blank" class="num pcnt">' + $('.num', this).html() + '</a></td>\n';
html += '<td style="padding:3px 10px 6px">' + $('.mname', this).html() + '</td>\n'; html += '<td style="padding:3px 10px 6px">' + $('.mname', this).html() + '</td>\n';
html += '<td style="padding:3px 0 6px 10px; color:#777" class="r">' + _text['UP_ROUTE'] + ':</td>\n'; html += '<td style="padding:3px 0 6px 10px; color:#777" class="r">' + _text['UP_ROUTE'] + ':</td>\n';
html += '<td style="padding:3px 7px" class="nw"><input type="text" class="route" name="route[' + nid + ']" style="width:40px; font-weight:bold; text-align:center" maxlength="7" value="">, <input type="text" class="notes" name="notes[' + nid + ']" style="width:170px" maxlength="100" value="" placeholder="' + _text['UP_NOTES'] + '"></td>\n'; html += '<td style="padding:3px 7px" class="nw"><input type="text" class="route" name="route[' + vid + ']" style="width:40px; font-weight:bold; text-align:center" maxlength="7" value="">, <input type="text" class="notes" name="notes[' + vid + ']" style="width:170px" maxlength="100" value="" placeholder="' + _text['UP_NOTES'] + '"></td>\n';
html += '<td class="r"><a href="#" class="delLink" style="font-size:16px">&times;</a></td>\n'; html += '<td class="r"><a href="#" class="delLink" style="font-size:16px">&times;</a></td>\n';
html += '</tr>\n'; html += '</tr>\n';

View file

@ -7,37 +7,41 @@ use \App\Models\{User, Vehicle};
$vehicle = DB::query('SELECT * FROM entities WHERE id=:id', array(':id' => $_GET['id']))[0]; $vehicle = DB::query('SELECT * FROM entities WHERE id=:id', array(':id' => $_GET['id']))[0];
if (isset($_POST['create'])) { if (isset($_POST['create'])) {
$postData = $_POST;
$inputs = $_POST;
$filteredInputs = [];
foreach ($inputs as $key => $value) {
if (strpos($key, 'modelinput_') === 0) {
$filteredInputs[$key] = $value;
}
}
ksort($filteredInputs);
$result = []; $result = [];
foreach ($postData as $key => $value) { $counter = 1;
if (strpos($key, 'variable') === 0) {
preg_match('/_(\d+)$/', $key, $matches);
if (isset($matches[1])) {
$index = $matches[1];
if (!isset($result[$index])) { foreach ($filteredInputs as $key => $value) {
$result[$index] = []; $result[$counter] = [
'value' => $value
];
$counter++;
} }
$newKey = preg_replace('/^variable/', '', $key); $jsonResult = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$newKey = preg_replace('/_\d+$/', '', $newKey);
$result[$index][$newKey] = $value;
}
}
}
$jsonResult = json_encode($result, JSON_PRETTY_PRINT); DB::query('INSERT INTO entities_data VALUES (\'0\', :title, :createdate, :entityid, :comment, :content)', array(':title' => $_POST['title'], ':createdate'=>time(), ':entityid' => $_POST['entityid'], ':content' => $jsonResult, ':comment' => $_POST['comment']));
header('Location: /admin?type=Models');
DB::query('INSERT INTO entities VALUES (\'0\', :title, :createdate, :sampledata, :color)', array(':title' => $_POST['title'], ':createdate' => time(), ':sampledata' => $jsonResult, ':color' => $_POST['color']));
header('Location: /admin?type=Entities');
} }
?> ?>
<h1><b>Создание модели</b></h1> <h1><b>Создание модели</b></h1>
<form action="/admin?type=ModelsCreate" method="post" name="form" id="form" enctype="multipart/form-data" style="display:inline-block; min-width:500px;">
<div id="inputsMain">
<label>Сущность</label> <label>Сущность</label>
<select id="entitySelect" class="form-select" aria-label="Default select example">
<option selected disabled>Выберите сущность</option> <select name="entityid" id="entitySelect" class="form-select" aria-label="Default select example" required>
<option selected disabled value="">Выберите сущность</option>
<?php <?php
$datad = DB::query('SELECT * FROM entities'); $datad = DB::query('SELECT * FROM entities');
foreach ($datad as $d) { foreach ($datad as $d) {
@ -47,11 +51,22 @@ if (isset($_POST['create'])) {
</select> </select>
<form action="/admin?type=EntityCreate" method="post" name="form" id="form" enctype="multipart/form-data" style="display:inline-block; min-width:500px;">
<div class="mt-3">
<label for="exampleFormControlInput1" class="form-label">Название</label>
<input type="text" name="title" class="form-control" id="exampleFormControlInput1" required="">
</div>
<div class="mt-3">
<label for="exampleFormControlInput1" class="form-label">Описание</label>
<input type="text" name="comment" class="form-control" id="exampleFormControlInput1" required="">
</div>
</div>
<div id="mainContent">
</div>
<button id="addButton" type="submit" name="create" class="btn btn-primary mt-5">Добавить модель</button>
</form> </form>
@ -68,10 +83,10 @@ if (isset($_POST['create'])) {
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) { if (xhr.status === 200) {
document.getElementById('form').innerHTML = ''; document.getElementById('mainContent').innerHTML = '';
document.getElementById('form').innerHTML = '<button id="addButton" type="submit" name="create" class="btn btn-primary mt-5">Добавить модель</button>'; document.getElementById('mainContent').innerHTML = '<button id="addButton" type="submit" name="create" class="btn btn-primary mt-5">Добавить модель</button>';
document.getElementById('form').insertAdjacentHTML('afterbegin', xhr.responseText); document.getElementById('mainContent').insertAdjacentHTML('afterbegin', xhr.responseText);
} else { } else {
console.error('Ошибка при загрузке данных:', xhr.statusText); console.error('Ошибка при загрузке данных:', xhr.statusText);

View file

@ -1,7 +1,7 @@
<?php <?php
use App\Services\{DB, Auth, Date, Json}; use App\Services\{DB, Auth, Date, Json};
use App\Models\{User, Vote, Comment}; use App\Models\{User, Vote, Comment, Vehicle};
$id = explode('/', $_SERVER['REQUEST_URI'])[2]; $id = explode('/', $_SERVER['REQUEST_URI'])[2];
$photo = new \App\Models\Photo($id); $photo = new \App\Models\Photo($id);
@ -15,6 +15,10 @@ if ($photo->i('id') !== null) {
} }
$photouser = new \App\Models\User($photo->i('user_id')); $photouser = new \App\Models\User($photo->i('user_id'));
$user = new \App\Models\User(Auth::userid()); $user = new \App\Models\User(Auth::userid());
if ($photo->i('entitydata_id') >= 1) {
$entitydata = DB::query('SELECT * FROM entities_data WHERE id=:id', array(':id' => $photo->i('entitydata_id')))[0];
$vehicle = new Vehicle($entitydata['entityid']);
}
if ($photo->i('moderated') === 0) { if ($photo->i('moderated') === 0) {
if ($photo->i('user_id') === Auth::userid() || $user->i('admin') > 0) { if ($photo->i('user_id') === Auth::userid() || $user->i('admin') > 0) {
$moderated = true; $moderated = true;
@ -181,6 +185,16 @@ if ($photo->i('id') !== null) {
?> ?>
</div> </div>
</div> </div>
<?php
if ((int)$photo->i('entitydata_id') >= 1) { ?>
<tr>
<td class="nw" valign="top" align="right"><a href="/vehicle/<?= $photo->i('entitydata_id') ?>"><?= $entitydata['title'] ?></a></td>
<td class="nw" align="left" valign="top">&nbsp; &nbsp;маршрут <b><?= $photo->content('entityroute') ?></b></td>
</tr>
<?php } ?>
<div> <div>
<?php <?php
if ($photo->content('comment') != null) { ?> if ($photo->content('comment') != null) { ?>
@ -194,7 +208,7 @@ if ($photo->i('id') !== null) {
$date = Date::zmdate($photo->i('posted_at')); $date = Date::zmdate($photo->i('posted_at'));
} }
?> ?>
<div>Прислал <a href="/author/<?= $photo->i('user_id') ?>/"><?= $photouser->i('username') ?></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Дата: <b><?= $date ?></b></div> <div>Автор: <a href="/author/<?= $photo->i('user_id') ?>/"><?= $photouser->i('username') ?></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Дата: <b><?= $date ?></b></div>
<table id="pp-items"> <table id="pp-items">
<tr> <tr>
<td id="pp-left-col"> <td id="pp-left-col">
@ -241,8 +255,8 @@ if ($photo->i('id') !== null) {
<a href="#" vote="0" class="vote_btn <?php if (Vote::photo(Auth::userid(), $id) === 0) { <a href="#" vote="0" class="vote_btn <?php if (Vote::photo(Auth::userid(), $id) === 0) {
echo 'voted'; echo 'voted';
} ?>"><span>Мне не&nbsp;нравится</span></a> } ?>"><span>Мне не&nbsp;нравится</span></a>
<a class="konk_btn" vote="1" href="#" ><span>Красиво, на&nbsp;конкурс!</span></a> <!--a class="konk_btn" vote="1" href="#"><span>Красиво, на&nbsp;конкурс!</span></!--a>
<a href="#" vote="0" class="konk_btn"><span>Неконкурсное фото</span></a> <a-- href="#" vote="0" class="konk_btn"><span>Неконкурсное фото</span></a-->
</div> </div>
<?php } ?> <?php } ?>
<div id="votes" class="votes"> <div id="votes" class="votes">
@ -304,9 +318,41 @@ if ($photo->i('id') !== null) {
} }
</style> </style>
<td id="pp-main-col"> <td id="pp-main-col">
<?php
if ($photo->i('entitydata_id') >= 1) { ?>
<div id="pp-item-vdata">
<div class="p0">
<h4 class="pp-item-header"><b><a href="/vehicle/<?= $photo->i('entitydata_id') ?>"><?= $entitydata['title'] ?></a></b></h4>
<div class="pp-item-body">
<table class="linetable">
<colgroup>
<col width="25%">
</colgroup>
<tbody>
<?php
$vehiclevariables = json_decode($vehicle->i('sampledata'), true);
$vehicledatavariables = json_decode($vehicle->i('content'), true);
$num = 1;
foreach ($vehiclevariables as $vb) {
echo ' <tr class="s11 h21">
<td class="ds nw">' . $vb['name'] . ':</td>
<td class="ds"><b>' . $vehicledatavariables[$num]['value'] . '</b></td>
</tr>';
$num++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php } ?>
<div id="pp-item-vdata"> <div id="pp-item-vdata">
<?php <?php
if (($photo->content('type') != 'none') && (json_decode($photo->i('exif'), true)['type'] != 'none') && ($photo->content('rating') != 'disabled')) { if (($photo->content('type') != 'none') && (json_decode($photo->i('exif'), true)['type'] != 'none') && ($photo->content('rating') != 'disabled') && ($photo->i('exif') != NULL)) {
?> ?>
<div class="p0" id="pp-item-exif"> <div class="p0" id="pp-item-exif">
<div class="header-container"> <div class="header-container">
@ -369,7 +415,8 @@ if ($photo->i('id') !== null) {
'GPS.GPSTimeStamp' => 'Время GPS', 'GPS.GPSTimeStamp' => 'Время GPS',
'GPS.GPSDateStamp' => 'Дата GPS' 'GPS.GPSDateStamp' => 'Дата GPS'
]; ];
function translate_flash_value($flash_value) { function translate_flash_value($flash_value)
{
$flash_descriptions = [ $flash_descriptions = [
0 => 'Выключена', 0 => 'Выключена',
1 => 'Включена', 1 => 'Включена',
@ -493,6 +540,7 @@ if ($photo->i('id') !== null) {
</div> </div>
</div> </div>
<?php } ?> <?php } ?>
<?php <?php
if ($photo->content('lat') != null && $photo->content('lng') != null) { ?> if ($photo->content('lat') != null && $photo->content('lng') != null) { ?>
<div class="p0" id="pp-item-exif"> <div class="p0" id="pp-item-exif">

View file

@ -39,7 +39,7 @@ foreach ($photos as $pd) {
<td style="text-align:center; padding:10px"><b style="font-size:25px">'.$top.'</b><br><br><small>Новых просмотров:</small><br><b>+'.$pd['view_count'].'</b><br><br> <td style="text-align:center; padding:10px"><b style="font-size:25px">'.$top.'</b><br><br><small>Новых просмотров:</small><br><b>+'.$pd['view_count'].'</b><br><br>
</td> </td>
<td class="pb_photo" id="p1977446"><a href="/photo/1977446/" target="_blank" class="prw"><img class="f" src="'.$p['photourl'].'" alt="347 КБ"> <td class="pb_photo" id="p1977446"><a href="/photo/'.$p['id'].'/" target="_blank" class="prw"><img class="f" src="'.$p['photourl'].'" alt="347 КБ">
</a></td> </a></td>
<td class="pb_descr"> <td class="pb_descr">

View file

@ -1,7 +1,7 @@
<?php <?php
use \App\Services\{Auth, DB, Date}; use \App\Services\{Auth, DB, Date};
use \App\Models\Vehicle; use \App\Models\{Vehicle, User};
$id = explode('/', $_SERVER['REQUEST_URI'])[2]; $id = explode('/', $_SERVER['REQUEST_URI'])[2];
$data = DB::query('SELECT * FROM entities_data WHERE id=:id', array(':id' => $id))[0]; $data = DB::query('SELECT * FROM entities_data WHERE id=:id', array(':id' => $id))[0];
@ -34,7 +34,7 @@ $vehicledatavariables = json_decode($data['content'], true);
<col width="150"> <col width="150">
<col> <col>
<?php <?php
$vehiclevariables = json_decode($vehicle->getvehicle('sampledata'), true); $vehiclevariables = json_decode($vehicle->i('sampledata'), true);
$num = 1; $num = 1;
foreach ($vehiclevariables as $vb) { foreach ($vehiclevariables as $vb) {
echo '<tr class="h21"><td class="ds nw">' . $vb['name'] . ':</td><td class="d"><b>' . $vehicledatavariables[$num]['value'] . '</b></td></tr>'; echo '<tr class="h21"><td class="ds nw">' . $vb['name'] . ':</td><td class="d"><b>' . $vehicledatavariables[$num]['value'] . '</b></td></tr>';
@ -44,6 +44,28 @@ $vehicledatavariables = json_decode($data['content'], true);
</table><br> </table><br>
<?php
$photos = DB::query('SELECT * FROM photos WHERE entitydata_id=:id', array(':id'=>$id));
foreach ($photos as $p) {
$author = new User($p['user_id']);
echo '<div class="p20p s11"><table><tbody><tr>
<td class="pb_photo" id="p1987895"><a href="/photo/1987895/ target="_blank" class="prw"><img class="f" src="/api/photo/compress?url='.$p['photourl'].'" alt="678 КБ">
<div class="hpshade">';
if (DB::query('SELECT COUNT(*) FROM photos_comments WHERE photo_id=:id', array(':id'=>$p['id']))[0]['COUNT(*)'] >= 1) {
echo '<div class="com-icon">'.DB::query('SELECT COUNT(*) FROM photos_comments WHERE photo_id=:id', array(':id'=>$p['id']))[0]['COUNT(*)'].'</div>';
}
echo '
<div class="eye-icon">'.DB::query('SELECT COUNT(*) FROM photos_views WHERE photo_id=:id', array(':id'=>$p['id']))[0]['COUNT(*)'].'</div></div>
</div></a></td>
<td class="pb_descr">
<p><b class="pw-place">'.htmlspecialchars($p['place']).'</b></p>
<span class="pw-descr">'.htmlspecialchars($p['postbody']).'</span>
<p class="sm"><b>'.Date::zmdate($p['timeupload']).'</b><br>Автор: <a href="/author/'.$author->i('user_id').'/">'.htmlspecialchars($author->i('username')).'</a></p>
</td>
</tr></tbody></table></div>';
}
?>

View file

@ -1,90 +1,95 @@
<?php
$rand = mt_rand(1, 12);
if ($rand === 1) {
$text = 'Что-то грядёт.';
} else if ($rand === 2) {
$text = 'Может, пора запустить СТТС Собаки?';
} else if ($rand === 3) {
$text = 'Не снижая обороты.';
} else if ($rand === 4) {
$text = 'Мы соскучились по твоим фотографиям.';
} else if ($rand === 5) {
$text = 'Хм-м...';
} else if ($rand === 6) {
$text = 'Весьма очень даже.';
} else if ($rand === 7) {
$text = 'Не забудь взять царских припасов с собой.';
} else if ($rand === 8) {
$text = 'Бобровы будут гордиться.ю';
} else if ($rand === 9) {
$text = 'Нельзя было стучаться, что-ли?';
} else if ($rand === 10) {
$text = 'Ха-ха.';
} else if ($rand === 11) {
$text = 'Недурно.';
} else if ($rand === 12) {
$text = '...';
}
?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="ru">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Face Detection with TensorFlow.js</title> <title>Таймер обратного отсчета</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,100..900;1,100..900&display=swap');
body {
font-family: Inter Tight !important;
}
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 100px;
}
#countdown {
font-size: 100px;
color: #333;
}
</style>
</head> </head>
<body> <body>
<h1>Face Detection using TensorFlow.js</h1> <center><img src="/static/img/sttslogo.png" width="500"></center>
<input type="file" id="imageUpload" accept="image/*"> <h1><?=$text?></h1>
<br><br> <div id="countdown">00:00:00</div>
<canvas style="width: 100px;" id="canvas"></canvas>
<br><br>
<div id="inputFields"></div> <!-- Контейнер для динамически создаваемых полей ввода -->
<br>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/blazeface"></script>
<script> <script>
// app.js function updateCountdown() {
const imageUpload = document.getElementById('imageUpload'); const now = new Date();
const canvas = document.getElementById('canvas'); const nowUtc = new Date(now.getTime() + now.getTimezoneOffset() * 60000); // Преобразуем текущее время в UTC
const ctx = canvas.getContext('2d');
const inputFieldsContainer = document.getElementById('inputFields');
// Переменная для хранения модели // Определяем текущее время в UTC+3 (МСК)
let model; const nowMoscow = new Date(nowUtc.setHours(nowUtc.getUTCHours() + 3));
// Функция для загрузки модели // Устанавливаем время окончания на 17:00 текущего дня по МСК
async function loadModel() { let targetTime = new Date(nowMoscow.getFullYear(), nowMoscow.getMonth(), nowMoscow.getDate(), 17, 0, 0);
model = await blazeface.load();
console.log("BlazeFace model loaded"); // Если текущее время уже прошло 17:00, устанавливаем на следующий день
if (nowMoscow >= targetTime) {
targetTime.setDate(targetTime.getDate() + 1);
} }
// Функция для распознавания лиц const timeDifference = targetTime - nowMoscow;
async function detectFaces(image) {
const predictions = await model.estimateFaces(image, false);
return predictions;
}
// Загрузка модели при инициализации if (timeDifference <= 0) {
loadModel(); location.reload(); // Перезагрузить страницу по истечению времени
imageUpload.addEventListener('change', async () => {
const file = imageUpload.files[0];
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = async () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// Очищаем предыдущие поля ввода
inputFieldsContainer.innerHTML = '';
// Используем кэшированную модель для распознавания
const predictions = await detectFaces(img);
if (predictions.length > 0) {
predictions.forEach((prediction, index) => {
// Получаем координаты лица
const [x, y, width, height] = prediction.topLeft.concat(prediction.bottomRight).flat();
// Рисуем рамку вокруг лица
ctx.beginPath();
ctx.rect(x, y, width - x, height - y);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.stroke();
// Добавляем номер лица на изображении
ctx.fillStyle = 'red';
ctx.font = '16px Arial';
ctx.fillText(`Лицо ${index + 1}`, x, y > 10 ? y - 10 : 10);
// Создаем поле ввода для каждого распознанного лица
const inputField = document.createElement('input');
inputField.type = 'text';
inputField.placeholder = `Информация о лице ${index + 1}`;
inputFieldsContainer.appendChild(inputField);
inputFieldsContainer.appendChild(document.createElement('br'));
});
} else { } else {
alert('No faces detected'); const hours = Math.floor((timeDifference / (1000 * 60 * 60)) % 24);
} const minutes = Math.floor((timeDifference / (1000 * 60)) % 60);
}; const seconds = Math.floor((timeDifference / 1000) % 60);
});
document.getElementById('countdown').textContent =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
}
setInterval(updateCountdown, 1000); // Обновляем каждую секунду
updateCountdown(); // Начальная установка
</script> </script>
</body> </body>
</html> </html>