diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e89653..05d42f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security - Nothing yet -## [2.6.0] - 2026-11-01 +## [2.7.0] - 2026-11-07 + +### Added +- `PATCH /api/tickets-update.php/{number}.json` accepts `subject` to rename a ticket. The subject is written as the answer of the ticket form's subject field, so `ticket__cdata` and the subject search follow. The change is logged as an "edited" thread event with the old and the new subject, like an edit in the staff UI. An unchanged subject is skipped. +- Validation, before any other field of the request is changed: string, trimmed, not empty, valid UTF-8, a single line without control characters, no HTML (refused, not stripped), at most the length configured on the subject field of the ticket form (255 if none). Errors are answered with 400. + ### Added - Task endpoints for osTicket tasks, standalone or linked to a ticket: @@ -287,9 +292,10 @@ Release of the studio-prisma fork on top of upstream [v2.4.0](https://github.com [2.3.2]: https://github.com/markus-michalski/osticket-api-endpoints/releases/tag/v2.3.2 [2.3.3]: https://github.com/markus-michalski/osticket-api-endpoints/releases/tag/v2.3.3 [2.3.4]: https://github.com/markus-michalski/osticket-api-endpoints/releases/tag/v2.3.4 -[Unreleased]: https://github.com/studio-prisma/osticket-api-endpoints/compare/v2.6.0...HEAD +[Unreleased]: https://github.com/studio-prisma/osticket-api-endpoints/compare/v2.7.0...HEAD [2.4.0]: https://github.com/markus-michalski/osticket-api-endpoints/releases/tag/v2.4.0 [2.4.1]: https://github.com/studio-prisma/osticket-api-endpoints/releases/tag/v2.4.1 [2.5.0]: https://github.com/studio-prisma/osticket-api-endpoints/releases/tag/v2.5.0 [2.5.1]: https://github.com/studio-prisma/osticket-api-endpoints/releases/tag/v2.5.1 [2.6.0]: https://github.com/studio-prisma/osticket-api-endpoints/releases/tag/v2.6.0 +[2.7.0]: https://github.com/studio-prisma/osticket-api-endpoints/releases/tag/v2.7.0 diff --git a/controllers/ExtendedTicketApiController.php b/controllers/ExtendedTicketApiController.php index 47b0fa6..cefea47 100644 --- a/controllers/ExtendedTicketApiController.php +++ b/controllers/ExtendedTicketApiController.php @@ -195,6 +195,10 @@ public function createTicket($data, $source = 'API'): ?Ticket * Allows updating ticket properties that can't be set during creation * due to osTicket's internal rules (e.g., Topic overriding departmentId) * + * `subject` renames the ticket. It is validated before any other change + * (non-empty single line, no HTML, form-configured length) and logged as + * an "edited" thread event, as in the staff UI. + * * @param string $ticketNumber Ticket number * @param array $data Update data * @param bool $skipPermissionCheck Skip permission check (internal calls only) @@ -220,8 +224,21 @@ public function update(string $ticketNumber, array $data, bool $skipPermissionCh throw new Exception('Ticket not found', 404); } + // Validate the subject before the first change, so a bad subject + // does not leave the ticket half updated. + $subject = array_key_exists('subject', $data) + ? $this->validateSubject($data['subject']) + : null; + $updated = false; + // Update subject if provided (answer of the ticket form, like the staff UI) + if ($subject !== null && $subject !== (string)$ticket->getSubject()) { + if ($this->setTicketSubject($ticket, $subject)) { + $updated = true; + } + } + // Update departmentId if provided if (isset($data['departmentId'])) { $deptId = $this->validator->validateDepartmentId($data['departmentId']); @@ -640,6 +657,95 @@ private function setTicketPriority(Ticket $ticket, int $priorityId): bool throw new Exception('Ticket has no priority field', 400); } + /** Subject length when the ticket form does not configure one */ + public const SUBJECT_DEFAULT_LENGTH = 255; + + /** + * Validated subject: a non-empty single line of plain text + * + * The limit is the length configured on the subject field of the ticket + * form (Admin > Manage > Forms > Ticket Details), so the API accepts + * what the staff UI accepts. HTML is refused rather than stripped: the + * caller should see that the subject would not be stored as sent. + * + * @throws Exception 400 on invalid input + */ + public function validateSubject(mixed $subject): string + { + if (!is_string($subject)) { + throw new Exception('subject must be a string', 400); + } + $subject = trim($subject); + if ($subject === '') { + throw new Exception('subject must not be empty', 400); + } + if (!mb_check_encoding($subject, 'UTF-8')) { + throw new Exception('subject must be valid UTF-8', 400); + } + if (preg_match('/[\p{Cc}\x{2028}\x{2029}]/u', $subject)) { + throw new Exception('subject must be a single line without control characters', 400); + } + if (strip_tags($subject) !== $subject) { + throw new Exception('subject must not contain HTML', 400); + } + $max = $this->subjectMaxLength(); + if (mb_strlen($subject) > $max) { + throw new Exception(sprintf('subject exceeds %d characters', $max), 400); + } + return $subject; + } + + /** + * Length configured on the ticket form's subject field + */ + private function subjectMaxLength(): int + { + if (class_exists('TicketForm') + && ($form = TicketForm::getInstance()) + && ($field = $form->getField('subject')) + ) { + $config = $field->getConfiguration(); + if (!empty($config['length']) && (int)$config['length'] > 0) { + return (int)$config['length']; + } + } + return self::SUBJECT_DEFAULT_LENGTH; + } + + /** + * Set the ticket subject + * + * The subject is the answer to the built-in "subject" field of the ticket + * form and is mirrored into ticket__cdata. Saving the form entry fires + * the signal that refreshes that view. Like Ticket::updateField() in the + * staff UI, the change is logged as an "edited" thread event with the old + * and the new value, and the ticket's last update is set. + * + * @throws Exception If the ticket has no subject field (400) + */ + private function setTicketSubject(Ticket $ticket, string $subject): bool + { + $previous = (string)$ticket->getSubject(); + foreach (DynamicFormEntry::forTicket($ticket->getId()) as $form) { + if (!($field = $form->getField('subject')) || !$form->getAnswer('subject')) { + continue; + } + $form->setAnswer('subject', $subject); + // saveAnswers() returns false on failure, else the number of saved answers + if ($form->save() === false) { + throw new Exception('Failed to save subject', 500); + } + $ticket->loadDynamicData(true); + $ticket->logEvent('edited', ['fields' => [$field->get('id') => [$previous, $subject]]], 'API'); + $ticket->lastupdate = SqlFunction::NOW(); + $ticket->save(); + + return true; + } + + throw new Exception('Ticket has no subject field', 400); + } + // ========================================================================= // Attachment Helpers // ========================================================================= diff --git a/openapi.yaml b/openapi.yaml index 0b1e027..d8cd509 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -124,8 +124,8 @@ paths: operationId: updateTicket summary: Update a ticket description: | - Update ticket properties such as status, department, priority, SLA, staff - assignment, due date, and add internal notes with attachments. + Update ticket properties such as subject, status, department, priority, + SLA, staff assignment, due date, and add internal notes with attachments. Also accepts `PUT` method. @@ -1102,6 +1102,16 @@ components: UpdateTicketRequest: type: object properties: + subject: + type: string + description: | + New ticket subject. Trimmed; must be a non-empty single line of + plain text (no HTML, no control characters) within the length + configured on the ticket form's subject field (255 if none). + Validated before any other change. The change is logged as an + "edited" thread event with the old and the new subject. + examples: + - 'Printer on 2nd floor offline' statusId: oneOf: - type: string diff --git a/plugin.php b/plugin.php index d23cb4e..2da69c1 100644 --- a/plugin.php +++ b/plugin.php @@ -2,7 +2,7 @@ return array( 'id' => 'com.osticket:api-endpoints', - 'version' => '2.6.0', + 'version' => '2.7.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/UpdateTicketSubjectTest.php b/tests/Integration/UpdateTicketSubjectTest.php new file mode 100644 index 0000000..76639a6 --- /dev/null +++ b/tests/Integration/UpdateTicketSubjectTest.php @@ -0,0 +1,188 @@ + 'test-api-key', 'can_update_tickets' => true]); + } + + protected function tearDown(): void { + DynamicFormEntry::$withoutSubject = []; + DynamicFormEntry::$saveFails = false; + TicketForm::$subjectLength = null; + } + + private function ticket(string $subject = 'Alter Betreff', int $id = 123): Ticket { + $ticket = new Ticket(['id' => $id, 'number' => self::NUMBER, 'subject' => $subject, 'dept_id' => 1]); + Ticket::$mockDataByNumber[self::NUMBER] = $ticket; + return $ticket; + } + + private function update(array $data): Ticket { + return (new ExtendedTicketApiController())->update(self::NUMBER, $data); + } + + private function assertRefused(array $data, string $message): void { + try { + $this->update($data); + $this->fail('Expected a 400 for ' . json_encode($data)); + } catch (Exception $e) { + $this->assertSame(400, $e->getCode()); + $this->assertStringContainsString($message, $e->getMessage()); + } + } + + public function testRenamesTicketAndLogsEditedEvent(): void { + $ticket = $this->ticket(); + + $result = $this->update(['subject' => 'Neuer Betreff']); + + $this->assertSame('Neuer Betreff', $result->getSubject()); + $this->assertSame( + [['edited', ['fields' => [20 => ['Alter Betreff', 'Neuer Betreff']]], 'API']], + $ticket->events + ); + $this->assertInstanceOf(SqlFunction::class, $ticket->lastupdate); + } + + public function testTrimsSurroundingWhitespace(): void { + $this->ticket(); + $this->assertSame('Neu', $this->update(['subject' => " Neu "])->getSubject()); + } + + public function testKeepsUmlautsAndSpecialCharacters(): void { + $this->ticket(); + $subject = 'Größe ändern: 5 < 7 & "Zitat" – ok'; + $this->assertSame($subject, $this->update(['subject' => $subject])->getSubject()); + } + + public function testUnchangedSubjectLogsNoEvent(): void { + $ticket = $this->ticket('Gleich'); + $this->update(['subject' => ' Gleich ']); + $this->assertSame([], $ticket->events); + } + + public function testRefusesEmptySubject(): void { + $this->ticket(); + $this->assertRefused(['subject' => ''], 'must not be empty'); + $this->assertRefused(['subject' => " \t "], 'must not be empty'); + } + + public function testRefusesNonStringSubject(): void { + $this->ticket(); + $this->assertRefused(['subject' => null], 'must be a string'); + $this->assertRefused(['subject' => 42], 'must be a string'); + $this->assertRefused(['subject' => ['a']], 'must be a string'); + } + + public function testRefusesHtml(): void { + $this->ticket(); + $this->assertRefused(['subject' => 'Hallo Welt'], 'must not contain HTML'); + $this->assertRefused(['subject' => ''], 'must not contain HTML'); + $this->assertRefused(['subject' => 'x'], 'must not contain HTML'); + $this->assertRefused(['subject' => 'a c'], 'must not contain HTML'); + } + + public function testRefusesLineBreaksAndControlCharacters(): void { + $this->ticket(); + $this->assertRefused(['subject' => "Zeile 1\nZeile 2"], 'single line'); + $this->assertRefused(['subject' => "a\rb"], 'single line'); + $this->assertRefused(['subject' => "a\tb"], 'single line'); + $this->assertRefused(['subject' => "a\x00b"], 'single line'); + $this->assertRefused(['subject' => "a\u{2028}b"], 'single line'); + } + + public function testRefusesInvalidUtf8(): void { + $this->ticket(); + $this->assertRefused(['subject' => "Betreff \xC3\x28"], 'valid UTF-8'); + } + + public function testDefaultLengthLimitIs255Characters(): void { + $this->ticket(); + $this->assertSame(255, mb_strlen($this->update(['subject' => str_repeat('ä', 255)])->getSubject())); + $this->assertRefused(['subject' => str_repeat('a', 256)], 'exceeds 255 characters'); + } + + public function testUsesLengthConfiguredOnTicketForm(): void { + TicketForm::$subjectLength = 50; + $this->ticket(); + $this->assertSame(50, mb_strlen($this->update(['subject' => str_repeat('b', 50)])->getSubject())); + $this->assertRefused(['subject' => str_repeat('b', 51)], 'exceeds 50 characters'); + } + + public function testInvalidSubjectChangesNothingElse(): void { + Dept::$mockData[1] = new Dept(['id' => 1, 'name' => 'Sales', 'active' => true]); + Dept::$mockData[5] = new Dept(['id' => 5, 'name' => 'Support', 'active' => true]); + $ticket = $this->ticket(); + + $this->assertRefused(['departmentId' => 5, 'subject' => 'x'], 'HTML'); + + $this->assertSame(1, $ticket->getDeptId()); + $this->assertSame('Alter Betreff', $ticket->getSubject()); + } + + public function testSubjectCombinesWithOtherFields(): void { + Dept::$mockData[1] = new Dept(['id' => 1, 'name' => 'Sales', 'active' => true]); + Dept::$mockData[5] = new Dept(['id' => 5, 'name' => 'Support', 'active' => true]); + $this->ticket(); + + $result = $this->update(['departmentId' => 5, 'subject' => 'Umbenannt']); + + $this->assertSame(5, $result->getDeptId()); + $this->assertSame('Umbenannt', $result->getSubject()); + } + + public function testTicketWithoutSubjectFieldGets400(): void { + $this->ticket(); + DynamicFormEntry::$withoutSubject = [123]; + $this->assertRefused(['subject' => 'Neu'], 'no subject field'); + } + + public function testFailedSaveGets500AndLogsNoEvent(): void { + $ticket = $this->ticket(); + DynamicFormEntry::$saveFails = true; + try { + $this->update(['subject' => 'Neu']); + $this->fail('Expected a 500'); + } catch (Exception $e) { + $this->assertSame(500, $e->getCode()); + } + $this->assertSame([], $ticket->events); + } + + public function testRequiresUpdatePermission(): void { + $ticket = $this->ticket(); + API::$mockData['test-key'] = new API([ + 'key' => 'test-api-key', + 'can_update_tickets' => false, + 'permissions' => ['can_create_tickets' => false], + ]); + try { + $this->update(['subject' => 'Neu']); + $this->fail('Expected a 401'); + } catch (Exception $e) { + $this->assertSame(401, $e->getCode()); + } + $this->assertSame('Alter Betreff', $ticket->getSubject()); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 4daab57..800510b 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -205,7 +205,10 @@ public static function objects() { private $userName; private $userEmail; private $customData; + private $lastupdate; public $ht = []; + /** Thread events logged via logEvent(): [state, data, user] */ + public array $events = []; /** * Magic setter to emulate VerySimpleModel ORM behavior @@ -345,6 +348,15 @@ public function loadDynamicData($force = false) { return []; } + public function logEvent($state, $data = null, $user = null, $annul = null) { + $this->events[] = [$state, $data, $user]; + } + + /** Test helper: what DynamicFormEntry::save() writes for the subject */ + public function setSubjectAnswer(string $subject): void { + $this->subject = $subject; + } + public function setStatus($statusId) { $this->statusId = $statusId; return true; @@ -585,13 +597,16 @@ public function __toString() { return $this->name; } } } -// Mock DynamicFormEntry: only the ticket-form priority answer. -// $withoutPriority lists ticket IDs whose form lacks the field. +// Mock DynamicFormEntry: the ticket-form priority and subject answers. +// $withoutPriority / $withoutSubject list ticket IDs whose form lacks the field. if (!class_exists('DynamicFormEntry')) { class DynamicFormEntry { public static array $withoutPriority = []; + public static array $withoutSubject = []; + public static bool $saveFails = false; private $ticket; private $pendingPriorityId = null; + private $pendingSubject = null; private function __construct($ticket) { $this->ticket = $ticket; @@ -607,27 +622,82 @@ public static function forTicket($ticketId) { } public function getAnswer($name) { + if ($name === 'subject') { + return in_array($this->ticket->getId(), self::$withoutSubject, true) + ? null : $this->ticket->getSubject(); + } if ($name !== 'priority' || in_array($this->ticket->getId(), self::$withoutPriority, true)) { return null; } return $this->ticket->getPriorityId(); } + public function getField($name) { + if ($name === 'subject' && !in_array($this->ticket->getId(), self::$withoutSubject, true)) { + return new MockFormField(['id' => 20, 'name' => 'subject']); + } + return null; + } + public function setAnswer($name, $value, $id = false) { if ($name === 'priority') { $this->pendingPriorityId = $id; } + if ($name === 'subject') { + $this->pendingSubject = $value; + } } + // Like saveAnswers(): false on failure, else the number of saved answers public function save() { + if (self::$saveFails) { + return false; + } + $saved = 0; if ($this->pendingPriorityId !== null) { $this->ticket->setPriorityId($this->pendingPriorityId); + $saved++; } - return true; + if ($this->pendingSubject !== null) { + $this->ticket->setSubjectAnswer($this->pendingSubject); + $saved++; + } + return $saved ?: true; } } } +// Mock form field: get() and getConfiguration() +if (!class_exists('MockFormField')) { + class MockFormField { + public function __construct(private array $ht, private array $config = []) {} + public function get($name) { return $this->ht[$name] ?? null; } + public function getConfiguration() { return $this->config; } + } +} + +// Mock TicketForm: $subjectLength is the configured subject length (null = not set) +if (!class_exists('TicketForm')) { + class TicketForm { + public static ?int $subjectLength = null; + public static function getInstance() { return new self(); } + public function getField($name) { + if ($name !== 'subject') { + return null; + } + $config = self::$subjectLength === null ? [] : ['length' => self::$subjectLength]; + return new MockFormField(['id' => 20, 'name' => 'subject'], $config); + } + } +} + +if (!class_exists('SqlFunction')) { + class SqlFunction { + public function __construct(public string $func) {} + public static function NOW() { return new self('NOW'); } + } +} + // Mock TicketStatus class if (!class_exists('TicketStatus')) { class TicketStatus {