-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrecordHomeDashboard.php
536 lines (467 loc) · 16.2 KB
/
recordHomeDashboard.php
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
<?php
namespace STPH\recordHomeDashboard;
/**
* REDCap External Module: Record Home Dashboard
* A REDCap External Module that enables to add a customized Dashboard to the Record Homepage.
*
* @author Ekin Tertemiz, Swiss Tropical and Public Health Institute
*
*/
// used for development
if( file_exists("vendor/autoload.php") ){
require 'vendor/autoload.php';
}
// used for list rendering
use \Piping;
use \REDCap;
class recordHomeDashboard extends \ExternalModules\AbstractExternalModule {
/** @var object */
protected $project_settings;
protected $hasMultipleEvents;
protected $hasMultipleArms;
protected $events;
protected $table_pk;
// /**
// * Constructs the class
// * @return void
// * @since 1.0.0
// *
// */
// public function __construct() {
// parent::__construct();
// //global $Proj;
//
// // $this->hasMultipleEvents= $Proj->longitudinal;
// // $this->hasMultipleArms = $Proj->multiple_arms;
// // $this->events = (is_array($Proj->eventsForms) ? array_keys($Proj->eventsForms) : null);
// // $this->table_pk = $Proj->table_pk;
// }
/**
*
* Renders Dashboard on Record Home Page
* @param string $project_id
* @return void
* @since 1.0.0
*
*/
public function redcap_every_page_top($project_id = null) {
if( $this->isPage('DataEntry/record_home.php') && isset( $_GET['id']) && defined('USERID') ) {
$this->renderDashboard();
}
}
/**
*
* Renders the dashboard by including target Wrapper and Javascripts
*
* @return void
* @since 1.0.0
*
*/
private function renderDashboard() {
?>
<!-- Insert Dashboard Render Wrapper so Vue.js can mount it -->
<div id="STPH_DASHBOARD_WRAPPER" style="display: none;">
<div id="STPH_DASHBOARD_RENDER"></div>
</div>
<link rel="stylesheet" href="<?= $this->getUrl('dist/style.css')?>">
<script>
$(function() {
$(document).ready(function(){
$('#center').addClass("<?= $this->displayClasses() ?>")
$('#event_grid_table').after('<div id="record_home_dashboard_title"><?= $this->getProjectSetting('dashboard-title') == "" ? "Record Home Dashboard" : $this->getProjectSetting('dashboard-title') ?></div>');
// We have to move our wrapper element to the correct position and then show it
let wrapper = $('#STPH_DASHBOARD_WRAPPER');
$('#record_home_dashboard_title').after(wrapper)
wrapper.show()
})
});
</script>
<script>
const stph_rhd_getBaseUrlFromBackend = function() {
return '<?= $this->getBaseUrl() ?>'
}
const stph_rhd_getBaseParametersFromBackend = function() {
return {
project_id: '<?= $this->getProjectId() ?>',
record: '<?= htmlentities($_GET['id'], ENT_QUOTES) ?>'
}
}
</script>
<script src="<?= $this->getUrl("./dist/appRender.js") ?>"></script>
<?php
}
/**
* Gets Project Parameters needed to support additional features of REDCap
*
* @return array
* @since 1.1.0
*
*/
public function getProjectParameters() {
global $Proj;
$this->hasMultipleEvents= $Proj->longitudinal;
$this->hasMultipleArms = $Proj->multiple_arms;
return [
"hasMultipleEvents" => $this->hasMultipleEvents,
"hasMultipleArms" => $this->hasMultipleArms
];
}
/**
*
* Gets Display options for current user (xor impersonifed user)
*
* @return mixed
* @since 1.0.0
*
*/
private function getDisplayOptions() {
$current_user = "";
$userRights = [];
$userRole = "";
$displayOptions = [];
$current_user = ($this->getUser())->getUsername();
# Check if Impersonification is active (trumps super-user)
if(\UserRights::isImpersonatingUser()){
$current_user = $_SESSION['impersonate_user'][PROJECT_ID]['impersonating'];
}
$userRights = REDCap::getUserRights($current_user);
if($userRights) {
$userRole = $userRights[$current_user]["role_id"];
}
if($userRole) {
$allDisplayOptions = $this->getSubSettings("display-option");
$displayOptions = reset(array_filter( $allDisplayOptions, function($e) use ($userRole) {
return $e["user-role"] == $userRole;
})
);
}
if($displayOptions) {
return $displayOptions;
}
return null;
}
/**
*
* Gets all instances needed for table data and ensures dates are formatted correctly
*
* @param string $project_id
* @param string $record
* @param string $instrument
* @param array $fields
* @return void
* @since 1.0.0
*
*/
private function getInstancesData( $project_id , $record, $instrument, $fields=null, $events=[]) {
global $Proj;
$this->table_pk = $Proj->table_pk;
$field_names_array = [];
$params = [];
$instances = [];
// Get a list of all fields for a form if not specified and limit to 10
if($fields == null) {
$fields = array_slice($this->getFieldNames($instrument), 0, 10);
}
// Prepare for fields query
foreach ($fields as $key => $field) {
$field_names_array[] = '"'.$field . '"';
}
$field_names = implode(",", $field_names_array);
// Gets all element validation types (mainly to support text field formatting)
// Gets field labels (table header output)
// Order by field_order!
$sql = 'SELECT element_validation_type, field_name, element_label FROM redcap_metadata WHERE project_id = ? AND field_name IN('.$field_names.') ORDER BY field_order';
$result = $this->query($sql, [$project_id]);
$array_to_format = [];
$fieldLabels = array();
while($row = $result->fetch_object()) {
$label = $row->element_label;
if (strlen($label) > 30) $label = substr($label, 0, 15)."...".substr($label, -6);
$fieldLabels[] =array("key"=>$row->field_name, "label"=>$label);
if($row->element_validation_type) {
$array_to_format[$row->field_name] = $row->element_validation_type;
}
}
// Fetch all data as JSON so that labels (piped values) are exported (all events)
$params = array(
"project_id" => $project_id,
"records" =>$record,
"events" => $events,
"exportAsLabels" => true,
"exportDataAccessGroups" => false,
"return_format" => "json",
"fields" => $fields,
"returnIncludeRecordEventArray"=> true
);
$data = json_decode(REDCap::getData($params), true);
// Filter by instrument
$instrument_name = REDCap::getInstrumentNames($instrument);
$mapped = array_map(function($instance) use($instrument_name){
// case-insensitive compare because instrument name may be capitalized
if( strcasecmp($instance["redcap_repeat_instrument"], $instrument_name) == 0 ) {
// Remove Record Event Info
// Hard coded...
unset($instance[$this->table_pk]);
unset($instance["redcap_data_access_group"]);
unset($instance["redcap_event_name"]);
unset($instance["redcap_repeat_instrument"]);
unset($instance["redcap_repeat_instance"]);
return $instance;
} else {
return false;
}
}, $data);
$filtered = array_filter($mapped);
// Use Formatter Class to render date formats correctly
if (!class_exists("Formatter")) include_once("classes/Formatter.php");
$formatter = new Formatter;
// Reset final array and handle field formatting
foreach ($filtered as $key => $instance) {
// Adjust formatting (dates)
foreach ($array_to_format as $field_to_format => $valtype) {
// Skip empty fields otherwise it will be filled with invalid data
if(empty($instance[$field_to_format])) {
continue;
}
$instance[$field_to_format] = $formatter::renderDateFormat($instance[$field_to_format], $valtype);
}
// Data Access
$instances[] = $instance;
}
// Reverse order so that greates instance number is first
$reversed = array_reverse($instances);
return array("items"=> $reversed, "fields"=>$fieldLabels);
}
// ==== A P I ====
// Called with Axios via RequestHandler
/**
*
* Gets Dashboard Data from database
*
* @return void
* @since 1.0.0
*
*/
public function getDashboardData() {
$data = $this->getProjectSetting("dashboard-data");
$this->sendResponse($data);
}
/**
*
* Saves Dashboard Data into database
*
* @return void
* @since 1.0.0
*
*/
public function saveDashboardData($new) {
$this->setProjectSetting("dashboard-data", $new);
$this->getDashboardData();
}
/**
*
* Renders Element Content for each type
*
* @param string $type
* @param object $content
* @param object $params
* @return void
* @since 1.0.0
*
*/
public function renderElementContent($type, $content, $params, $event) {
$project_id = $params->project_id;
$record = $params->record;
$event_id = $event;
if($event_id == null) {
$event_id = $this->getFirstEventId($project_id);
//$event_id = $this->getEventId();
}
// Prepare data access check arrays
$user_id = USERID;
$user_rights = REDCap::getUserRights($user_id);
$no_access_forms = array_keys(array_filter($user_rights[$user_id]["forms"], function($value){
return $value == 0;
}));
$no_access_fields = [];
foreach ($no_access_forms as $key => $form) {
$no_access_fields = array_merge($no_access_fields, $this->getFieldNames($form));
}
// Send Error if user has not the rights to access data
if(isset($content->instrument) && in_array($content->instrument, $no_access_forms)) {
//$this->sendError(403);
}
switch ($type) {
case 'link':
$response= Piping::replaceVariablesInLabel($content->url, $record, $event_id, 1, array(), true, $project_id, false);
if (filter_var($response, FILTER_VALIDATE_URL) === FALSE) {
$this->sendError();
}
break;
case 'list';
$response = [];
foreach ($content as $key => $el) {
// Check if has data access on form level
if(in_array( trim($el->value, '[]'), $no_access_fields)) {
$response[] = false;
} else {
$response[] = Piping::replaceVariablesInLabel($el->value, $record, $event_id, 1, array(), true, $project_id, false);
}
}
break;
case 'table':
// Check if has data access on form level
if(isset($content->instrument) && in_array($content->instrument, $no_access_forms)) {
$response = false;
} else {
$response = $this->getInstancesData($project_id, $record, $content->instrument, $content->columns, $content->event);
}
break;
default:
$this->sendError();
break;
}
$this->sendResponse($response);
}
/**
*
* Gets field names for an instrument (needed for prefilling list modal)
*
* @param string $instrument
* @return void
* @since 1.0.0
*
*/
public function getFieldForInstrument($instrument) {
$response = $this->getFieldNames($instrument);
$this->sendResponse($response);
}
// ==== H E L P E R S ====
/**
*
* Gets Repeating Forms for single or multiple events projects
*
* @return array
* @since 1.0.0
*
*/
public function getSafeRepeatingForms() {
global $Proj;
$this->hasMultipleEvents= $Proj->longitudinal;
$this->events = (is_array($Proj->eventsForms) ? array_keys($Proj->eventsForms) : null);
$repeatingForms = [];
if($this->hasMultipleEvents) {
// Stack repeating forms for all events
foreach ($this->events as $event) {
$repeatingForms = array_merge( $repeatingForms, $this->getRepeatingForms($event, PROJECT_ID));
}
// Remove duplicates
$repeatingForms = array_unique($repeatingForms);
} else {
$repeatingForms = $this->getRepeatingForms();
}
return $repeatingForms;
}
/**
* Gets event info for current project, that can be used to define event in multple event context
* redcap_v10.6.28\Classes\Project.php::loadEvents()
*
* @return array
* @since 1.1.0
*
*/
public function getEventInfo() {
$eventInfo = [];
$sql = "select * from redcap_events_metadata e, redcap_events_arms a where a.project_id = " . PROJECT_ID . "
and a.arm_id = e.arm_id order by a.arm_num, e.day_offset, e.descrip";
$q = db_query($sql);
while ($row = db_fetch_assoc($q)){
$eventInfo[] = array( 'value' => (string)(int) $row['event_id'], 'text' => htmlspecialchars($row['descrip'], ENT_QUOTES));
}
db_free_result($q);
return $eventInfo;
}
/**
*
* Gets Base URL to Request Handler
*
* @return string
* @since 1.0.0
*
*/
public function getBaseUrl(){
return $this->getUrl("requestHandler.php");
}
/**
*
* Checks if Editor is disabled for current user role
*
* @return bool
* @since 1.0.0
*
*/
public function isDisabledEditor() {
$displayOptions = [];
$displayOptions = $this->getDisplayOptions();
if($displayOptions == null) {
return false;
}
return $displayOptions["disable-editor"];
}
/**
*
* Returns classes referencing to display options per user role
*
* @return string
* @since 1.0.0
*
*/
public function displayClasses() {
$displayOptions = [];
$displayOptions = $this->getDisplayOptions();
$classes = "";
if($displayOptions["hide-top-render"]) {
$classes .= " hide-data_table";
}
if($displayOptions["hide-bottom-render"]) {
$classes .= " hide-repeating_forms_table";
}
return $classes;
}
/**
*
* Echoes sucessful JSON response
*
* @return void
* @since 1.0.0
*
*/
private function sendResponse($response) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($response);
exit();
}
/**
*
* Echoes error JSON response
*
* @return void
* @since 1.0.0
*
*/
private function sendError($status = 400) {
header('Content-Type: application/json; charset=UTF-8');
switch ($status) {
case 400:
header("HTTP/1.1 400 Bad Request");
break;
case 403:
header("HTTP/1.1 403 Forbidden");
break;
default:
# code...
break;
}
die();
}
}