diff --git a/ServiceAPI/Photos.php b/ServiceAPI/Photos.php
new file mode 100644
index 00000000..16d602f2
--- /dev/null
+++ b/ServiceAPI/Photos.php
@@ -0,0 +1,92 @@
+user = $user;
+ $this->photos = new PhotosRepo;
+ }
+
+ function getPhotos(int $page = 1, int $album = 0, callable $resolve, callable $reject)
+ {
+ if($album == 0) {
+ $photos = $this->photos->getEveryUserPhoto($this->user, $page, 24);
+ $count = $this->photos->getUserPhotosCount($this->user);
+ } else {
+ $album = (new Albums)->get($album);
+
+ if(!$album || $album->isDeleted())
+ $reject(55, "Invalid .");
+
+ if($album->getOwner() instanceof User) {
+ if($album->getOwner()->getId() != $this->user->getId())
+ $reject(555, "Access to album denied");
+ } else {
+ if(!$album->getOwner()->canBeModifiedBy($this->user))
+ $reject(555, "Access to album denied");
+ }
+
+ $photos = $album->getPhotos($page, 24);
+ $count = $album->size();
+ }
+
+ $arr = [
+ "count" => $count,
+ "items" => [],
+ ];
+
+ foreach($photos as $photo) {
+ $res = json_decode(json_encode($photo->toVkApiStruct()), true);
+
+ $arr["items"][] = $res;
+ }
+
+ $resolve($arr);
+ }
+
+ function getAlbums(int $club, callable $resolve, callable $reject)
+ {
+ $albumsRepo = (new Albums);
+
+ $count = $albumsRepo->getUserAlbumsCount($this->user);
+ $albums = $albumsRepo->getUserAlbums($this->user, 1, $count);
+
+ $arr = [
+ "count" => $count,
+ "items" => [],
+ ];
+
+ foreach($albums as $album) {
+ $res = ["id" => $album->getId(), "name" => $album->getName()];
+
+ $arr["items"][] = $res;
+ }
+
+ if($club > 0) {
+ $cluber = (new Clubs)->get($club);
+
+ if(!$cluber || !$cluber->canBeModifiedBy($this->user))
+ $reject(1337, "Invalid (club), or you can't modify him");
+
+ $clubCount = (new Albums)->getClubAlbumsCount($cluber);
+ $clubAlbums = (new Albums)->getClubAlbums($cluber, 1, $clubCount);
+
+ foreach($clubAlbums as $albumr) {
+ $res = ["id" => $albumr->getId(), "name" => $albumr->getName()];
+
+ $arr["items"][] = $res;
+ }
+
+ $arr["count"] = $arr["count"] + $clubCount;
+ }
+
+ $resolve($arr);
+ }
+}
diff --git a/ServiceAPI/Wall.php b/ServiceAPI/Wall.php
index 5677f7ba..787a998e 100644
--- a/ServiceAPI/Wall.php
+++ b/ServiceAPI/Wall.php
@@ -2,7 +2,7 @@
namespace openvk\ServiceAPI;
use openvk\Web\Models\Entities\Post;
use openvk\Web\Models\Entities\User;
-use openvk\Web\Models\Repositories\{Posts, Notes};
+use openvk\Web\Models\Repositories\{Posts, Notes, Videos};
class Wall implements Handler
{
@@ -15,6 +15,7 @@ class Wall implements Handler
$this->user = $user;
$this->posts = new Posts;
$this->notes = new Notes;
+ $this->videos = new Videos;
}
function getPost(int $id, callable $resolve, callable $reject): void
@@ -95,4 +96,45 @@ class Wall implements Handler
$resolve($arr);
}
+
+ function getVideos(int $page = 1, callable $resolve, callable $reject)
+ {
+ $videos = $this->videos->getByUser($this->user, $page, 8);
+ $count = $this->videos->getUserVideosCount($this->user);
+
+ $arr = [
+ "count" => $count,
+ "items" => [],
+ ];
+
+ foreach($videos as $video) {
+ $res = json_decode(json_encode($video->toVkApiStruct()), true);
+ $res["video"]["author_name"] = $video->getOwner()->getCanonicalName();
+
+ $arr["items"][] = $res;
+ }
+
+ $resolve($arr);
+ }
+
+ function searchVideos(int $page = 1, string $query, callable $resolve, callable $reject)
+ {
+ $dbc = $this->videos->find($query);
+ $videos = $dbc->page($page, 8);
+ $count = $dbc->size();
+
+ $arr = [
+ "count" => $count,
+ "items" => [],
+ ];
+
+ foreach($videos as $video) {
+ $res = json_decode(json_encode($video->toVkApiStruct()), true);
+ $res["video"]["author_name"] = $video->getOwner()->getCanonicalName();
+
+ $arr["items"][] = $res;
+ }
+
+ $resolve($arr);
+ }
}
diff --git a/VKAPI/Handlers/Wall.php b/VKAPI/Handlers/Wall.php
index ca65e961..61c75703 100644
--- a/VKAPI/Handlers/Wall.php
+++ b/VKAPI/Handlers/Wall.php
@@ -471,28 +471,25 @@ final class Wall extends VKAPIRequestHandler
if($attachmentType == "photo") {
$attacc = (new PhotosRepo)->getByOwnerAndVID($attachmentOwner, $attachmentId);
if(!$attacc || $attacc->isDeleted())
- $this->fail(100, "Photo does not exists");
- if($attacc->getOwner()->getId() != $this->getUser()->getId())
- $this->fail(43, "You do not have access to this photo");
+ $this->fail(100, "Invalid photo");
+ if(!$attacc->getOwner()->getPrivacyPermission('photos.read', $this->getUser()))
+ $this->fail(43, "Access to photo denied");
$post->attach($attacc);
} elseif($attachmentType == "video") {
$attacc = (new VideosRepo)->getByOwnerAndVID($attachmentOwner, $attachmentId);
if(!$attacc || $attacc->isDeleted())
$this->fail(100, "Video does not exists");
- if($attacc->getOwner()->getId() != $this->getUser()->getId())
- $this->fail(43, "You do not have access to this video");
+ if(!$attacc->getOwner()->getPrivacyPermission('videos.read', $this->getUser()))
+ $this->fail(43, "Access to video denied");
$post->attach($attacc);
} elseif($attachmentType == "note") {
$attacc = (new NotesRepo)->getNoteById($attachmentOwner, $attachmentId);
if(!$attacc || $attacc->isDeleted())
$this->fail(100, "Note does not exist");
- if($attacc->getOwner()->getId() != $this->getUser()->getId())
- $this->fail(43, "You do not have access to this note");
-
- if($attacc->getOwner()->getPrivacySetting("notes.read") < 1)
- $this->fail(11, "You can't attach note to post, because your notes list is closed. Change it in privacy settings in web-version.");
+ if(!$attacc->getOwner()->getPrivacyPermission('notes.read', $this->getUser()))
+ $this->fail(11, "Access to note denied");
$post->attach($attacc);
} elseif($attachmentType == "poll") {
@@ -695,7 +692,7 @@ final class Wall extends VKAPIRequestHandler
return $response;
}
- function createComment(int $owner_id, int $post_id, string $message, int $from_group = 0, string $attachments = "") {
+ function createComment(int $owner_id, int $post_id, string $message = "", int $from_group = 0, string $attachments = "") {
$this->requireUser();
$this->willExecuteWriteAction();
@@ -753,16 +750,16 @@ final class Wall extends VKAPIRequestHandler
$attacc = (new PhotosRepo)->getByOwnerAndVID($attachmentOwner, $attachmentId);
if(!$attacc || $attacc->isDeleted())
$this->fail(100, "Photo does not exists");
- if($attacc->getOwner()->getId() != $this->getUser()->getId())
- $this->fail(43, "You do not have access to this photo");
+ if(!$attacc->getOwner()->getPrivacyPermission('photos.read', $this->getUser()))
+ $this->fail(11, "Access to photo denied");
$comment->attach($attacc);
} elseif($attachmentType == "video") {
$attacc = (new VideosRepo)->getByOwnerAndVID($attachmentOwner, $attachmentId);
if(!$attacc || $attacc->isDeleted())
$this->fail(100, "Video does not exists");
- if($attacc->getOwner()->getId() != $this->getUser()->getId())
- $this->fail(43, "You do not have access to this video");
+ if(!$attacc->getOwner()->getPrivacyPermission('videos.read', $this->getUser()))
+ $this->fail(11, "Access to video denied");
$comment->attach($attacc);
}
diff --git a/Web/Models/Entities/Club.php b/Web/Models/Entities/Club.php
index 79ce08a4..46e8e747 100644
--- a/Web/Models/Entities/Club.php
+++ b/Web/Models/Entities/Club.php
@@ -224,7 +224,7 @@ class Club extends RowModel
"shape" => "spline",
"color" => "#597da3",
],
- "name" => $unique ? "Полный охват" : "Все просмотры",
+ "name" => $unique ? tr("full_coverage") : tr("all_views"),
],
"subs" => [
"x" => array_reverse(range(1, 7)),
@@ -235,7 +235,7 @@ class Club extends RowModel
"color" => "#b05c91",
],
"fill" => "tozeroy",
- "name" => $unique ? "Охват подписчиков" : "Просмотры подписчиков",
+ "name" => $unique ? tr("subs_coverage") : tr("subs_views"),
],
"viral" => [
"x" => array_reverse(range(1, 7)),
@@ -246,7 +246,7 @@ class Club extends RowModel
"color" => "#4d9fab",
],
"fill" => "tozeroy",
- "name" => $unique ? "Виральный охват" : "Виральные просмотры",
+ "name" => $unique ? tr("viral_coverage") : tr("viral_views"),
],
];
}
diff --git a/Web/Models/Entities/Comment.php b/Web/Models/Entities/Comment.php
index fdfb6b8c..90057bdd 100644
--- a/Web/Models/Entities/Comment.php
+++ b/Web/Models/Entities/Comment.php
@@ -11,7 +11,7 @@ class Comment extends Post
function getPrettyId(): string
{
- return $this->getRecord()->id;
+ return (string)$this->getRecord()->id;
}
function getVirtualId(): int
@@ -90,7 +90,7 @@ class Comment extends Post
{
return "/wall" . $this->getTarget()->getPrettyId() . "#_comment" . $this->getId();
}
-
+
function toNotifApiStruct()
{
$res = (object)[];
@@ -103,7 +103,7 @@ class Comment extends Post
return $res;
}
-
+
function canBeEditedBy(?User $user = NULL): bool
{
if(!$user)
diff --git a/Web/Models/Entities/IP.php b/Web/Models/Entities/IP.php
index df2c9787..0d9b8fd0 100644
--- a/Web/Models/Entities/IP.php
+++ b/Web/Models/Entities/IP.php
@@ -105,7 +105,7 @@ class IP extends RowModel
$this->stateChanges("ip", $ip);
}
- function save($log): void
+ function save(?bool $log = false): void
{
if(is_null($this->getRecord()))
$this->stateChanges("first_seen", time());
diff --git a/Web/Models/Entities/Media.php b/Web/Models/Entities/Media.php
index 9377f3e8..648d3564 100644
--- a/Web/Models/Entities/Media.php
+++ b/Web/Models/Entities/Media.php
@@ -121,14 +121,14 @@ abstract class Media extends Postable
$this->stateChanges("hash", $hash);
}
- function save(): void
+ function save(?bool $log = false): void
{
if(!is_null($this->processingPlaceholder) && is_null($this->getRecord())) {
$this->stateChanges("processed", 0);
$this->stateChanges("last_checked", time());
}
- parent::save();
+ parent::save($log);
}
function delete(bool $softly = true): void
diff --git a/Web/Models/Entities/Post.php b/Web/Models/Entities/Post.php
index 38a9f850..a8d444eb 100644
--- a/Web/Models/Entities/Post.php
+++ b/Web/Models/Entities/Post.php
@@ -245,7 +245,7 @@ class Post extends Postable
$this->unwire();
$this->save();
}
-
+
function toNotifApiStruct()
{
$res = (object)[];
@@ -262,7 +262,7 @@ class Post extends Postable
return $res;
}
-
+
function canBeEditedBy(?User $user = NULL): bool
{
if(!$user)
diff --git a/Web/Models/Entities/Postable.php b/Web/Models/Entities/Postable.php
index c86aec96..365c0f26 100644
--- a/Web/Models/Entities/Postable.php
+++ b/Web/Models/Entities/Postable.php
@@ -153,7 +153,7 @@ abstract class Postable extends Attachable
throw new ISE("Setting virtual id manually is forbidden");
}
- function save(): void
+ function save(?bool $log = false): void
{
$vref = $this->upperNodeReferenceColumnName;
@@ -168,11 +168,11 @@ abstract class Postable extends Attachable
$this->stateChanges("created", time());
$this->stateChanges("virtual_id", $pCount + 1);
- } else {
+ } /*else {
$this->stateChanges("edited", time());
- }
+ }*/
- parent::save();
+ parent::save($log);
}
use Traits\TAttachmentHost;
diff --git a/Web/Models/Entities/Traits/TAttachmentHost.php b/Web/Models/Entities/Traits/TAttachmentHost.php
index cbe7cad2..db814cce 100644
--- a/Web/Models/Entities/Traits/TAttachmentHost.php
+++ b/Web/Models/Entities/Traits/TAttachmentHost.php
@@ -1,6 +1,7 @@
get($rel->attachable_id);
}
}
+
+ function getChildrenWithLayout(int $w, int $h = -1): object
+ {
+ if($h < 0)
+ $h = $w;
+
+ $children = $this->getChildren();
+ $skipped = $photos = $result = [];
+ foreach($children as $child) {
+ if($child instanceof Photo) {
+ $photos[] = $child;
+ continue;
+ }
+
+ $skipped[] = $child;
+ }
+
+ $height = "unset";
+ $width = $w;
+ if(sizeof($photos) < 2) {
+ if(isset($photos[0]))
+ $result[] = ["100%", "unset", $photos[0], "unset"];
+ } else {
+ $mak = new Makima($photos);
+ $layout = $mak->computeMasonryLayout($w, $h);
+ $height = $layout->height;
+ $width = $layout->width;
+ for($i = 0; $i < sizeof($photos); $i++) {
+ $tile = $layout->tiles[$i];
+ $result[] = [$tile->width . "px", $tile->height . "px", $photos[$i], "left"];
+ }
+ }
+
+ return (object) [
+ "width" => $width . "px",
+ "height" => $height . "px",
+ "tiles" => $result,
+ "extras" => $skipped,
+ ];
+ }
function attach(Attachable $attachment): void
{
diff --git a/Web/Models/Entities/User.php b/Web/Models/Entities/User.php
index e5b8da06..aaf00ec9 100644
--- a/Web/Models/Entities/User.php
+++ b/Web/Models/Entities/User.php
@@ -462,6 +462,7 @@ class User extends RowModel
"news",
"links",
"poster",
+ "apps"
],
])->get($id);
}
@@ -1026,6 +1027,7 @@ class User extends RowModel
"news",
"links",
"poster",
+ "apps"
],
])->set($id, (int) $status)->toInteger();
diff --git a/Web/Models/Repositories/Gifts.php b/Web/Models/Repositories/Gifts.php
index f36b82a5..3baa2397 100644
--- a/Web/Models/Repositories/Gifts.php
+++ b/Web/Models/Repositories/Gifts.php
@@ -42,4 +42,10 @@ class Gifts
foreach($cats as $cat)
yield new GiftCategory($cat);
}
+
+ function getCategoriesCount(): int
+ {
+ $cats = $this->cats->where("deleted", false);
+ return $cats->count();
+ }
}
diff --git a/Web/Models/Repositories/Photos.php b/Web/Models/Repositories/Photos.php
index 88c7e804..0698c914 100644
--- a/Web/Models/Repositories/Photos.php
+++ b/Web/Models/Repositories/Photos.php
@@ -33,14 +33,26 @@ class Photos
return new Photo($photo);
}
- function getEveryUserPhoto(User $user): \Traversable
+ function getEveryUserPhoto(User $user, int $page = 1, ?int $perPage = NULL): \Traversable
{
+ $perPage = $perPage ?? OPENVK_DEFAULT_PER_PAGE;
$photos = $this->photos->where([
- "owner" => $user->getId()
- ]);
+ "owner" => $user->getId(),
+ "deleted" => 0
+ ])->order("id DESC");
- foreach($photos as $photo) {
+ foreach($photos->page($page, $perPage) as $photo) {
yield new Photo($photo);
}
}
+
+ function getUserPhotosCount(User $user)
+ {
+ $photos = $this->photos->where([
+ "owner" => $user->getId(),
+ "deleted" => 0
+ ]);
+
+ return sizeof($photos);
+ }
}
diff --git a/Web/Presenters/AdminPresenter.php b/Web/Presenters/AdminPresenter.php
index f5c40bcc..14fbbc74 100644
--- a/Web/Presenters/AdminPresenter.php
+++ b/Web/Presenters/AdminPresenter.php
@@ -283,7 +283,7 @@ final class AdminPresenter extends OpenVKPresenter
$this->notFound();
$gift->delete();
- $this->flashFail("succ", "Gift moved successfully", "This gift will now be in Recycle Bin.");
+ $this->flashFail("succ", tr("admin_gift_moved_successfully"), tr("admin_gift_moved_to_recycle"));
break;
case "copy":
case "move":
@@ -302,7 +302,7 @@ final class AdminPresenter extends OpenVKPresenter
$catTo->addGift($gift);
$name = $catTo->getName();
- $this->flash("succ", "Gift moved successfully", "This gift will now be in $name.");
+ $this->flash("succ", tr("admin_gift_moved_successfully"), "This gift will now be in $name.");
$this->redirect("/admin/gifts/" . $catTo->getSlug() . "." . $catTo->getId() . "/");
break;
default:
@@ -333,10 +333,10 @@ final class AdminPresenter extends OpenVKPresenter
$gift->setUsages((int) $this->postParam("usages"));
if(isset($_FILES["pic"]) && $_FILES["pic"]["error"] === UPLOAD_ERR_OK) {
if(!$gift->setImage($_FILES["pic"]["tmp_name"]))
- $this->flashFail("err", "Не удалось сохранить подарок", "Изображение подарка кривое.");
+ $this->flashFail("err", tr("error_when_saving_gift"), tr("error_when_saving_gift_bad_image"));
} else if($gen) {
# If there's no gift pic but it's newly created
- $this->flashFail("err", "Не удалось сохранить подарок", "Пожалуйста, загрузите изображение подарка.");
+ $this->flashFail("err", tr("error_when_saving_gift"), tr("error_when_saving_gift_no_image"));
}
$gift->save();
@@ -363,7 +363,7 @@ final class AdminPresenter extends OpenVKPresenter
if (str_contains($this->queryParam("reason"), "*"))
exit(json_encode([ "error" => "Incorrect reason" ]));
- $unban_time = strtotime($this->queryParam("date")) ?: NULL;
+ $unban_time = strtotime($this->queryParam("date")) ?: "permanent";
$user = $this->users->get($id);
if(!$user)
diff --git a/Web/Presenters/AuthPresenter.php b/Web/Presenters/AuthPresenter.php
index 23b55dc9..c6a7f143 100644
--- a/Web/Presenters/AuthPresenter.php
+++ b/Web/Presenters/AuthPresenter.php
@@ -1,7 +1,7 @@
authenticator->authenticate($chUser->getId());
- (new Logs)->create($user->getId(), "profiles", "openvk\\Web\\Models\\Entities\\User", 0, $user, $user, $_SERVER["REMOTE_ADDR"], $_SERVER["HTTP_USER_AGENT"]);
$this->redirect("/id" . $user->getId());
$user->save();
}
diff --git a/Web/Presenters/CommentPresenter.php b/Web/Presenters/CommentPresenter.php
index cb0efd0d..e005af86 100644
--- a/Web/Presenters/CommentPresenter.php
+++ b/Web/Presenters/CommentPresenter.php
@@ -2,7 +2,7 @@
namespace openvk\Web\Presenters;
use openvk\Web\Models\Entities\{Comment, Notifications\MentionNotification, Photo, Video, User, Topic, Post};
use openvk\Web\Models\Entities\Notifications\CommentNotification;
-use openvk\Web\Models\Repositories\{Comments, Clubs};
+use openvk\Web\Models\Repositories\{Comments, Clubs, Videos, Photos};
final class CommentPresenter extends OpenVKPresenter
{
@@ -54,9 +54,6 @@ final class CommentPresenter extends OpenVKPresenter
if ($entity instanceof Post && $entity->getWallOwner()->isBanned())
$this->flashFail("err", tr("error"), tr("forbidden"));
- if($_FILES["_vid_attachment"] && OPENVK_ROOT_CONF['openvk']['preferences']['videos']['disableUploading'])
- $this->flashFail("err", tr("error"), "Video uploads are disabled by the system administrator.");
-
$flags = 0;
if($this->postParam("as_group") === "on" && !is_null($club) && $club->canBeModifiedBy($this->user->identity))
$flags |= 0b10000000;
@@ -66,31 +63,49 @@ final class CommentPresenter extends OpenVKPresenter
try {
$photo = Photo::fastMake($this->user->id, $this->postParam("text"), $_FILES["_pic_attachment"]);
} catch(ISE $ex) {
- $this->flashFail("err", "Не удалось опубликовать пост", "Файл изображения повреждён, слишком велик или одна сторона изображения в разы больше другой.");
+ $this->flashFail("err", tr("error_when_publishing_comment"), tr("error_when_publishing_comment_description"));
}
}
- # TODO move to trait
- try {
- $photo = NULL;
- $video = NULL;
- if($_FILES["_pic_attachment"]["error"] === UPLOAD_ERR_OK) {
- $album = NULL;
- if($wall > 0 && $wall === $this->user->id)
- $album = (new Albums)->getUserWallAlbum($wallOwner);
-
- $photo = Photo::fastMake($this->user->id, $this->postParam("text"), $_FILES["_pic_attachment"], $album);
+ $photos = [];
+ if(!empty($this->postParam("photos"))) {
+ $un = rtrim($this->postParam("photos"), ",");
+ $arr = explode(",", $un);
+
+ if(sizeof($arr) < 11) {
+ foreach($arr as $dat) {
+ $ids = explode("_", $dat);
+ $photo = (new Photos)->getByOwnerAndVID((int)$ids[0], (int)$ids[1]);
+
+ if(!$photo || $photo->isDeleted())
+ continue;
+
+ $photos[] = $photo;
+ }
}
+ }
+
+ $videos = [];
+
+ if(!empty($this->postParam("videos"))) {
+ $un = rtrim($this->postParam("videos"), ",");
+ $arr = explode(",", $un);
- if($_FILES["_vid_attachment"]["error"] === UPLOAD_ERR_OK) {
- $video = Video::fastMake($this->user->id, $_FILES["_vid_attachment"]["name"], $this->postParam("text"), $_FILES["_vid_attachment"]);
+ if(sizeof($arr) < 11) {
+ foreach($arr as $dat) {
+ $ids = explode("_", $dat);
+ $video = (new Videos)->getByOwnerAndVID((int)$ids[0], (int)$ids[1]);
+
+ if(!$video || $video->isDeleted())
+ continue;
+
+ $videos[] = $video;
+ }
}
- } catch(ISE $ex) {
- $this->flashFail("err", "Не удалось опубликовать комментарий", "Файл медиаконтента повреждён или слишком велик.");
}
- if(empty($this->postParam("text")) && !$photo && !$video)
- $this->flashFail("err", "Не удалось опубликовать комментарий", "Комментарий пустой или слишком большой.");
+ if(empty($this->postParam("text")) && sizeof($photos) < 1 && sizeof($videos) < 1)
+ $this->flashFail("err", tr("error_when_publishing_comment"), tr("error_comment_empty"));
try {
$comment = new Comment;
@@ -102,14 +117,15 @@ final class CommentPresenter extends OpenVKPresenter
$comment->setFlags($flags);
$comment->save();
} catch (\LengthException $ex) {
- $this->flashFail("err", "Не удалось опубликовать комментарий", "Комментарий слишком большой.");
+ $this->flashFail("err", tr("error_when_publishing_comment"), tr("error_comment_too_big"));
}
- if(!is_null($photo))
- $comment->attach($photo);
+ foreach($photos as $photo)
+ $comment->attach($photo);
- if(!is_null($video))
- $comment->attach($video);
+ if(sizeof($videos) > 0)
+ foreach($videos as $vid)
+ $comment->attach($vid);
if($entity->getOwner()->getId() !== $this->user->identity->getId())
if(($owner = $entity->getOwner()) instanceof User)
@@ -124,7 +140,7 @@ final class CommentPresenter extends OpenVKPresenter
if($mentionee instanceof User)
(new MentionNotification($mentionee, $entity, $comment->getOwner(), strip_tags($comment->getText())))->emit();
- $this->flashFail("succ", "Комментарий добавлен", "Ваш комментарий появится на странице.");
+ $this->flashFail("succ", tr("comment_is_added"), tr("comment_is_added_desc"));
}
function renderDeleteComment(int $id): void
@@ -135,15 +151,15 @@ final class CommentPresenter extends OpenVKPresenter
$comment = (new Comments)->get($id);
if(!$comment) $this->notFound();
if(!$comment->canBeDeletedBy($this->user->identity))
- $this->throwError(403, "Forbidden", "У вас недостаточно прав чтобы редактировать этот ресурс.");
+ $this->throwError(403, "Forbidden", tr("error_access_denied"));
if ($comment->getTarget() instanceof Post && $comment->getTarget()->getWallOwner()->isBanned())
$this->flashFail("err", tr("error"), tr("forbidden"));
$comment->delete();
$this->flashFail(
"succ",
- "Успешно",
- "Этот комментарий больше не будет показыватся.
Отметить как спам?"
+ tr("success"),
+ tr("comment_will_not_appear")
);
}
}
diff --git a/Web/Presenters/GiftsPresenter.php b/Web/Presenters/GiftsPresenter.php
index 8f59bdcb..39359add 100644
--- a/Web/Presenters/GiftsPresenter.php
+++ b/Web/Presenters/GiftsPresenter.php
@@ -41,6 +41,7 @@ final class GiftsPresenter extends OpenVKPresenter
$this->template->user = $user;
$this->template->iterator = $cats;
+ $this->template->count = $this->gifts->getCategoriesCount();
$this->template->_template = "Gifts/Menu.xml";
}
@@ -49,7 +50,7 @@ final class GiftsPresenter extends OpenVKPresenter
$user = $this->users->get((int) ($this->queryParam("user") ?? 0));
$cat = $this->gifts->getCat((int) ($this->queryParam("pack") ?? 0));
if(!$user || !$cat)
- $this->flashFail("err", "Не удалось подарить", "Пользователь или набор не существуют.");
+ $this->flashFail("err", tr("error_when_gifting"), tr("error_user_not_exists"));
$this->template->page = $page = (int) ($this->queryParam("p") ?? 1);
$gifts = $cat->getGifts($page, null, $this->template->count);
@@ -66,14 +67,14 @@ final class GiftsPresenter extends OpenVKPresenter
$gift = $this->gifts->get((int) ($this->queryParam("elid") ?? 0));
$cat = $this->gifts->getCat((int) ($this->queryParam("pack") ?? 0));
if(!$user || !$cat || !$gift || !$cat->hasGift($gift))
- $this->flashFail("err", "Не удалось подарить", "Не удалось подтвердить права на подарок.");
+ $this->flashFail("err", tr("error_when_gifting"), tr("error_no_rights_gifts"));
if(!$gift->canUse($this->user->identity))
- $this->flashFail("err", "Не удалось подарить", "У вас больше не осталось таких подарков.");
+ $this->flashFail("err", tr("error_when_gifting"), tr("error_no_more_gifts"));
$coinsLeft = $this->user->identity->getCoins() - $gift->getPrice();
if($coinsLeft < 0)
- $this->flashFail("err", "Не удалось подарить", "Ору нищ не пук.");
+ $this->flashFail("err", tr("error_when_gifting"), tr("error_no_money"));
$this->template->_template = "Gifts/Confirm.xml";
if($_SERVER["REQUEST_METHOD"] !== "POST") {
@@ -91,7 +92,7 @@ final class GiftsPresenter extends OpenVKPresenter
$user->gift($this->user->identity, $gift, $comment, !is_null($this->postParam("anonymous")));
$gift->used();
- $this->flash("succ", "Подарок отправлен", "Вы отправили подарок " . $user->getFirstName() . " за " . $gift->getPrice() . " голосов.");
+ $this->flash("succ", tr("gift_sent"), tr("gift_sent_desc", $user->getFirstName(), $gift->getPrice()));
$this->redirect($user->getURL());
}
diff --git a/Web/Presenters/GroupPresenter.php b/Web/Presenters/GroupPresenter.php
index d8fbcb79..d3a46fd5 100644
--- a/Web/Presenters/GroupPresenter.php
+++ b/Web/Presenters/GroupPresenter.php
@@ -54,7 +54,7 @@ final class GroupPresenter extends OpenVKPresenter
$club->save();
} catch(\PDOException $ex) {
if($ex->getCode() == 23000)
- $this->flashFail("err", "Ошибка", "Произошла ошибка на стороне сервера. Обратитесь к системному администратору.");
+ $this->flashFail("err", tr("error"), tr("error_on_server_side"));
else
throw $ex;
}
@@ -62,7 +62,7 @@ final class GroupPresenter extends OpenVKPresenter
$club->toggleSubscription($this->user->identity);
$this->redirect("/club" . $club->getId());
}else{
- $this->flashFail("err", "Ошибка", "Вы не ввели название группы.");
+ $this->flashFail("err", tr("error"), tr("error_no_group_name"));
}
}
}
@@ -132,7 +132,7 @@ final class GroupPresenter extends OpenVKPresenter
$this->notFound();
if(!$club->canBeModifiedBy($this->user->identity ?? NULL))
- $this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
if(!is_null($hidden)) {
if($club->getOwner()->getId() == $user->getId()) {
@@ -150,9 +150,9 @@ final class GroupPresenter extends OpenVKPresenter
}
if($hidden) {
- $this->flashFail("succ", "Операция успешна", "Теперь " . $user->getCanonicalName() . " будет показываться как обычный подписчик всем кроме других администраторов");
+ $this->flashFail("succ", tr("success_action"), tr("x_is_now_hidden", $user->getCanonicalName()));
} else {
- $this->flashFail("succ", "Операция успешна", "Теперь все будут знать про то что " . $user->getCanonicalName() . " - администратор");
+ $this->flashFail("succ", tr("success_action"), tr("x_is_now_showed", $user->getCanonicalName()));
}
} elseif($removeComment) {
if($club->getOwner()->getId() == $user->getId()) {
@@ -164,11 +164,11 @@ final class GroupPresenter extends OpenVKPresenter
$manager->save();
}
- $this->flashFail("succ", "Операция успешна", "Комментарий к администратору удален");
+ $this->flashFail("succ", tr("success_action"), tr("comment_is_deleted"));
} elseif($comment) {
if(mb_strlen($comment) > 36) {
$commentLength = (string) mb_strlen($comment);
- $this->flashFail("err", "Ошибка", "Комментарий слишком длинный ($commentLength символов вместо 36 символов)");
+ $this->flashFail("err", tr("error"), tr("comment_is_too_long", $commentLength));
}
if($club->getOwner()->getId() == $user->getId()) {
@@ -180,16 +180,16 @@ final class GroupPresenter extends OpenVKPresenter
$manager->save();
}
- $this->flashFail("succ", "Операция успешна", "Комментарий к администратору изменён");
+ $this->flashFail("succ", tr("success_action"), tr("comment_is_changed"));
}else{
if($club->canBeModifiedBy($user)) {
$club->removeManager($user);
- $this->flashFail("succ", "Операция успешна", $user->getCanonicalName() . " более не администратор.");
+ $this->flashFail("succ", tr("success_action"), tr("x_no_more_admin", $user->getCanonicalName()));
} else {
$club->addManager($user);
(new ClubModeratorNotification($user, $club, $this->user->identity))->emit();
- $this->flashFail("succ", "Операция успешна", $user->getCanonicalName() . " назначен(а) администратором.");
+ $this->flashFail("succ", tr("success_action"), tr("x_is_admin", $user->getCanonicalName()));
}
}
@@ -245,7 +245,7 @@ final class GroupPresenter extends OpenVKPresenter
(new Albums)->getClubAvatarAlbum($club)->addPhoto($photo);
} catch(ISE $ex) {
$name = $album->getName();
- $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию.");
+ $this->flashFail("err", tr("error"), tr("error_when_uploading_photo"));
}
}
@@ -253,12 +253,12 @@ final class GroupPresenter extends OpenVKPresenter
$club->save();
} catch(\PDOException $ex) {
if($ex->getCode() == 23000)
- $this->flashFail("err", "Ошибка", "Произошла ошибка на стороне сервера. Обратитесь к системному администратору.");
+ $this->flashFail("err", tr("error"), tr("error_on_server_side"));
else
throw $ex;
}
- $this->flash("succ", "Изменения сохранены", "Новые данные появятся в вашей группе.");
+ $this->flash("succ", tr("changes_saved"), tr("new_changes_desc"));
}
}
@@ -298,7 +298,7 @@ final class GroupPresenter extends OpenVKPresenter
} catch(ISE $ex) {
$name = $album->getName();
- $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию.");
+ $this->flashFail("err", tr("error"), tr("error_when_uploading_photo"));
}
}
$this->returnJson([
@@ -350,7 +350,7 @@ final class GroupPresenter extends OpenVKPresenter
$this->assertUserLoggedIn();
if(!eventdb())
- $this->flashFail("err", "Ошибка подключения", "Не удалось подключится к службе телеметрии.");
+ $this->flashFail("err", tr("connection_error"), tr("connection_error_desc"));
$club = $this->clubs->get($id);
if(!$club->canBeModifiedBy($this->user->identity))
diff --git a/Web/Presenters/InternalAPIPresenter.php b/Web/Presenters/InternalAPIPresenter.php
index 1a107659..e2e6b50e 100644
--- a/Web/Presenters/InternalAPIPresenter.php
+++ b/Web/Presenters/InternalAPIPresenter.php
@@ -1,5 +1,6 @@
postParam("parentType", false) == "post") {
+ $post = (new Posts)->getPostById($owner_id, $post_id);
+ } else {
+ $post = (new Comments)->get($post_id);
+ }
+
+
+ if(is_null($post)) {
+ $this->returnJson([
+ "success" => 0
+ ]);
+ } else {
+ $response = [];
+ $attachments = $post->getChildren();
+ foreach($attachments as $attachment)
+ {
+ if($attachment instanceof \openvk\Web\Models\Entities\Photo)
+ {
+ $response[] = [
+ "url" => $attachment->getURLBySizeId('normal'),
+ "id" => $attachment->getPrettyId()
+ ];
+ }
+ }
+ $this->returnJson([
+ "success" => 1,
+ "body" => $response
+ ]);
+ }
+ }
}
diff --git a/Web/Presenters/NoSpamPresenter.php b/Web/Presenters/NoSpamPresenter.php
index 1560ba63..8164d05e 100644
--- a/Web/Presenters/NoSpamPresenter.php
+++ b/Web/Presenters/NoSpamPresenter.php
@@ -177,26 +177,25 @@ final class NoSpamPresenter extends OpenVKPresenter
if ($conditions) {
$logs = $db->query("SELECT * FROM `ChandlerLogs` $whereStart $conditions GROUP BY `object_id`, `object_model`");
- if (!$where) {
- foreach ($logs as $log) {
- $log = (new Logs)->get($log->id);
- $response[] = $log->getObject()->unwrap();
- }
- } else {
- foreach ($logs as $log) {
- $log = (new Logs)->get($log->id);
- $object = $log->getObject()->unwrap();
+ foreach ($logs as $log) {
+ $log = (new Logs)->get($log->id);
+ $object = $log->getObject()->unwrap();
- if (!$object) continue;
+ if (!$object) continue;
+ if ($where) {
if (str_starts_with($where, " AND")) {
$where = substr_replace($where, "", 0, strlen(" AND"));
}
- foreach ($db->query("SELECT * FROM `$table` WHERE $where")->fetchAll() as $o) {
- if ($object->id === $o["id"]) {
+ $a = $db->query("SELECT * FROM `$table` WHERE $where")->fetchAll();
+ foreach ($a as $o) {
+ if ($object->id == $o["id"]) {
$response[] = $object;
}
}
+
+ } else {
+ $response[] = $object;
}
}
}
@@ -206,70 +205,72 @@ final class NoSpamPresenter extends OpenVKPresenter
}
try {
- $response = [];
- $processed = 0;
+ $response = [];
+ $processed = 0;
- $where = $this->postParam("where");
- $ip = $this->postParam("ip");
- $useragent = $this->postParam("useragent");
- $searchTerm = $this->postParam("q");
- $ts = (int)$this->postParam("ts");
- $te = (int)$this->postParam("te");
- $user = $this->postParam("user");
+ $where = $this->postParam("where");
+ $ip = addslashes($this->postParam("ip"));
+ $useragent = addslashes($this->postParam("useragent"));
+ $searchTerm = addslashes($this->postParam("q"));
+ $ts = (int)$this->postParam("ts");
+ $te = (int)$this->postParam("te");
+ $user = addslashes($this->postParam("user"));
- if (!$ip && !$useragent && !$searchTerm && !$ts && !$te && !$where && !$searchTerm && !$user)
- $this->returnJson(["success" => false, "error" => "Нет запроса. Заполните поле \"подстрока\" или введите запрос \"WHERE\" в поле под ним."]);
-
- $models = explode(",", $this->postParam("models"));
-
- foreach ($models as $_model) {
- $model_name = NoSpamPresenter::ENTITIES_NAMESPACE . "\\" . $_model;
- if (!class_exists($model_name)) {
- continue;
+ if ($where) {
+ $where = explode(";", $where)[0];
}
- $model = new $model_name;
+ if (!$ip && !$useragent && !$searchTerm && !$ts && !$te && !$where && !$searchTerm && !$user)
+ $this->returnJson(["success" => false, "error" => "Нет запроса. Заполните поле \"подстрока\" или введите запрос \"WHERE\" в поле под ним."]);
- $c = new \ReflectionClass($model_name);
- if ($c->isAbstract() || $c->getName() == NoSpamPresenter::ENTITIES_NAMESPACE . "\\Correspondence") {
- continue;
- }
+ $models = explode(",", $this->postParam("models"));
- $db = DatabaseConnection::i()->getContext();
- $table = $model->getTableName();
- $columns = $db->getStructure()->getColumns($table);
-
- if ($searchTerm) {
- $conditions = [];
- $need_deleted = false;
- foreach ($columns as $column) {
- if ($column["name"] == "deleted") {
- $need_deleted = true;
- } else {
- $conditions[] = "`$column[name]` REGEXP '$searchTerm'";
- }
+ foreach ($models as $_model) {
+ $model_name = NoSpamPresenter::ENTITIES_NAMESPACE . "\\" . $_model;
+ if (!class_exists($model_name)) {
+ continue;
}
- $conditions = implode(" OR ", $conditions);
- $where = ($this->postParam("where") ? " AND ($conditions)" : "($conditions)");
- if ($need_deleted) $where .= " AND (`deleted` = 0)";
- }
+ $model = new $model_name;
- $rows = [];
- if ($ip || $useragent || $ts || $te || $user) {
- $rows = searchByAdditionalParams($table, $where, $ip, $useragent, $ts, $te, $user);
- }
+ $c = new \ReflectionClass($model_name);
+ if ($c->isAbstract() || $c->getName() == NoSpamPresenter::ENTITIES_NAMESPACE . "\\Correspondence") {
+ continue;
+ }
- if (count($rows) === 0) {
- if (!$searchTerm) {
- if (str_starts_with($where, " AND")) {
- if ($searchTerm && !$this->postParam("where")) {
- $where = substr_replace($where, "", 0, strlen(" AND"));
+ $db = DatabaseConnection::i()->getContext();
+ $table = $model->getTableName();
+ $columns = $db->getStructure()->getColumns($table);
+
+ if ($searchTerm) {
+ $conditions = [];
+ $need_deleted = false;
+ foreach ($columns as $column) {
+ if ($column["name"] == "deleted") {
+ $need_deleted = true;
} else {
- $where = "(" . $this->postParam("where") . ")" . $where;
+ $conditions[] = "`$column[name]` REGEXP '$searchTerm'";
}
}
+ $conditions = implode(" OR ", $conditions);
+ $where = ($this->postParam("where") ? " AND ($conditions)" : "($conditions)");
+ if ($need_deleted) $where .= " AND (`deleted` = 0)";
+ }
+
+ $rows = [];
+
+ if (str_starts_with($where, " AND")) {
+ if ($searchTerm && !$this->postParam("where")) {
+ $where = substr_replace($where, "", 0, strlen(" AND"));
+ } else {
+ $where = "(" . $this->postParam("where") . ")" . $where;
+ }
+ }
+
+ if ($ip || $useragent || $ts || $te || $user) {
+ $rows = searchByAdditionalParams($table, $where, $ip, $useragent, $ts, $te, $user);
+ } else {
if (!$where) {
$rows = [];
} else {
@@ -277,99 +278,105 @@ final class NoSpamPresenter extends OpenVKPresenter
$rows = $result->fetchAll();
}
}
- }
- if (!in_array((int)$this->postParam("ban"), [1, 2, 3])) {
- foreach ($rows as $key => $object) {
- $object = (array)$object;
- $_obj = [];
- foreach ($object as $key => $value) {
- foreach ($columns as $column) {
- if ($column["name"] === $key && in_array(strtoupper($column["nativetype"]), ["BLOB", "BINARY", "VARBINARY", "TINYBLOB", "MEDIUMBLOB", "LONGBLOB"])) {
- $value = "[BINARY]";
- break;
- }
- }
-
- $_obj[$key] = $value;
- $_obj["__model_name"] = $_model;
- }
- $response[] = $_obj;
- }
- } else {
- $ids = [];
-
- foreach ($rows as $object) {
- $object = new $model_name($db->table($table)->get($object->id));
- if (!$object) continue;
- $ids[] = $object->getId();
- }
-
- $log = new NoSpamLog;
- $log->setUser($this->user->id);
- $log->setModel($_model);
- if ($searchTerm) {
- $log->setRegex($searchTerm);
- } else {
- $log->setRequest($where);
- }
- $log->setBan_Type((int)$this->postParam("ban"));
- $log->setCount(count($rows));
- $log->setTime(time());
- $log->setItems(implode(",", $ids));
- $log->save();
-
- $banned_ids = [];
- foreach ($rows as $object) {
- $object = new $model_name($db->table($table)->get($object->id));
- if (!$object) continue;
-
- $owner = NULL;
- $methods = ["getOwner", "getUser", "getRecipient", "getInitiator"];
-
- if (method_exists($object, "ban")) {
- $owner = $object;
- } else {
- foreach ($methods as $method) {
- if (method_exists($object, $method)) {
- $owner = $object->$method();
- break;
- }
- }
- }
-
- if ($owner instanceof User && $owner->getId() === $this->user->id) {
- if (count($rows) === 1) {
- $this->returnJson(["success" => false, "error" => "\"Производственная травма\" — Вы не можете блокировать или удалять свой же контент"]);
- } else {
- continue;
- }
- }
-
- if (in_array((int)$this->postParam("ban"), [2, 3])) {
- if ($owner) {
- $_id = ($owner instanceof Club ? $owner->getId() * -1 : $owner->getId());
- if (!in_array($_id, $banned_ids)) {
- if ($owner instanceof User) {
- $owner->ban("**content-noSpamTemplate-" . $log->getId() . "**", false, time() + $owner->getNewBanTime(), $this->user->id);
- } else {
- $owner->ban("Подозрительная активность");
+ if (!in_array((int)$this->postParam("ban"), [1, 2, 3])) {
+ foreach ($rows as $key => $object) {
+ $object = (array)$object;
+ $_obj = [];
+ foreach ($object as $key => $value) {
+ foreach ($columns as $column) {
+ if ($column["name"] === $key && in_array(strtoupper($column["nativetype"]), ["BLOB", "BINARY", "VARBINARY", "TINYBLOB", "MEDIUMBLOB", "LONGBLOB"])) {
+ $value = "[BINARY]";
+ break;
}
-
- $banned_ids[] = $_id;
}
+
+ $_obj[$key] = $value;
+ $_obj["__model_name"] = $_model;
}
+ $response[] = $_obj;
+ }
+ } else {
+ $ids = [];
+
+ foreach ($rows as $object) {
+ $object = new $model_name($db->table($table)->get($object->id));
+ if (!$object) continue;
+ $ids[] = $object->getId();
}
- if (in_array((int)$this->postParam("ban"), [1, 3]))
- $object->delete();
+ $log = new NoSpamLog;
+ $log->setUser($this->user->id);
+ $log->setModel($_model);
+ if ($searchTerm) {
+ $log->setRegex($searchTerm);
+ } else {
+ $log->setRequest($where);
+ }
+ $log->setBan_Type((int)$this->postParam("ban"));
+ $log->setCount(count($rows));
+ $log->setTime(time());
+ $log->setItems(implode(",", $ids));
+ $log->save();
+
+ $banned_ids = [];
+ foreach ($rows as $object) {
+ $object = new $model_name($db->table($table)->get($object->id));
+ if (!$object) continue;
+
+ $owner = NULL;
+ $methods = ["getOwner", "getUser", "getRecipient", "getInitiator"];
+
+ if (method_exists($object, "ban")) {
+ $owner = $object;
+ } else {
+ foreach ($methods as $method) {
+ if (method_exists($object, $method)) {
+ $owner = $object->$method();
+ break;
+ }
+ }
+ }
+
+ if ($owner instanceof User && $owner->getId() === $this->user->id) {
+ if (count($rows) === 1) {
+ $this->returnJson(["success" => false, "error" => "\"Производственная травма\" — Вы не можете блокировать или удалять свой же контент"]);
+ } else {
+ continue;
+ }
+ }
+
+ if (in_array((int)$this->postParam("ban"), [2, 3])) {
+ $reason = mb_strlen(trim($this->postParam("ban_reason"))) > 0 ? addslashes($this->postParam("ban_reason")) : ("**content-noSpamTemplate-" . $log->getId() . "**");
+ $is_forever = (string)$this->postParam("is_forever") === "true";
+ $unban_time = $is_forever ? 0 : (int)$this->postParam("unban_time") ?? NULL;
+
+ if ($owner) {
+ $_id = ($owner instanceof Club ? $owner->getId() * -1 : $owner->getId());
+ if (!in_array($_id, $banned_ids)) {
+ if ($owner instanceof User) {
+ if (!$unban_time && !$is_forever)
+ $unban_time = time() + $owner->getNewBanTime();
+
+ $owner->ban($reason, false, $unban_time, $this->user->id);
+ } else {
+ $owner->ban("Подозрительная активность");
+ }
+
+ $banned_ids[] = $_id;
+ }
+ }
+ }
+
+ if (in_array((int)$this->postParam("ban"), [1, 3]))
+ $object->delete();
+ }
+
+ $processed++;
}
-
- $processed++;
}
- }
- $this->returnJson(["success" => true, "processed" => $processed, "count" => count($response), "list" => $response]);
+ $this->returnJson(["success" => true, "processed" => $processed, "count" => count($response), "list" => $response]);
} catch (\Throwable $e) {
$this->returnJson(["success" => false, "error" => $e->getMessage()]);
}
diff --git a/Web/Presenters/NotesPresenter.php b/Web/Presenters/NotesPresenter.php
index 50437ad7..4b71c8b1 100644
--- a/Web/Presenters/NotesPresenter.php
+++ b/Web/Presenters/NotesPresenter.php
@@ -107,7 +107,7 @@ final class NotesPresenter extends OpenVKPresenter
if(!$note || $note->getOwner()->getId() !== $owner || $note->isDeleted())
$this->notFound();
if(is_null($this->user) || !$note->canBeModifiedBy($this->user->identity))
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$this->template->note = $note;
if($_SERVER["REQUEST_METHOD"] === "POST") {
@@ -135,11 +135,11 @@ final class NotesPresenter extends OpenVKPresenter
if(!$note) $this->notFound();
if($note->getOwner()->getId() . "_" . $note->getId() !== $owner . "_" . $id || $note->isDeleted()) $this->notFound();
if(is_null($this->user) || !$note->canBeModifiedBy($this->user->identity))
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$name = $note->getName();
$note->delete();
- $this->flash("succ", "Заметка удалена", "Заметка \"$name\" была успешно удалена.");
+ $this->flash("succ", tr("note_is_deleted"), tr("note_x_is_now_deleted", $name));
$this->redirect("/notes" . $this->user->id);
}
}
diff --git a/Web/Presenters/PhotosPresenter.php b/Web/Presenters/PhotosPresenter.php
index 9d64ba20..0a8b87e4 100644
--- a/Web/Presenters/PhotosPresenter.php
+++ b/Web/Presenters/PhotosPresenter.php
@@ -27,7 +27,7 @@ final class PhotosPresenter extends OpenVKPresenter
if(!$user) $this->notFound();
if (!$user->getPrivacyPermission('photos.read', $this->user->identity ?? NULL))
$this->flashFail("err", tr("forbidden"), tr("forbidden_comment"));
- $this->template->albums = $this->albums->getUserAlbums($user, $this->queryParam("p") ?? 1);
+ $this->template->albums = $this->albums->getUserAlbums($user, (int)($this->queryParam("p") ?? 1));
$this->template->count = $this->albums->getUserAlbumsCount($user);
$this->template->owner = $user;
$this->template->canEdit = false;
@@ -36,7 +36,7 @@ final class PhotosPresenter extends OpenVKPresenter
} else {
$club = (new Clubs)->get(abs($owner));
if(!$club) $this->notFound();
- $this->template->albums = $this->albums->getClubAlbums($club, $this->queryParam("p") ?? 1);
+ $this->template->albums = $this->albums->getClubAlbums($club, (int)($this->queryParam("p") ?? 1));
$this->template->count = $this->albums->getClubAlbumsCount($club);
$this->template->owner = $club;
$this->template->canEdit = false;
@@ -46,7 +46,7 @@ final class PhotosPresenter extends OpenVKPresenter
$this->template->paginatorConf = (object) [
"count" => $this->template->count,
- "page" => $this->queryParam("p") ?? 1,
+ "page" => (int)($this->queryParam("p") ?? 1),
"amount" => NULL,
"perPage" => OPENVK_DEFAULT_PER_PAGE,
];
@@ -94,7 +94,7 @@ final class PhotosPresenter extends OpenVKPresenter
if(!$album) $this->notFound();
if($album->getPrettyId() !== $owner . "_" . $id || $album->isDeleted()) $this->notFound();
if(is_null($this->user) || !$album->canBeModifiedBy($this->user->identity) || $album->isDeleted())
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$this->template->album = $album;
if($_SERVER["REQUEST_METHOD"] === "POST") {
@@ -106,7 +106,7 @@ final class PhotosPresenter extends OpenVKPresenter
$album->setEdited(time());
$album->save();
- $this->flash("succ", "Изменения сохранены", "Новые данные приняты.");
+ $this->flash("succ", tr("changes_saved"), tr("new_data_accepted"));
}
}
@@ -120,13 +120,13 @@ final class PhotosPresenter extends OpenVKPresenter
if(!$album) $this->notFound();
if($album->getPrettyId() !== $owner . "_" . $id || $album->isDeleted()) $this->notFound();
if(is_null($this->user) || !$album->canBeModifiedBy($this->user->identity))
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$name = $album->getName();
$owner = $album->getOwner();
$album->delete();
- $this->flash("succ", "Альбом удалён", "Альбом $name был успешно удалён.");
+ $this->flash("succ", tr("album_is_deleted"), tr("album_x_is_deleted", $name));
$this->redirect("/albums" . ($owner instanceof Club ? "-" : "") . $owner->getId());
}
@@ -147,7 +147,7 @@ final class PhotosPresenter extends OpenVKPresenter
$this->template->photos = iterator_to_array( $album->getPhotos( (int) ($this->queryParam("p") ?? 1), 20) );
$this->template->paginatorConf = (object) [
"count" => $album->getPhotosCount(),
- "page" => $this->queryParam("p") ?? 1,
+ "page" => (int)($this->queryParam("p") ?? 1),
"amount" => sizeof($this->template->photos),
"perPage" => 20,
"atBottom" => true
@@ -205,13 +205,13 @@ final class PhotosPresenter extends OpenVKPresenter
$photo = $this->photos->getByOwnerAndVID($ownerId, $photoId);
if(!$photo) $this->notFound();
if(is_null($this->user) || $this->user->id != $ownerId)
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
if($_SERVER["REQUEST_METHOD"] === "POST") {
$photo->setDescription(empty($this->postParam("desc")) ? NULL : $this->postParam("desc"));
$photo->save();
- $this->flash("succ", "Изменения сохранены", "Обновлённое описание появится на странице с фоткой.");
+ $this->flash("succ", tr("changes_saved"), tr("new_description_will_appear"));
$this->redirect("/photo" . $photo->getPrettyId());
}
@@ -221,39 +221,82 @@ final class PhotosPresenter extends OpenVKPresenter
function renderUploadPhoto(): void
{
$this->assertUserLoggedIn();
- $this->willExecuteWriteAction();
-
- if(is_null($this->queryParam("album")))
- $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию в DELETED.");
-
- [$owner, $id] = explode("_", $this->queryParam("album"));
- $album = $this->albums->get((int) $id);
+ $this->willExecuteWriteAction(true);
+
+ if(is_null($this->queryParam("album"))) {
+ $album = $this->albums->getUserWallAlbum($this->user->identity);
+ } else {
+ [$owner, $id] = explode("_", $this->queryParam("album"));
+ $album = $this->albums->get((int) $id);
+ }
+
if(!$album)
- $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию в DELETED.");
- if(is_null($this->user) || !$album->canBeModifiedBy($this->user->identity))
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error"), tr("error_adding_to_deleted"), 500, true);
+
+ # Для быстрой загрузки фоток из пикера фотографий нужен альбом, но юзер не может загружать фото
+ # в системные альбомы, так что так.
+ if(is_null($this->user) || !is_null($this->queryParam("album")) && !$album->canBeModifiedBy($this->user->identity))
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"), 500, true);
if($_SERVER["REQUEST_METHOD"] === "POST") {
- if(!isset($_FILES["blob"]))
- $this->flashFail("err", "Нету фотографии", "Выберите файл.");
-
- try {
- $photo = new Photo;
- $photo->setOwner($this->user->id);
- $photo->setDescription($this->postParam("desc"));
- $photo->setFile($_FILES["blob"]);
- $photo->setCreated(time());
- $photo->save();
- } catch(ISE $ex) {
- $name = $album->getName();
- $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию в $name.");
- }
-
- $album->addPhoto($photo);
- $album->setEdited(time());
- $album->save();
+ if($this->queryParam("act") == "finish") {
+ $result = json_decode($this->postParam("photos"), true);
+
+ foreach($result as $photoId => $description) {
+ $phot = $this->photos->get($photoId);
- $this->redirect("/photo" . $photo->getPrettyId() . "?from=album" . $album->getId());
+ if(!$phot || $phot->isDeleted() || $phot->getOwner()->getId() != $this->user->id)
+ continue;
+
+ if(iconv_strlen($description) > 255)
+ $this->flashFail("err", tr("error"), tr("description_too_long"), 500, true);
+
+ $phot->setDescription($description);
+ $phot->save();
+
+ $album = $phot->getAlbum();
+ }
+
+ $this->returnJson(["success" => true,
+ "album" => $album->getId(),
+ "owner" => $album->getOwner() instanceof User ? $album->getOwner()->getId() : $album->getOwner()->getId() * -1]);
+ }
+
+ if(!isset($_FILES))
+ $this->flashFail("err", tr("no_photo"), tr("select_file"), 500, true);
+
+ $photos = [];
+ if((int)$this->postParam("count") > 10)
+ $this->flashFail("err", tr("no_photo"), "ты еблан", 500, true);
+
+ for($i = 0; $i < $this->postParam("count"); $i++) {
+ try {
+ $photo = new Photo;
+ $photo->setOwner($this->user->id);
+ $photo->setDescription("");
+ $photo->setFile($_FILES["photo_".$i]);
+ $photo->setCreated(time());
+ $photo->save();
+
+ $photos[] = [
+ "url" => $photo->getURLBySizeId("tiny"),
+ "id" => $photo->getId(),
+ "vid" => $photo->getVirtualId(),
+ "owner" => $photo->getOwner()->getId(),
+ "link" => $photo->getURL()
+ ];
+ } catch(ISE $ex) {
+ $name = $album->getName();
+ $this->flashFail("err", "Неизвестная ошибка", "Не удалось сохранить фотографию в $name.", 500, true);
+ }
+
+ $album->addPhoto($photo);
+ $album->setEdited(time());
+ $album->save();
+ }
+
+ $this->returnJson(["success" => true,
+ "photos" => $photos]);
} else {
$this->template->album = $album;
}
@@ -269,7 +312,7 @@ final class PhotosPresenter extends OpenVKPresenter
if(!$album || !$photo) $this->notFound();
if(!$album->hasPhoto($photo)) $this->notFound();
if(is_null($this->user) || !$album->canBeModifiedBy($this->user->identity))
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
if($_SERVER["REQUEST_METHOD"] === "POST") {
$this->assertNoCSRF();
@@ -277,7 +320,7 @@ final class PhotosPresenter extends OpenVKPresenter
$album->setEdited(time());
$album->save();
- $this->flash("succ", "Фотография удалена", "Эта фотография была успешно удалена.");
+ $this->flash("succ", tr("photo_is_deleted"), tr("photo_is_deleted_desc"));
$this->redirect("/album" . $album->getPrettyId());
}
}
@@ -285,20 +328,23 @@ final class PhotosPresenter extends OpenVKPresenter
function renderDeletePhoto(int $ownerId, int $photoId): void
{
$this->assertUserLoggedIn();
- $this->willExecuteWriteAction();
+ $this->willExecuteWriteAction($_SERVER["REQUEST_METHOD"] === "POST");
$this->assertNoCSRF();
$photo = $this->photos->getByOwnerAndVID($ownerId, $photoId);
if(!$photo) $this->notFound();
if(is_null($this->user) || $this->user->id != $ownerId)
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$redirect = $photo->getAlbum()->getOwner() instanceof User ? "/id0" : "/club" . $ownerId;
$photo->isolate();
$photo->delete();
- $this->flash("succ", "Фотография удалена", "Эта фотография была успешно удалена.");
+ if($_SERVER["REQUEST_METHOD"] === "POST")
+ $this->returnJson(["success" => true]);
+
+ $this->flash("succ", tr("photo_is_deleted"), tr("photo_is_deleted_desc"));
$this->redirect($redirect);
}
}
diff --git a/Web/Presenters/ReportPresenter.php b/Web/Presenters/ReportPresenter.php
index 68d27861..a87154c8 100644
--- a/Web/Presenters/ReportPresenter.php
+++ b/Web/Presenters/ReportPresenter.php
@@ -118,22 +118,22 @@ final class ReportPresenter extends OpenVKPresenter
$report->deleteContent();
$report->banUser($this->user->identity->getId());
- $this->flash("suc", "Смэрть...", "Пользователь успешно забанен.");
+ $this->flash("suc", tr("death"), tr("user_successfully_banned"));
} else if ($this->postParam("delete")) {
$report->deleteContent();
- $this->flash("suc", "Нехай живе!", "Контент удалён, а пользователю прилетело предупреждение.");
+ $this->flash("suc", tr("nehay"), tr("content_is_deleted"));
} else if ($this->postParam("ignore")) {
$report->delete();
- $this->flash("suc", "Нехай живе!", "Жалоба проигнорирована.");
+ $this->flash("suc", tr("nehay"), tr("report_is_ignored"));
} else if ($this->postParam("banClubOwner") || $this->postParam("banClub")) {
if ($report->getContentType() !== "group")
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
$club = $report->getContentObject();
if (!$club || $club->isBanned())
- $this->flashFail("err", "Ошибка доступа", "Недостаточно прав для модификации данного ресурса.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
if ($this->postParam("banClubOwner")) {
$club->getOwner()->ban("**content-" . $report->getContentType() . "-" . $report->getContentId() . "**", false, $club->getOwner()->getNewBanTime(), $this->user->identity->getId());
@@ -143,7 +143,7 @@ final class ReportPresenter extends OpenVKPresenter
$report->delete();
- $this->flash("suc", "Смэрть...", ($this->postParam("banClubOwner") ? "Создатель сообщества успешно забанен." : "Сообщество успешно забанено"));
+ $this->flash("suc", tr("death"), ($this->postParam("banClubOwner") ? tr("group_owner_is_banned") : tr("group_is_banned")));
}
$this->redirect("/scumfeed");
diff --git a/Web/Presenters/TopicsPresenter.php b/Web/Presenters/TopicsPresenter.php
index e7b08ac3..92d67e84 100644
--- a/Web/Presenters/TopicsPresenter.php
+++ b/Web/Presenters/TopicsPresenter.php
@@ -111,7 +111,7 @@ final class TopicsPresenter extends OpenVKPresenter
$video = Video::fastMake($this->user->id, $_FILES["_vid_attachment"]["name"], $this->postParam("text"), $_FILES["_vid_attachment"]);
}
} catch(ISE $ex) {
- $this->flash("err", "Не удалось опубликовать комментарий", "Файл медиаконтента повреждён или слишком велик.");
+ $this->flash("err", tr("error_when_publishing_comment"), tr("error_comment_file_too_big"));
$this->redirect("/topic" . $topic->getPrettyId());
}
@@ -126,7 +126,7 @@ final class TopicsPresenter extends OpenVKPresenter
$comment->setFlags($flags);
$comment->save();
} catch (\LengthException $ex) {
- $this->flash("err", "Не удалось опубликовать комментарий", "Комментарий слишком большой.");
+ $this->flash("err", tr("error_when_publishing_comment"), tr("error_comment_too_big"));
$this->redirect("/topic" . $topic->getPrettyId());
}
diff --git a/Web/Presenters/UserPresenter.php b/Web/Presenters/UserPresenter.php
index 9cfa3654..51ddc6aa 100644
--- a/Web/Presenters/UserPresenter.php
+++ b/Web/Presenters/UserPresenter.php
@@ -72,7 +72,7 @@ final class UserPresenter extends OpenVKPresenter
if(!is_null($this->user)) {
if($this->template->mode !== "friends" && $this->user->id !== $id) {
$name = $user->getFullName();
- $this->flash("err", "Ошибка доступа", "Вы не можете просматривать полный список подписок $name.");
+ $this->flash("err", tr("error_access_denied_short"), tr("error_viewing_subs", $name));
$this->redirect($user->getURL());
}
@@ -107,11 +107,11 @@ final class UserPresenter extends OpenVKPresenter
$this->notFound();
if(!$club->canBeModifiedBy($this->user->identity ?? NULL))
- $this->flashFail("err", "Ошибка доступа", "У вас недостаточно прав, чтобы изменять этот ресурс.", NULL, true);
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"), NULL, true);
$isClubPinned = $this->user->identity->isClubPinned($club);
if(!$isClubPinned && $this->user->identity->getPinnedClubCount() > 10)
- $this->flashFail("err", "Ошибка", "Находится в левом меню могут максимум 10 групп", NULL, true);
+ $this->flashFail("err", tr("error"), tr("error_max_pinned_clubs"), NULL, true);
if($club->getOwner()->getId() === $this->user->identity->getId()) {
$club->setOwner_Club_Pinned(!$isClubPinned);
@@ -237,7 +237,7 @@ final class UserPresenter extends OpenVKPresenter
} elseif($_GET['act'] === "status") {
if(mb_strlen($this->postParam("status")) > 255) {
$statusLength = (string) mb_strlen($this->postParam("status"));
- $this->flashFail("err", "Ошибка", "Статус слишком длинный ($statusLength символов вместо 255 символов)", NULL, true);
+ $this->flashFail("err", tr("error"), tr("error_status_too_long", $statusLength), NULL, true);
}
$user->setStatus(empty($this->postParam("status")) ? NULL : $this->postParam("status"));
@@ -281,7 +281,7 @@ final class UserPresenter extends OpenVKPresenter
if($_SERVER["REQUEST_METHOD"] === "POST") {
if(!$user->verifyNumber($this->postParam("code") ?? 0))
- $this->flashFail("err", "Ошибка", "Не удалось подтвердить номер телефона: неверный код.");
+ $this->flashFail("err", tr("error"), tr("invalid_code"));
$this->flash("succ", tr("changes_saved"), tr("changes_saved_comment"));
}
@@ -481,6 +481,7 @@ final class UserPresenter extends OpenVKPresenter
"menu_novajoj" => "news",
"menu_ligiloj" => "links",
"menu_standardo" => "poster",
+ "menu_aplikoj" => "apps"
];
foreach($settings as $checkbox => $setting)
$user->setLeftMenuItemStatus($setting, $this->checkbox($checkbox));
diff --git a/Web/Presenters/VideosPresenter.php b/Web/Presenters/VideosPresenter.php
index 4e4d484a..9d2fddc6 100644
--- a/Web/Presenters/VideosPresenter.php
+++ b/Web/Presenters/VideosPresenter.php
@@ -58,7 +58,7 @@ final class VideosPresenter extends OpenVKPresenter
$this->willExecuteWriteAction();
if(OPENVK_ROOT_CONF['openvk']['preferences']['videos']['disableUploading'])
- $this->flashFail("err", tr("error"), "Video uploads are disabled by the system administrator.");
+ $this->flashFail("err", tr("error"), tr("video_uploads_disabled"));
if($_SERVER["REQUEST_METHOD"] === "POST") {
if(!empty($this->postParam("name"))) {
@@ -74,18 +74,18 @@ final class VideosPresenter extends OpenVKPresenter
else if(!empty($this->postParam("link")))
$video->setLink($this->postParam("link"));
else
- $this->flashFail("err", "Нету видеозаписи", "Выберите файл или укажите ссылку.");
+ $this->flashFail("err", tr("no_video"), tr("no_video_desc"));
} catch(\DomainException $ex) {
- $this->flashFail("err", "Произошла ошибка", "Файл повреждён или не содержит видео." );
+ $this->flashFail("err", tr("error_occured"), tr("error_video_damaged_file"));
} catch(ISE $ex) {
- $this->flashFail("err", "Произошла ошибка", "Возможно, ссылка некорректна.");
+ $this->flashFail("err", tr("error_occured"), tr("error_video_incorrect_link"));
}
$video->save();
$this->redirect("/video" . $video->getPrettyId());
} else {
- $this->flashFail("err", "Произошла ошибка", "Видео не может быть опубликовано без названия.");
+ $this->flashFail("err", tr("error_occured"), tr("error_video_no_title"));
}
}
}
@@ -99,14 +99,14 @@ final class VideosPresenter extends OpenVKPresenter
if(!$video)
$this->notFound();
if(is_null($this->user) || $this->user->id !== $owner)
- $this->flashFail("err", "Ошибка доступа", "Вы не имеете права редактировать этот ресурс.");
+ $this->flashFail("err", tr("error_access_denied_short"), tr("error_access_denied"));
if($_SERVER["REQUEST_METHOD"] === "POST") {
$video->setName(empty($this->postParam("name")) ? NULL : $this->postParam("name"));
$video->setDescription(empty($this->postParam("desc")) ? NULL : $this->postParam("desc"));
$video->save();
- $this->flash("succ", "Изменения сохранены", "Обновлённое описание появится на странице с видосиком.");
+ $this->flash("succ", tr("changes_saved"), tr("new_data_video"));
$this->redirect("/video" . $video->getPrettyId());
}
@@ -128,7 +128,7 @@ final class VideosPresenter extends OpenVKPresenter
$video->deleteVideo($owner, $vid);
}
} else {
- $this->flashFail("err", "Не удалось удалить пост", "Вы не вошли в аккаунт.");
+ $this->flashFail("err", tr("error_deleting_video"), tr("login_please"));
}
$this->redirect("/videos" . $owner);
diff --git a/Web/Presenters/WallPresenter.php b/Web/Presenters/WallPresenter.php
index 3e115ec7..2f9d611d 100644
--- a/Web/Presenters/WallPresenter.php
+++ b/Web/Presenters/WallPresenter.php
@@ -3,7 +3,7 @@ namespace openvk\Web\Presenters;
use openvk\Web\Models\Exceptions\TooMuchOptionsException;
use openvk\Web\Models\Entities\{Poll, Post, Photo, Video, Club, User};
use openvk\Web\Models\Entities\Notifications\{MentionNotification, RepostNotification, WallPostNotification};
-use openvk\Web\Models\Repositories\{Posts, Users, Clubs, Albums, Notes};
+use openvk\Web\Models\Repositories\{Posts, Users, Clubs, Albums, Notes, Videos, Comments, Photos};
use Chandler\Database\DatabaseConnection;
use Nette\InvalidStateException as ISE;
use Bhaktaraz\RSSGenerator\Item;
@@ -231,10 +231,7 @@ final class WallPresenter extends OpenVKPresenter
if(!$canPost)
$this->flashFail("err", tr("not_enough_permissions"), tr("not_enough_permissions_comment"));
-
- if($_FILES["_vid_attachment"] && OPENVK_ROOT_CONF['openvk']['preferences']['videos']['disableUploading'])
- $this->flashFail("err", tr("error"), "Video uploads are disabled by the system administrator.");
-
+
$anon = OPENVK_ROOT_CONF["openvk"]["preferences"]["wall"]["anonymousPosting"]["enable"];
if($wallOwner instanceof Club && $this->postParam("as_group") === "on" && $this->postParam("force_sign") !== "on" && $anon) {
$manager = $wallOwner->getManager($this->user->identity);
@@ -252,23 +249,23 @@ final class WallPresenter extends OpenVKPresenter
if($this->postParam("force_sign") === "on")
$flags |= 0b01000000;
- try {
- $photo = NULL;
- $video = NULL;
- if($_FILES["_pic_attachment"]["error"] === UPLOAD_ERR_OK) {
- $album = NULL;
- if(!$anon && $wall > 0 && $wall === $this->user->id)
- $album = (new Albums)->getUserWallAlbum($wallOwner);
-
- $photo = Photo::fastMake($this->user->id, $this->postParam("text"), $_FILES["_pic_attachment"], $album, $anon);
+ $photos = [];
+
+ if(!empty($this->postParam("photos"))) {
+ $un = rtrim($this->postParam("photos"), ",");
+ $arr = explode(",", $un);
+
+ if(sizeof($arr) < 11) {
+ foreach($arr as $dat) {
+ $ids = explode("_", $dat);
+ $photo = (new Photos)->getByOwnerAndVID((int)$ids[0], (int)$ids[1]);
+
+ if(!$photo || $photo->isDeleted())
+ continue;
+
+ $photos[] = $photo;
+ }
}
-
- if($_FILES["_vid_attachment"]["error"] === UPLOAD_ERR_OK)
- $video = Video::fastMake($this->user->id, $_FILES["_vid_attachment"]["name"], $this->postParam("text"), $_FILES["_vid_attachment"], $anon);
- } catch(\DomainException $ex) {
- $this->flashFail("err", tr("failed_to_publish_post"), tr("media_file_corrupted"));
- } catch(ISE $ex) {
- $this->flashFail("err", tr("failed_to_publish_post"), tr("media_file_corrupted_or_too_large"));
}
try {
@@ -295,8 +292,27 @@ final class WallPresenter extends OpenVKPresenter
$this->flashFail("err", " ");
}
}
+
+ $videos = [];
+
+ if(!empty($this->postParam("videos"))) {
+ $un = rtrim($this->postParam("videos"), ",");
+ $arr = explode(",", $un);
+
+ if(sizeof($arr) < 11) {
+ foreach($arr as $dat) {
+ $ids = explode("_", $dat);
+ $video = (new Videos)->getByOwnerAndVID((int)$ids[0], (int)$ids[1]);
+
+ if(!$video || $video->isDeleted())
+ continue;
+
+ $videos[] = $video;
+ }
+ }
+ }
- if(empty($this->postParam("text")) && !$photo && !$video && !$poll && !$note)
+ if(empty($this->postParam("text")) && sizeof($photos) < 1 && sizeof($videos) < 1 && !$poll && !$note)
$this->flashFail("err", tr("failed_to_publish_post"), tr("post_is_empty_or_too_big"));
try {
@@ -313,11 +329,12 @@ final class WallPresenter extends OpenVKPresenter
$this->flashFail("err", tr("failed_to_publish_post"), tr("post_is_too_big"));
}
- if(!is_null($photo))
- $post->attach($photo);
+ foreach($photos as $photo)
+ $post->attach($photo);
- if(!is_null($video))
- $post->attach($video);
+ if(sizeof($videos) > 0)
+ foreach($videos as $vid)
+ $post->attach($vid);
if(!is_null($poll))
$post->attach($poll);
@@ -498,4 +515,64 @@ final class WallPresenter extends OpenVKPresenter
# TODO localize message based on language and ?act=(un)pin
$this->flashFail("succ", tr("information_-1"), tr("changes_saved_comment"));
}
+
+ function renderEdit()
+ {
+ $this->assertUserLoggedIn();
+ $this->willExecuteWriteAction();
+
+ if($_SERVER["REQUEST_METHOD"] !== "POST")
+ $this->redirect("/id0");
+
+ if($this->postParam("type") == "post")
+ $post = $this->posts->get((int)$this->postParam("postid"));
+ else
+ $post = (new Comments)->get((int)$this->postParam("postid"));
+
+ if(!$post || $post->isDeleted())
+ $this->returnJson(["error" => "Invalid post"]);
+
+ if(!$post->canBeEditedBy($this->user->identity))
+ $this->returnJson(["error" => "Access denied"]);
+
+ $attachmentsCount = sizeof(iterator_to_array($post->getChildren()));
+
+ if(empty($this->postParam("newContent")) && $attachmentsCount < 1)
+ $this->returnJson(["error" => "Empty post"]);
+
+ $post->setEdited(time());
+
+ try {
+ $post->setContent($this->postParam("newContent"));
+ } catch(\LengthException $e) {
+ $this->returnJson(["error" => $e->getMessage()]);
+ }
+
+ if($this->postParam("type") === "post") {
+ $post->setNsfw($this->postParam("nsfw") == "true");
+ $flags = 0;
+
+ if($post->getTargetWall() < 0 && $post->getWallOwner()->canBeModifiedBy($this->user->identity)) {
+ if($this->postParam("fromgroup") == "true") {
+ $flags |= 0b10000000;
+ $post->setFlags($flags);
+ } else
+ $post->setFlags($flags);
+ }
+ }
+
+ $post->save(true);
+
+ $this->returnJson(["error" => "no",
+ "new_content" => $post->getText(),
+ "new_edited" => (string)$post->getEditTime(),
+ "nsfw" => $this->postParam("type") === "post" ? (int)$post->isExplicit() : 0,
+ "from_group" => $this->postParam("type") === "post" && $post->getTargetWall() < 0 ?
+ ((int)$post->isPostedOnBehalfOfGroup()) : "false",
+ "new_text" => $post->getText(false),
+ "author" => [
+ "name" => $post->getOwner()->getCanonicalName(),
+ "avatar" => $post->getOwner()->getAvatarUrl()
+ ]]);
+ }
}
diff --git a/Web/Presenters/templates/@layout.xml b/Web/Presenters/templates/@layout.xml
index 3d724cf5..f8a975e0 100644
--- a/Web/Presenters/templates/@layout.xml
+++ b/Web/Presenters/templates/@layout.xml
@@ -38,9 +38,8 @@