<?php
 class vB_Api_Bookmark extends vB_Api { private ?array $bookmarksCache = null; public function canUseBookmarks() : array { $canuse = (vB::getUserContext()->hasPermission('genericpermissions2', 'canusebookmarks') AND vB::getCurrentSession()->get('userid')); return ['canuse' => $canuse]; } private function checkCanUse(int $currentUserId) : void { if (!$currentUserId) { throw new vB_Exception_Api('not_logged_no_permission'); } $this->checkHasPermission('genericpermissions2', 'canusebookmarks'); } public function addBookmark(int $nodeid) : array { $currentUserId = vB::getCurrentSession()->get('userid'); $this->checkCanUse($currentUserId); $timenow = vB::getRequest()->getTimeNow(); $assertor = vB::getDbAssertor(); $id = $assertor->replace('nodebookmark', [ 'userid' => $currentUserId, 'nodeid' => $nodeid, 'created' => $timenow, ]); $this->bookmarksCache[$currentUserId][$nodeid] = [ 'bookmarkid' => $id, 'userid' => $currentUserId, 'nodeid' => $nodeid, 'created' => $timenow, ]; return ['success' => true, 'created' => $timenow, 'bookmarkid' => $id,]; } public function removeBookmark(int $nodeid) : array { $currentUserId = vB::getCurrentSession()->get('userid'); $this->checkCanUse($currentUserId); $assertor = vB::getDbAssertor(); $assertor->delete('nodebookmark', [ 'userid' => $currentUserId, 'nodeid' => $nodeid, ]); unset($this->bookmarksCache[$currentUserId][$nodeid]); return ['success' => true,]; } public function isBookMarked(int $nodeid) : array { $currentUserId = vB::getCurrentSession()->get('userid'); $this->checkCanUse($currentUserId); $bookmarks = $this->fetchAndCacheBookmarksForUser($currentUserId); return [ 'isBookmarked' => !empty($bookmarks[$nodeid]), ]; } private function fetchAndCacheBookmarksForUser(int $userid) : array { if (!isset($this->bookmarksCache[$userid])) { $assertor = vB::getDbAssertor(); $this->bookmarksCache[$userid] = $assertor->getRows('nodebookmark', ['userid' => $userid,], false, 'nodeid'); } return $this->bookmarksCache[$userid]; } public function getBookmarks(int $page = 1, int $perpage = 10) : array { $currentUserId = vB::getCurrentSession()->get('userid'); $this->checkCanUse($currentUserId); $bookmarks = $this->fetchAndCacheBookmarksForUser($currentUserId); $nodeids = array_column($bookmarks, 'nodeid', 'nodeid'); $return = []; $nodeApi = vB_Api::instanceInternal('node'); $nodes = $nodeApi->getContentforNodes($nodeids, ['showVM' => true,]); foreach ($nodes AS $__nodeid => $__node) { $__created = $bookmarks[$__nodeid]['created'] ?? 0; $return[] = ['nodeid' => $__nodeid, 'created' => $__created, 'node' => $__node]; } $total = count($return); array_subkey_sort($return, 'created'); $return = array_slice($return, ($page - 1) * $perpage, $perpage); return ['bookmarks' => $return, 'totalcount' => $total, 'page' => $page, 'perpage' => $perpage]; } } 