diff --git a/CHANGELOG.md b/CHANGELOG.md index 05d42f4..10e5310 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security - Nothing yet +## [2.8.0] - 2026-11-08 + +### Added +- Knowledge base endpoints for FAQ categories and articles. There is no delete; hiding an article means setting it to `internal`. + - `GET /api/kb-categories-list.php`: all categories with parent, visibility and article count. + - `POST /api/kb-categories-create.php`, `PATCH /api/kb-categories-update.php/{id}.json`: name, description, notes, parent, visibility. A category cannot become its own parent or move below one of its subcategories. + - `GET /api/kb-faq-search.php`: text, category, visibility, slug; paging. + - `GET /api/kb-faq-get.php/{id}.json`: article with answer (HTML), notes and help topics. + - `POST /api/kb-faq-create.php`, `PATCH /api/kb-faq-update.php/{id}.json`: title, answer, category, notes, visibility (`internal`, `public`, `featured`). Fields left out keep their value; help topics and attachments stay linked. +- Changes go through osTicket's `FAQ::update()` and `Category::update()`, so the answer is sanitized like in the staff UI and duplicate titles/names are refused. New articles and categories are internal unless `visibility` is set. +- Article responses report `visibleInPortal` (article and category public), and `slug`/`publicUrl` for friendly `/kb/` URLs. The slugs are read from the `RewriteRule ^kb/$ kb/faq.php?id=` lines of the root `.htaccess`; the file is never written. +- Two API key permissions, off by default: `can_read_kb`, `can_write_kb`. Write does not imply read. + +### Fixed +- Updating the plugin left the task rewrite rules behind in `api/.htaccess`: removing the old rule block stopped at the subticket unlink rule. The template now ends with an explicit end marker, and leftover plugin rules from earlier updates are removed. + ## [2.7.0] - 2026-11-07 ### Added diff --git a/README.md b/README.md index 5e34b7d..4c372f5 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Extends osTicket's REST API with powerful endpoints for advanced ticket manageme - Subticket API for parent-child relationships (requires [Subticket Manager Plugin](https://github.com/studio-prisma/osticket-subticket-manager)) - Ticket Statistics (global, by department, by staff) - Task API: read, search, create, update (edit, link to a ticket, assign, transfer, due date, close/reopen, notes) and delete osTicket tasks, run as a configurable agent +- Knowledge Base API: list, create and change FAQ categories; search, read, create and change FAQ articles (internal/public/featured), with friendly `/kb/` URLs read from the root `.htaccess`. No delete - Granular API Key Permissions per endpoint - Name-Based Filters (human-readable names instead of IDs) - No Core Modifications (Signal-based architecture, update-safe) diff --git a/api/kb-categories-create.php b/api/kb-categories-create.php new file mode 100644 index 0000000..54539f6 --- /dev/null +++ b/api/kb-categories-create.php @@ -0,0 +1,33 @@ +parsePathInfo('#^(?:\.(?Pjson|xml))?$#'); + +// Only accept POST: every call creates a new category +$bootstrap->requireMethod('POST'); + +$data = $bootstrap->parseJsonBody(required: true); + +$bootstrap->execute(function() use ($bootstrap, $data) { + return $bootstrap->getController()->createKbCategory($data); +}, 201); diff --git a/api/kb-categories-list.php b/api/kb-categories-list.php new file mode 100644 index 0000000..de50e0b --- /dev/null +++ b/api/kb-categories-list.php @@ -0,0 +1,30 @@ +parsePathInfo('#^(?:\.(?Pjson|xml))?$#'); + +$bootstrap->requireMethod('GET'); + +$bootstrap->execute(function() use ($bootstrap) { + return $bootstrap->getController()->listKbCategories(); +}); diff --git a/api/kb-categories-update.php b/api/kb-categories-update.php new file mode 100644 index 0000000..b1d024d --- /dev/null +++ b/api/kb-categories-update.php @@ -0,0 +1,35 @@ +parsePathInfo( + '#^/(?P[0-9]{1,10})\.(?Pjson|xml)$#', + 'Invalid URL format. Expected: /api/kb-categories-update.php/{id}.json' +); + +$bootstrap->requireMethod(['PATCH', 'PUT']); + +$data = $bootstrap->parseJsonBody(required: true); + +$bootstrap->execute(function() use ($bootstrap, $params, $data) { + return $bootstrap->getController()->updateKbCategory($params['id'], $data); +}); diff --git a/api/kb-faq-create.php b/api/kb-faq-create.php new file mode 100644 index 0000000..96d704f --- /dev/null +++ b/api/kb-faq-create.php @@ -0,0 +1,33 @@ +parsePathInfo('#^(?:\.(?Pjson|xml))?$#'); + +// Only accept POST: every call creates a new article +$bootstrap->requireMethod('POST'); + +$data = $bootstrap->parseJsonBody(required: true); + +$bootstrap->execute(function() use ($bootstrap, $data) { + return $bootstrap->getController()->createKbArticle($data); +}, 201); diff --git a/api/kb-faq-get.php b/api/kb-faq-get.php new file mode 100644 index 0000000..1c9f159 --- /dev/null +++ b/api/kb-faq-get.php @@ -0,0 +1,33 @@ +parsePathInfo( + '#^/(?P[0-9]{1,10})\.(?Pjson|xml)$#', + 'Invalid URL format. Expected: /api/kb-faq-get.php/{id}.json' +); + +$bootstrap->requireMethod('GET'); + +$bootstrap->execute(function() use ($bootstrap, $params) { + return $bootstrap->getController()->getKbArticle($params['id']); +}); diff --git a/api/kb-faq-search.php b/api/kb-faq-search.php new file mode 100644 index 0000000..3150488 --- /dev/null +++ b/api/kb-faq-search.php @@ -0,0 +1,39 @@ +parsePathInfo('#^(?:\.(?Pjson|xml))?$#'); + +$bootstrap->requireMethod('GET'); + +$params = $bootstrap->parseQueryParams([ + 'query' => null, + 'categoryId' => null, + 'visibility' => null, + 'slug' => null, + 'limit' => null, + 'offset' => null, +]); + +$bootstrap->execute(function() use ($bootstrap, $params) { + return $bootstrap->getController()->searchKbArticles($params); +}); diff --git a/api/kb-faq-update.php b/api/kb-faq-update.php new file mode 100644 index 0000000..24ef18a --- /dev/null +++ b/api/kb-faq-update.php @@ -0,0 +1,36 @@ +parsePathInfo( + '#^/(?P[0-9]{1,10})\.(?Pjson|xml)$#', + 'Invalid URL format. Expected: /api/kb-faq-update.php/{id}.json' +); + +$bootstrap->requireMethod(['PATCH', 'PUT']); + +$data = $bootstrap->parseJsonBody(required: true); + +$bootstrap->execute(function() use ($bootstrap, $params, $data) { + return $bootstrap->getController()->updateKbArticle($params['id'], $data); +}); diff --git a/class.ApiEndpointsPlugin.php b/class.ApiEndpointsPlugin.php index ea0499c..8667956 100644 --- a/class.ApiEndpointsPlugin.php +++ b/class.ApiEndpointsPlugin.php @@ -575,6 +575,16 @@ function extendApiKeyTable(&$errors) { 'name' => 'can_delete_tasks', 'definition' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', 'after' => 'can_search_tasks' + ), + array( + 'name' => 'can_read_kb', + 'definition' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', + 'after' => 'can_delete_tasks' + ), + array( + 'name' => 'can_write_kb', + 'definition' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', + 'after' => 'can_read_kb' ) ); @@ -636,6 +646,8 @@ function removeApiKeyTableExtensions() { // List of columns to remove (in reverse order of adding) $columnsToRemove = array( + 'can_write_kb', + 'can_read_kb', 'can_delete_tasks', 'can_search_tasks', 'can_read_tasks', @@ -826,12 +838,16 @@ function removeHtaccessRule() { return true; // Nothing to remove } - // Find end of template block (next empty line or closing IfModule) - // The template ends with the last RewriteRule line, so we look for the pattern: - // RewriteRule ^tickets-subtickets-unlink\.php/ - [L] + // Find end of template block. Since 2.8.0 the template ends with an + // explicit end marker. Older blocks end with the subticket unlink rule; + // their later rules (tasks) are removed as leftovers below. $search_start = $start_pos; - $end_marker = 'RewriteRule ^tickets-subtickets-unlink\.php/ - [L]'; + $end_marker = '# End of API Endpoints Plugin rules'; $end_pos = strpos($content, $end_marker, $search_start); + if ($end_pos === false) { + $end_marker = 'RewriteRule ^tickets-subtickets-unlink\.php/ - [L]'; + $end_pos = strpos($content, $end_marker, $search_start); + } if ($end_pos === false) { // Fallback: look for any RewriteRule pattern and find the last one in our block @@ -853,6 +869,9 @@ function removeHtaccessRule() { // Remove the entire block (including leading newline) $content = substr_replace($content, '', $start_pos, $end_pos - $start_pos); + // Remove leftovers of older blocks whose end was detected too early + $content = self::stripLeftoverRules($content, __DIR__ . '/htaccess.template'); + // Write back $result = file_put_contents($htaccess_file, $content); if ($result === false) { @@ -864,6 +883,46 @@ function removeHtaccessRule() { return true; } + /** + * Remove plugin rules left outside the template block + * + * Up to 2.7.0 the block removal stopped at the subticket unlink rule, + * so every update left the rules after it (tasks) behind. This removes + * pass-through rules for the plugin's own endpoint files + * (tickets-*.php, kb-*.php) and comment lines that appear verbatim in + * the template. osTicket's own rules are never touched. + * + * @param string $content .htaccess content without the template block + * @param string $templateFile Path of htaccess.template + * @return string Cleaned content + */ + static function stripLeftoverRules($content, $templateFile) { + $comments = array(); + if (is_readable($templateFile)) { + foreach (preg_split('/\R/', (string)file_get_contents($templateFile)) as $line) { + $line = trim($line); + // Only specific comments: skip "#", separator and empty lines + if (strlen($line) > 12 && $line[0] === '#' && strpos($line, '=====') === false) { + $comments[$line] = true; + } + } + } + + $kept = array(); + foreach (preg_split('/\R/', $content) as $line) { + $trimmed = trim($line); + if (preg_match('#^RewriteRule \^(tickets|kb)-[a-z-]+\\\\\.php(/|\.\*\$) - \[L\]$#', $trimmed)) { + continue; + } + if (isset($comments[$trimmed])) { + continue; + } + $kept[] = $line; + } + + return preg_replace("/\n{3,}/", "\n\n", implode("\n", $kept)); + } + /** * Remove deployed API files from /api/ directory (DYNAMIC) * diff --git a/config.php b/config.php index 6e55282..2ae00b8 100644 --- a/config.php +++ b/config.php @@ -65,7 +65,7 @@ function getOptions() { 'default' => '', 'configuration' => array( 'html' => true, - 'content' => '

The following API endpoints are available:

  • ✓ POST /tickets - Create tickets with format (markdown/html/text) and department
    Controlled by: can_create_tickets permission
  • ✓ PATCH/PUT /tickets/:id - Update tickets (department, topic, parent, priority, status, SLA, staff)
    Controlled by: can_update_tickets permission
  • ✓ GET /tickets-get.php/:number - Retrieve ticket by number with full details and thread
    Controlled by: can_read_tickets permission
  • ✓ GET /tickets-search.php - Search tickets by query, status, department with pagination
    Controlled by: can_search_tickets permission
  • ✓ DELETE /tickets-delete.php/:number - Delete tickets with cascading cleanup
    Controlled by: can_delete_tickets permission
  • ✓ GET /tickets-stats.php - Retrieve ticket statistics for dashboards and reporting
    Controlled by: can_read_stats permission
  • ✓ Subticket Operations - Manage parent-child ticket relationships (get parent, list children, create/unlink)
    Controlled by: can_manage_subtickets permission (requires Subticket Manager Plugin)
  • ✓ POST /tickets-reply.php/:number - Reply to the customer (public reply, sends the reply email)
    Controlled by: can_reply_tickets permission and the "Reply as Agent" setting
  • ✓ Task Operations - Read, search, create, update (edit, assign, transfer, due date, close/reopen, link to a ticket, notes) and delete tasks
    Controlled by: can_create_tasks, can_update_tasks, can_read_tasks, can_search_tasks, can_delete_tasks; changes also need the "Tasks as Agent" setting

⚠ Important: Access to these endpoints is controlled individually per API Key using the permissions below.

' + 'content' => '

The following API endpoints are available:

  • ✓ POST /tickets - Create tickets with format (markdown/html/text) and department
    Controlled by: can_create_tickets permission
  • ✓ PATCH/PUT /tickets/:id - Update tickets (department, topic, parent, priority, status, SLA, staff)
    Controlled by: can_update_tickets permission
  • ✓ GET /tickets-get.php/:number - Retrieve ticket by number with full details and thread
    Controlled by: can_read_tickets permission
  • ✓ GET /tickets-search.php - Search tickets by query, status, department with pagination
    Controlled by: can_search_tickets permission
  • ✓ DELETE /tickets-delete.php/:number - Delete tickets with cascading cleanup
    Controlled by: can_delete_tickets permission
  • ✓ GET /tickets-stats.php - Retrieve ticket statistics for dashboards and reporting
    Controlled by: can_read_stats permission
  • ✓ Subticket Operations - Manage parent-child ticket relationships (get parent, list children, create/unlink)
    Controlled by: can_manage_subtickets permission (requires Subticket Manager Plugin)
  • ✓ POST /tickets-reply.php/:number - Reply to the customer (public reply, sends the reply email)
    Controlled by: can_reply_tickets permission and the "Reply as Agent" setting
  • ✓ Task Operations - Read, search, create, update (edit, assign, transfer, due date, close/reopen, link to a ticket, notes) and delete tasks
    Controlled by: can_create_tasks, can_update_tasks, can_read_tasks, can_search_tasks, can_delete_tasks; changes also need the "Tasks as Agent" setting
  • ✓ Knowledge Base - List, create and change FAQ categories; search, read, create and change FAQ articles, including internal/public/featured. Nothing is deleted. Friendly /kb/changes also need the "Tasks as Agent" setting
lt;slugchanges also need the "Tasks as Agent" settinggt; URLs are read from the root .htaccess
Controlled by: can_read_kb, can_write_kb

⚠ Important: Access to these endpoints is controlled individually per API Key using the permissions below.

' ) )), @@ -219,6 +219,28 @@ static function taskPermissions() { ); } + /** + * Knowledge base permissions: column => [form field, label, endpoint] + * + * @return array + */ + static function kbPermissions() { + return array( + 'can_read_kb' => array('api_key_kb_read_permissions', 'Read Knowledge Base', 'GET /kb-categories-list, /kb-faq-search, /kb-faq-get/:id'), + 'can_write_kb' => array('api_key_kb_write_permissions', 'Change Knowledge Base', 'POST/PATCH /kb-categories-*, /kb-faq-create, /kb-faq-update/:id (no delete)'), + ); + } + + /** + * Task and knowledge base permissions (rendered, saved and + * whitelisted the same way) + * + * @return array + */ + static function extraPermissions() { + return array_merge(self::taskPermissions(), self::kbPermissions()); + } + /** * Get list of allowed permission columns for validation * @@ -234,7 +256,7 @@ private function getAllowedPermissionColumns() { 'can_read_stats', 'can_manage_subtickets', 'can_reply_tickets' - ), array_keys(self::taskPermissions())); + ), array_keys(self::extraPermissions())); } /** @@ -264,7 +286,7 @@ private static function columnExistsStatic($columnName) { 'can_read_stats', 'can_manage_subtickets', 'can_reply_tickets' - ), array_keys(self::taskPermissions())); + ), array_keys(self::extraPermissions())); // Validate column name against whitelist if (!in_array($columnName, $allowedColumns)) { @@ -291,7 +313,7 @@ private static function columnExistsStatic($columnName) { function pre_save(&$config = [], &$errors = []) { // Handle API Key permissions from $_POST (not in $config because FreeTextField doesn't register fields) $taskPermissionPosted = false; - foreach (self::taskPermissions() as $taskField) { + foreach (self::extraPermissions() as $taskField) { if (isset($_POST[$taskField[0]])) { $taskPermissionPosted = true; } @@ -306,7 +328,7 @@ function pre_save(&$config = [], &$errors = []) { $hasSubticketColumn = $this->columnExists('can_manage_subtickets'); $hasReplyColumn = $this->columnExists('can_reply_tickets'); $taskColumns = array(); - foreach (self::taskPermissions() as $column => $taskField) { + foreach (self::extraPermissions() as $column => $taskField) { if ($this->columnExists($column)) { $taskColumns[$column] = $taskField[0]; } @@ -385,7 +407,7 @@ function pre_save(&$config = [], &$errors = []) { $setClauses[] = sprintf('`can_reply_tickets` = %d', (int)$canReply); } - // Column names come from taskPermissions() and exist (checked above) + // Column names come from extraPermissions() and exist (checked above) foreach ($taskColumns as $column => $field) { $granted = isset($_POST[$field]) && is_array($_POST[$field]) && isset($_POST[$field][$apiKeyId]); $setClauses[] = sprintf('`%s` = %d', $column, $granted ? 1 : 0); @@ -436,7 +458,7 @@ static function renderApiKeyPermissionsTable() { if ($hasSubticketColumn) $columns .= ', can_manage_subtickets'; if ($hasReplyColumn) $columns .= ', can_reply_tickets'; $taskColumns = array(); - foreach (self::taskPermissions() as $column => $taskField) { + foreach (self::extraPermissions() as $column => $taskField) { if (self::columnExistsStatic($column)) { $taskColumns[$column] = $taskField; $columns .= ', ' . $column; diff --git a/controllers/ExtendedTicketApiController.php b/controllers/ExtendedTicketApiController.php index cefea47..1eb41f6 100644 --- a/controllers/ExtendedTicketApiController.php +++ b/controllers/ExtendedTicketApiController.php @@ -21,6 +21,7 @@ public function requireApiKey() { return true; } require_once __DIR__ . '/../lib/Services/PermissionChecker.php'; require_once __DIR__ . '/../lib/Services/TicketService.php'; require_once __DIR__ . '/../lib/Services/TaskService.php'; +require_once __DIR__ . '/../lib/Services/KbService.php'; require_once __DIR__ . '/../lib/Enums/Permission.php'; /** @@ -631,6 +632,66 @@ public function deleteTask(string $number, ?string $comments = null): array return TaskService::getInstance()->deleteTask($this->resolveTaskAgent(), $number, $comments); } + // ========================================================================= + // Knowledge base (FAQ articles and categories) + // Two API key permissions: can_read_kb, can_write_kb. FAQs have no + // department, so no agent is involved. Nothing is ever deleted. + // ========================================================================= + + /** + * @throws Exception 401 key/permission + */ + private function requireKbPermission(Permission $permission): void + { + $key = $this->requireApiKey(); + if (!$key) { + throw new Exception('API key not authorized', 401); + } + $this->permissionChecker->require($key, $permission); + } + + public function listKbCategories(): array + { + $this->requireKbPermission(Permission::ReadKb); + return KbService::getInstance()->listCategories(); + } + + public function createKbCategory(array $data): array + { + $this->requireKbPermission(Permission::WriteKb); + return KbService::getInstance()->createCategory($data); + } + + public function updateKbCategory(string $id, array $data): array + { + $this->requireKbPermission(Permission::WriteKb); + return KbService::getInstance()->updateCategory($id, $data); + } + + public function searchKbArticles(array $params): array + { + $this->requireKbPermission(Permission::ReadKb); + return KbService::getInstance()->searchArticles($params); + } + + public function getKbArticle(string $id): array + { + $this->requireKbPermission(Permission::ReadKb); + return KbService::getInstance()->getArticle($id); + } + + public function createKbArticle(array $data): array + { + $this->requireKbPermission(Permission::WriteKb); + return KbService::getInstance()->createArticle($data); + } + + public function updateKbArticle(string $id, array $data): array + { + $this->requireKbPermission(Permission::WriteKb); + return KbService::getInstance()->updateArticle($id, $data); + } + /** * Set the ticket priority. * diff --git a/htaccess.template b/htaccess.template index 4eceaa5..415f7ae 100644 --- a/htaccess.template +++ b/htaccess.template @@ -59,3 +59,19 @@ RewriteRule ^tickets-tasks-update\.php/ - [L] # Task Delete API endpoint (path parameter: task number) RewriteRule ^tickets-tasks-delete\.php/ - [L] + +# Knowledge base: category list and create (no path parameter - optional .json in PATH_INFO) +RewriteRule ^kb-categories-list\.php.*$ - [L] +RewriteRule ^kb-categories-create\.php.*$ - [L] + +# Knowledge base: category update (path parameter: category id) +RewriteRule ^kb-categories-update\.php/ - [L] + +# Knowledge base: article search and create (no path parameter - optional .json in PATH_INFO) +RewriteRule ^kb-faq-search\.php.*$ - [L] +RewriteRule ^kb-faq-create\.php.*$ - [L] + +# Knowledge base: article get and update (path parameter: article id) +RewriteRule ^kb-faq-get\.php/ - [L] +RewriteRule ^kb-faq-update\.php/ - [L] +# End of API Endpoints Plugin rules diff --git a/lib/Enums/Permission.php b/lib/Enums/Permission.php index 67d6763..e41edab 100644 --- a/lib/Enums/Permission.php +++ b/lib/Enums/Permission.php @@ -23,6 +23,8 @@ enum Permission: string case ReadTasks = 'can_read_tasks'; case SearchTasks = 'can_search_tasks'; case DeleteTasks = 'can_delete_tasks'; + case ReadKb = 'can_read_kb'; + case WriteKb = 'can_write_kb'; /** * Get human-readable label for this permission @@ -45,6 +47,8 @@ public function label(): string self::ReadTasks => 'Read Tasks', self::SearchTasks => 'Search Tasks', self::DeleteTasks => 'Delete Tasks', + self::ReadKb => 'Read Knowledge Base', + self::WriteKb => 'Change Knowledge Base', }; } @@ -69,6 +73,8 @@ public function endpoint(): string self::ReadTasks => 'GET /tickets-tasks-get/:number', self::SearchTasks => 'GET /tickets-tasks-search', self::DeleteTasks => 'DELETE /tickets-tasks-delete/:number', + self::ReadKb => 'GET /kb-categories-list, /kb-faq-search, /kb-faq-get/:id', + self::WriteKb => 'POST/PATCH /kb-categories-*, /kb-faq-create, /kb-faq-update/:id', }; } @@ -94,6 +100,8 @@ public function unauthorizedMessage(string $context = 'this operation'): string self::ReadTasks => 'read tasks', self::SearchTasks => 'search tasks', self::DeleteTasks => 'delete tasks', + self::ReadKb => 'read the knowledge base', + self::WriteKb => 'change the knowledge base', }); } diff --git a/lib/Services/KbService.php b/lib/Services/KbService.php new file mode 100644 index 0000000..79e5a33 --- /dev/null +++ b/lib/Services/KbService.php @@ -0,0 +1,669 @@ +) are configured by hand in the + * .htaccess of the osTicket root. The service only reads that file to + * report the slug of an article; it never writes it. + */ + +declare(strict_types=1); + +class KbService +{ + /** TEXT columns (answer, FAQ notes, category description) in bytes */ + public const TEXT_MAX_BYTES = 65535; + + /** faq.question is VARCHAR(255) */ + public const QUESTION_MAX_LENGTH = 255; + + /** faq_category.name is VARCHAR(125), osTicket needs at least 3 */ + public const CATEGORY_NAME_MIN_LENGTH = 3; + public const CATEGORY_NAME_MAX_LENGTH = 125; + + /** faq_category.notes is TINYTEXT */ + public const CATEGORY_NOTES_MAX_BYTES = 255; + + /** Search page size */ + public const SEARCH_DEFAULT_LIMIT = 50; + public const SEARCH_MAX_LIMIT = 100; + public const QUERY_MAX_LENGTH = 200; + + /** Largest .htaccess the slug reader parses */ + public const HTACCESS_MAX_BYTES = 262144; + + /** Deepest category nesting the parent check walks */ + private const MAX_CATEGORY_DEPTH = 20; + + /** API name => osTicket value (faq.ispublished, faq_category.ispublic) */ + public const VISIBILITY = [ + 'internal' => 0, + 'public' => 1, + 'featured' => 2, + ]; + + /** @var array|null article id => slug, read once per request */ + private ?array $slugs = null; + + /** Path of the .htaccess with the slug rules (tests point it elsewhere) */ + private ?string $htaccessPath; + + public function __construct(?string $htaccessPath = null) + { + $this->htaccessPath = $htaccessPath; + } + + // ========================================================================= + // Categories + // ========================================================================= + + /** + * All categories with parent, visibility and article count + */ + public function listCategories(): array + { + $categories = []; + foreach (Category::objects()->order_by('name') as $category) { + $categories[] = $this->buildCategoryResponse($category); + } + + usort($categories, fn($a, $b) => strcasecmp($a['fullName'], $b['fullName'])); + + return [ + 'total' => count($categories), + 'categories' => $categories, + ]; + } + + /** + * Create a category (internal unless visibility says otherwise) + * + * @throws Exception 400 invalid input + */ + public function createCategory(array $data): array + { + $vars = [ + 'id' => 0, + 'name' => $this->categoryName($data['name'] ?? null), + 'description' => $this->requiredHtml($data['description'] ?? null, 'description'), + 'notes' => $this->categoryNotes($data['notes'] ?? ''), + 'ispublic' => $this->visibility($data['visibility'] ?? 'internal'), + 'pid' => $this->parentId($data['parentId'] ?? null, null), + ]; + + $category = Category::create(); + $errors = []; + if (!$category->update($vars, $errors)) { + throw new Exception($this->errorMessage($errors, 'Unable to create the category'), 400); + } + + return $this->buildCategoryResponse($this->lookupCategory((int)$category->getId())); + } + + /** + * Change a category; fields left out keep their value + * + * @throws Exception 400 invalid input, 404 unknown category + */ + public function updateCategory(string $id, array $data): array + { + $category = $this->lookupCategory($this->parseId($id, 'category')); + $categoryId = (int)$category->getId(); + + $vars = [ + 'id' => $categoryId, + 'name' => array_key_exists('name', $data) + ? $this->categoryName($data['name']) + : (string)$category->getName(), + 'description' => array_key_exists('description', $data) + ? $this->requiredHtml($data['description'], 'description') + : (string)$category->getDescription(), + 'notes' => array_key_exists('notes', $data) + ? $this->categoryNotes($data['notes']) + : (string)$category->getNotes(), + 'ispublic' => array_key_exists('visibility', $data) + ? $this->visibility($data['visibility']) + : (int)$category->ispublic, + 'pid' => array_key_exists('parentId', $data) + ? $this->parentId($data['parentId'], $categoryId) + : ((int)$category->category_pid ?: null), + ]; + + $errors = []; + if (!$category->update($vars, $errors)) { + throw new Exception($this->errorMessage($errors, 'Unable to update the category'), 400); + } + + return $this->buildCategoryResponse($this->lookupCategory($categoryId)); + } + + /** + * @throws Exception 404 + */ + public function lookupCategory(int $id): Category + { + $category = Category::lookup($id); + if (!$category) { + throw new Exception('Category not found', 404); + } + return $category; + } + + public function buildCategoryResponse(Category $category): array + { + $parentId = (int)$category->category_pid ?: null; + $parent = $parentId ? Category::lookup($parentId) : null; + + return [ + 'id' => (int)$category->getId(), + 'name' => (string)$category->getName(), + 'fullName' => (string)($category->getFullName() ?: $category->getName()), + 'parentId' => $parent ? $parentId : null, + 'parent' => $parent ? (string)$parent->getName() : null, + 'visibility' => $this->visibilityName((int)$category->ispublic), + 'description' => (string)$category->getDescription(), + 'notes' => (string)$category->getNotes(), + 'articleCount' => (int)FAQ::objects()->filter(['category_id' => (int)$category->getId()])->count(), + 'created' => $this->dateValue($category->created ?? null, FAQ_CATEGORY_TABLE, 'category_id', (int)$category->getId(), 'created'), + 'updated' => $this->dateValue($category->updated ?? null, FAQ_CATEGORY_TABLE, 'category_id', (int)$category->getId(), 'updated'), + ]; + } + + // ========================================================================= + // Articles + // ========================================================================= + + /** + * Search articles + * + * Filters: query (title and answer), categoryId, visibility, slug. + * + * @throws Exception 400 invalid filter + */ + public function searchArticles(array $params): array + { + $articles = FAQ::objects(); + + $query = trim((string)($params['query'] ?? '')); + if ($query !== '') { + if (mb_strlen($query) > self::QUERY_MAX_LENGTH) { + throw new Exception('query is too long (max ' . self::QUERY_MAX_LENGTH . ' characters)', 400); + } + $articles = $articles->filter(Q::any([ + 'question__contains' => $query, + 'answer__contains' => $query, + ])); + } + + if (isset($params['categoryId']) && $params['categoryId'] !== '') { + $articles = $articles->filter(['category_id' => $this->parseId((string)$params['categoryId'], 'categoryId')]); + } + + if (isset($params['visibility']) && $params['visibility'] !== '') { + $articles = $articles->filter(['ispublished' => $this->visibility($params['visibility'])]); + } + + if (isset($params['slug']) && $params['slug'] !== '') { + $slug = (string)$params['slug']; + if (!self::isValidSlug($slug)) { + throw new Exception('Invalid slug: use a-z, 0-9 and hyphens', 400); + } + $id = array_search($slug, $this->slugs(), true); + $articles = $articles->filter(['faq_id' => $id === false ? 0 : (int)$id]); + } + + $limit = $this->intParam($params['limit'] ?? null, self::SEARCH_DEFAULT_LIMIT, 1, self::SEARCH_MAX_LIMIT, 'limit'); + $offset = $this->intParam($params['offset'] ?? null, 0, 0, PHP_INT_MAX, 'offset'); + + $total = (int)$articles->count(); + $page = $articles->order_by('-updated')->limit($limit)->offset($offset); + + $results = []; + foreach ($page as $faq) { + $results[] = $this->buildArticleResponse($faq, false); + } + + return [ + 'total' => $total, + 'limit' => $limit, + 'offset' => $offset, + 'articles' => $results, + ]; + } + + /** + * One article with answer, notes and help topics + * + * @throws Exception 400 malformed id, 404 unknown article + */ + public function getArticle(string $id): array + { + return $this->buildArticleResponse($this->lookupArticle($this->parseId($id, 'article')), true); + } + + /** + * Create an article (internal unless visibility says otherwise) + * + * @throws Exception 400 invalid input + */ + public function createArticle(array $data): array + { + $categoryId = $this->parseId((string)($data['categoryId'] ?? ''), 'categoryId'); + $this->lookupCategory($categoryId); + + $vars = [ + 'id' => 0, + 'question' => $this->question($data['question'] ?? null), + 'answer' => $this->requiredHtml($data['answer'] ?? null, 'answer'), + 'category_id' => $categoryId, + 'ispublished' => $this->visibility($data['visibility'] ?? 'internal'), + 'notes' => $this->optionalHtml($data['notes'] ?? '', 'notes'), + 'topics' => [], + ]; + + $faq = FAQ::create(); + $errors = []; + if (!$faq->update($vars, $errors)) { + throw new Exception($this->errorMessage($errors, 'Unable to create the article'), 400); + } + + return $this->buildArticleResponse($this->lookupArticle((int)$faq->getId()), true); + } + + /** + * Change an article; fields left out keep their value + * + * FAQ::update() expects the whole article: missing notes or help + * topics would be cleared. The current values fill the gaps. + * + * @throws Exception 400 invalid input, 404 unknown article or category + */ + public function updateArticle(string $id, array $data): array + { + $faq = $this->lookupArticle($this->parseId($id, 'article')); + $faqId = (int)$faq->getId(); + + $categoryId = (int)$faq->getCategoryId(); + if (array_key_exists('categoryId', $data)) { + $categoryId = $this->parseId((string)$data['categoryId'], 'categoryId'); + $this->lookupCategory($categoryId); + } + + $vars = [ + 'id' => $faqId, + 'question' => array_key_exists('question', $data) + ? $this->question($data['question']) + : (string)$faq->getQuestion(), + 'answer' => array_key_exists('answer', $data) + ? $this->requiredHtml($data['answer'], 'answer') + : (string)$faq->getAnswer(), + 'category_id' => $categoryId, + 'ispublished' => array_key_exists('visibility', $data) + ? $this->visibility($data['visibility']) + : (int)$faq->ispublished, + 'notes' => array_key_exists('notes', $data) + ? $this->optionalHtml($data['notes'], 'notes') + : (string)$faq->getNotes(), + 'topics' => $faq->getHelpTopicsIds(), + ]; + + $errors = []; + if (!$faq->update($vars, $errors)) { + throw new Exception($this->errorMessage($errors, 'Unable to update the article'), 400); + } + + return $this->buildArticleResponse($this->lookupArticle($faqId), true); + } + + /** + * @throws Exception 404 + */ + public function lookupArticle(int $id): FAQ + { + $faq = FAQ::lookup($id); + if (!$faq) { + throw new Exception('Article not found', 404); + } + return $faq; + } + + /** + * @param bool $withContent Include answer, notes and help topics + */ + public function buildArticleResponse(FAQ $faq, bool $withContent): array + { + $id = (int)$faq->getId(); + $category = $faq->getCategory(); + $categoryVisibility = $category ? (int)$category->ispublic : 0; + $visibility = (int)$faq->ispublished; + $slug = $this->slugs()[$id] ?? null; + $base = $this->baseUrl(); + + $response = [ + 'id' => $id, + 'question' => (string)$faq->getQuestion(), + 'categoryId' => (int)$faq->getCategoryId(), + 'category' => $category ? (string)($category->getFullName() ?: $category->getName()) : null, + 'categoryVisibility' => $this->visibilityName($categoryVisibility), + 'visibility' => $this->visibilityName($visibility), + // Customers see an article only when it and its category are public + 'visibleInPortal' => $visibility > 0 && $categoryVisibility > 0, + 'slug' => $slug, + 'publicUrl' => $slug !== null && $base !== '' ? $base . '/kb/' . $slug : null, + 'portalUrl' => $base !== '' ? $base . '/kb/faq.php?id=' . $id : null, + 'staffUrl' => $base !== '' ? $base . '/scp/faq.php?id=' . $id : null, + 'created' => $this->dateValue($faq->getCreateDate(), FAQ_TABLE, 'faq_id', $id, 'created'), + 'updated' => $this->dateValue($faq->getUpdateDate(), FAQ_TABLE, 'faq_id', $id, 'updated'), + ]; + + if ($withContent) { + $response['answer'] = (string)$faq->getAnswer(); + $response['notes'] = (string)$faq->getNotes(); + $topics = []; + foreach ($faq->getHelpTopics() as $link) { + $topic = $link->topic ?? null; + if ($topic) { + $topics[] = ['id' => (int)$topic->getId(), 'name' => (string)$topic->getFullName()]; + } + } + $response['helpTopics'] = $topics; + } + + return $response; + } + + // ========================================================================= + // Slugs (read-only) + // ========================================================================= + + /** + * Slug format of the friendly URLs: lowercase letters, digits, hyphens + */ + public static function isValidSlug(string $slug): bool + { + return strlen($slug) <= 100 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1; + } + + /** + * Parse the slug rules of the root .htaccess + * + * Rule format: RewriteRule ^kb/$ kb/faq.php?id= [QSA,L] + * Commented-out lines are skipped. The first rule for an id wins. + * + * @return array article id => slug + */ + public static function parseSlugRules(string $content): array + { + $slugs = []; + $pattern = '#^[ \t]*RewriteRule[ \t]+\^kb/([a-z0-9-]+)\$[ \t]+/?kb/faq\.php\?id=(\d+)[ \t]#m'; + if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) { + foreach ($matches as $match) { + $id = (int)$match[2]; + if ($id > 0 && !isset($slugs[$id]) && self::isValidSlug($match[1])) { + $slugs[$id] = $match[1]; + } + } + } + return $slugs; + } + + /** + * @return array article id => slug ([] if the file is missing) + */ + public function slugs(): array + { + if ($this->slugs !== null) { + return $this->slugs; + } + + $this->slugs = []; + $path = $this->htaccessPath ?? (defined('ROOT_DIR') ? ROOT_DIR . '.htaccess' : null); + if ($path === null || !is_file($path) || !is_readable($path)) { + return $this->slugs; + } + + $size = @filesize($path); + if ($size === false || $size > self::HTACCESS_MAX_BYTES) { + error_log('[API Endpoints] Root .htaccess not parsed for KB slugs (unreadable or too large)'); + return $this->slugs; + } + + $content = @file_get_contents($path); + if ($content !== false) { + $this->slugs = self::parseSlugRules($content); + } + return $this->slugs; + } + + // ========================================================================= + // Validation helpers + // ========================================================================= + + /** + * @throws Exception 400 + */ + public function parseId(string $value, string $field): int + { + $value = trim($value); + if (!preg_match('/^[1-9][0-9]{0,9}$/', $value)) { + throw new Exception("Invalid {$field}: expected a positive integer", 400); + } + return (int)$value; + } + + /** + * @throws Exception 400 + */ + public function visibility(mixed $value): int + { + if (!is_string($value) || !array_key_exists($value, self::VISIBILITY)) { + throw new Exception('Invalid visibility: use internal, public or featured', 400); + } + return self::VISIBILITY[$value]; + } + + public function visibilityName(int $value): string + { + $name = array_search($value, self::VISIBILITY, true); + return $name === false ? 'internal' : $name; + } + + /** + * @throws Exception 400 + */ + private function question(mixed $value): string + { + if (!is_string($value) || trim($value) === '') { + throw new Exception('question is required', 400); + } + $value = trim($value); + if (mb_strlen($value) > self::QUESTION_MAX_LENGTH) { + throw new Exception('question is too long (max ' . self::QUESTION_MAX_LENGTH . ' characters)', 400); + } + return $value; + } + + /** + * @throws Exception 400 + */ + private function categoryName(mixed $value): string + { + if (!is_string($value) || trim($value) === '') { + throw new Exception('name is required', 400); + } + $value = trim($value); + $length = mb_strlen($value); + if ($length < self::CATEGORY_NAME_MIN_LENGTH || $length > self::CATEGORY_NAME_MAX_LENGTH) { + throw new Exception(sprintf('name must have %d to %d characters', + self::CATEGORY_NAME_MIN_LENGTH, self::CATEGORY_NAME_MAX_LENGTH), 400); + } + return $value; + } + + /** + * @throws Exception 400 + */ + private function categoryNotes(mixed $value): string + { + if ($value === null) { + return ''; + } + if (!is_string($value)) { + throw new Exception('notes must be a string', 400); + } + if (strlen($value) > self::CATEGORY_NOTES_MAX_BYTES) { + throw new Exception('notes is too long (max ' . self::CATEGORY_NOTES_MAX_BYTES . ' bytes for categories)', 400); + } + return $value; + } + + /** + * @throws Exception 400 + */ + private function requiredHtml(mixed $value, string $field): string + { + if (!is_string($value) || trim(strip_tags($value)) === '') { + throw new Exception("{$field} is required", 400); + } + return $this->optionalHtml($value, $field); + } + + /** + * @throws Exception 400 + */ + private function optionalHtml(mixed $value, string $field): string + { + if ($value === null) { + return ''; + } + if (!is_string($value)) { + throw new Exception("{$field} must be a string", 400); + } + if (strlen($value) > self::TEXT_MAX_BYTES) { + throw new Exception("{$field} is too long (max " . self::TEXT_MAX_BYTES . ' bytes)', 400); + } + return $value; + } + + /** + * Validate a parent category; null or 0 means top level + * + * @param int|null $self Category being changed (must not become its own ancestor) + * @throws Exception 400 invalid parent, 404 unknown parent + */ + private function parentId(mixed $value, ?int $self): ?int + { + if ($value === null || $value === 0 || $value === '0' || $value === '') { + return null; + } + $parentId = $this->parseId((string)$value, 'parentId'); + if ($self !== null && $parentId === $self) { + throw new Exception('A category cannot be its own parent', 400); + } + + $current = $this->lookupCategory($parentId); + for ($depth = 0; $depth < self::MAX_CATEGORY_DEPTH; $depth++) { + $next = (int)$current->category_pid; + if ($next === 0) { + return $parentId; + } + if ($self !== null && $next === $self) { + throw new Exception('A category cannot be moved below one of its subcategories', 400); + } + $current = Category::lookup($next); + if (!$current) { + return $parentId; + } + } + throw new Exception('Category nesting is too deep', 400); + } + + /** + * @throws Exception 400 + */ + private function intParam(mixed $value, int $default, int $min, int $max, string $field): int + { + if ($value === null || $value === '') { + return $default; + } + if (!is_numeric($value) || (int)$value != $value) { + throw new Exception("Invalid {$field}", 400); + } + $value = (int)$value; + if ($value < $min || $value > $max) { + throw new Exception("{$field} must be between {$min} and {$max}", 400); + } + return $value; + } + + /** + * First osTicket validation error as client message + */ + private function errorMessage(array $errors, string $fallback): string + { + $messages = []; + foreach ($errors as $field => $message) { + if (is_string($message) && $message !== '') { + $messages[] = $field === 'err' ? $message : "{$field}: {$message}"; + } + } + return $messages ? implode('; ', $messages) : $fallback; + } + + private function baseUrl(): string + { + global $cfg; + if (!$cfg || !method_exists($cfg, 'getBaseUrl')) { + return ''; + } + return rtrim((string)$cfg->getBaseUrl(), '/'); + } + + /** + * Stored date + * + * After a change in this request the ORM still holds the NOW() + * expression it wrote, not the stored value, so it is read back. + * Table and column names come from this class, never from input. + */ + private function dateValue(mixed $value, string $table, string $idColumn, int $id, string $column): ?string + { + if ($value === null || is_string($value)) { + return $value; + } + if (!function_exists('db_query')) { + return null; + } + $result = db_query(sprintf('SELECT `%s` FROM %s WHERE `%s` = %d', $column, $table, $idColumn, $id)); + $row = $result ? db_fetch_array($result) : null; + return $row ? (string)$row[$column] : null; + } + + // ========================================================================= + // Singleton + // ========================================================================= + + private static ?self $instance = null; + + public static function getInstance(): self + { + if (self::$instance === null) { + self::$instance = new self(); + } + return self::$instance; + } + + /** For tests */ + public static function setInstance(?self $instance): void + { + self::$instance = $instance; + } +} diff --git a/openapi.yaml b/openapi.yaml index d8cd509..1d13e24 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -48,6 +48,11 @@ tags: linked to a ticket. Each operation has its own API key permission. Changes run as the agent set in "Tasks as Agent"; osTicket applies that agent's role in the task's department, like in the staff UI. + - name: Knowledge Base + description: | + FAQ categories and articles: list, search, read, create and change, + including internal/public/featured. There is no delete. Reading needs + `can_read_kb`, changes need `can_write_kb`. security: - ApiKeyAuth: [] @@ -898,6 +903,252 @@ paths: '404': $ref: '#/components/responses/NotFound' + # =========================================================================== + # Knowledge Base + # =========================================================================== + + /kb-categories-list.php: + get: + operationId: listKbCategories + summary: List FAQ categories + description: All categories with parent, visibility and article count. Requires `can_read_kb`. + tags: + - Knowledge Base + responses: + '200': + description: Categories + content: + application/json: + schema: + type: object + properties: + total: + type: integer + categories: + type: array + items: + $ref: '#/components/schemas/KbCategory' + '401': + $ref: '#/components/responses/Unauthorized' + + /kb-categories-create.php: + post: + operationId: createKbCategory + summary: Create an FAQ category + description: | + Creates a category through osTicket's `Category::update()` (same + validation and HTML sanitizing as the staff UI). Internal unless + `visibility` is set. Requires `can_write_kb`. + tags: + - Knowledge Base + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/KbCategoryRequest' + responses: + '201': + description: Category created + content: + application/json: + schema: + $ref: '#/components/schemas/KbCategory' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + + /kb-categories-update.php/{id}.{format}: + patch: + operationId: updateKbCategory + summary: Change an FAQ category + description: | + Fields left out keep their value. A category cannot become its own + parent or move below one of its subcategories. Nothing is deleted. + Requires `can_write_kb`. + tags: + - Knowledge Base + parameters: + - $ref: '#/components/parameters/kbId' + - $ref: '#/components/parameters/responseFormat' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/KbCategoryRequest' + responses: + '200': + description: Category changed + content: + application/json: + schema: + $ref: '#/components/schemas/KbCategory' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + + /kb-faq-search.php: + get: + operationId: searchKbArticles + summary: Search FAQ articles + description: | + Newest change first. Text search covers title and answer. `slug` + finds the article behind a friendly URL. Requires `can_read_kb`. + tags: + - Knowledge Base + parameters: + - name: query + in: query + schema: + type: string + maxLength: 200 + - name: categoryId + in: query + schema: + type: integer + - name: visibility + in: query + schema: + type: string + enum: [internal, public, featured] + - name: slug + in: query + schema: + type: string + pattern: '^[a-z0-9]+(-[a-z0-9]+)*$' + - name: limit + in: query + schema: + type: integer + minimum: 1 + maximum: 100 + default: 50 + - name: offset + in: query + schema: + type: integer + minimum: 0 + default: 0 + responses: + '200': + description: Matching articles (without answer) + content: + application/json: + schema: + type: object + properties: + total: + type: integer + limit: + type: integer + offset: + type: integer + articles: + type: array + items: + $ref: '#/components/schemas/KbArticle' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + + /kb-faq-get.php/{id}.{format}: + get: + operationId: getKbArticle + summary: Get an FAQ article + description: Article with answer (HTML), notes and help topics. Requires `can_read_kb`. + tags: + - Knowledge Base + parameters: + - $ref: '#/components/parameters/kbId' + - $ref: '#/components/parameters/responseFormat' + responses: + '200': + description: Article + content: + application/json: + schema: + $ref: '#/components/schemas/KbArticleDetail' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + + /kb-faq-create.php: + post: + operationId: createKbArticle + summary: Create an FAQ article + description: | + Creates an article through osTicket's `FAQ::update()`: the answer is + sanitized like in the staff UI, tags are stripped from the title, + duplicate titles are refused. Internal unless `visibility` is set. + Requires `can_write_kb`. + tags: + - Knowledge Base + requestBody: + required: true + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/KbArticleRequest' + - required: [question, answer, categoryId] + responses: + '201': + description: Article created + content: + application/json: + schema: + $ref: '#/components/schemas/KbArticleDetail' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + + /kb-faq-update.php/{id}.{format}: + patch: + operationId: updateKbArticle + summary: Change an FAQ article + description: | + Fields left out keep their value; linked help topics and attachments + stay. `visibility: internal` hides an article from the portal. There + is no delete. Requires `can_write_kb`. + tags: + - Knowledge Base + parameters: + - $ref: '#/components/parameters/kbId' + - $ref: '#/components/parameters/responseFormat' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/KbArticleRequest' + responses: + '200': + description: Article changed + content: + application/json: + schema: + $ref: '#/components/schemas/KbArticleDetail' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '404': + $ref: '#/components/responses/NotFound' + # ============================================================================= # Components # ============================================================================= @@ -935,6 +1186,15 @@ components: type: string pattern: '^[A-Za-z0-9-]{1,20}$' + kbId: + name: id + in: path + required: true + description: Article or category ID + schema: + type: integer + minimum: 1 + responseFormat: name: format in: path @@ -1781,3 +2041,132 @@ components: type: boolean default: true description: Send osTicket's agent alerts for transfer, assignment, note and update + + KbVisibility: + type: string + enum: [internal, public, featured] + description: | + internal = staff only; public = portal; featured = portal and start + page. An article shows in the portal only if its category is public + or featured too. + + KbCategory: + type: object + properties: + id: + type: integer + name: + type: string + fullName: + type: string + description: Name with parent, e.g. "Prozesse / Intern" + parentId: + type: [integer, 'null'] + parent: + type: [string, 'null'] + visibility: + $ref: '#/components/schemas/KbVisibility' + description: + type: string + description: HTML + notes: + type: string + articleCount: + type: integer + created: + type: [string, 'null'] + updated: + type: [string, 'null'] + + KbCategoryRequest: + type: object + additionalProperties: false + description: For create, `name` and `description` are required. + properties: + name: + type: string + minLength: 3 + maxLength: 125 + description: + type: string + description: HTML, required by osTicket + notes: + type: string + maxLength: 255 + parentId: + type: [integer, 'null'] + description: null or 0 = top level + visibility: + $ref: '#/components/schemas/KbVisibility' + + KbArticle: + type: object + properties: + id: + type: integer + question: + type: string + categoryId: + type: integer + category: + type: [string, 'null'] + categoryVisibility: + $ref: '#/components/schemas/KbVisibility' + visibility: + $ref: '#/components/schemas/KbVisibility' + visibleInPortal: + type: boolean + slug: + type: [string, 'null'] + description: Friendly URL slug, read from the RewriteRules in the root .htaccess (never written) + publicUrl: + type: [string, 'null'] + description: /kb/ + portalUrl: + type: [string, 'null'] + staffUrl: + type: [string, 'null'] + created: + type: [string, 'null'] + updated: + type: [string, 'null'] + + KbArticleDetail: + allOf: + - $ref: '#/components/schemas/KbArticle' + - type: object + properties: + answer: + type: string + description: HTML + notes: + type: string + description: Internal notes (HTML) + helpTopics: + type: array + items: + type: object + properties: + id: + type: integer + name: + type: string + + KbArticleRequest: + type: object + additionalProperties: false + properties: + question: + type: string + maxLength: 255 + description: Title; HTML tags are stripped + answer: + type: string + description: HTML, sanitized by osTicket (max 65535 bytes) + categoryId: + type: integer + notes: + type: string + description: Internal notes (HTML) + visibility: + $ref: '#/components/schemas/KbVisibility' diff --git a/plugin.php b/plugin.php index 2da69c1..bacb3cb 100644 --- a/plugin.php +++ b/plugin.php @@ -2,7 +2,7 @@ return array( 'id' => 'com.osticket:api-endpoints', - 'version' => '2.7.0', + 'version' => '2.8.0', 'name' => 'API Endpoints', 'author' => 'Markus Michalski', 'description' => 'Extends osTicket API with additional endpoints and parameters: ticket creation with Markdown support, department selection, and subticket functionality.', diff --git a/tests/Integration/KbEndpointAccessTest.php b/tests/Integration/KbEndpointAccessTest.php new file mode 100644 index 0000000..17c767f --- /dev/null +++ b/tests/Integration/KbEndpointAccessTest.php @@ -0,0 +1,108 @@ + 'test-api-key'] + $permissions); + } + + /** + * @return array + */ + public static function readEndpoints(): array { + return [ + 'categories' => ['read the knowledge base', fn($c) => $c->listKbCategories()], + 'search' => ['read the knowledge base', fn($c) => $c->searchKbArticles([])], + 'get' => ['read the knowledge base', fn($c) => $c->getKbArticle('1')], + ]; + } + + /** + * @return array + */ + public static function writeEndpoints(): array { + return [ + 'category create' => ['change the knowledge base', fn($c) => $c->createKbCategory(['name' => 'xyz', 'description' => 'd'])], + 'category update' => ['change the knowledge base', fn($c) => $c->updateKbCategory('1', ['name' => 'xyz'])], + 'article create' => ['change the knowledge base', fn($c) => $c->createKbArticle(['question' => 'q', 'answer' => 'a', 'categoryId' => 1])], + 'article update' => ['change the knowledge base', fn($c) => $c->updateKbArticle('1', ['question' => 'q'])], + ]; + } + + public static function allEndpoints(): array { + return self::readEndpoints() + self::writeEndpoints(); + } + + #[DataProvider('allEndpoints')] + public function testTicketAndTaskPermissionsDoNotGrantKbAccess(string $action, callable $call): void { + $this->useKey([ + 'can_create_tickets' => true, + 'can_update_tickets' => true, + 'can_read_tickets' => true, + 'can_search_tickets' => true, + 'can_delete_tickets' => true, + 'can_reply_tickets' => true, + 'can_create_tasks' => true, + 'can_update_tasks' => true, + 'can_read_tasks' => true, + 'can_delete_tasks' => true, + ]); + + $this->expectException(Exception::class); + $this->expectExceptionCode(401); + $this->expectExceptionMessage('API key not authorized to ' . $action); + $call(new ExtendedTicketApiController()); + } + + #[DataProvider('writeEndpoints')] + public function testReadPermissionDoesNotAllowChanges(string $action, callable $call): void { + $this->useKey(['can_read_kb' => true]); + + $this->expectException(Exception::class); + $this->expectExceptionCode(401); + $this->expectExceptionMessage('API key not authorized to ' . $action); + $call(new ExtendedTicketApiController()); + } + + #[DataProvider('readEndpoints')] + public function testWritePermissionDoesNotAllowReading(string $action, callable $call): void { + $this->useKey(['can_write_kb' => true]); + + $this->expectException(Exception::class); + $this->expectExceptionCode(401); + $this->expectExceptionMessage('API key not authorized to ' . $action); + $call(new ExtendedTicketApiController()); + } + + public function testConfigAndEnumListTheSameKbColumns(): void { + $kbColumns = ['can_read_kb', 'can_write_kb']; + + foreach ($kbColumns as $column) { + $this->assertContains($column, Permission::columnNames()); + } + $this->assertSame($kbColumns, array_keys(ApiEndpointsConfig::kbPermissions())); + $this->assertSame( + array_merge(array_keys(ApiEndpointsConfig::taskPermissions()), $kbColumns), + array_keys(ApiEndpointsConfig::extraPermissions()) + ); + } +} diff --git a/tests/Unit/HtaccessLeftoverTest.php b/tests/Unit/HtaccessLeftoverTest.php new file mode 100644 index 0000000..dcf6e8c --- /dev/null +++ b/tests/Unit/HtaccessLeftoverTest.php @@ -0,0 +1,68 @@ +', + '', + 'RewriteEngine On', + '', + 'RewriteCond %{REQUEST_FILENAME} !-f', + 'RewriteCond %{REQUEST_FILENAME} !-d', + 'RewriteCond %{REQUEST_URI} (.*/api)', + '', + 'RewriteRule ^(.*)$ %1/http.php/$1 [L]', + '', + '', + '', + '# Task Get API endpoint (path parameter: task number)', + 'RewriteRule ^tickets-tasks-get\.php/ - [L]', + '', + '# Task Search API endpoint (no path parameter - uses query params + optional .json in PATH_INFO)', + 'RewriteRule ^tickets-tasks-search\.php.*$ - [L]', + 'RewriteRule ^kb-faq-get\.php/ - [L]', + '# my own note', + 'RewriteRule ^custom\.php - [L]', + '', + '', + '', + ]); + + $cleaned = ApiEndpointsPlugin::stripLeftoverRules($content, __DIR__ . '/../../htaccess.template'); + + $this->assertStringNotContainsString('tickets-tasks', $cleaned); + $this->assertStringNotContainsString('kb-faq', $cleaned); + $this->assertStringNotContainsString('Task Get API endpoint', $cleaned); + $this->assertStringContainsString('RewriteRule ^(.*)$ %1/http.php/$1 [L]', $cleaned); + $this->assertStringContainsString('RewriteCond %{REQUEST_URI} (.*/api)', $cleaned); + $this->assertStringContainsString('# my own note', $cleaned); + $this->assertStringContainsString('RewriteRule ^custom\.php - [L]', $cleaned); + $this->assertStringContainsString('', $cleaned); + $this->assertDoesNotMatchRegularExpression("/\n{3,}/", $cleaned); + } + + public function testTemplateEndsWithEndMarker(): void { + $template = rtrim((string)file_get_contents(__DIR__ . '/../../htaccess.template')); + $this->assertStringEndsWith('# End of API Endpoints Plugin rules', $template); + } + + public function testEveryEndpointFileHasARewriteRule(): void { + $template = (string)file_get_contents(__DIR__ . '/../../htaccess.template'); + foreach (glob(__DIR__ . '/../../api/*.php') as $file) { + $name = preg_quote(basename($file, '.php'), '#'); + $this->assertMatchesRegularExpression('#RewriteRule \^' . $name . '\\\\\.php#', $template, basename($file)); + } + } +} diff --git a/tests/Unit/KbServiceTest.php b/tests/Unit/KbServiceTest.php new file mode 100644 index 0000000..8bc22a3 --- /dev/null +++ b/tests/Unit/KbServiceTest.php @@ -0,0 +1,118 @@ +/ -> /kb/ +RewriteRule ^kb/([a-z0-9-]+)/$ /kb/$1 [R=301,L] + +# --- Liste 1 --- +RewriteCond %{THE_REQUEST} ^[A-Z]+\s/kb/faq\.php\?id=75\s +RewriteRule ^kb/faq\.php$ /kb/subunternehmer? [R=301,L] + +# --- Liste 2: slug -> Artikel-ID (interne Umschreibung) --- +RewriteRule ^kb/subunternehmer$ kb/faq.php?id=75 [QSA,L] +RewriteRule ^kb/wordpress-bilder-hochladen$ kb/faq.php?id=56 [QSA,L] + RewriteRule ^kb/avv$ /kb/faq.php?id=77 [QSA,L] +# RewriteRule ^kb/alt$ kb/faq.php?id=12 [QSA,L] +RewriteRule ^kb/doppelt$ kb/faq.php?id=75 [QSA,L] +RewriteRule ^kb/Gross$ kb/faq.php?id=13 [QSA,L] +HT; + + public function testParsesSlugRules(): void { + $this->assertSame([ + 75 => 'subunternehmer', + 56 => 'wordpress-bilder-hochladen', + 77 => 'avv', + ], KbService::parseSlugRules(self::HTACCESS)); + } + + public function testParsesNothingFromEmptyFile(): void { + $this->assertSame([], KbService::parseSlugRules('')); + } + + public function testReadsSlugsFromFile(): void { + $path = tempnam(sys_get_temp_dir(), 'kb'); + file_put_contents($path, self::HTACCESS); + try { + $service = new KbService($path); + $this->assertSame('avv', $service->slugs()[77]); + } finally { + unlink($path); + } + } + + public function testMissingFileMeansNoSlugs(): void { + $service = new KbService(sys_get_temp_dir() . '/does-not-exist-' . uniqid() . '/.htaccess'); + $this->assertSame([], $service->slugs()); + } + + public static function slugs(): array { + return [ + ['avv', true], + ['wordpress-bilder-hochladen', true], + ['a1-b2', true], + ['', false], + ['AVV', false], + ['ueber-uns', true], + ['über-uns', false], + ['-avv', false], + ['avv-', false], + ['a--b', false], + ['a/b', false], + ['a_b', false], + [str_repeat('a', 101), false], + ]; + } + + #[DataProvider('slugs')] + public function testSlugFormat(string $slug, bool $valid): void { + $this->assertSame($valid, KbService::isValidSlug($slug)); + } + + public static function invalidIds(): array { + return [[''], ['0'], ['-1'], ['1.5'], ['abc'], ['1 OR 1=1'], ['12345678901']]; + } + + #[DataProvider('invalidIds')] + public function testRejectsInvalidIds(string $id): void { + $this->expectException(Exception::class); + $this->expectExceptionCode(400); + (new KbService())->parseId($id, 'article'); + } + + public function testAcceptsPositiveIds(): void { + $this->assertSame(77, (new KbService())->parseId(' 77 ', 'article')); + } + + public function testVisibilityValues(): void { + $service = new KbService(); + $this->assertSame(0, $service->visibility('internal')); + $this->assertSame(1, $service->visibility('public')); + $this->assertSame(2, $service->visibility('featured')); + $this->assertSame('featured', $service->visibilityName(2)); + $this->assertSame('internal', $service->visibilityName(9)); + } + + public static function invalidVisibility(): array { + return [['Public'], ['private'], [''], [1], [null], [true]]; + } + + #[DataProvider('invalidVisibility')] + public function testRejectsUnknownVisibility(mixed $value): void { + $this->expectException(Exception::class); + $this->expectExceptionCode(400); + (new KbService())->visibility($value); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 800510b..da219c2 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -521,7 +521,7 @@ public function __construct($data) { 'can_reply_tickets' => $this->permissions['can_reply_tickets'] ?? ($data['can_reply_tickets'] ?? false), 'can_manage_subtickets' => $this->permissions['can_manage_subtickets'] ?? ($data['can_manage_subtickets'] ?? false), ]; - foreach (['can_create_tasks', 'can_update_tasks', 'can_read_tasks', 'can_search_tasks', 'can_delete_tasks'] as $column) { + foreach (['can_create_tasks', 'can_update_tasks', 'can_read_tasks', 'can_search_tasks', 'can_delete_tasks', 'can_read_kb', 'can_write_kb'] as $column) { $this->ht[$column] = $this->permissions[$column] ?? ($data[$column] ?? false); } }