-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathsearch.class.php
executable file
·7692 lines (6798 loc) · 301 KB
/
search.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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Search Class
*
* Generic class for Search Engine
**/
class Search {
// Default number of items displayed in global search
const GLOBAL_DISPLAY_COUNT = 10;
// EXPORT TYPE
const GLOBAL_SEARCH = -1;
const HTML_OUTPUT = 0;
const SYLK_OUTPUT = 1;
const PDF_OUTPUT_LANDSCAPE = 2;
const CSV_OUTPUT = 3;
const PDF_OUTPUT_PORTRAIT = 4;
const LBBR = '#LBBR#';
const LBHR = '#LBHR#';
const SHORTSEP = '$#$';
const LONGSEP = '$$##$$';
const NULLVALUE = '__NULL__';
static $output_type = self::HTML_OUTPUT;
static $search = [];
/**
* Display search engine for an type
*
* @param string $itemtype Item type to manage
*
* @return void
**/
static function show($itemtype) {
$params = self::manageParams($itemtype, $_GET);
echo "<div class='search_page'>";
self::showGenericSearch($itemtype, $params);
if ($params['as_map'] == 1) {
self::showMap($itemtype, $params);
} else {
self::showList($itemtype, $params);
}
echo "</div>";
}
/**
* Display result table for search engine for an type
*
* @param $itemtype item type to manage
* @param $params search params passed to prepareDatasForSearch function
*
* @return nothing
**/
static function showList($itemtype, $params) {
$data = self::prepareDatasForSearch($itemtype, $params);
self::constructSQL($data);
self::constructData($data);
self::displayData($data);
}
/**
* Display result table for search engine for an type as a map
*
* @param string $itemtype item type to manage
* @param array $params search params passed to prepareDatasForSearch function
*
* @return void
**/
static function showMap($itemtype, $params) {
global $CFG_GLPI;
$params['criteria'][] = [
'link' => 'AND NOT',
'field' => ($itemtype == 'Location') ? 21 : 998,
'searchtype' => 'contains',
'value' => 'NULL'
];
$params['criteria'][] = [
'link' => 'AND NOT',
'field' => ($itemtype == 'Location') ? 20 : 999,
'searchtype' => 'contains',
'value' => 'NULL'
];
$data = self::prepareDatasForSearch($itemtype, $params);
self::constructSQL($data);
self::constructData($data);
self::displayData($data);
if ($data['data']['totalcount'] > 0) {
$target = $data['search']['target'];
$criteria = $data['search']['criteria'];
array_pop($criteria);
array_pop($criteria);
$criteria[] = [
'link' => 'AND',
'field' => ($itemtype == 'Location') ? 1 : (($itemtype == 'Ticket') ? 83 : 3),
'searchtype' => 'equals',
'value' => 'CURLOCATION'
];
$globallinkto = Toolbox::append_params(
[
'criteria' => Toolbox::stripslashes_deep($criteria),
'metacriteria' => Toolbox::stripslashes_deep($data['search']['metacriteria'])
],
'&'
);
$parameters = "as_map=0&sort=".$data['search']['sort']."&order=".$data['search']['order'].'&'.
$globallinkto;
if (strpos($target, '?') == false) {
$fulltarget = $target."?".$parameters;
} else {
$fulltarget = $target."&".$parameters;
}
$typename = class_exists($itemtype) ? $itemtype::getTypeName($data['data']['totalcount']) :
($itemtype == 'AllAssets' ? __('assets') : $itemtype);
echo "<div class='center'><p>".__('Search results for localized items only')."</p>";
$js = "$(function() {
var map = initMap($('#page'), 'map', 'full');
_loadMap(map, '$itemtype');
});
var _loadMap = function(map_elt, itemtype) {
L.AwesomeMarkers.Icon.prototype.options.prefix = 'far';
var _micon = 'circle';
var stdMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'blue'
});
var aMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'cadetblue'
});
var bMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'purple'
});
var cMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'darkpurple'
});
var dMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'red'
});
var eMarker = L.AwesomeMarkers.icon({
icon: _micon,
markerColor: 'darkred'
});
//retrieve geojson data
map_elt.spin(true);
$.ajax({
dataType: 'json',
method: 'POST',
url: '{$CFG_GLPI['root_doc']}/ajax/map.php',
data: {
itemtype: itemtype,
params: ".json_encode($params)."
}
}).done(function(data) {
var _points = data.points;
var _markers = L.markerClusterGroup({
iconCreateFunction: function(cluster) {
var childCount = cluster.getChildCount();
var markers = cluster.getAllChildMarkers();
var n = 0;
for (var i = 0; i < markers.length; i++) {
n += markers[i].count;
}
var c = ' marker-cluster-';
if (n < 10) {
c += 'small';
} else if (n < 100) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({ html: '<div><span>' + n + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
}
});
$.each(_points, function(index, point) {
var _title = '<strong>' + point.title + '</strong><br/><a href=\''+'$fulltarget'.replace(/CURLOCATION/, point.loc_id)+'\'>".sprintf(__('%1$s %2$s'), 'COUNT', $typename)."'.replace(/COUNT/, point.count)+'</a>';
if (point.types) {
$.each(point.types, function(tindex, type) {
_title += '<br/>".sprintf(__('%1$s %2$s'), 'COUNT', 'TYPE')."'.replace(/COUNT/, type.count).replace(/TYPE/, type.name);
});
}
var _icon = stdMarker;
if (point.count < 10) {
_icon = stdMarker;
} else if (point.count < 100) {
_icon = aMarker;
} else if (point.count < 1000) {
_icon = bMarker;
} else if (point.count < 5000) {
_icon = cMarker;
} else if (point.count < 10000) {
_icon = dMarker;
} else {
_icon = eMarker;
}
var _marker = L.marker([point.lat, point.lng], { icon: _icon, title: point.title });
_marker.count = point.count;
_marker.bindPopup(_title);
_markers.addLayer(_marker);
});
map_elt.addLayer(_markers);
map_elt.fitBounds(
_markers.getBounds(), {
padding: [50, 50],
maxZoom: 12
}
);
}).fail(function (response) {
var _data = response.responseJSON;
var _message = '".__s('An error occured loading data :(')."';
if (_data.message) {
_message = _data.message;
}
var fail_info = L.control();
fail_info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'fail_info');
this._div.innerHTML = _message + '<br/><span id=\'reload_data\'><i class=\'fa fa-sync\'></i> ".__s('Reload')."</span>';
return this._div;
};
fail_info.addTo(map_elt);
$('#reload_data').on('click', function() {
$('.fail_info').remove();
_loadMap(map_elt);
});
}).always(function() {
//hide spinner
map_elt.spin(false);
});
}
";
echo Html::scriptBlock($js);
echo "</div>";
}
}
/**
* Get datas based on search parameters
*
* @since 0.85
*
* @param $itemtype item type to manage
* @param $params search params passed to prepareDatasForSearch function
* @param $forcedisplay array of columns to display (default empty = empty use display pref and search criterias)
*
* @return data array
**/
static function getDatas($itemtype, $params, array $forcedisplay = []) {
$data = self::prepareDatasForSearch($itemtype, $params, $forcedisplay);
self::constructSQL($data);
self::constructData($data);
return $data;
}
/**
* Prepare search criteria to be used for a search
*
* @since 0.85
*
* @param $itemtype item type
* @param $params array of parameters
* may include sort, order, start, list_limit, deleted, criteria, metacriteria
* @param $forcedisplay array of columns to display (default empty = empty use display pref and search criterias)
*
* @return array prepare to be used for a search (include criterias and others needed informations)
**/
static function prepareDatasForSearch($itemtype, array $params, array $forcedisplay = []) {
global $CFG_GLPI;
// Default values of parameters
$p['criteria'] = [];
$p['metacriteria'] = [];
$p['sort'] = '1'; //
$p['order'] = 'ASC';//
$p['start'] = 0;//
$p['is_deleted'] = 0;
$p['export_all'] = 0;
if (class_exists($itemtype)) {
$p['target'] = $itemtype::getSearchURL();
} else {
$p['target'] = Toolbox::getItemTypeSearchURL($itemtype);
}
$p['display_type'] = self::HTML_OUTPUT;
$p['list_limit'] = $_SESSION['glpilist_limit'];
$p['massiveactionparams'] = [];
foreach ($params as $key => $val) {
switch ($key) {
case 'order':
if (in_array($val, ['ASC', 'DESC'])) {
$p[$key] = $val;
}
break;
case 'sort':
$p[$key] = intval($val);
if ($p[$key] <= 0) {
$p[$key] = 1;
}
break;
case 'is_deleted':
if ($val == 1) {
$p[$key] = '1';
}
break;
default:
$p[$key] = $val;
break;
}
}
// Set display type for export if define
if (isset($p['display_type'])) {
// Limit to 10 element
if ($p['display_type'] == self::GLOBAL_SEARCH) {
$p['list_limit'] = self::GLOBAL_DISPLAY_COUNT;
}
}
if ($p['export_all']) {
$p['start'] = 0;
}
$data = [];
$data['search'] = $p;
$data['itemtype'] = $itemtype;
// Instanciate an object to access method
$data['item'] = null;
if ($itemtype != 'AllAssets') {
$data['item'] = getItemForItemtype($itemtype);
}
$data['display_type'] = $data['search']['display_type'];
if (!$CFG_GLPI['allow_search_all']) {
foreach ($p['criteria'] as $val) {
if (isset($val['field']) && $val['field'] == 'all') {
Html::displayRightError();
}
}
}
if (!$CFG_GLPI['allow_search_view']) {
foreach ($p['criteria'] as $val) {
if (isset($val['field']) && $val['field'] == 'view') {
Html::displayRightError();
}
}
}
/// Get the items to display
// Add searched items
$forcetoview = false;
if (is_array($forcedisplay) && count($forcedisplay)) {
$forcetoview = true;
}
$data['search']['all_search'] = false;
$data['search']['view_search'] = false;
// If no research limit research to display item and compute number of item using simple request
$data['search']['no_search'] = true;
$data['toview'] = self::addDefaultToView($itemtype, $params);
$data['meta_toview'] = [];
if (!$forcetoview) {
// Add items to display depending of personal prefs
$displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID());
if (count($displaypref)) {
foreach ($displaypref as $val) {
array_push($data['toview'], $val);
}
}
} else {
$data['toview'] = array_merge($data['toview'], $forcedisplay);
}
if (count($p['criteria']) > 0) {
// use a recursive clojure to push searchoption when using nested criteria
$parse_criteria = function($criteria) use (&$parse_criteria, &$data) {
foreach ($criteria as $criterion) {
// recursive call
if (isset($criterion['criteria'])) {
$parse_criteria($criterion['criteria']);
} else {
// normal behavior
if (isset($criterion['field'])
&& !in_array($criterion['field'], $data['toview'])) {
if ($criterion['field'] != 'all'
&& $criterion['field'] != 'view'
&& (!isset($criterion['meta'])
|| !$criterion['meta'])) {
array_push($data['toview'], $criterion['field']);
} else if ($criterion['field'] == 'all') {
$data['search']['all_search'] = true;
} else if ($criterion['field'] == 'view') {
$data['search']['view_search'] = true;
}
}
if (isset($criterion['value'])
&& (strlen($criterion['value']) > 0)) {
$data['search']['no_search'] = false;
}
}
}
};
// call the clojure
$parse_criteria($p['criteria']);
}
if (count($p['metacriteria'])) {
$data['search']['no_search'] = false;
}
// Add order item
if (!in_array($p['sort'], $data['toview'])) {
array_push($data['toview'], $p['sort']);
}
// Special case for Ticket : put ID in front
if ($itemtype == 'Ticket') {
array_unshift($data['toview'], 2);
}
$limitsearchopt = self::getCleanedOptions($itemtype);
// Clean and reorder toview
$tmpview = [];
foreach ($data['toview'] as $val) {
if (isset($limitsearchopt[$val]) && !in_array($val, $tmpview)) {
$tmpview[] = $val;
}
}
$data['toview'] = $tmpview;
$data['tocompute'] = $data['toview'];
// Force item to display
if ($forcetoview) {
foreach ($data['toview'] as $val) {
if (!in_array($val, $data['tocompute'])) {
array_push($data['tocompute'], $val);
}
}
}
return $data;
}
/**
* Construct SQL request depending of search parameters
*
* add to data array a field sql containing an array of requests :
* search : request to get items limited to wanted ones
* count : to count all items based on search criterias
* may be an array a request : need to add counts
* maybe empty : use search one to count
*
* @since 0.85
*
* @param $data array of search datas prepared to generate SQL
*
* @return nothing
**/
static function constructSQL(array &$data) {
global $CFG_GLPI, $DB;
if (!isset($data['itemtype'])) {
return false;
}
$data['sql']['count'] = [];
$data['sql']['search'] = '';
$searchopt = &self::getOptions($data['itemtype']);
$blacklist_tables = [];
if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {
$itemtable = $CFG_GLPI['union_search_type'][$data['itemtype']];
$blacklist_tables[] = $data['itemtype']::getTable();
} else {
$itemtable = $data['itemtype']::getTable();
}
// hack for AllAssets
if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {
$entity_restrict = true;
} else {
$entity_restrict = $data['item']->isEntityAssign() && $data['item']->isField('entities_id');
}
// Construct the request
//// 1 - SELECT
// request currentuser for SQL supervision, not displayed
$SELECT = "SELECT DISTINCT `$itemtable`.`id` AS id, '".Toolbox::addslashes_deep($_SESSION['glpiname'])."' AS currentuser,
".self::addDefaultSelect($data['itemtype']);
// Add select for all toview item
foreach ($data['toview'] as $val) {
$SELECT .= self::addSelect($data['itemtype'], $val);
}
if (isset($data['search']['as_map']) && $data['search']['as_map'] == 1) {
$SELECT .= ' `glpi_locations`.`id` AS loc_id, ';
}
//// 2 - FROM AND LEFT JOIN
// Set reference table
$FROM = " FROM `$itemtable`";
// Init already linked tables array in order not to link a table several times
$already_link_tables = [];
// Put reference table
array_push($already_link_tables, $itemtable);
// Add default join
$COMMONLEFTJOIN = self::addDefaultJoin($data['itemtype'], $itemtable, $already_link_tables);
$FROM .= $COMMONLEFTJOIN;
// Add all table for toview items
foreach ($data['tocompute'] as $val) {
if (!in_array($searchopt[$val]["table"], $blacklist_tables)) {
$FROM .= self::addLeftJoin($data['itemtype'], $itemtable, $already_link_tables,
$searchopt[$val]["table"],
$searchopt[$val]["linkfield"], 0, 0,
$searchopt[$val]["joinparams"],
$searchopt[$val]["field"]);
}
}
// Search all case :
if ($data['search']['all_search']) {
foreach ($searchopt as $key => $val) {
// Do not search on Group Name
if (is_array($val) && isset($val['table'])) {
if (!in_array($searchopt[$key]["table"], $blacklist_tables)) {
$FROM .= self::addLeftJoin($data['itemtype'], $itemtable, $already_link_tables,
$searchopt[$key]["table"],
$searchopt[$key]["linkfield"], 0, 0,
$searchopt[$key]["joinparams"],
$searchopt[$key]["field"]);
}
}
}
}
//// 3 - WHERE
// default string
$COMMONWHERE = self::addDefaultWhere($data['itemtype']);
$first = empty($COMMONWHERE);
// Add deleted if item have it
if ($data['item'] && $data['item']->maybeDeleted()) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
$COMMONWHERE .= $LINK."`$itemtable`.`is_deleted` = ".(int)$data['search']['is_deleted']." ";
}
// Remove template items
if ($data['item'] && $data['item']->maybeTemplate()) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
$COMMONWHERE .= $LINK."`$itemtable`.`is_template` = 0 ";
}
// Add Restrict to current entities
if ($entity_restrict) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
if ($data['itemtype'] == 'Entity') {
$COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, 'id', '', true);
} else if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
// Will be replace below in Union/Recursivity Hack
$COMMONWHERE .= $LINK." ENTITYRESTRICT ";
} else {
$COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, '', '',
$data['item']->maybeRecursive() && $data['item']->isField('is_recursive'));
}
}
$WHERE = "";
$HAVING = "";
// Add search conditions
// If there is search items
if (count($data['search']['criteria'])) {
$WHERE = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt);
$HAVING = self::constructCriteriaSQL($data['search']['criteria'], $data, $searchopt, true);
// if criteria (with meta flag) need additional join/from sql
self::constructAdditionalSqlForMetacriteria($data['search']['criteria'], $SELECT, $FROM, $already_link_tables, $data);
}
//// 4 - ORDER
$ORDER = " ORDER BY `id` ";
foreach ($data['tocompute'] as $val) {
if ($data['search']['sort'] == $val) {
$ORDER = self::addOrderBy(
$data['itemtype'],
$data['search']['sort'],
$data['search']['order']
);
}
}
$SELECT = rtrim(trim($SELECT), ',');
//// 7 - Manage GROUP BY
$GROUPBY = "";
// Meta Search / Search All / Count tickets
$criteria_with_meta = array_filter($data['search']['criteria'], function($criterion) {
return isset($criterion['meta'])
&& $criterion['meta'];
});
if ((count($data['search']['metacriteria']))
|| count($criteria_with_meta)
|| !empty($HAVING)
|| $data['search']['all_search']) {
$GROUPBY = " GROUP BY `$itemtable`.`id`";
}
if (empty($GROUPBY)) {
foreach ($data['toview'] as $val2) {
if (!empty($GROUPBY)) {
break;
}
if (isset($searchopt[$val2]["forcegroupby"])) {
$GROUPBY = " GROUP BY `$itemtable`.`id`";
}
}
}
$LIMIT = "";
$numrows = 0;
//No search : count number of items using a simple count(ID) request and LIMIT search
if ($data['search']['no_search']) {
$LIMIT = " LIMIT ".(int)$data['search']['start'].", ".(int)$data['search']['list_limit'];
// Force group by for all the type -> need to count only on table ID
if (!isset($searchopt[1]['forcegroupby'])) {
$count = "count(*)";
} else {
$count = "count(DISTINCT `$itemtable`.`id`)";
}
// request currentuser for SQL supervision, not displayed
$query_num = "SELECT $count,
'".Toolbox::addslashes_deep($_SESSION['glpiname'])."' AS currentuser
FROM `$itemtable`".
$COMMONLEFTJOIN;
$first = true;
if (!empty($COMMONWHERE)) {
$LINK = " AND ";
if ($first) {
$LINK = " WHERE ";
$first = false;
}
$query_num .= $LINK.$COMMONWHERE;
}
// Union Search :
if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
$tmpquery = $query_num;
foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$data['itemtype']]] as $ctype) {
$ctable = $ctype::getTable();
if (($citem = getItemForItemtype($ctype))
&& $citem->canView()) {
// State case
if ($data['itemtype'] == 'AllAssets') {
$query_num = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']],
$ctable, $tmpquery);
$query_num = str_replace($data['itemtype'], $ctype, $query_num);
$query_num .= " AND `$ctable`.`id` IS NOT NULL ";
// Add deleted if item have it
if ($citem && $citem->maybeDeleted()) {
$query_num .= " AND `$ctable`.`is_deleted` = 0 ";
}
// Remove template items
if ($citem && $citem->maybeTemplate()) {
$query_num .= " AND `$ctable`.`is_template` = 0 ";
}
} else {// Ref table case
$reftable = $data['itemtype']::getTable();
if ($data['item'] && $data['item']->maybeDeleted()) {
$tmpquery = str_replace("`".$CFG_GLPI["union_search_type"][$data['itemtype']]."`.
`is_deleted`",
"`$reftable`.`is_deleted`", $tmpquery);
}
$replace = "FROM `$reftable`
INNER JOIN `$ctable`
ON (`$reftable`.`items_id` =`$ctable`.`id`
AND `$reftable`.`itemtype` = '$ctype')";
$query_num = str_replace("FROM `".
$CFG_GLPI["union_search_type"][$data['itemtype']]."`",
$replace, $tmpquery);
$query_num = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']],
$ctable, $query_num);
}
$query_num = str_replace("ENTITYRESTRICT",
getEntitiesRestrictRequest('', $ctable, '', '',
$citem->maybeRecursive()),
$query_num);
$data['sql']['count'][] = $query_num;
}
}
} else {
$data['sql']['count'][] = $query_num;
}
}
// If export_all reset LIMIT condition
if ($data['search']['export_all']) {
$LIMIT = "";
}
if (!empty($WHERE) || !empty($COMMONWHERE)) {
if (!empty($COMMONWHERE)) {
$WHERE = ' WHERE '.$COMMONWHERE.(!empty($WHERE)?' AND ( '.$WHERE.' )':'');
} else {
$WHERE = ' WHERE '.$WHERE.' ';
}
$first = false;
}
if (!empty($HAVING)) {
$HAVING = ' HAVING '.$HAVING;
}
// Create QUERY
if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
$first = true;
$QUERY = "";
foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$data['itemtype']]] as $ctype) {
$ctable = $ctype::getTable();
if (($citem = getItemForItemtype($ctype))
&& $citem->canView()) {
if ($first) {
$first = false;
} else {
$QUERY .= " UNION ";
}
$tmpquery = "";
// AllAssets case
if ($data['itemtype'] == 'AllAssets') {
$tmpquery = $SELECT.", '$ctype' AS TYPE ".
$FROM.
$WHERE;
$tmpquery .= " AND `$ctable`.`id` IS NOT NULL ";
// Add deleted if item have it
if ($citem && $citem->maybeDeleted()) {
$tmpquery .= " AND `$ctable`.`is_deleted` = 0 ";
}
// Remove template items
if ($citem && $citem->maybeTemplate()) {
$tmpquery .= " AND `$ctable`.`is_template` = 0 ";
}
$tmpquery.= $GROUPBY.
$HAVING;
// Replace 'asset_types' by itemtype table name
$tmpquery = str_replace(
$CFG_GLPI["union_search_type"][$data['itemtype']],
$ctable,
$tmpquery
);
// Replace 'AllAssets' by itemtype
// Use quoted value to prevent replacement of AllAssets in column identifiers
$tmpquery = str_replace(
$DB->quoteValue('AllAssets'),
$DB->quoteValue($ctype),
$tmpquery
);
} else {// Ref table case
$reftable = $data['itemtype']::getTable();
$tmpquery = $SELECT.", '$ctype' AS TYPE,
`$reftable`.`id` AS refID, "."
`$ctable`.`entities_id` AS ENTITY ".
$FROM.
$WHERE;
if ($data['item']->maybeDeleted()) {
$tmpquery = str_replace("`".$CFG_GLPI["union_search_type"][$data['itemtype']]."`.
`is_deleted`",
"`$reftable`.`is_deleted`", $tmpquery);
}
$replace = "FROM `$reftable`"."
INNER JOIN `$ctable`"."
ON (`$reftable`.`items_id`=`$ctable`.`id`"."
AND `$reftable`.`itemtype` = '$ctype')";
$tmpquery = str_replace("FROM `".
$CFG_GLPI["union_search_type"][$data['itemtype']]."`",
$replace, $tmpquery);
$tmpquery = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']],
$ctable, $tmpquery);
}
$tmpquery = str_replace("ENTITYRESTRICT",
getEntitiesRestrictRequest('', $ctable, '', '',
$citem->maybeRecursive()),
$tmpquery);
// SOFTWARE HACK
if ($ctype == 'Software') {
$tmpquery = str_replace("`glpi_softwares`.`serial`", "''", $tmpquery);
$tmpquery = str_replace("`glpi_softwares`.`otherserial`", "''", $tmpquery);
}
$QUERY .= $tmpquery;
}
}
if (empty($QUERY)) {
echo self::showError($data['display_type']);
return;
}
$QUERY .= str_replace($CFG_GLPI["union_search_type"][$data['itemtype']].".", "", $ORDER) .
$LIMIT;
} else {
$QUERY = $SELECT.
$FROM.
$WHERE.
$GROUPBY.
$HAVING.
$ORDER.
$LIMIT;
}
$data['sql']['search'] = $QUERY;
}
/**
* Construct WHERE (or HAVING) part of the sql based on passed criteria
*
* @since 9.4
*
* @param array $criteria list of search criterion, we should have these keys:
* - link (optionnal): AND, OR, NOT AND, NOT OR
* - field: id of the searchoption
* - searchtype: how to match value (contains, equals, etc)
* - value
* @param array $data common array used by search engine,
* contains all the search part (sql, criteria, params, itemtype etc)
* TODO: should be a property of the class
* @param array $searchopt Search options for the current itemtype
* @param boolean $is_having Do we construct sql WHERE or HAVING part
*
* @return string the sql sub string
*/
static function constructCriteriaSQL($criteria = [], $data = [], $searchopt = [], $is_having = false) {
$sql = "";
foreach ($criteria as $criterion) {
if (!isset($criterion['criteria'])
&& (!isset($criterion['value'])
|| strlen($criterion['value']) <= 0)) {
continue;
}
$itemtype = $data['itemtype'];
$meta = false;
if (isset($criterion['meta'])
&& $criterion['meta']
&& isset($criterion['itemtype'])) {
$itemtype = $criterion['itemtype'];
$meta = true;
}
// common search
if (!isset($criterion['field'])
|| ($criterion['field'] != "all"
&& $criterion['field'] != "view")) {
$LINK = " ";
$NOT = 0;
$tmplink = "";
if (isset($criterion['link'])
&& in_array($criterion['link'], array_keys(self::getLogicalOperators()))) {
if (strstr($criterion['link'], "NOT")) {
$tmplink = " ".str_replace(" NOT", "", $criterion['link']);
$NOT = 1;
} else {
$tmplink = " ".$criterion['link'];
}
} else {
$tmplink = " AND ";
}
// Manage Link if not first item
if (!empty($sql)) {
$LINK = $tmplink;
}
if (isset($criterion['criteria']) && count($criterion['criteria'])) {
$sub_sql = self::constructCriteriaSQL($criterion['criteria'], $data, $searchopt, $is_having);
if (strlen($sub_sql)) {
if ($NOT) {
$sql .= "$LINK NOT($sub_sql)";
} else {
$sql .= "$LINK ($sub_sql)";
}
}
} else if (isset($searchopt[$criterion['field']]["usehaving"])
|| ($meta && "AND NOT" === $criterion['link'])) {
if (!$is_having) {
// the having part will be managed in a second pass
continue;
}
$new_having = self::addHaving($LINK, $NOT, $itemtype,
$criterion['field'], $criterion['searchtype'],
$criterion['value']);
if ($new_having !== false) {
$sql .= $new_having;
}
} else {