-
Notifications
You must be signed in to change notification settings - Fork 8
/
tripal_elasticsearch.ws.inc
640 lines (567 loc) · 14.4 KB
/
tripal_elasticsearch.ws.inc
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
<?php
/**
* Provides web services support to Elasticsearch server.
*
* @file includes/tripal_elasticsearch.ws.inc
*/
/**
* Report the status of the elastic search index.
*
* @return bool
*/
function tripal_elasticsearch_api_v1_status() {
try {
$params['v'] = TRUE;
$es = new ESInstance();
$health = current($es->client->cat()->health($params));
} catch (Exception $exception) {
return ESResponse::error(
[
'status' => 'Inactive',
'healthy' => FALSE,
]
);
}
if (empty($health)) {
return ESResponse::error(
[
'status' => 'Inactive',
'healthy' => FALSE,
]
);
}
return ESResponse::success(
[
'status' => 'Active',
'healthy' => TRUE,
]
);
}
/**
* Allow https/http connections to communicate.
*
* @param $remote_id
*
* @return bool
*/
function tripal_elasticsearch_api_v1_remote_status($remote_id) {
$remote_id = abs(intval(trim($remote_id)));
if (!is_int($remote_id)) {
return ESResponse::error(
[
'remote_id' => ['Invalid remote server id'],
]
);
}
// Get the remote host url
$host = db_query(
'SELECT url FROM {tripal_elasticsearch_servers} WHERE id=:id',
[':id' => $remote_id]
)->fetchObject();
if (!$host) {
return ESResponse::error(
[
'remote_id' => ['Remote server record does not exist'],
]
);
}
$url = trim(trim($host->url), '/') . '/elasticsearch/api/v1/status';
try {
$response = ESRequest::get($url);
} catch (Exception $exception) {
return ESResponse::error(['server' => $exception->getMessage()], 500);
}
return ESResponse::success($response->data);
}
/**
* Send a search request to the given host and return rendered results.
*
* @param $remote_host_id
*
* @return bool
*/
function tripal_elasticsearch_api_v1_search($remote_host_id) {
$remote_host_id = abs(intval(trim($remote_host_id)));
if (!isset($_GET['terms'])) {
return ESResponse::error(['terms' => ['Please provide search terms']]);
}
$size = 0;
if (isset($_GET['size'])) {
$size = abs(intval($_GET['size']));
}
if ($remote_host_id === 0) {
$response = tripal_elasticsearch_api_v1_local_search(FALSE);
$host = tripal_elasticsearch_get_local_server_entry();
}
else {
$host = db_query(
'SELECT * FROM {tripal_elasticsearch_servers} WHERE id=:id',
[':id' => $remote_host_id]
)->fetchObject();
$url = rtrim(trim($host->url), '/') . '/elasticsearch/api/v1/local-search';
try {
$response = ESRequest::get(
$url, [
'terms' => $_GET['terms'],
'category' => isset($_GET['category']) ? $_GET['category'] : '',
'size' => $size,
]
);
} catch (Exception $exception) {
return ESResponse::error(['server' => $exception->getMessage()], 500);
}
}
$markup = tripal_elasticsearch_get_website_search_result_table(
$response->data->results, FALSE, $host->url
);
// Render results into fields and send them back
return ESResponse::success(
[
'count' => $response->data->count,
'url' => $response->data->url,
'markup' => $markup,
]
);
}
/**
* Perform a local search.
* This method is normally called by other sites looking for
* results from our site.
*
* @param bool $http Whether this is an http request or an internal
* request. (TRUE for http)
* Set this option to FALSE to retrieve an object instead
* of printing a JSON string.
*/
function tripal_elasticsearch_api_v1_local_search($http = TRUE) {
global $base_url;
$exposed = tripal_elasticsearch_is_index_exposed(['website', 'entities']);
if (!$exposed) {
return ESResponse::error(
'403 Forbidden. The request index is not available
for cross site search. Contact the admin to mark the index as public', 403
);
}
// Validate the request
$terms = isset($_GET['terms']) ? $_GET['terms'] : '';
$size = isset($_GET['size']) ? abs(intval($_GET['size'])) : 0;
$category = isset($_GET['category']) ? $_GET['category'] : NULL;
if ($size !== 0 && $size > 20) {
return ESResponse::error(
[
'size' => ['Please provide a valid size between 1 and 20'],
]
);
}
if ($size === 0) {
$size = 5;
}
try {
$es = new ESInstance();
$results = $es->searchWebIndices($terms, $size, $category);
} catch (Exception $exception) {
return ESResponse::error($exception->getMessage(), 500);
}
return ESResponse::success(
array_merge(
$results, [
'url' => url(
rtrim($base_url, '/') . '/tripal_elasticsearch/search_website/'
. $category, [
'query' => [
'search_box' => $terms,
'category' => $category,
],
]
),
]
), $http
);
}
/**
* Perform a table index search.
*
* @param $index_name
* @param $remote_host_id
*
* @return array|bool|object
*/
function tripal_elasticsearch_api_v1_table_index_search(
$index_name, $remote_host_id
) {
$remote_id = abs(intval(trim($remote_host_id)));
if (!tripal_elasticsearch_is_index_exposed($index_name)) {
return ESResponse::error(
'403 Forbidden. The request index is not available
for cross site search. Contact the admin to mark the index as public', 403
);
}
if ($remote_id === 0) {
$host = tripal_elasticsearch_get_local_server_entry();
try {
$results = tripal_elasticsearch_api_v1_table_index_local_search(
$index_name, FALSE
);
} catch (Exception $exception) {
return ESResponse::error(
[
'results' => [$exception->getMessage()],
]
);
}
}
else {
$host = db_query(
'SELECT * FROM {tripal_elasticsearch_servers} WHERE id=:id',
[':id' => $remote_id]
)->fetchObject();
if (!$host) {
return ESResponse::error(
[
'remote_id' => ['Invalid remote host provided. ID: ' . $remote_id],
]
);
}
$url = trim($host->url, '/') . '/elasticsearch/api/v1/index-search/'
. $index_name;
try {
$data = $_GET;
if (isset($data['q'])) {
unset($data['q']);
}
$results = ESRequest::get($url, $data);
} catch (Exception $exception) {
return ESResponse::error(
[
'remote_id' => [
'The host returned an invalid response',
$exception->getMessage(),
],
]
);
}
}
$markup = tripal_elasticsearch_results_formatter(
$results->data->results, $index_name, $host
);
return ESResponse::success(
[
'url' => $results->data->url,
'markup' => $markup,
'count' => $results->data->count,
]
);
}
/**
* Perform a local table index search.
*
* @param $index_name
* @param bool $http
*
* @return array|bool|object
* @throws \Exception
*/
function tripal_elasticsearch_api_v1_table_index_local_search(
$index_name, $http = TRUE
) {
try {
$es = new ESInstance();
$fields = $es->getIndexFields($index_name);
$field_content_pairs = [];
foreach ($fields as $field) {
if (isset($_GET[$field])) {
$field_content_pairs[$field] = $_GET[$field];
}
}
if (function_exists(
'tripal_elasticsearch_' . $index_name . '_query_mapper'
)
) {
$query = call_user_func(
'tripal_elasticsearch_' . $index_name . '_query_mapper', $_GET
);
}
else {
$query = tripal_elasticsearch_build_search_query_from_field_content_pairs(
$field_content_pairs
);
}
$results = $es->setTableSearchParams($index_name, '', $query, [0, 2], TRUE);
} catch (Exception $exception) {
if ($http) {
return ESResponse::error(
[
'results' => [$exception->getMessage()],
]
);
}
else {
throw $exception;
}
}
$count = $results->count();
$search_results = $results->search();
// Get the url for the index
$url = db_query(
'SELECT url FROM {tripal_elasticsearch_indices} WHERE index_name=:index LIMIT 1',
[
':index' => $index_name,
]
)->fetchField();
global $base_url;
$query = $_GET;
unset($query['q']);
return ESResponse::success(
[
'count' => $count,
'url' => $url ? url($base_url . '/' . $url, ['query' => $query])
: $base_url,
'results' => $search_results,
], $http
);
}
/**
* Results formatter.
*
* @param $search_results
* @param null $index_name
*
* @return mixed|string
*/
function tripal_elasticsearch_results_formatter(
$search_results, $index_name = NULL, $host = NULL
) {
if ($index_name !== NULL
&& function_exists(
'tripal_elasticsearch_' . $index_name . '_results_formatter'
)
) {
return call_user_func(
'tripal_elasticsearch_' . $index_name . '_results_formatter',
$search_results, $host
);
}
$rows = [];
foreach ($search_results as $row) {
$fields = [];
foreach ($row as $entry) {
if (is_array($entry)) {
$fields[] = elasticsearch_recursive_implode('<br>', $entry);
}
else {
$fields[] = $entry;
}
}
$rows[] = $fields;
}
return theme(
'table', [
'header' => isset($search_results[0]) ? array_keys($search_results[0])
: [],
'rows' => $rows,
]
);
}
/**
* Recursively implode an array.
*
* @param $glue
* @param $array
*
* @return string
*/
function elasticsearch_recursive_implode($glue, $array) {
$result = [];
elasticsearch_recursive_flatten($array, $result);
$unique = array_unique($result);
return implode($glue, $unique);
}
/**
* Flatten a nested array.
*
* @param array $array The input nested array
* @param array $result The resulting flattened array
*/
function elasticsearch_recursive_flatten($array, &$result) {
if (!is_array($array)) {
$result[] = $array;
return;
}
foreach ($array as $value) {
if (is_array($value)) {
elasticsearch_recursive_flatten($value, $result);
}
else {
$result[] = $value;
}
}
}
/**
* Get local categories.
*
* @return array|bool|object
*/
function tripal_elasticsearch_api_v1_categories() {
return ESResponse::success(
[
[
'label' => 'Gene',
'table' => 'chado.feature',
],
[
'label' => 'mRNA',
'table' => 'chado.feature',
],
[
'label' => 'Organism',
'table' => 'chado.organism',
],
]
);
}
/**
* Get the search page.
*
* @param $form
* @param $form_state
*
* @return mixed
*/
function tripal_elasticsearch_cross_site_search_form($form, &$form_state) {
global $base_url;
$remotes =
db_query('SELECT * FROM {tripal_elasticsearch_servers}')->fetchAll();
// Add local server as the first remote
array_unshift($remotes, tripal_elasticsearch_get_local_server_entry());
tripal_elasticsearch_load_logos($remotes);
$form['options'] = [
'#type' => 'fieldset',
'#attributes' => [
'class' => [
'container-inline',
'es-cross-site-search-form',
],
],
];
$default_category = ['Any Type' => 'Any Type'];
try {
$es = new ESInstance();
$categories = drupal_map_assoc($es->getAllCategories());
} catch (Exception $exception) {
$categories = [];
}
$form['options']['category'] = [
'#type' => 'select',
'#attributes' => [
'id' => 'tripal-elasticsearch-search-category',
],
'#options' => array_merge($default_category, $categories),
'#default_value' => 'Any Type',
'#required' => TRUE,
];
$form['options']['search_term'] = [
'#type' => 'textfield',
'#size' => '50',
'#attributes' => [
'placeholder' => t('E,g. Fraxinus Excelsior mRNA'),
'id' => 'tripal-elasticsearch-search-field',
],
'#required' => TRUE,
];
$form['options']['search_button'] = [
'#type' => 'submit',
'#value' => t('Search'),
'#attributes' => [
'id' => 'tripal-elasticsearch-search-button',
],
];
$logos_table = tripal_elasticsearch_make_logos_table($remotes);
$form['results_block'] = [
'#type' => 'markup',
'#markup' => '<div id="tripal-elasticsearch-results-block">'.$logos_table.'</div>',
];
$form['#atached']['js'][] = [
'data' => drupal_add_js(
drupal_get_path('module', 'tripal_elasticsearch') . '/js/axios.min.js'
),
'type' => 'file',
];
drupal_add_js(
drupal_get_path('module', 'tripal_elasticsearch')
. '/js/tripal_elasticsearch.js'
);
drupal_add_js(
[
'remotes' => $remotes,
'action' => 'setupSearchPage',
'base' => $base_url,
], 'setting'
);
return $form;
}
/**
* Mock the local server as a remote server for AJAX to work.
*
* @return object
*/
function tripal_elasticsearch_get_local_server_entry() {
global $base_url;
return (object) [
'id' => 0,
'label' => variable_get('site_name', 'Drupal'),
'description' => '',
'url' => $base_url,
];
}
/**
* Checks if an index is exposed.
*
* @param $index_name
*
* @return bool
*/
function tripal_elasticsearch_is_index_exposed($index_name) {
// Check if the index is publicly exposed
$indices = db_query(
'SELECT * FROM {tripal_elasticsearch_indices} WHERE index_name IN (:indices)',
[
':indices' => is_array($index_name) ? $index_name : [$index_name],
]
)->fetchAll();
$exposed = FALSE;
foreach ($indices as $index) {
if ($index->exposed) {
$exposed = TRUE;
break;
}
}
return $exposed;
}
function tripal_elasticsearch_load_logos(array &$remotes) {
foreach ($remotes as $remote) {
if ($remote->id === 0) {
$remote->logo_url = variable_get('elasticsearch_host_logo', '');
continue;
}
$remote->logo_url =
$remote->logo ? file_create_url(file_load($remote->logo)->uri) : '';
}
}
function tripal_elasticsearch_make_logos_table($remotes) {
$header = ['Logo', 'Database'];
$rows = [];
foreach ($remotes as $remote) {
$img = '';
if (!empty($remote->logo_url)) {
$img = '<img src="' . $remote->logo_url
. '" style="width:auto; height: 50px"/>';
}
$rows[] = [$img, l($remote->label, !empty($remote->url) ? $remote->url : '<front>')];
}
return '<h4>Available Databases</h4>' . theme(
'table', [
'header' => $header,
'rows' => $rows,
]
);
}