Repository navigation
Expand file tree
/
Copy pathDefaultFromQuery.php
More file actions
755 lines (684 loc) · 24.9 KB
/
Copy pathDefaultFromQuery.php
File metadata and controls
755 lines (684 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
<?php
/**
* @file
* Provides DefaultFromQuery class for Default From Query.
*/
namespace UF_CTSI\DefaultFromQuery;
use ExternalModules\AbstractExternalModule;
use Form;
use Records;
/**
* DefaultFromQuery class for Default From Query.
*/
class DefaultFromQuery extends AbstractExternalModule
{
/**
* Placeholders whose values are bound as query parameters.
*/
const SQL_VARIABLES = [
'project-id',
'field-name',
'record-name',
'record-dag-id',
'event-id',
'current-instance',
'pid-1',
'pid-2',
'pid-3',
];
/**
* @inheritdoc
*/
function redcap_data_entry_form_top($project_id, $record, $instrument, $event_id, $group_id, $repeat_instance)
{
if ($record === null || !$this->currentFormHasData($record, $instrument, $event_id, $repeat_instance)) {
$this->setDefaultValues(
$project_id,
$record,
$instrument,
$event_id,
$group_id,
$repeat_instance,
);
}
}
/**
* @inheritdoc
*
* On survey pages REDCap builds the form elements (including each field's
* action tag list) before this hook fires, so in addition to injecting
* the @DEFAULT value into the field metadata we must add @DEFAULT to the
* already-built element so renderForm() applies it.
*/
function redcap_survey_page_top($project_id, $record, $instrument, $event_id, $group_id, $survey_hash, $response_id, $repeat_instance)
{
// $record is null on the first load of a survey page, even for
// existing records. REDCap always sets $_GET['id']: either the real
// record or a provisional auto-number for a new public survey.
$record = $record ?? ($_GET['id'] ?? null);
if ($record !== null && $this->currentFormHasData($record, $instrument, $event_id, $repeat_instance)) {
return;
}
$filled = $this->setDefaultValues(
$project_id,
$record,
$instrument,
$event_id,
$group_id,
$repeat_instance,
true,
);
if (empty($filled)) {
return;
}
global $elements;
if (!is_array($elements)) {
return;
}
foreach ($elements as &$element) {
if (!isset($element['name']) || !in_array($element['name'], $filled, true)) {
continue;
}
$tags = explode(' ', trim($element['action_tag_class'] ?? ''));
if (!in_array('@DEFAULT', $tags, true)) {
$element['action_tag_class'] = trim(($element['action_tag_class'] ?? '') . ' @DEFAULT');
}
}
unset($element);
}
/**
* @inheritdoc
*
* Records survey approvals. A save by a super user approves the current
* version of every query marked "Allow on survey pages". A save by anyone
* else leaves approvals unchanged, so any query they altered stops running
* on surveys until a super user saves the configuration again.
*/
function redcap_module_save_configuration($project_id)
{
if (empty($project_id)) {
return;
}
$queries = $this->getSubSettings('queries', $project_id);
if ($this->isSuperUser()) {
$approved = [];
foreach ($queries as $query) {
if (!empty($query['allow_on_surveys'])) {
$approved[] = $this->queryFingerprint($query);
}
}
$this->setSystemSetting($this->surveyApprovalsKey($project_id), array_values(array_unique($approved)));
return;
}
$suspended = $this->getSuspendedSurveyQueryNames($project_id, $queries);
if (empty($suspended)) {
return;
}
$message = 'Survey use suspended pending REDCap administrator approval for query: ' . implode(', ', $suspended);
$this->log($message, ['project_id' => $project_id]);
\REDCap::logEvent('Default From Query: survey use suspended', $message, null, null, null, $project_id);
}
/**
* @inheritdoc
*
* Warns project users when a query allowed on surveys has been changed by
* a non-admin and is waiting for re-approval.
*/
function redcap_every_page_top($project_id)
{
if (empty($project_id) || !defined('PAGE')) {
return;
}
// REDCap sets PAGE from the last two path components, so the project
// External Modules page (ExternalModules/manager/project.php, or
// external_modules/manager/project.php on older installs) is
// "manager/project.php".
if (!in_array(PAGE, ['manager/project.php', 'Design/online_designer.php'], true)) {
return;
}
$suspended = $this->getSuspendedSurveyQueryNames($project_id, $this->getSubSettings('queries', $project_id));
if (empty($suspended)) {
return;
}
$names = implode(', ', array_map(function ($name) {
return '<code>' . htmlspecialchars((string) $name, ENT_QUOTES) . '</code>';
}, $suspended));
echo '<div class="alert alert-warning" style="max-width:800px;margin:10px 0;">'
. '<b>Default From Query:</b> these queries were changed after a REDCap administrator allowed them on survey pages, '
. 'so they will not run on surveys: ' . $names . '. '
. 'Ask a REDCap administrator to review the queries and save the module configuration to re-approve them. '
. '<a href="' . htmlspecialchars($this->getUrl('queries.php'), ENT_QUOTES) . '">View the queries</a>.'
. '</div>';
}
/**
* Computes a fingerprint of the parts of a query that a non-admin could
* change or that determine what the query reads.
*
* @param array $query A query sub-settings entry.
* @return string
*/
function queryFingerprint(array $query)
{
return hash('sha256', json_encode([
(string) ($query['query_name'] ?? ''),
(string) ($query['query_sql'] ?? ''),
(string) ($query['pid1'] ?? ''),
(string) ($query['pid2'] ?? ''),
(string) ($query['pid3'] ?? ''),
]));
}
/**
* System-setting key holding the approved query fingerprints for a project.
* A system setting is used because non-admins cannot write system settings.
*
* @param int $project_id
* @return string
*/
function surveyApprovalsKey($project_id)
{
return 'survey-approvals-pid-' . (int) $project_id;
}
/**
* Returns TRUE if a query may run on survey pages.
*
* @param array $query
* @param int $project_id
* @return bool
*/
function isApprovedForSurveys(array $query, $project_id)
{
if (empty($query['allow_on_surveys'])) {
return false;
}
$approved = $this->getSystemSetting($this->surveyApprovalsKey($project_id));
return is_array($approved) && in_array($this->queryFingerprint($query), $approved, true);
}
/**
* Lists names of queries marked "Allow on survey pages" that have no
* matching admin approval.
*
* @param int $project_id
* @param array $queries
* @return string[]
*/
function getSuspendedSurveyQueryNames($project_id, array $queries)
{
$suspended = [];
foreach ($queries as $query) {
if (!empty($query['allow_on_surveys']) && !$this->isApprovedForSurveys($query, $project_id)) {
$suspended[] = (string) ($query['query_name'] ?? '');
}
}
return $suspended;
}
/**
* Sets default values for fields tagged with @DEFAULT-FROM-QUERY.
*
* Iterates project metadata for the current form, looks up the named query
* from project settings, executes it, and injects the result as the value
* of the @DEFAULT action tag so REDCap renders it as the field default.
*
* @param int $project_id
* @param string $record
* @param string $instrument
* @param int $event_id
* @param int $group_id
* @param int $repeat_instance
* @param bool $is_survey Only run queries approved for survey pages.
* @return string[] Names of the fields whose default was set.
*/
function setDefaultValues($project_id, $record, $instrument, $event_id, $group_id, $repeat_instance, $is_survey = false)
{
$filled = [];
global $Proj;
// Support draft preview mode
$fields = $Proj->getFormFields($instrument);
$metadata = $Proj->getMetadata();
$draft_preview_enabled = ($GLOBALS["draft_preview_enabled"] ?? false);
$update_misc = function ($field, $value) use ($Proj, $draft_preview_enabled) {
if ($draft_preview_enabled) {
$Proj->metadata_temp[$field]['misc'] = $value;
} else {
$Proj->metadata[$field]['misc'] = $value;
}
};
foreach ($fields as $field_name) {
$misc = $metadata[$field_name]['misc'];
$query_name = Form::getValueInQuotesActionTag($misc, '@DEFAULT-FROM-QUERY');
if (empty($query_name)) {
continue;
}
$query = $this->getQueryByName($query_name);
if ($query === null) {
continue;
}
if ($is_survey && !$this->isApprovedForSurveys($query, $project_id)) {
continue;
}
// Optional other project references
$pids = [
'pid-1' => $query['pid1'] ?? null,
'pid-2' => $query['pid2'] ?? null,
'pid-3' => $query['pid3'] ?? null,
];
// The SQL text and the bound values are built separately so that
// request-derived values (e.g. the record) can only ever be bound.
$sql = $this->substituteDataTables($query['query_sql'], $project_id, $pids);
$params = $this->getSqlParams($sql, [
'project-id' => $project_id,
'field-name' => $field_name,
'record-name' => $record,
'record-dag-id' => $group_id,
'event-id' => $event_id,
'current-instance' => $repeat_instance,
'pid-1' => $pids['pid-1'],
'pid-2' => $pids['pid-2'],
'pid-3' => $pids['pid-3'],
]);
$sql = $this->pipeSqlVariables($sql);
$value = $this->executeQuery($sql, $params);
if ($value === null) {
continue;
}
$update_misc($field_name, $this->overrideActionTag('@DEFAULT', $value, $misc));
$filled[] = $field_name;
}
return $filled;
}
/**
* Looks up a named query entry from project settings.
*
* @param string $query_name
* @return array|null The query settings array, or null if not found.
*/
function getQueryByName($query_name)
{
$queries = $this->getSubSettings('queries');
foreach ($queries as $query) {
if ($query['query_name'] === $query_name) {
return $query;
}
}
return null;
}
/**
* Substitutes data table placeholders with REDCap data table names.
*
* Table names cannot be bound as parameters, so [data-table],
* [data-table:N], [data-table:pid-1], [data-table:pid-2] and
* [data-table:pid-3] are replaced directly. Their values come only from
* the current project ID and the query's admin-defined project IDs.
*
* @param string $sql The raw SQL string containing placeholders.
* @param int $project_id The current REDCap project ID.
* @param array $pids The query's other project IDs, keyed pid-1 to pid-3.
* @return string
*/
function substituteDataTables($sql, $project_id, $pids)
{
$sql = preg_replace_callback(
'/\[data-table(?::(\d+))?\]/',
function ($m) use ($project_id) {
$pid = isset($m[1]) && $m[1] !== '' ? (int)$m[1] : $project_id;
return $this->framework->getDataTable($pid);
},
$sql
);
foreach (['pid-1', 'pid-2', 'pid-3'] as $key) {
if (!empty($pids[$key])) {
$sql = str_replace("[data-table:$key]", $this->framework->getDataTable($pids[$key]), $sql);
}
}
return $sql;
}
/**
* Regex matching any placeholder listed in SQL_VARIABLES.
*
* @return string
*/
function sqlVariablePattern()
{
return '/\[(' . implode('|', array_map(function ($name) {
return preg_quote($name, '/');
}, self::SQL_VARIABLES)) . ')\]/';
}
/**
* Replaces each smart variable placeholder in a SQL string with a ?
* parameter marker.
*
* Supported placeholders: [project-id], [field-name], [record-name],
* [record-dag-id], [event-id], [current-instance], [pid-1], [pid-2],
* [pid-3]. Call substituteDataTables() first, and build the bound values
* with getSqlParams() from the same string.
*
* @param string $sql SQL with data table placeholders already substituted.
* @return string
*/
function pipeSqlVariables($sql)
{
return preg_replace($this->sqlVariablePattern(), '?', $sql);
}
/**
* Returns the values to bind for the ? markers pipeSqlVariables() will
* produce from the same SQL string, in order of appearance.
*
* @param string $sql SQL with data table placeholders already substituted.
* @param array $values Values keyed by placeholder name (see SQL_VARIABLES).
* Note: not yet existing (new) records have a record-name of null.
* @return array
*/
function getSqlParams($sql, array $values)
{
preg_match_all($this->sqlVariablePattern(), $sql, $matches);
$params = [];
foreach ($matches[1] as $name) {
$params[] = $values[$name] ?? null;
}
return $params;
}
/**
* Executes a SQL query and returns the first column of the first row.
*
* @param string $sql
* @param array $params Bound parameter values for prepared statement placeholders.
* @return string|null The scalar result, or null if no rows returned.
*/
function executeQuery($sql, $params = [])
{
$safe = $this->checkSafeQuery($sql);
if (!$safe) {
return null;
}
$this->query('START TRANSACTION READ ONLY', []);
try {
$result = $this->query($sql, $params);
$this->query('ROLLBACK', []);
if (!$result) {
return null;
}
$row = $result->fetch_row();
return $row ? (string) $row[0] : null;
} catch (\Throwable $e) {
$this->query('ROLLBACK', []);
return null;
}
}
/**
* Injects a value into the @DEFAULT action tag within a misc field string.
*
* Replaces the existing @DEFAULT value if present, otherwise appends it.
*
* @param string $key The action tag name (e.g. @DEFAULT).
* @param string $value The value to inject.
* @param string $subject The misc field string.
* @return string
*/
function overrideActionTag($key, $value, $subject)
{
$escaped = str_replace('"', '\\"', $value);
$pattern = '/' . preg_quote($key, '/') . '\s*=\s*("[^"]*"|\'[^\']*\')/';
if (preg_match($pattern, $subject)) {
return preg_replace($pattern, $key . '="' . $escaped . '"', $subject);
}
return $subject . ' ' . $key . '="' . $escaped . '"';
}
/**
* Checks if the current form already has data.
*
* Prevents overwriting existing record data with defaults.
*
* @param string $record The current record name.
* @param string $instrument The current instrument/form name.
* @param int $event_id The current event ID.
* @param int $repeat_instance The current repeat instance number.
* @return bool TRUE if the form contains data, FALSE otherwise.
*/
function currentFormHasData($record, $instrument, $event_id, $repeat_instance)
{
global $double_data_entry, $user_rights;
// $user_rights is not set on survey pages.
if ($double_data_entry && is_array($user_rights) && ($user_rights['double_data'] ?? 0) != 0) {
$record = $record . '--' . $user_rights['double_data'];
}
return (bool) Records::formHasData($record, $instrument, $event_id, $repeat_instance);
}
/**
* Best-effort safety check for SQL expected to be read-only.
*
* IMPORTANT:
* - This is intentionally conservative.
* - False negatives are acceptable; false positives are not.
* - Still run accepted queries inside START TRANSACTION READ ONLY ... ROLLBACK.
* - This is not a full SQL parser.
*/
function checkSafeQuery(string $sql): bool
{
$sql = trim($sql);
if ($sql === '') {
return false;
}
// Remove comments and string literals so keyword scanning is less error-prone.
$scan = $this->stripSqlStringsAndComments($sql);
$scan = trim($scan);
if ($scan === '') {
return false;
}
// Reject multi-statement input.
// We strip a single trailing semicolon and reject any remaining semicolon.
$scanNoTrailingSemicolon = preg_replace('/;\s*$/', '', $scan);
if (strpos($scanNoTrailingSemicolon, ';') !== false) {
return false;
}
$scan = $scanNoTrailingSemicolon;
// Normalize whitespace and lowercase for matching.
$norm = strtolower(preg_replace('/\s+/', ' ', $scan));
$normForStart = $this->normalizeLeadingGroupingParens($norm);
// Allow only clearly read-style top-level starts.
// Conservative on purpose. Add more only if you really need them.
if (!preg_match('/^(select|with|show|describe|desc|explain)\b/', $normForStart)) {
return false;
}
// EXPLAIN is only allowed for read-style statements.
// Reject EXPLAIN UPDATE/DELETE/INSERT/etc. even though EXPLAIN itself is non-writing,
// because the function's contract is "harmless read-like query".
if (preg_match('/^explain\b/', $normForStart)) {
$afterExplain = preg_replace('/^explain\s+/', '', $normForStart, 1);
$afterExplain = $this->normalizeLeadingGroupingParens($afterExplain);
if (!preg_match('/^(select|with|show|describe|desc)\b/', $afterExplain)) {
return false;
}
}
// Hard reject suspicious / non-harmless constructs anywhere.
$denyPatterns = [
// DML / write-like
'/\binsert\b/',
'/\bupdate\b/',
'/\bdelete\b/',
'/\breplace\b/',
'/\bupsert\b/',
'/\bmerge\b/',
'/\bload\s+data\b/',
'/\btruncate\b/',
// DDL
'/\bcreate\b/',
'/\balter\b/',
'/\bdrop\b/',
'/\brename\b/',
'/\bcomment\b/',
'/\brepair\b/',
'/\boptimize\b/',
'/\banalyze\b/', // MariaDB ANALYZE statement, not EXPLAIN ANALYZE syntax
'/\bcheck\b/',
'/\bcache\s+index\b/',
// Transaction / locking / admin
'/\block\s+tables?\b/',
'/\bunlock\s+tables?\b/',
'/\bfor\s+update\b/',
'/\bfor\s+share\b/',
'/\block\s+in\s+share\s+mode\b/',
'/\bflush\b/',
'/\breset\b/',
'/\bset\s+transaction\b/',
'/\bstart\s+transaction\b/',
'/\bbegin\b/',
'/\bcommit\b/',
'/\brollback\b/',
// File / external effects
'/\binto\s+outfile\b/',
'/\binto\s+dumpfile\b/',
// Routines / dynamic SQL / eventing
'/\bcall\b/',
'/\bexecute\b/',
'/\bprepare\b/',
'/\bdeallocate\b/',
'/\bdo\b/',
'/\bsignal\b/',
'/\bresignal\b/',
'/\bhandler\b/'
];
foreach ($denyPatterns as $pattern) {
if (preg_match($pattern, $norm)) {
return false;
}
}
// Reject user-variable assignment patterns like "@x :=".
if (preg_match('/@[\w$]+\s*:=/', $norm)) {
return false;
}
// Reject SELECT ... INTO @var / local var
// This is not a DB write, but it is a side effect.
if (preg_match('/\bselect\b.*\binto\b\s+(@|[a-z_][a-z0-9_]*)/is', $norm)) {
return false;
}
return true;
}
/**
* Removes SQL comments and string/backtick literals, replacing them with spaces.
* This avoids matching dangerous keywords that occur only inside strings/comments.
*
* Handles:
* - -- comment
* - # comment
* - /* block comment *\/
* - 'single quoted strings'
* - "double quoted strings"
* - `backtick identifiers`
*/
function stripSqlStringsAndComments(string $sql): string
{
$len = strlen($sql);
$out = '';
$i = 0;
while ($i < $len) {
$ch = $sql[$i];
$next = ($i + 1 < $len) ? $sql[$i + 1] : '';
// -- comment (treat --<space> and --\n conservatively as comment start)
if ($ch === '-' && $next === '-') {
$third = ($i + 2 < $len) ? $sql[$i + 2] : '';
if ($third === '' || ctype_space($third)) {
$out .= ' ';
$i += 2;
while ($i < $len && $sql[$i] !== "\n") {
$i++;
}
continue;
}
}
// # comment
if ($ch === '#') {
$out .= ' ';
$i++;
while ($i < $len && $sql[$i] !== "\n") {
$i++;
}
continue;
}
// /* block comment */
if ($ch === '/' && $next === '*') {
$out .= ' ';
$i += 2;
while ($i + 1 < $len && !($sql[$i] === '*' && $sql[$i + 1] === '/')) {
$i++;
}
$i += 2; // skip closing */
continue;
}
// Single-quoted string
if ($ch === "'") {
$out .= ' ';
$i++;
while ($i < $len) {
if ($sql[$i] === "\\") {
$i += 2;
continue;
}
if ($sql[$i] === "'") {
// handle doubled single quote ''
if ($i + 1 < $len && $sql[$i + 1] === "'") {
$i += 2;
continue;
}
$i++;
break;
}
$i++;
}
continue;
}
// Double-quoted string
if ($ch === '"') {
$out .= ' ';
$i++;
while ($i < $len) {
if ($sql[$i] === "\\") {
$i += 2;
continue;
}
if ($sql[$i] === '"') {
if ($i + 1 < $len && $sql[$i + 1] === '"') {
$i += 2;
continue;
}
$i++;
break;
}
$i++;
}
continue;
}
// Backtick identifier
if ($ch === '`') {
$out .= ' ';
$i++;
while ($i < $len) {
if ($sql[$i] === '`') {
if ($i + 1 < $len && $sql[$i + 1] === '`') {
$i += 2;
continue;
}
$i++;
break;
}
$i++;
}
continue;
}
$out .= $ch;
$i++;
}
return $out;
}
/**
* Removes leading parentheses
* @param string $sql
* @return string
*/
function normalizeLeadingGroupingParens(string $sql): string
{
$sql = ltrim($sql);
while (isset($sql[0]) && $sql[0] === '(') {
$sql = ltrim(substr($sql, 1));
}
return $sql;
}
}