Skip to content

Commit 7ca8511

Browse files
feat(conditional): add short and long text as trigger
A text trigger activates a branch when the answer equals (short text only) or contains a text, or matches a regular expression. Regular expressions use the same /pattern/modifiers format as validationRegex, are checked when saving, and an invalid one is not saved by the editor. Matching is limited in subject length and backtracking. The code comes from the original pull request #3123 by Micke Nordin and TimedIn, with the review fixes applied. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger <info@andy-scherzinger.de>
1 parent bdd436e commit 7ca8511

8 files changed

Lines changed: 325 additions & 1 deletion

File tree

‎docs/DataStructure.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,8 @@ Supported trigger types for conditional questions:
308308
| `multiple_unique` | `option_selected` | Radio buttons - the selected option |
309309
| `dropdown` | `option_selected` | Dropdown - the selected option |
310310
| `multiple` | `options_combination` | Checkboxes - all options of a combination |
311+
| `short` | `string_equals`, `string_contains`, `regex` | Short text - string or regex matching |
312+
| `long` | `string_contains`, `regex` | Long text - string or regex matching |
311313
| `linearscale` | `value_equals`, `value_not_equals`, `value_range`, `value_min`, `value_max` | Linear scale - numeric value matching |
312314
| `date` | `date_range` | Date - range including its bounds (`YYYY-MM-DD`) |
313315
| `datetime` | `date_range` | Deprecated date and time (`YYYY-MM-DD HH:mm`) |
@@ -363,6 +365,26 @@ Conditions determine when a branch is activated. The structure depends on the tr
363365

364366
All options in `optionIds` must be selected for the condition to match.
365367

368+
#### string_equals (for short)
369+
370+
```json
371+
{ "type": "string_equals", "value": "yes" }
372+
```
373+
374+
#### string_contains (for short, long)
375+
376+
```json
377+
{ "type": "string_contains", "value": "keyword" }
378+
```
379+
380+
#### regex (for short, long)
381+
382+
```json
383+
{ "type": "regex", "value": "/^yes/i" }
384+
```
385+
386+
The expression uses the same format as `validationRegex`: enclosed in slashes, with the optional modifiers `i`, `m` and `s`.
387+
366388
#### value_equals, value_not_equals (for linearscale), value_equals (for color)
367389

368390
```json

‎lib/Constants.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ class Constants {
261261
*/
262262
public const CONDITION_TYPE_OPTION_SELECTED = 'option_selected';
263263
public const CONDITION_TYPE_OPTIONS_COMBINATION = 'options_combination';
264+
public const CONDITION_TYPE_STRING_EQUALS = 'string_equals';
265+
public const CONDITION_TYPE_STRING_CONTAINS = 'string_contains';
266+
public const CONDITION_TYPE_REGEX = 'regex';
264267
public const CONDITION_TYPE_VALUE_EQUALS = 'value_equals';
265268
public const CONDITION_TYPE_VALUE_NOT_EQUALS = 'value_not_equals';
266269
public const CONDITION_TYPE_VALUE_RANGE = 'value_range';
@@ -277,6 +280,8 @@ class Constants {
277280
self::ANSWER_TYPE_MULTIPLEUNIQUE => [self::CONDITION_TYPE_OPTION_SELECTED],
278281
self::ANSWER_TYPE_DROPDOWN => [self::CONDITION_TYPE_OPTION_SELECTED],
279282
self::ANSWER_TYPE_MULTIPLE => [self::CONDITION_TYPE_OPTIONS_COMBINATION],
283+
self::ANSWER_TYPE_SHORT => [self::CONDITION_TYPE_STRING_EQUALS, self::CONDITION_TYPE_STRING_CONTAINS, self::CONDITION_TYPE_REGEX],
284+
self::ANSWER_TYPE_LONG => [self::CONDITION_TYPE_STRING_CONTAINS, self::CONDITION_TYPE_REGEX],
280285
self::ANSWER_TYPE_LINEARSCALE => [self::CONDITION_TYPE_VALUE_EQUALS, self::CONDITION_TYPE_VALUE_NOT_EQUALS, self::CONDITION_TYPE_VALUE_RANGE, self::CONDITION_TYPE_VALUE_MIN, self::CONDITION_TYPE_VALUE_MAX],
281286
self::ANSWER_TYPE_DATE => [self::CONDITION_TYPE_DATE_RANGE],
282287
self::ANSWER_TYPE_DATETIME => [self::CONDITION_TYPE_DATE_RANGE],

‎lib/Service/FormsService.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -965,6 +965,9 @@ private function areBranchConditionsValid(string $triggerType, array $conditions
965965
return false;
966966
}
967967
}
968+
if (($condition['type'] ?? null) === Constants::CONDITION_TYPE_REGEX && !$this->isValidRegex((string)($condition['value'] ?? ''))) {
969+
return false;
970+
}
968971
}
969972
return true;
970973
}

‎lib/Service/SubmissionService.php‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1159,6 +1159,33 @@ private function evaluateBranchConditions(string $triggerType, array $triggerAns
11591159
}
11601160
}
11611161
return false;
1162+
case Constants::ANSWER_TYPE_SHORT:
1163+
case Constants::ANSWER_TYPE_LONG:
1164+
// Text-based: evaluate regex/string conditions
1165+
$text = is_scalar($triggerAnswer[0] ?? null) ? (string)$triggerAnswer[0] : '';
1166+
foreach ($conditions as $condition) {
1167+
$type = $condition['type'] ?? Constants::CONDITION_TYPE_STRING_CONTAINS;
1168+
$value = $condition['value'] ?? '';
1169+
1170+
switch ($type) {
1171+
case Constants::CONDITION_TYPE_STRING_EQUALS:
1172+
if ($text === $value) {
1173+
return true;
1174+
}
1175+
break;
1176+
case Constants::CONDITION_TYPE_STRING_CONTAINS:
1177+
if (str_contains($text, $value)) {
1178+
return true;
1179+
}
1180+
break;
1181+
case Constants::CONDITION_TYPE_REGEX:
1182+
if ($this->safeRegexMatch($value, $text)) {
1183+
return true;
1184+
}
1185+
break;
1186+
}
1187+
}
1188+
return false;
11621189
case Constants::ANSWER_TYPE_LINEARSCALE:
11631190
$numValue = (float)($triggerAnswer[0] ?? 0);
11641191
foreach ($conditions as $condition) {
@@ -1240,4 +1267,33 @@ private function evaluateBranchConditions(string $triggerType, array $triggerAns
12401267
return false;
12411268
}
12421269
}
1270+
1271+
/**
1272+
* Safely execute a regex match with validation to prevent ReDoS attacks
1273+
*
1274+
* @param string $pattern The regex pattern to match
1275+
* @param string $subject The string to match against
1276+
* @return bool True if the pattern matches, false otherwise
1277+
*/
1278+
private function safeRegexMatch(string $pattern, string $subject): bool {
1279+
if (empty($pattern) || strlen($subject) > 10000) {
1280+
return false;
1281+
}
1282+
1283+
// Validate regex syntax
1284+
if (@preg_match($pattern, '') === false) {
1285+
return false;
1286+
}
1287+
1288+
// Set backtrack limit to prevent catastrophic backtracking
1289+
$previousLimit = ini_get('pcre.backtrack_limit');
1290+
ini_set('pcre.backtrack_limit', '10000');
1291+
1292+
try {
1293+
$result = @preg_match($pattern, $subject);
1294+
return $result === 1;
1295+
} finally {
1296+
ini_set('pcre.backtrack_limit', $previousLimit);
1297+
}
1298+
}
12431299
}

‎src/components/Conditional/BranchConditionEditor.vue‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,33 @@
3232
</div>
3333
</template>
3434

35+
<!-- Text-based conditions (short, long) -->
36+
<template v-else-if="isTextBasedTrigger">
37+
<div class="condition-row">
38+
<NcSelect
39+
v-model="conditionType"
40+
:options="textConditionTypes"
41+
:placeholder="t('forms', 'Condition type')"
42+
:ariaLabelCombobox="t('forms', 'Condition type')"
43+
label="label"
44+
:reduce="(opt) => opt.value"
45+
class="condition-type-select" />
46+
<NcTextField
47+
v-model="textConditionValue"
48+
:label="conditionValuePlaceholder"
49+
:error="isRegexInvalid"
50+
:helperText="
51+
isRegexInvalid
52+
? t(
53+
'forms',
54+
'Invalid regular expression, use the format /pattern/',
55+
)
56+
: ''
57+
"
58+
class="condition-value-input" />
59+
</div>
60+
</template>
61+
3562
<!-- Value-based conditions (linearscale, color) -->
3663
<template v-else-if="isValueBasedTrigger">
3764
<div class="condition-row">
@@ -147,6 +174,7 @@ import NcColorPicker from '@nextcloud/vue/components/NcColorPicker'
147174
import NcDateTimePicker from '@nextcloud/vue/components/NcDateTimePicker'
148175
import NcSelect from '@nextcloud/vue/components/NcSelect'
149176
import NcTextField from '@nextcloud/vue/components/NcTextField'
177+
import { validateExpression } from '../../utils/RegularExpression.ts'
150178
151179
export default {
152180
name: 'BranchConditionEditor',
@@ -188,6 +216,13 @@ export default {
188216
189217
emits: ['update:branch'],
190218
219+
data() {
220+
return {
221+
// Text being typed, an invalid regular expression is not saved
222+
textDraft: null,
223+
}
224+
},
225+
191226
computed: {
192227
/**
193228
* Check if trigger is option-based (radio, dropdown, checkbox)
@@ -205,6 +240,13 @@ export default {
205240
return ['multiple_unique', 'dropdown'].includes(this.triggerType)
206241
},
207242
243+
/**
244+
* Check if trigger is text-based (short, long)
245+
*/
246+
isTextBasedTrigger() {
247+
return ['short', 'long'].includes(this.triggerType)
248+
},
249+
208250
/**
209251
* Check if trigger is value-based (linearscale, color)
210252
*/
@@ -262,6 +304,22 @@ export default {
262304
return this.isSingleSelect ? selected[0] || null : selected
263305
},
264306
307+
/**
308+
* Text condition type options
309+
*/
310+
textConditionTypes() {
311+
const types = [
312+
{ value: 'string_equals', label: t('forms', 'Equals') },
313+
{ value: 'string_contains', label: t('forms', 'Contains') },
314+
{ value: 'regex', label: t('forms', 'Matches regex') },
315+
]
316+
// Long text doesn't support string_equals
317+
if (this.triggerType === 'long') {
318+
return types.filter((t) => t.value !== 'string_equals')
319+
}
320+
return types
321+
},
322+
265323
/**
266324
* Value condition type options (for linear scale)
267325
*/
@@ -292,6 +350,7 @@ export default {
292350
* Default condition type based on trigger
293351
*/
294352
defaultConditionType() {
353+
if (this.isTextBasedTrigger) return 'string_contains'
295354
if (this.triggerType === 'linearscale') return 'value_equals'
296355
if (this.isDateBasedTrigger) return 'date_range'
297356
return null
@@ -310,6 +369,29 @@ export default {
310369
},
311370
},
312371
372+
/**
373+
* Value of a text condition, regular expressions are only saved when valid
374+
*/
375+
textConditionValue: {
376+
get() {
377+
return this.textDraft ?? this.conditionValue
378+
},
379+
380+
set(value) {
381+
this.textDraft = value
382+
if (this.conditionType !== 'regex' || validateExpression(value)) {
383+
this.conditionValue = value
384+
}
385+
},
386+
},
387+
388+
isRegexInvalid() {
389+
return (
390+
this.conditionType === 'regex'
391+
&& !validateExpression(this.textConditionValue)
392+
)
393+
},
394+
313395
/**
314396
* Storage format of date and time conditions, the same as for answers
315397
*/
@@ -370,6 +452,19 @@ export default {
370452
return this.branch.conditions?.[0]?.fileUploaded ?? true
371453
},
372454
455+
/**
456+
* Placeholder for condition value input
457+
*/
458+
conditionValuePlaceholder() {
459+
if (this.conditionType === 'regex') {
460+
return t('forms', 'Regular expression, e.g. /^yes$/i')
461+
}
462+
if (this.conditionType === 'string_equals') {
463+
return t('forms', 'Exact text to match')
464+
}
465+
return t('forms', 'Text to search for')
466+
},
467+
373468
/**
374469
* Date picker type based on trigger type
375470
*/

‎src/components/Questions/QuestionConditional.vue‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ import {
345345
import answerTypes from '../../models/AnswerTypes.ts'
346346
import logger from '../../utils/Logger.ts'
347347
import OcsResponse2Data from '../../utils/OcsResponse2Data.ts'
348+
import { splitRegex } from '../../utils/RegularExpression.ts'
348349
349350
// Types of subquestions, conditional questions can not be nested
350351
const SUBQUESTION_TYPES = [
@@ -411,6 +412,10 @@ export default defineComponent({
411412
label: t('forms', 'Choice'),
412413
types: ['multiple_unique', 'multiple', 'dropdown'],
413414
},
415+
{
416+
label: t('forms', 'Text'),
417+
types: ['short', 'long'],
418+
},
414419
{
415420
label: t('forms', 'Date and time'),
416421
types: ['date', 'time'],
@@ -975,6 +980,22 @@ export default defineComponent({
975980
return false
976981
}
977982
983+
if (['short', 'long'].includes(this.triggerType)) {
984+
const text = this.triggerValues[0] || ''
985+
return branch.conditions.some((c) => {
986+
if (c.type === 'regex') {
987+
return this.safeRegexMatch(c.value, text)
988+
}
989+
if (c.type === 'string_contains') {
990+
return text.includes(c.value || '')
991+
}
992+
if (c.type === 'string_equals') {
993+
return text === c.value
994+
}
995+
return false
996+
})
997+
}
998+
978999
if (this.triggerType === 'linearscale') {
9791000
const numValue = parseFloat(this.triggerValues[0]) || 0
9801001
return branch.conditions.some((c) => {
@@ -1033,6 +1054,29 @@ export default defineComponent({
10331054
return false
10341055
},
10351056
1057+
/**
1058+
* Safely execute a regex match to prevent ReDoS attacks
1059+
*
1060+
* @param {string} pattern The regular expression with delimiters, e.g. `/^yes$/i`
1061+
* @param {string} subject The string to match against
1062+
* @return {boolean} True if pattern matches
1063+
*/
1064+
safeRegexMatch(pattern, subject) {
1065+
if (!pattern || subject.length > 10000) {
1066+
return false
1067+
}
1068+
// Same format as the server: `/pattern/modifiers`
1069+
const { pattern: source, modifiers } = splitRegex(pattern)
1070+
if (!source) {
1071+
return false
1072+
}
1073+
try {
1074+
return new RegExp(source, modifiers).test(subject)
1075+
} catch {
1076+
return false
1077+
}
1078+
},
1079+
10361080
async validate() {
10371081
if (this.$refs.triggerQuestion?.validate) {
10381082
const triggerValid = await this.$refs.triggerQuestion.validate()

0 commit comments

Comments
 (0)