openvk/Web/Models/Entities/Postable.php

220 lines
6.1 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2020-06-07 19:04:43 +03:00
namespace openvk\Web\Models\Entities;
2020-06-07 19:04:43 +03:00
use openvk\Web\Util\DateTime;
use openvk\Web\Models\RowModel;
use openvk\Web\Models\Entities\User;
use openvk\Web\Models\Repositories\Users;
use openvk\Web\Models\Repositories\Clubs;
use openvk\Web\Models\Repositories\Comments;
use Chandler\Database\DatabaseConnection as DB;
use Nette\InvalidStateException as ISE;
use Nette\Database\Table\Selection;
abstract class Postable extends Attachable
{
use Traits\TAttachmentHost;
use Traits\TOwnable;
2020-06-07 19:04:43 +03:00
/**
* Column name, that references to an object, that
* is hieararchically higher than this Postable.
*
2020-06-07 19:04:43 +03:00
* For example: Images belong to User, but Posts belong to Wall.
* Formally users still own posts, but walls also own posts and they are
* their direct parent.
*
2020-06-07 19:04:43 +03:00
* @var string
*/
protected $upperNodeReferenceColumnName = "owner";
2020-06-07 19:04:43 +03:00
private function getTable(): Selection
{
return DB::i()->getContext()->table($this->tableName);
}
public function getOwner(bool $real = false): RowModel
2020-06-07 19:04:43 +03:00
{
$oid = (int) $this->getRecord()->owner;
if (!$real && $this->isAnonymous()) {
Groups: Wall: add suggestions (#935) * Wall: add early suggestions * Fix br * Fix empty posts * fck * Add offset for api * Add notifications of new suggestion posts * Fix mentions in suggested posts * 🤮🤢 * Change regex Теперь оно удаляет все теги а не только <br> * Add da koroche pohuy * Эдд апи метходс Методы нестандартные немного * Pon * Add skloneniyia * newlines * int * Update loaders and add avtopodgruzka postov * Update JOERGK.strings * Blin * Remove repeated code, fix loaded buttons on chr... ...ome and fix getting suggested posts via API.Wall.getPost * Fix polls * Fihes Теперь уведомление о принятии поста не приходит, если вы приняли свой же пост Пофикшен баг перехода в предложку Добавлен старый вид постов в предложке Теперь счётчик постов в предложке у прикреплённой группы обновляется при принятии или отклонении поста Убрано всплывающее уведомление об отклонении поста (оно раздражает) Теперь если вы посмотрели все посты на одной странице (не на первой) и на ней не осталось постов, вас телепортирует на предыдущую страницу * Remove ability to delete your accepted psto * oi blin * Improvements 2 api * g * openvk.uk Возможно, приведение кода к кодстайлу (удаление скобочек то есть) * aiaks * al_wall.js -> al_suggestions.js * 👨‍💻 Add 👨‍💻 fading 👨‍💻 * Add "owner's posts' and "other's posts" Давайте рофлить👨‍💻👨‍💻👨‍💻 * planshet openvk Add tabs for post view, add signer's object in wall get and add person icon in microblog * Simplefai ze kod * PHP 8 FIX WATAFAK * Add indesk
2023-11-16 19:44:12 +03:00
$oid = (int) OPENVK_ROOT_CONF["openvk"]["preferences"]["wall"]["anonymousPosting"]["account"];
}
$oid = abs($oid);
if ($oid > 0) {
return (new Users())->get($oid);
} else {
return (new Clubs())->get($oid * -1);
}
2020-06-07 19:04:43 +03:00
}
public function getVirtualId(): int
2020-06-07 19:04:43 +03:00
{
return $this->getRecord()->virtual_id;
}
public function getPrettyId(): string
2020-06-07 19:04:43 +03:00
{
return $this->getRecord()->owner . "_" . $this->getVirtualId();
}
public function getPublicationTime(): DateTime
2020-06-07 19:04:43 +03:00
{
return new DateTime($this->getRecord()->created);
}
public function getEditTime(): ?DateTime
2020-06-07 19:04:43 +03:00
{
$edited = $this->getRecord()->edited;
if (is_null($edited)) {
return null;
}
2020-06-07 19:04:43 +03:00
return new DateTime($edited);
}
public function getComments(int $page, ?int $perPage = null): \Traversable
2020-06-07 19:04:43 +03:00
{
return (new Comments())->getCommentsByTarget($this, $page, $perPage);
2020-06-07 19:04:43 +03:00
}
public function getCommentsCount(): int
2020-06-07 19:04:43 +03:00
{
return (new Comments())->getCommentsCountByTarget($this);
2020-06-07 19:04:43 +03:00
}
2021-11-28 14:39:42 +03:00
public function getLastComments(int $count): \Traversable
2020-08-01 17:23:08 +03:00
{
return (new Comments())->getLastCommentsByTarget($this, $count);
2020-08-01 17:23:08 +03:00
}
public function getLikesCount(): int
2020-06-07 19:04:43 +03:00
{
return sizeof(DB::i()->getContext()->table("likes")->where([
"model" => static::class,
"target" => $this->getRecord()->id,
])->group("origin"));
2020-06-07 19:04:43 +03:00
}
public function getLikers(int $page = 1, ?int $perPage = null): \Traversable
{
$perPage ??= OPENVK_DEFAULT_PER_PAGE;
$sel = DB::i()->getContext()->table("likes")->where([
"model" => static::class,
"target" => $this->getRecord()->id,
])->page($page, $perPage);
foreach ($sel as $like) {
$user = (new Users())->get($like->origin);
if ($user->isPrivateLikes() && OPENVK_ROOT_CONF["openvk"]["preferences"]["wall"]["anonymousPosting"]["enable"]) {
$user = (new Users())->get((int) OPENVK_ROOT_CONF["openvk"]["preferences"]["wall"]["anonymousPosting"]["account"]);
}
yield $user;
}
}
public function getAccessKey(): string
{
return $this->getRecord()->access_key;
}
public function checkAccessKey(?string $access_key): bool
{
if ($this->getAccessKey() === $access_key) {
return true;
}
return !$this->isPrivate();
}
public function isPrivate(): bool
{
return (bool) $this->getRecord()->unlisted;
}
public function isAnonymous(): bool
2021-11-15 22:45:48 +03:00
{
return (bool) $this->getRecord()->anonymous;
}
public function toggleLike(User $user): bool
2020-06-07 19:04:43 +03:00
{
$searchData = [
"origin" => $user->getId(),
"model" => static::class,
"target" => $this->getRecord()->id,
];
if (sizeof(DB::i()->getContext()->table("likes")->where($searchData)) > 0) {
2020-06-07 19:04:43 +03:00
DB::i()->getContext()->table("likes")->where($searchData)->delete();
return false;
}
DB::i()->getContext()->table("likes")->insert($searchData);
return true;
}
public function setLike(bool $liked, User $user): void
{
$searchData = [
"origin" => $user->getId(),
"model" => static::class,
"target" => $this->getRecord()->id,
];
if ($liked) {
if (!$this->hasLikeFrom($user)) {
DB::i()->getContext()->table("likes")->insert($searchData);
}
} else {
if ($this->hasLikeFrom($user)) {
DB::i()->getContext()->table("likes")->where($searchData)->delete();
}
}
2020-06-07 19:04:43 +03:00
}
public function hasLikeFrom(User $user): bool
2020-06-07 19:04:43 +03:00
{
$searchData = [
"origin" => $user->getId(),
"model" => static::class,
"target" => $this->getRecord()->id,
];
2020-06-07 19:04:43 +03:00
return sizeof(DB::i()->getContext()->table("likes")->where($searchData)) > 0;
}
public function setVirtual_Id(int $id): void
2020-06-07 19:04:43 +03:00
{
throw new ISE("Setting virtual id manually is forbidden");
}
public function save(?bool $log = false): void
2020-06-07 19:04:43 +03:00
{
$vref = $this->upperNodeReferenceColumnName;
2020-06-07 19:04:43 +03:00
$vid = $this->getRecord()->{$vref} ?? $this->changes[$vref];
if (!$vid) {
2020-06-07 19:04:43 +03:00
throw new ISE("Can't presist post due to inability to calculate it's $vref post count. Have you set it?");
}
2020-06-07 19:04:43 +03:00
$pCount = sizeof($this->getTable()->where($vref, $vid));
if (is_null($this->getRecord())) {
2020-06-07 19:04:43 +03:00
# lol allow ppl to taint created value
if (!isset($this->changes["created"])) {
2020-06-07 19:04:43 +03:00
$this->stateChanges("created", time());
}
2020-06-07 19:04:43 +03:00
$this->stateChanges("virtual_id", $pCount + 1);
} /*else {
2020-06-07 19:04:43 +03:00
$this->stateChanges("edited", time());
}*/
[WIP] Textarea: Upload multiple pictures (#800) * VKAPI: Fix bug when DELETED user appear if there is no user_ids * Textarea: Make multiple attachments * постмодернистское искусство * Use only attachPic for grabbing pic attachments TODO throw flashFail on bruh moment with pic attachments * draft masonry picture layout in posts xddd где мои опиаты??? * fix funny typos in computeMasonryLayout * Fix video bruh moment in textarea * Posts: add multiple kakahi for microblog * Photo: Add minimal implementation of миниатюра открывашка Co-authored-by: Daniel <60743585+myslivets@users.noreply.github.com> * Photo: Add ability to slide trough photos in one post This also gives ability to easily implement comments and actions * Photo: The Fxck Is This implementation of comments under photo in viewer * FloatingPhotoViewer: Better CSS - Fix that details background issue - Make slide buttons slightly shorter by height * FloatingPhotoViewer: Refactor, and make it better - Now you can actually check the comments under EVERY photo - Fix for textarea. Now you can publish comments * Fix funny typos xddd * Kinda fix poll display in non-microblog posts * Posts: Fix poll display in microblog posts * Add photos picker (#986) * early implementation of photos pickir Добавлен пикер фоточек и быстрая загрузка фото. Так же пофикшен просмотрщик фото в группах. Но, правда, я сломал копипейст, но это ладн. * Fiks fotos viver four coments. * Add picking photos from clubs albums Копипейст и граффити так и не пофикшены * Fix graffiti and copypaste Какого-то хуя копипаста у постов срабатывает два раза. * some fixesx * dragon drop * Fix PHP 8 compatibility * 5 (#988) --------- Co-authored-by: celestora <kitsuruko@gmail.com> Co-authored-by: Daniel <60743585+myslivets@users.noreply.github.com> Co-authored-by: lalka2016 <99399973+lalka2016@users.noreply.github.com> Co-authored-by: Alexander Minkin <weryskok@gmail.com>
2023-10-03 19:40:13 +03:00
parent::save($log);
2020-06-07 19:04:43 +03:00
}
}