Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
106 changes: 106 additions & 0 deletions controllers/ExtendedTicketApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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']);
Expand Down Expand Up @@ -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
// =========================================================================
Expand Down
14 changes: 12 additions & 2 deletions openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
188 changes: 188 additions & 0 deletions tests/Integration/UpdateTicketSubjectTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

use PHPUnit\Framework\TestCase;

require_once __DIR__ . '/../../controllers/ExtendedTicketApiController.php';

/**
* PATCH /api/tickets-update.php: renaming a ticket via `subject`
*
* The subject is the answer to the ticket form's subject field. A change is
* logged as an "edited" thread event with old and new value, like the staff
* UI does. Invalid subjects are refused with 400 before anything changes.
*/
class UpdateTicketSubjectTest extends TestCase {

private const NUMBER = '781258';

protected function setUp(): void {
Ticket::$mockData = [];
Ticket::$mockDataByNumber = [];
API::$mockData = [];
Dept::$mockData = [];
DynamicFormEntry::$withoutSubject = [];
DynamicFormEntry::$saveFails = false;
TicketForm::$subjectLength = null;
API::$mockData['test-key'] = new API(['key' => '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 <b>Welt</b>'], 'must not contain HTML');
$this->assertRefused(['subject' => '<script>alert(1)</script>'], 'must not contain HTML');
$this->assertRefused(['subject' => 'x<img src=x onerror=alert(1)>'], 'must not contain HTML');
$this->assertRefused(['subject' => 'a <!-- b --> 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' => '<b>x</b>'], '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());
}
}
Loading
Loading