-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathconfig.class.php
758 lines (644 loc) · 25.8 KB
/
config.class.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
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
756
757
758
<?php
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class PluginMetabaseConfig extends Config {
static function getTypeName($nb = 0) {
return __('Metabase', 'metabase');
}
/**
* Return the current config of the plugin store in the glpi config table
*
* @return array config with keys => values
*/
static function getConfig() {
return Config::getConfigurationValues('plugin:metabase');
}
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
switch ($item->getType()) {
case "Config":
return self::createTabEntry(self::getTypeName());
}
return '';
}
static function displayTabContentForItem(CommonGLPI $item,
$tabnum = 1,
$withtemplate = 0) {
switch ($item->getType()) {
case "Config":
return self::showForConfig($item, $withtemplate);
}
return true;
}
static function showForConfig(Config $config, $withtemplate = 0) {
global $CFG_GLPI;
if (!self::canView()) {
return false;
}
$current_config = self::getConfig();
$canedit = Session::haveRight(self::$rightname, UPDATE);
echo "<div class='metabase_config'>";
echo "<h1>".__("Configuration of Metabase integration")."</h1>";
if ($canedit) {
echo "<form name='form' action='".Toolbox::getItemTypeFormURL("Config")."' method='post'>";
}
echo "<div id='base_config' class='metabase_config_block'>";
echo self::showField([
'label' => __("Metabase host", 'metabase'),
'attrs' => [
'name' => 'host',
'value' => $current_config['host'],
'placeholder' => '127.0.0.1',
]
]);
echo self::showField([
'label' => __("Metabase port", 'metabase'),
'attrs' => [
'name' => 'port',
'value' => $current_config['port'],
'required' => false,
'placeholder' => '3000',
]
]);
echo self::showField([
'label' => __("username (metabase admin)", 'metabase'),
'attrs' => [
'name' => 'username',
'value' => $current_config['username'],
'style' => 'width:200px;',
]
]);
if (!empty($CFG_GLPI['proxy_name'])) {
echo self::showField([
'label' => __("Use proxy"),
'inputtype' => 'yesno',
'attrs' => [
'name' => 'use_proxy',
'value' => $current_config['use_proxy'],
'style' => 'width:200px;',
]
]);
}
echo self::showField([
'inputtype' => 'password',
'label' => __("password"),
'attrs' => [
'name' => 'password',
'value' => '',
'style' => 'width:200px;',
'required' => false,
]
]);
echo self::showField([
'label' => __("Metabase embedded token (to display dashboard in GLPI)", 'metabase'),
'attrs' => [
'name' => 'embedded_token',
'value' => $current_config['embedded_token'],
'placeholder' => '',
'required' => false
]
]);
echo self::showField([
'label' => __("Metabase url", 'metabase'),
'help' => __("You may want to have a different dashboard url (with https for example) than the host (used to push the data) ", 'metabase'),
'attrs' => [
'name' => 'metabase_url',
'value' => $current_config['metabase_url'],
'placeholder' => 'http(s)://...',
]
]);
echo self::showField([
'inputtype' => 'number',
'label' => __("Timeout for sending data (in seconds)", 'metabase'),
'attrs' => [
'name' => 'timeout',
'value' => $current_config['timeout'],
'placeholder' => '',
'required' => false
]
]);
if ($canedit) {
echo Html::hidden('config_class', ['value' => __CLASS__]);
echo Html::hidden('config_context', ['value' => 'plugin:metabase']);
echo Html::submit(_sx('button', 'Save'), [
'name' => 'update'
]);
}
echo "</div>";
Html::closeForm();
if (self::isValid()) {
echo "<h1>".__("API status", 'metabase')."</h1>";
$apiclient = new PluginMetabaseAPIClient;
$all_status = $apiclient->status();
echo "<ul>";
foreach ($all_status as $status_label => $status) {
$color_png = "greenbutton.png";
if (!$status) {
$color_png = "redbutton.png";
}
echo "<li>";
echo Html::image($CFG_GLPI['root_doc']."/pics/$color_png");
echo " ".$status_label;
echo "</li>";
}
echo "</ul>";
$error = $apiclient->getLastError();
if (count($error)) {
echo "<h1>".__("Last Error", 'metabase')."</h1>";
if (isset($error['exception'])) {
echo $error['exception'];
} else {
Html::printCleanArray($error);
}
echo "<p><strong>".GLPINetwork::getErrorMessage()."</strong></p>";
}
echo "<div id='actions'>";
if ($canedit) {
echo "<form name='form' action='".self::getFormUrl()."' method='post'>";
}
echo "<h1>".__("Action(s)", 'metabase')."</h1>";
// If session is OK but database cannot be found, it has been probably deleted on metabase side
$previousDbNotFound = $current_config['glpi_db_id'] != 0
&& $apiclient->checkSession()
&& false === $apiclient->getGlpiDatabase();
if ($current_config['glpi_db_id'] == 0 || $previousDbNotFound) {
if ($previousDbNotFound) {
echo '<p><strong>' . __('Previously stored database is not existing anymore.', 'metabase') . '</strong></p>';
}
echo Html::submit(__("Create GLPI database in local Metabase", 'metabase'), [
'name' => 'create_database'
]);
$databases = $apiclient->getDatabases();
if (is_array($databases) && count($databases) > 0) {
echo __("OR set an existing database: ", 'metabase');
Dropdown::showFromArray('db_id', array_column($databases, 'name', 'id'));
echo Html::submit(__("Set database", 'metabase'), [
'name' => 'set_database'
]);
}
} else if ($apiclient->checkSession()) {
echo Html::hidden('glpi_db_id', ['value' => $current_config['glpi_db_id']]);
if ($current_config['datamodel_done']) {
echo Html::submit(__("Push reports and dashboards in Metabase", 'metabase'), [
'name' => 'push_json'
]);
}
echo Html::submit(__("(Re)generate datamodel in Metabase", 'metabase'), [
'name' => 'push_datamodel'
]);
echo '<a href="' . $CFG_GLPI["root_doc"] . '/plugins/metabase/front/collections.php" class="vsubmit">'
. __('Show reports and dashboards specifications', 'metabase')
. '</a>';
}
Html::closeForm();
echo "</div>"; // #actions
}
echo "</div>"; // .metabase_config
}
static function createGLPIDatabase() {
$apiclient = new PluginMetabaseAPIClient;
// Remove previous database configuration
Config::setConfigurationValues(
'plugin:metabase',
[
'glpi_db_id' => 0,
'datamodel_done' => 0,
]
);
$data = $apiclient->createGlpiDatabase();
if ($data !== false) {
self::setExistingDatabase($data['id']);
return true;
}
return false;
}
static function setExistingDatabase($db_id) {
return Config::setConfigurationValues('plugin:metabase', [
'glpi_db_id'=> $db_id
]);
}
static function createDataModel($db_id) {
$api = new PluginMetabaseAPIClient;
self::loadTablesAndFields($db_id);
// detect foreign keys
$fk_count = 0;
$tables = $_SESSION['metabase']['tables'];
$fields = $_SESSION['metabase']['fields'];
foreach ($fields as $fieldname => $f_id_src) {
list($table, $field) = explode('.', $fieldname);
if (($fk_table = getTableNameForForeignKeyField($field)) !== ""
&& isset($tables[$fk_table])) {
// create foreign key
if (isset($fields[$fk_table.".id"])) {
$api->createForeignKey($f_id_src, $fields[$fk_table.".id"]);
$fk_count++;
}
}
}
Session::addMessageAfterRedirect("Foreign keys created: $fk_count");
// map value for itilobjects harcoded fields
$harcoded = $api->setItiObjectHardcodedMapping();
// set config done
if ($fk_count
&& $harcoded) {
Config::setConfigurationValues('plugin:metabase', [
'datamodel_done' => 1
]);
}
return true;
}
static function loadTablesAndFields($db_id) {
$api = new PluginMetabaseAPIClient;
$metadata = $api->getDatabaseMetadata($db_id);
if ((!array_key_exists('tables', $metadata) || count($metadata['tables']) == 0)
&& (!array_key_exists(ERROR, $_SESSION["MESSAGE_AFTER_REDIRECT"]) || count($_SESSION["MESSAGE_AFTER_REDIRECT"][ERROR]) == 0)) {
Session::addMessageAfterRedirect('Issue with db metadata, no tables found. You should discard saved field values for this db in metabase databases administration.', true, ERROR);
}
//flat all tables and fields to have their id
$tables = [];
$fields = [];
if (isset($metadata['tables'])) {
foreach ($metadata['tables'] as $table) {
$tables[$table['name']] = $table['id'];
foreach ($table['fields'] as $field) {
$fields[$table['name'].".".$field['name']] = $field['id'];
}
}
}
$_SESSION['metabase']['tables'] = $tables;
$_SESSION['metabase']['fields'] = $fields;
}
static function pushReports() {
$current_config = self::getConfig();
self::loadReports();
self::loadTablesAndFields($current_config['glpi_db_id']);
$api = new PluginMetabaseAPIClient;
$col_counts = 0;
$rep_counts = 0;
// create collections
$collections = array_unique(array_column($_SESSION['metabase']['reports'], 'collection'));
$collections_keys = [];
foreach ($collections as $collection) {
if ($collection_id = $api->createOrGetCollection($collection)) {
$col_counts++;
$collections_keys[$collection] = $collection_id;
}
}
Session::addMessageAfterRedirect("Collections created: $col_counts");
// create reports (cards or questions in metabase)
foreach ($_SESSION['metabase']['reports'] as &$report) {
if ($report['card_id'] = $api->createOrUpdateCard($report['title'], [
'database_id' => $current_config['glpi_db_id'],
'sql' => $report['sql'],
'collection_id' => $collections_keys[$report['collection']],
'description' => $report['description'],
'display' => $report['display'],
'visualization_settings' => $report['visualization_settings'],
'template_tags' => $report['template_tags'],
])) {
$rep_counts++;
}
}
Session::addMessageAfterRedirect("questions created: $rep_counts");
}
static function pushDashboards() {
self::loadDashboards();
$api = new PluginMetabaseAPIClient;
$dsh_count = 0;
// Build collection "name to ID" mapping
$collections = $api->getCollections();
$collections_keys = [];
foreach ($collections as $collection) {
$collections_keys[$collection['name']] = $collection['id'];
}
// create reports (cards or questions in metabase)
foreach ($_SESSION['metabase']['dashboards'] as &$dashboard) {
// Defines collection ID using "name to ID" mapping
$dashboard['collection_id'] = $collections_keys[$dashboard['collection']];
unset($dashboard['collection']);
if ($dashboard['id'] = $api->createOrGetDashboard($dashboard['name'], $dashboard)) {
$dsh_count++;
// prepare parameters (tags)
$dashboard_cfg = [];
$r_index = 0;
foreach ($dashboard['reports'] as $report_key => &$report_cfg) {
if (isset($_SESSION['metabase']['reports'][$report_key]['card_id'])) {
$card_id = $_SESSION['metabase']['reports'][$report_key]['card_id'];
$report_cfg['card_id'] = (int) $card_id;
$r_index++;
$final_parameter_mapping = [];
if (isset($report_cfg['parameter_mappings'])) {
foreach ($report_cfg['parameter_mappings'] as $map_slug => $fieldname) {
$parameter_index = array_search($map_slug,
array_column($dashboard['parameters'], 'slug'));
$parameters_id = $dashboard['parameters'][$parameter_index]['id'];
$final_parameter_mapping[] = [
'card_id' => (int) $card_id,
'parameter_id' => $parameters_id,
'target' => [
'dimension',
[
"template-tag",
$map_slug
]
]
];
}
}
$report_cfg['parameter_mappings'] = $final_parameter_mapping;
$dashboard_cfg[] = $report_cfg;
} else {
Session::addMessageAfterRedirect("Report not found: $report_key");
}
}
$api->setDashboardCards($dashboard['id'], ['cards' => $dashboard_cfg]);
}
}
Session::addMessageAfterRedirect("Dashboards created: $dsh_count");
}
static function loadReports() {
return self::loadDir(PLUGINMETABASE_REPORTS_DIR, 'reports');
}
static function loadDashboards() {
return self::loadDir(PLUGINMETABASE_DASHBOARDS_DIR, 'dashboards');
}
static function loadDir($path = '', $session_key = '') {
$_SESSION['metabase'][$session_key] = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$success = true;
foreach ($iterator as $file) {
if ($file->isFile() && 'json' === $file->getExtension()) {
$json = file_get_contents($file->getPathname());
if (($report_array = json_decode($json, true))) {
$_SESSION['metabase'][$session_key][$file->getBasename(".json")] = $report_array;
} else {
Session::addMessageAfterRedirect(sprintf(__("Cannot validate json for file %s"),
$file->getPathname()));
$success = false;
}
}
}
return $success;
}
static function displayQuestionJson($question_id) {
$apiclient = new PluginMetabaseAPIClient;
$card = $apiclient->getCard($question_id);
$extract = [
'title' => $card['name'],
'description' => $card['description'],
'collection' => isset($card['collection']['name'])
? $card['collection']['name']
: "",
'display' => $card['display'],
'visualization_settings' => $card['visualization_settings'],
'template_tags' => [],
'sql' => $card['dataset_query']['native']['query'],
];
foreach ($card['dataset_query']['native']['template-tags'] as $tag_name => $tag) {
$extract['template_tags'][$tag_name] = [
'type' => $tag['type'],
'display_name' => $tag['display-name'],
];
if (isset($tag['default'])) {
$extract['template_tags'][$tag_name]['default'] = $tag['default'];
}
if (isset($tag['required'])) {
$extract['template_tags'][$tag_name]['required'] = (bool) $tag['required'];
}
if (isset($tag['widget-type'])) {
$extract['template_tags'][$tag_name]['widget_type'] = $tag['widget-type'];
}
if (isset($tag['dimension'][1])) {
$extract['template_tags'][$tag_name]['field']
= array_search($tag['dimension'][1], $_SESSION['metabase']['fields']);
}
}
self::displayPrettyJson($extract);
}
static function displayDashboardJson($dashboard_id) {
$apiclient = new PluginMetabaseAPIClient;
$dashboard = $apiclient->getDashboard($dashboard_id);
$extract = [
'name' => $dashboard['name'],
'description' => $dashboard['description'],
'reports' => [],
'parameters' => [],
];
$parameters_id = [];
foreach ($dashboard['parameters'] as $parameter) {
$extract['parameters'][] = [
'default' => isset($parameter['default'])
? $parameter['default']
: "",
'name' => $parameter['name'],
'slug' => $parameter['slug'],
'type' => $parameter['type'],
];
$parameters_id[$parameter['id']] = $parameter['slug'];
}
foreach ($dashboard['ordered_cards'] as $card) {
if (isset($card['card_id']) // only question (TODO support markdown cards)
&& $card['card']['dataset_query']['type'] === "native") { // only native questions
$key = null;
foreach ($_SESSION['metabase']['reports'] as $session_key => $session_report) {
if ($session_report['title'] === $card['card']['name']) {
$key = $session_key;
}
}
if ($key !== null) {
$extract['reports'][$key] = [
'col' => $card['col'],
'row' => $card['row'],
'sizeX' => $card['sizeX'],
'sizeY' => $card['sizeY'],
];
foreach ($card['parameter_mappings'] as $mapping) {
$mapping_key = $mapping['target'][1][1];
$field_id = $card['card']['dataset_query']
['native']['template-tags']
[$mapping_key]['dimension'][1];
$field_name = array_search($field_id, $_SESSION['metabase']['fields']);
if ($field_name !== false) {
$extract['reports'][$key]['parameter_mappings']
[$parameters_id[$mapping['parameter_id']]] = $field_name;
}
}
}
}
}
self::displayPrettyJson($extract);
Html::printCleanArray($dashboard);
}
static function displayPrettyJson($array = []) {
echo Html::css("lib/prism/prism.css");
echo Html::script("lib/prism/prism.js");
echo "<pre><code class='language-json'>";
echo preg_replace("/(^|\G) {4}/m", " ", // replace indentation from 4 to 3 spaces
json_encode($array, JSON_PRETTY_PRINT
+ JSON_UNESCAPED_UNICODE
+ JSON_UNESCAPED_SLASHES));
echo "</code></pre>";
}
/**
* Show a single config field
* Generic method who call the different GLPI function to display a field
*
* @param array $options a list of options:
* - inputtype (string), can be
* * text
* * password
* * yesno
* * dropdown
* - itemtype (only for input=dropdown)
* - label, <label> tag to append to the field
* - attrs, an array containing html attributes
* @return string the html
*/
static function showField($options = []) {
$rand = mt_rand();
$default_options = [
'inputtype' => 'text',
'itemtype' => '',
'label' => '',
'help' => '',
'attrs' => [
'name' => '',
'value' => '',
'placeholder' => '',
'style' => 'width:50%;',
'id' => "metabaseconfig_field_$rand",
'class' => 'metabase_input',
'required' => 'required',
'on_change' => ''
]
];
$options = array_replace_recursive($default_options, $options);
if ($options['attrs']['required'] === false) {
unset($options['attrs']['required']);
}
$out = "";
$out.= "<div class='metabase_field'>";
// call the field according to its type
switch ($options['inputtype']) {
default:
case 'text':
$out.= Html::input('fakefield', ['style' => 'display:none;']);
$out.= Html::input($options['attrs']['name'], $options['attrs']);
break;
case 'password':
$out.= "<input type='password' name='fakefield' style='display:none;'>";
$out.= "<input type='password'";
foreach ($options['attrs'] as $key => $value) {
$out.= "$key='$value' ";
}
$out.= ">";
break;
case 'yesno':
$options['attrs']['display'] = false;
$out.= Dropdown::showYesNo($options['attrs']['name'], $options['attrs']['value'], -1, $options['attrs']);
break;
case 'dropdown':
$options['attrs']['display'] = false;
$out.= Dropdown::show($options['itemtype'], $options['attrs']);
break;
case 'number':
$options['attrs']['display'] = false;
$out.= Dropdown::showNumber($options['attrs']['name'], $options['attrs']);
break;
}
$out.= "<label class='metabase_label' for='{$options['attrs']['id']}'>
{$options['label']}</label>";
if (strlen($options['help'])) {
$out.= "<i class='fa metabase_help fa-info-circle' title='{$options['help']}'></i>";
}
$out.= "</div>";
return $out;
}
/**
* Check if current saved config is valid
* @param boolean $with_api also check api status
* @return boolean
*/
static function isValid($with_api = false) {
$current_config = self::getConfig();
$valid_config = (!empty($current_config['host'])
&& !empty($current_config['username'])
&& !empty($current_config['password']));
$valid_api = true;
if ($with_api) {
$apiclient = new PluginMetabaseAPIClient;
$apiclient->connect();
$valid_api = !in_array(false, $apiclient->status());
}
return ($valid_config && $valid_api);
}
/**
* Hook called when updating plugin configuration.
*
* @param array $input
* @return array
* @see Config::prepareInputForUpdate()
*/
public static function configUpdate($input) {
if (isset($input["password"])) {
if (empty($input["password"])) {
unset($input["password"]);
} else {
$input["password"] = Toolbox::encrypt(stripslashes($input["password"]), GLPIKEY);
// Remove existing metabase session token to force reconnection
unset($_SESSION['metabase']['session_token']);
}
}
return $input;
}
/**
* Database table installation for the item type
*
* @param Migration $migration
* @return boolean True on success
*/
static function install(Migration $migration) {
$current_config = self::getConfig();
// Encrypt password if previously stored without encryption
if (!array_key_exists('is_password_encrypted', $current_config) || !$current_config['is_password_encrypted']) {
if (!empty($current_config['password'])) {
Config::setConfigurationValues(
'plugin:metabase',
[
'password' => Toolbox::encrypt($current_config['password'], GLPIKEY),
]
);
}
// Add flag in config to prevent re-encrypt
Config::setConfigurationValues('plugin:metabase', ['is_password_encrypted' => 1]);
}
// fill config table with default values if missing
foreach ([
// api access
'host' => '',
'port' => 3000,
'username' => '',
'password' => '',
'glpi_db_id' => 0,
'datamodel_done' => 0,
'embedded_token' => '',
'metabase_url' => '',
'use_proxy' => 1,
'timeout' => 30,
] as $key => $value) {
if (!isset($current_config[$key])) {
Config::setConfigurationValues('plugin:metabase', [$key => $value]);
}
}
}
/**
* Database table uninstallation for the item type
*
* @return boolean True on success
*/
static function uninstall() {
$config = new Config();
$config->deleteByCriteria(['context' => 'plugin:metabase']);
return true;
}
}