Workflow Reply Text Developer Guide - edmozley/freeitsm GitHub Wiki
Discussion #451 (asked by @marek557, gap found by @chaseakub) ยท Workflows ยท built after 5.13.0 (#3253-#3255)
How The requester replies to a ticket (ticket.reply_received) gives a workflow the reply itself as {{reply.*}} merge codes, and the rules that keep that text where it belongs. For what an administrator sees, start at Workflows โ The requester's reply; for the decisions, the design page.
Key: ๐๏ธ schema ยท ๐ read ยท โ๏ธ write ยท โ๏ธ engine ยท ๐ฅ๏ธ UI ยท ๐งช test
| ๐จ | File | What it does |
|---|---|---|
| ๐ | includes/workflow_reply.php |
All of the reply logic. Loads the stored message, its short fields, its text as plain text, cuts quoted history, caps the length, and says whether a workflow uses the text |
| โ๏ธ | workflow/includes/engine.php |
Offers the codes (availableFields(), FIELD_NOTES), fills them (enrichWithReply()), blanks the text per action on a confidential ticket (replyTextForAction()), escapes it into an HTML email (emailBodyVars()) |
| โ๏ธ | api/tickets/check_mailbox_email.php |
Fires ticket.reply_received for an emailed reply, now with reply.email_id
|
| โ๏ธ | api/self-service/reply_ticket.php |
Fires it for a portal reply - after the commit (section 6) |
| ๐ฅ๏ธ |
workflow/help.php, lang/en/workflow.php (help.variables_reply) |
The in-app help note |
| ๐ฅ๏ธ | includes/feature_bingo/cards/workflow.php |
Card workflow.reply_text
|
| ๐งช | tests/workflow-reply-text.php |
30 checks: the cutting rules, the escaping, the editor's list, and a real portal reply through the endpoint running a workflow |
What is NOT touched: no schema. The trigger carries one id and the engine reads the emails row it already has. No editor JavaScript either: the editor's variable list is built from availableVariables(), so new fields show up by themselves.
a reply arrives a workflow runs (runInner)
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโ
emails row saved enrichPayloadForTemplates()
โ enrichWithReply($conn, $p, false) โ from, subject, received...
โผ INSERT workflow_executions (trigger_payload = $p) โ snapshot
WorkflowEngine::dispatch( โ
'ticket.reply_received', [ โผ
'ticket' => ..., workflowReplyTextWanted(conditions, actions)?
'source' => 'email' | 'portal', โโ yes โ enrichWithReply($conn, $p, true) โ body, new_text
'reply' => ['email_id' => N], conditions โ actions
]) each action gets replyTextForAction($type, $p)
send_email renders its body from emailBodyVars($p, $isHtml)
The dispatch carries only the id. Everything else is looked up when a workflow runs, so the notification bell and the search index (which also subscribe to dispatch()) never see the reply text.
// workflow/includes/engine.php - runInner()
$payload = self::enrichPayloadForTemplates($conn, $payload);
$payload = self::enrichWithReply($conn, $payload, false); // discussion #451: from, subject...
// ... INSERT INTO workflow_executions (... trigger_payload ...) ...
require_once dirname(__DIR__, 2) . '/includes/workflow_reply.php';
if (workflowReplyTextWanted($conditions, $actions)) {
$payload = self::enrichWithReply($conn, $payload, true);
}-
The short fields (
from,from_name,received,subject,has_attachments) are cheap and harmless, so they are filled before the snapshot and appear in Workflows โ History like the ticket's own fields. -
The text is loaded after the snapshot, and only when the workflow's saved conditions or actions mention
reply.bodyorreply.new_text(a plain string search of their JSON). A workflow that doesn't use it costs nothing, and the text isn't stored a second time. -
Never clobbers.
enrichWithReply()only sets a key that's missing, so a Test fire's made-upreply.new_textstays as typed.
received is formatted with fmt_datetime(). The mailbox poll has no analyst session, so that's the install's time zone and date format.
// includes/workflow_reply.php
function workflowReplyText(PDO $conn, int $emailId): array
{
$row = workflowReplyRow($conn, $emailId);
...
$body = workflowReplyPlain($html, $type);
// A portal reply has no quoted history: it was typed into a box, not replied to.
$new = $isPortal ? $body : workflowReplyPlain(workflowReplyCutHtml($html), $type);
$new = workflowReplyCutText($new);
if ($new === '') $new = $body;
return ['body' => workflowReplyCap($body), 'new_text' => workflowReplyCap($new)];
}reply.body is already trimmed once. An inbound reply is cut at FreeITSM's own "Please reply above this line" marker (or the data-reply-marker div, the old SDREF line, or the first <blockquote>) before it is stored, by stripInboundThread() in api/tickets/check_mailbox_email.php. So body is what analysts see on the ticket. new_text cuts further, for replies that marker didn't catch (someone replying to an email FreeITSM didn't send, or a mail program that dropped the marker).
| Step | Function | Cuts at |
|---|---|---|
| 1. HTML | workflowReplyCutHtml() |
The earliest of: Outlook's div#appendonsend / div#divRplyFwdMsg, Gmail's div.gmail_quote, Thunderbird's moz-cite-prefix, Yahoo's yahoo_quoted, <blockquote type="cite"> (Apple Mail, Thunderbird), Outlook desktop's border-top header div followed by From:
|
| 2. To text | workflowReplyPlain() |
Not a cut: style/script/head/title and comments go entirely; br, p, div, tr, ul, ol, headings and blockquote end a line; li becomes - item; entities are decoded; whitespace is collapsed |
| 3. Text | workflowReplyCutText() |
The first line that is -----Original Message-----; a row of underscores followed by From:; From: followed within four lines by Sent:/Date: and To:/Subject:; On ... wrote: (also wrapped over two lines); two > lines in a row |
| 4. Cap | workflowReplyCap() |
10,000 characters, then "... (cut short - the whole reply is on the ticket)" |
It is cautious on purpose. Cutting removes words, so:
- an HTML marker with nothing before it is ignored (the HTML is returned whole);
- a cut that leaves nothing returns
'', and the caller then uses the whole body; - a lone From: line ("From: the 2nd floor, all three printers") or a single
>line ("Speed > 10 MB/s") is not a cut. The test pins both.
Per action, not per run. The text is loaded once; what each action sees depends on its type:
// workflow/includes/engine.php
private static function replyTextForAction(string $type, array $payload): array
{
if ($type === 'send_email' || !isset($payload['reply']) || !is_array($payload['reply'])) return $payload;
...
$confidential = $tid > 0 && ticketIsConfidential(connectToDatabase(), $tid);
... // could not check: treat it as confidential
if ($confidential) $payload['reply']['body'] = $payload['reply']['new_text'] = '';
return $payload;
}It is applied where executeActionList() calls executeAction() and where a dry run builds its preview. The rules it follows were already there (discussion #62):
| Action | On a confidential ticket |
|---|---|
send_email |
Text filled in. action_send_email() already refuses to send a confidential ticket to anyone but its requester or an active analyst (ticketEmailRecipientsAllowed()) |
send_webhook (Slack, Teams, any URL) |
Never had it: ticketRedactForOutbound() keeps an allow-list of scalar ticket fields, and reply is an array, so it's dropped |
| Everything else | Text blank, the same rule as {{ticket.full}} in fullForTemplates()
|
Escaping into an HTML email. Whether the body is HTML is decided from the template, never from the rendered result:
// action_send_email()
$bodyTmpl = (string)($args['body'] ?? '');
$bodyHtml = strip_tags($bodyTmpl) !== $bodyTmpl;
$body = self::argString($args, 'body', self::emailBodyVars($payload, $bodyHtml));
...
$fullBody = $ticketRef !== ''
? buildTemplateEmailBody($body, $ticketRef, $bodyHtml)
: self::plainEmailBody($body, $bodyHtml);emailBodyVars() runs nl2br(htmlspecialchars(...)) over reply.body, new_text, subject, from_name and from when the template is HTML. A plain-text template is escaped whole afterwards by buildTemplateEmailBody() / plainEmailBody(), as before.
โ ๏ธ TRAP: decide HTML from the template. Both builders used to look at the rendered body. A plain-text template with{{reply.new_text}}in it, and a reply saying<b>hello</b>, rendered to a body that contained tags, so it was sent as HTML with the requester's markup in it. Passing$bodyHtmlfrom the template closes that for every merge code, not only the reply (#3255).
โ ๏ธ TRAP:WorkflowEngine::dispatch()reads with its own connection.connectToDatabase()returns a new PDO every time.api/self-service/reply_ticket.phpused to dispatch inside itsbeginTransaction(), so the engine couldn't see theemailsrow it was being told about. Every{{reply.*}}came out blank, while a Test fire with the same id worked. The dispatch now sits after$conn->commit()(#3254). Any new trigger fired from inside a transaction has the same problem: dispatch after the commit.
The emailed path (api/tickets/check_mailbox_email.php) has no transaction around the insert, so it was never affected.
FREEITSM_TEST_DATABASE=freeitsm_prtest FREEITSM_TEST_URL=http://localhost/freeitsm-prtest \
FREEITSM_SESS_DIR=C:/wamp64/tmp php tests/workflow-reply-text.php (from the prtest folder)
| Part | How |
|---|---|
| Cutting rules, plain text, cap | Direct calls, no database |
emailBodyVars() |
ReflectionMethod, with an HTML and a plain-text template |
| Editor list |
availableVariables('ticket.reply_received') has the codes and notes; ticket.created doesn't |
| An emailed reply | A stored Gmail-quoted emails row: new_text cut, body whole, short fields right |
| A portal reply, for real | A forged portal session posts to api/self-service/reply_ticket.php; a ZZ workflow writes {{reply.new_text}} into a note; the note and the run snapshot are read back |
| Confidential | Same ticket marked confidential: the note's text is blank, its sender isn't; a Send email dry run does get the text |
Everything is tagged zzwr and removed in finally.
-
Another mail program's quote marker: add a pattern to
$markersinworkflowReplyCutHtml()(HTML) or a line test toworkflowReplyCutText()(text), with a test case for it and one for a reply that merely looks similar. -
Another reply field: add it to
workflowReplyFields(), to the trigger's list inavailableFields(), and a sentence toFIELD_NOTES. If it can hold text a requester typed, add it toemailBodyVars()too. -
The optional AI step (design section 6): it belongs in
workflowReplyText()after the non-AI cut, with its answer accepted only when it's found word for word in the original. Run it in the background, never inside the mailbox poll.