Beautiful Open-Source Form Builder
<?php
namespace App\Service\Forms;
use App\Models\Forms\Form;
use App\Service\Storage\FilenameUrlEncoder;
use App\Service\Storage\StorageFileNameParser;
use Carbon\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Stevebauman\Purify\Facades\Purify;
class FormSubmissionFormatter
{
public const SIGNED_FILE_URL_EXPIRATION_MINUTES = 60 * 24;
/**
* If true, creates html <a> links for emails and urls
*
* @var bool
*/
private $createLinks = false;
/**
* If true, serialize arrays
*
* @var bool
*/
private $outputStringsOnly = false;
private $showHiddenFields = false;
private $setEmptyForNoValue = false;
private $showRemovedFields = false;
private $useSignedUrlForFiles = false;
private ?Carbon $signedFileUrlExpiration = null;
/**
* Logic resolver needs an array id => value, so we create it here
*/
private $idFormData = null;
public function __construct(private Form $form, private array $formData)
{
$this->initIdFormData();
}
public function createLinks()
{
$this->createLinks = true;
return $this;
}
public function showHiddenFields()
{
$this->showHiddenFields = true;
return $this;
}
public function outputStringsOnly()
{
$this->outputStringsOnly = true;
return $this;
}
public function setEmptyForNoValue()
{
$this->setEmptyForNoValue = true;
return $this;
}
public function showRemovedFields()
{
$this->showRemovedFields = true;
return $this;
}
public function useSignedUrlForFiles(?Carbon $expiresAt = null)
{
$this->useSignedUrlForFiles = true;
$this->signedFileUrlExpiration = $expiresAt ?? app(ExternalSubmissionFileLinkPolicy::class)
->expiresAt($this->form->workspace);
return $this;
}
public function getMatrixString(array $val): string
{
$parts = [];
foreach ($val as $key => $value) {
if ($key !== null && $value !== null) {
$parts[] = "$key: $value";
}
}
return implode(' | ', $parts);
}
/**
* Return a nice "FieldName": "Field Response" array
* - If createLink enabled, returns html link for emails and links
* Used for CSV exports
*/
public function getCleanKeyValue()
{
$data = $this->formData;
$fields = collect($this->form->properties);
$removeFields = collect($this->form->removed_properties)->map(function ($field) {
return [
...$field,
'removed' => true,
];
});
if ($this->showRemovedFields) {
$fields = $fields->merge($removeFields);
}
$fields = $fields->filter(function ($field) {
return !Str::of($field['type'])->startsWith('nf-');
})->values();
$returnArray = [];
foreach ($fields as $field) {
if ($field['removed'] ?? false) {
$field['name'] = $field['name'] . ' (deleted)';
}
// Add ID to avoid name clashes
$field['name'] = $field['name'] . ' (' . Str::of($field['id']) . ')';
// If not present skip
if (!isset($data[$field['id']])) {
if ($this->setEmptyForNoValue) {
$returnArray[$field['name']] = '';
}
continue;
}
// If hide hidden fields
if (!$this->showHiddenFields) {
if (FormLogicPropertyResolver::isHidden($field, $this->idFormData ?? [], $this->form)) {
continue;
}
}
if ($this->createLinks && $field['type'] == 'url') {
$returnArray[$field['name']] = $this->formatUrlLink($data[$field['id']]);
} elseif ($this->createLinks && $field['type'] == 'email') {
$returnArray[$field['name']] = $this->formatEmailLink($data[$field['id']]);
} elseif ($field['type'] == 'multi_select') {
$val = $data[$field['id']];
if ($this->outputStringsOnly && is_array($val)) {
$returnArray[$field['name']] = $this->implodeCsvSafe($val);
} else {
$returnArray[$field['name']] = $val;
}
} elseif ($field['type'] == 'matrix' && is_array($data[$field['id']])) {
$returnArray[$field['name']] = $this->getMatrixString($data[$field['id']]);
} elseif (in_array($field['type'], ['files', 'signature'])) {
if ($this->outputStringsOnly) {
$formId = $this->form->id;
$returnArray[$field['name']] = implode(
', ',
collect($data[$field['id']])->filter(function ($file) {
return !is_null($file) && !empty($file);
})->map(function ($file) use ($formId) {
return $this->getFileUrl($formId, $file);
})->toArray()
);
} else {
$formId = $this->form->id;
$returnArray[$field['name']] = collect($data[$field['id']])->map(function ($file) use ($formId) {
return [
'file_url' => $this->getFileUrl($formId, $file),
'file_name' => $file,
];
});
}
} else {
if (is_array($data[$field['id']]) && $this->outputStringsOnly) {
$data[$field['id']] = $this->implodeCsvSafe($data[$field['id']]);
}
$returnArray[$field['name']] = $data[$field['id']];
}
}
return $returnArray;
}
/**
* Return a list of fields, with a filled value attribute.
* Used for humans.
*/
public function getFieldsWithValue()
{
$data = $this->formData;
$fields = $this->form->properties;
$transformedFields = [];
foreach ($fields as $field) {
if (!isset($field['id']) || !isset($data[$field['id']])) {
continue;
}
// If hide hidden fields
if (!$this->showHiddenFields) {
if (FormLogicPropertyResolver::isHidden($field, $this->idFormData, $this->form)) {
continue;
}
}
if ($this->createLinks && $field['type'] == 'url') {
$field['value'] = $this->formatUrlLink($data[$field['id']]);
$field['value_is_html'] = true;
} elseif ($this->createLinks && $field['type'] == 'email') {
$field['value'] = $this->formatEmailLink($data[$field['id']]);
$field['value_is_html'] = true;
} elseif ($field['type'] == 'checkbox') {
$field['value'] = $data[$field['id']] ? trans('validation.yes') : trans('validation.no');
} elseif ($field['type'] == 'date') {
$dateFormat = ($field['date_format'] ?? 'dd/MM/yyyy') == 'dd/MM/yyyy' ? 'd/m/Y' : 'm/d/Y';
if (isset($field['with_time']) && $field['with_time']) {
$dateFormat .= (isset($field['time_format']) && $field['time_format'] == 24) ? ' H:i' : ' g:ia';
}
if (is_array($data[$field['id']])) {
$field['value'] = isset($data[$field['id']][1]) ? (new Carbon($data[$field['id']][0]))->format($dateFormat)
. ' - ' . (new Carbon($data[$field['id']][1]))->format($dateFormat) : (new Carbon($data[$field['id']][0]))->format($dateFormat);
} else {
$field['value'] = (new Carbon($data[$field['id']]))->format($dateFormat);
}
} elseif ($field['type'] == 'multi_select') {
$val = $data[$field['id']];
if ($this->outputStringsOnly) {
$field['value'] = $this->implodeCsvSafe($val);
} else {
$field['value'] = $val;
}
} elseif ($field['type'] == 'matrix') {
$field['value'] = str_replace(' | ', "\n", $this->getMatrixString($data[$field['id']]));
} elseif ($field['type'] == 'rich_text') {
$value = $data[$field['id']];
if (is_string($value) && $value !== '') {
$field['value'] = Purify::clean($value);
$field['value_is_html'] = true;
} else {
$field['value'] = $value;
}
} elseif (in_array($field['type'], ['files', 'signature'])) {
if ($this->outputStringsOnly) {
$formId = $this->form->id;
$emailData = collect($data[$field['id']])->map(function ($file) use ($formId) {
$displayName = $this->getFileDisplayName($file);
return [
'file_name' => $file,
'unsigned_url' => route(
'open.forms.submissions.file',
[$formId, FilenameUrlEncoder::encode($file)]
),
'signed_url' => $this->getFileUrl($formId, $file),
'label' => $displayName,
'is_image' => $this->isImageFile($displayName),
];
})->toArray();
if ($this->createLinks) {
$field['value'] = implode('<br>', collect($emailData)->map(function ($file) {
$icon = $file['is_image'] ? '🖼️' : '📎';
return $this->buildSafeHtmlLink(
$file['signed_url'],
$icon . ' ' . $file['label']
);
})->toArray());
$field['value_is_html'] = true;
} else {
$field['value'] = implode(', ', collect($emailData)->pluck('signed_url')->toArray());
}
$field['email_data'] = $emailData;
} else {
$formId = $this->form->id;
$field['value'] = collect($data[$field['id']])->map(function ($file) use ($formId) {
return [
'file_url' => $this->getFileUrl($formId, $file),
'file_name' => $file,
];
});
}
} else {
if (is_array($data[$field['id']]) && $this->outputStringsOnly) {
$field['value'] = $this->implodeCsvSafe($data[$field['id']]);
} else {
$field['value'] = $data[$field['id']];
}
}
if ($this->createLinks && empty($field['value_is_html'])) {
$field['value'] = $this->escapeHtmlValue($field['value']);
$field['value_is_html'] = true;
}
$transformedFields[] = $field;
}
return $transformedFields;
}
private function formatUrlLink(mixed $value): string
{
if (!is_scalar($value)) {
return $this->escapeHtmlValue($value);
}
$label = trim((string) $value);
$scheme = parse_url($label, PHP_URL_SCHEME);
if ($scheme !== null && (!is_string($scheme) || !in_array(strtolower($scheme), ['http', 'https'], true))) {
return $this->escapeHtmlValue($label);
}
$url = $scheme === null ? 'https://' . $label : $label;
$urlParts = parse_url($url);
if (
!filter_var($url, FILTER_VALIDATE_URL)
|| !is_array($urlParts)
|| empty($urlParts['host'])
|| isset($urlParts['user'])
|| isset($urlParts['pass'])
) {
return $this->escapeHtmlValue($label);
}
return $this->buildSafeHtmlLink($url, $label);
}
private function formatEmailLink(mixed $value): string
{
$email = is_scalar($value) ? (string) $value : '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return $this->escapeHtmlValue($value);
}
return $this->buildSafeHtmlLink('mailto:' . $email, $email);
}
private function buildSafeHtmlLink(string $href, string $label): string
{
return '<a href="' . e($href) . '">' . e($label) . '</a>';
}
private function getFileDisplayName(string $fileName): string
{
$parser = StorageFileNameParser::parse($fileName);
if ($parser->fileName && $parser->extension) {
return $parser->fileName . '.' . $parser->extension;
}
return $fileName;
}
private function isImageFile(string $fileName): bool
{
return in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), [
'bmp',
'gif',
'jpeg',
'jpg',
'png',
'svg',
'tif',
'tiff',
'webp',
], true);
}
private function escapeHtmlValue(mixed $value): string
{
if (is_array($value)) {
$value = implode(', ', $value);
} elseif (is_bool($value)) {
$value = $value ? '1' : '0';
} elseif ($value === null) {
$value = '';
}
return e((string) $value);
}
private function initIdFormData()
{
$formProperties = collect($this->form->properties);
foreach ($this->formData as $key => $value) {
$property = $formProperties->first(function ($item) use ($key) {
return $item['id'] == $key;
});
if ($property) {
$this->idFormData[$property['id']] = $value;
}
}
}
private function getFileUrl($formId, $file)
{
try {
// Use base64url encoding to avoid URL encoding issues with special characters
// See: https://github.com/OpnForm/OpnForm/issues/1024
$encodedFilename = FilenameUrlEncoder::encode($file);
return $this->useSignedUrlForFiles ? URL::temporaryPublicSignedRoute(
'open.forms.submissions.file',
$this->signedFileUrlExpiration ?? now()->addMinutes(self::SIGNED_FILE_URL_EXPIRATION_MINUTES),
[$formId, $encodedFilename]
) : route('open.forms.submissions.file', [$formId, $encodedFilename]);
} catch (\Exception $e) {
throw $e;
return null;
}
}
/**
* Escape a field value for CSV format
* Wraps fields containing commas or quotes in double quotes
* Escapes internal quotes by doubling them
*/
private function escapeCsvField($field)
{
// Convert to string if not already
$field = (string) $field;
// If field contains comma, double quote, or newline, wrap in quotes
if (strpos($field, ',') !== false || strpos($field, '"') !== false || strpos($field, "\n") !== false || strpos($field, "\r") !== false) {
// Escape any existing double quotes by doubling them
$field = str_replace('"', '""', $field);
// Wrap the entire field in double quotes
$field = '"' . $field . '"';
}
return $field;
}
/**
* Join array values with commas, properly escaping CSV fields
*/
private function implodeCsvSafe(array $values): string
{
return implode(',', array_map([$this, 'escapeCsvField'], $values));
}
}