-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathdisplayblock.class.inc.php
More file actions
2585 lines (2347 loc) · 95.1 KB
/
displayblock.class.inc.php
File metadata and controls
2585 lines (2347 loc) · 95.1 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
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
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
use Combodo\iTop\Application\Search\SearchForm;
use Combodo\iTop\Application\UI\Base\Component\Alert\AlertUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Button\ButtonUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Dashlet\DashletFactory;
use Combodo\iTop\Application\UI\Base\Component\DataTable\DataTableUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Html\Html;
use Combodo\iTop\Application\UI\Base\Component\Panel\PanelUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Pill\PillFactory;
use Combodo\iTop\Application\UI\Base\Component\PopoverMenu\PopoverMenu;
use Combodo\iTop\Application\UI\Base\Component\PopoverMenu\PopoverMenuItem\PopoverMenuItemFactory;
use Combodo\iTop\Application\UI\Base\Component\Toolbar\Separator\ToolbarSeparatorUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Toolbar\ToolbarUIBlockFactory;
use Combodo\iTop\Application\UI\Base\iUIBlock;
use Combodo\iTop\Application\UI\Base\Layout\UIContentBlock;
use Combodo\iTop\Application\UI\Base\Layout\UIContentBlockWithJSRefreshCallback;
use Combodo\iTop\Application\UI\DisplayBlock\BlockChart\BlockChart;
use Combodo\iTop\Application\UI\DisplayBlock\BlockChartAjaxBars\BlockChartAjaxBars;
use Combodo\iTop\Application\UI\DisplayBlock\BlockChartAjaxPie\BlockChartAjaxPie;
use Combodo\iTop\Application\UI\DisplayBlock\BlockCsv\BlockCsv;
use Combodo\iTop\Application\UI\DisplayBlock\BlockList\BlockList;
use Combodo\iTop\Application\WebPage\iTopWebPage;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Service\Router\Router;
require_once(APPROOT.'/application/utils.inc.php');
/**
* Helper class to manage 'blocks' of HTML pieces that are parts of a page and contain some list of cmdb objects
*
* Each block is actually rendered as a <div></div> tag that can be rendered synchronously
* or as a piece of Javascript/JQuery/Ajax that will get its content from another page (ajax.render.php).
*/
class DisplayBlock
{
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_COUNT = 'count';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_JOIN = 'join';
/**
* @var string For regular list (objects or static data)
* @since 3.1.0
*/
public const ENUM_STYLE_LIST = 'list';
/**
* @var string For search results
* @since 3.1.0
*/
public const ENUM_STYLE_LIST_SEARCH = 'list_search';
/**
* @var string For objects list in other objects (direct / indirect linksets)
* @since 3.1.0
*/
public const ENUM_STYLE_LIST_IN_OBJECT = 'listInObject';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_ACTIONS = 'actions';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_SUMMARY = 'summary';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_CSV = 'csv';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_SEARCH = 'search';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_CHART = 'chart';
/**
* @var string
* @since 3.1.0
*/
public const ENUM_STYLE_CHART_AJAX = 'chart_ajax';
const TAG_BLOCK = 'itopblock';
/** @var \DBSearch */
protected $m_oFilter;
protected $m_aConditions; // Conditions added to the filter -> avoid duplicate conditions
protected $m_sStyle;
protected $m_bAsynchronous;
protected $m_aParams;
/** @var \DBObjectSet|null */
protected $m_oSet;
protected $m_bShowObsoleteData = null;
/**
* @param \DBSearch $oFilter list of cmdbObjects to be displayed into the block
* @param string $sStyle one of :
* <ul>
* <li>actions : </li>
* <li>chart : </li>
* <li>chart_ajax : </li>
* <li>count : produces a paragraphs with a sentence saying 'cont' objects found</li>
* <li>csv : displays a textarea with the CSV export of the list of objects</li>
* <li>join : </li>
* <li>links : </li>
* <li>list : produces a table listing the objects</li>
* <li>list_search : </li>
* <li>search : displays a search form with the criteria of the filter set</li>
* <li>summary : </li>
* </ul>
* @param bool $bAsynchronous
* @param array $aParams
* @param \DBObjectSet $oSet
*
* @throws \ApplicationException
*/
public function __construct(DBSearch $oFilter, $sStyle = self::ENUM_STYLE_LIST, $bAsynchronous = false, $aParams = array(), $oSet = null)
{
$this->m_oFilter = $oFilter->DeepClone();
$this->m_aConditions = array();
$this->m_sStyle = $sStyle;
$this->m_bAsynchronous = $bAsynchronous;
$this->m_aParams = $aParams;
$this->m_oSet = $oSet;
if (array_key_exists('show_obsolete_data', $aParams))
{
$this->m_bShowObsoleteData = $aParams['show_obsolete_data'];
}
if ($this->m_bShowObsoleteData === null)
{
// User defined
$this->m_bShowObsoleteData = utils::ShowObsoleteData();
}
}
/**
* @param string $sStyle
*
* @return string[]
*/
protected function GetAllowedParams(string $sStyle): array
{
$aAllowedParams = [
static::ENUM_STYLE_ACTIONS => [
'context_filter',
/** int if != 0 filter with user context */
'display_limit',
/** for dashlet*/
],
static::ENUM_STYLE_CHART => [
'chart_type',
/** string 'pie' or 'bars' */
'group_by',
/** string group by att code */
'group_by_expr',
/** string group by expression */
'group_by_label',
/** string aggregation column name */
'aggregation_function',
/** string aggregation function ('count', 'sum', 'avg', 'min', 'max', ...) */
'aggregation_attribute',
/** string att code used for aggregation */
'limit',
/** int limit the chart results */
'order_by',
/** string either 'attribute' group_by attcode or 'function' aggregation_function value */
'order_direction',
/** string order direction 'asc' or 'desc' */
'chart_title',
/** string title */
'display_limit',
],
static::ENUM_STYLE_CHART_AJAX => [
'chart_type', /** string 'pie' or 'bars' */
'group_by', /** string group by att code */
'group_by_expr', /** string group by expression */
'group_by_label', /** string aggregation column name */
'aggregation_function', /** string aggregation function ('count', 'sum', 'avg', 'min', 'max', ...) */
'aggregation_attribute', /** string att code used for aggregation */
'limit', /** int limit the chart results */
'order_by', /** string either 'attribute' group_by attcode or 'function' aggregation_function value */
'order_direction', /** string order direction 'asc' or 'desc' */
],
static::ENUM_STYLE_COUNT => [
'group_by', /** string group by att code */
'group_by_expr', /** string group by expression */
'group_by_label', /** string aggregation column name */
'aggregation_function',
/** string aggregation function ('count', 'sum', 'avg', 'min', 'max', ...) */
'aggregation_attribute',
/** string att code used for aggregation */
'limit',
/** int limit the chart results */
'order_by',
/** string either 'attribute' group_by attcode or 'function' aggregation_function value */
'order_direction',
/** string order direction 'asc' or 'desc' */
'display_limit',
],
static::ENUM_STYLE_CSV => [],
static::ENUM_STYLE_JOIN => array_merge([
'display_aliases',
/** string comma separated list of class aliases to display */
'group_by',
/** string group by att code */
], DataTableUIBlockFactory::GetAllowedParams()),
'links' => DataTableUIBlockFactory::GetAllowedParams(),
static::ENUM_STYLE_LIST => array_merge([
'update_history',
/** bool add breadcrumb entry */
'default',
/** array of default attribute values */
'menu_actions_target',
/** string html link target */
'toolkit_menu',
/** bool add toolkit menu */
'selectionMode',
/**positive or negative*/
'max_height',
/** string Max. height of the list, if not specified will occupy all the available height no matter the pagination */
'localize_values',
/** param for export.php */
'refresh_action',
/**to add refresh button in datatable*/
], DataTableUIBlockFactory::GetAllowedParams()),
static::ENUM_STYLE_LIST_IN_OBJECT => array_merge([
'update_history',
/** bool add breadcrumb entry */
'default',
/** array of default attribute values */
'menu_actions_target',
/** string html link target */
'toolkit_menu',
/** bool add toolkit menu */
'selectionMode',
/**positive or negative*/
'max_height',
/** string Max. height of the list, if not specified will occupy all the available height no matter the pagination */
'localize_values',
/** param for export.php */
'refresh_action',
/**to add refresh button in datatable*/
], DataTableUIBlockFactory::GetAllowedParams()),
static::ENUM_STYLE_LIST_SEARCH => array_merge([
'update_history',
/** bool add breadcrumb entry */
'result_list_outer_selector',
/** string js selector of the search result display */
'table_inner_id',
/** string html id of the results table */
'json',
/** string */
'hidden_criteria',
/** string search criteria not visible */
'baseClass',
/** string base class */
'action',
/** string */
'open',
/** bool open by default the search */
'submit_on_load',
/** bool submit the search on loading page */
'class', /** class name */
'search_header_force_dropdown', /** Html for <select> to choose the class to search */
'this',
], DataTableUIBlockFactory::GetAllowedParams()),
static::ENUM_STYLE_SEARCH => array_merge([
'baseClass',
/** string search root class */
'open',
/** bool open the search panel by default */
'submit_on_load',
/** bool submit the search on loading page */
'result_list_outer_selector',
/** string js selector of the search result display */
'search_header_force_dropdown',
/** string Search class selection dropdown html code */
'action',
/** string search URL */
'table_inner_id',
/** string html id of the results table */
'json',
/** string */
'hidden_criteria',
/** string search criteria not visible */
'class',
/** string class searched */
], DataTableUIBlockFactory::GetAllowedParams()),
static::ENUM_STYLE_SUMMARY => [
'status[block]',
/** string object 'status' att code */
'status_codes[block]',
/** string comma separated list of object states */
'title[block]',
/** string title */
'label[block]',
/** string label */
'context_filter',
/** int if != 0 filter with user context */
'org_id',
],
];
$aAllowedGeneralParams = [
/** bool display obsolete data */
'show_obsolete_data',
/** string current block id overridden by $sId argument */
'currentId',
/** array query parameters */
'query_params',
/** int Id of the current object */
'this->id',
/** string class of the current object */
'this->class',
/** string comma separated list of attCodes */
'order_by',
/** bool|string|numeric 'fast' (reload faster) or 'standard' (= true or 'true') (reload standard) or reload interval value (numeric) */
'auto_reload',
/** string current navigation menu */
'c[menu]',
/** int current filtered organization */
'c[org_id]',
/** string workaround due to extraparams in menunode */
'c[menu',
/** int workaround due to extraparams in menunode */
'c[org_id',
/** string dashboard html div id */
'dashboard_div_id',
/** param true if block is in a dashboard*/
'withJSRefreshCallBack',
/** true if dashboard page */
'from_dashboard_page',
/** bool true if list may be render in panel block */
'surround_with_panel',
/** string title of panel block */
'panel_title',
/** string true if panel title should be displayed as html */
'panel_title_is_html',
/** string Description of the panel content, displayed as a hint on the title */
'panel_title_tooltip',
/** string class for panel block style */
'panel_class',
/** string class for panel block style */
'panel_icon',
];
if (isset($aAllowedParams[$sStyle])) {
return array_merge($aAllowedGeneralParams, $aAllowedParams[$sStyle]);
}
return $aAllowedGeneralParams;
}
/**
* @param string $sStyle
* @param array $aParams
*
* @throws \ApplicationException
*/
protected function CheckParams(string $sStyle, array $aParams)
{
if (!utils::IsDevelopmentEnvironment()) {
return;
}
$aAllowedParams = $this->GetAllowedParams($sStyle);
foreach (array_keys($aParams) as $sParamName) {
if (!in_array($sParamName, $aAllowedParams)) {
throw new ApplicationException("Unknown parameter $sParamName for DisplayBlock $sStyle");
}
}
}
public function GetFilter()
{
return $this->m_oFilter;
}
/**
* Constructs a DisplayBlock object from a DBObjectSet already in memory
*
* @param DBObjectSet $oSet
* @param string $sStyle
* @param array $aParams
*
* @return DisplayBlock The DisplayBlock object, or null if the creation failed
* @throws \CoreException
* @throws \Exception
*/
public static function FromObjectSet(DBObjectSet $oSet, $sStyle, $aParams = array())
{
$oDummyFilter = new DBObjectSearch($oSet->GetClass());
$aKeys = array();
$oSet->OptimizeColumnLoad(array($oSet->GetClassAlias() => array())); // No need to load all the columns just to get the id
while($oObject = $oSet->Fetch())
{
$aKeys[] = $oObject->GetKey();
}
$oSet->Rewind();
if (count($aKeys) > 0)
{
$oDummyFilter->AddCondition('id', $aKeys, 'IN');
}
else
{
$oDummyFilter->AddCondition('id', 0, '=');
}
$oBlock = new DisplayBlock($oDummyFilter, $sStyle, false, $aParams); // DisplayBlocks built this way are synchronous
return $oBlock;
}
/**
* Constructs a DisplayBlock object from an XML template
*
* @param $sTemplate string The XML template
*
* @return DisplayBlock The DisplayBlock object, or null if the template is invalid
* @throws \ApplicationException
* @throws \OQLException
*/
public static function FromTemplate($sTemplate)
{
$iStartPos = stripos($sTemplate, '<'.self::TAG_BLOCK.' ', 0);
$iEndPos = stripos($sTemplate, '</'.self::TAG_BLOCK.'>', $iStartPos);
$iEndTag = stripos($sTemplate, '>', $iStartPos);
$aParams = array();
if (($iStartPos === false) || ($iEndPos === false)) {
return null;
} // invalid template
$sITopData = substr($sTemplate, 1 + $iEndTag, $iEndPos - $iEndTag - 1);
$sITopTag = substr($sTemplate, $iStartPos + strlen('<'.self::TAG_BLOCK), $iEndTag - $iStartPos - strlen('<'.self::TAG_BLOCK));
$aMatches = array();
$sBlockClass = "DisplayBlock";
$bAsynchronous = false;
$sBlockType = 'list';
$sEncoding = 'text/serialize';
if (preg_match('/ type="(.*)"/U', $sITopTag, $aMatches)) {
$sBlockType = strtolower($aMatches[1]);
}
if (preg_match('/ asynchronous="(.*)"/U', $sITopTag, $aMatches)) {
$bAsynchronous = (strtolower($aMatches[1]) == 'true');
}
if (preg_match('/ blockclass="(.*)"/U', $sITopTag, $aMatches)) {
$sBlockClass = $aMatches[1];
}
if (preg_match('/ encoding="(.*)"/U', $sITopTag, $aMatches)) {
$sEncoding = strtolower($aMatches[1]);
}
if (preg_match('/ link_attr="(.*)"/U', $sITopTag, $aMatches)) {
// The list to display is a list of links to the specified object
$aParams['link_attr'] = $aMatches[1]; // Name of the Ext. Key that makes this linkage
}
if (preg_match('/ target_attr="(.*)"/U', $sITopTag, $aMatches)) {
// The list to display is a list of links to the specified object
$aParams['target_attr'] = $aMatches[1]; // Name of the Ext. Key that make this linkage
}
if (preg_match('/ object_id="(.*)"/U', $sITopTag, $aMatches)) {
// The list to display is a list of links to the specified object
$aParams['object_id'] = $aMatches[1]; // Id of the object to be linked to
}
// Parameters contains a list of extra parameters for the block
// the syntax is param_name1:value1;param_name2:value2;...
if (preg_match('/ parameters="(.*)"/U', $sITopTag, $aMatches)) {
$sParameters = $aMatches[1];
$aPairs = explode(';', $sParameters);
foreach ($aPairs as $sPair) {
if (preg_match('/(.*)\:(.*)/', $sPair, $aMatches)) {
$aParams[trim($aMatches[1])] = trim($aMatches[2]);
}
}
}
if (!empty($aParams['link_attr'])) {
// Check that all mandatory parameters are present:
if (empty($aParams['object_id'])) {
// if 'links' mode is requested the d of the object to link to must be specified
throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
}
if (empty($aParams['target_attr'])) {
// if 'links' mode is requested the id of the object to link to must be specified
throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
}
}
$oFilter = null;
switch ($sEncoding) {
case 'text/serialize':
$oFilter = DBSearch::unserialize($sITopData);
break;
case 'text/oql':
$oFilter = DBSearch::FromOQL($sITopData);
break;
}
return new $sBlockClass($oFilter, $sBlockType, $bAsynchronous, $aParams);
}
public function DisplayIntoContentBlock(UIContentBlock $oContentBlock, WebPage $oPage, $sId, $aExtraParams = array())
{
$oContentBlock->AddSubBlock($this->GetDisplay($oPage, $sId, $aExtraParams));
}
public function Display(WebPage $oPage, $sId, $aExtraParams = array())
{
$oPage->AddUiBlock($this->GetDisplay($oPage, $sId, $aExtraParams));
}
public function GetDisplay(WebPage $oPage, $sId, $aExtraParams = array()): UIContentBlock
{
$oHtml = new UIContentBlock($sId);
$oHtml->AddCSSClass("display_block");
$aExtraParams = array_merge($aExtraParams, $this->m_aParams);
$aExtraParams['currentId'] = $sId;
$sExtraParams = addslashes(str_replace('"', "'",
json_encode($aExtraParams))); // JSON encode, change the style of the quotes and escape them
if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params'];
} else {
if (isset($aExtraParams['this->id']) && isset($aExtraParams['this->class'])) {
$sClass = $aExtraParams['this->class'];
$iKey = $aExtraParams['this->id'];
$oObj = MetaModel::GetObject($sClass, $iKey);
$aQueryParams = array('this->object()' => $oObj);
} else {
$aQueryParams = array();
}
}
$sFilter = addslashes($this->m_oFilter->serialize(false, $aQueryParams)); // Used either for asynchronous or auto_reload
if (!$this->m_bAsynchronous) {
// render now
try {
$oHtml->AddSubBlock($this->GetRenderContent($oPage, $aExtraParams, $sId));
} catch (Exception $e) {
if (UserRights::IsAdministrator()) {
$sExceptionContent = 'Exception thrown:<br><code>'.utils::Sanitize($e->getMessage(), '', utils::ENUM_SANITIZATION_FILTER_STRING).'</code>';
$oExceptionAlert = AlertUIBlockFactory::MakeForFailure('Cannot display results', $sExceptionContent);
$oHtml->AddSubBlock($oExceptionAlert);
}
ExceptionLog::LogException($e);
}
} else {
// render it as an Ajax (asynchronous) call
$oHtml->AddCSSClass("loading");
$oHtml->AddHtml("<p><img src=\"".utils::GetAbsoluteUrlAppRoot()."images/indicator_arrows.gif\"> ".Dict::S('UI:Loading').'</p>');
$oPage->add_script('
$.post("ajax.render.php?style='.$this->m_sStyle.'",
{ operation: "ajax", filter: "'.$sFilter.'", extra_params: "'.$sExtraParams.'" },
function(data){
$("#'.$sId.'")
.empty()
.append(data)
.removeClass("loading")
;
}
);
');
}
if ($this->m_sStyle == static::ENUM_STYLE_LIST) // Search form need to extract result list extra data, the simplest way is to expose this configuration
{
$listJsonExtraParams = json_encode(json_encode($aExtraParams));
$oPage->add_ready_script("
$('#$sId').data('sExtraParams', ".$listJsonExtraParams.");
");
}
return $oHtml;
}
/**
* @param WebPage $oPage
* @param array $aExtraParams
*
* @throws \ApplicationException
* @throws \CoreException
* @throws \CoreWarning
* @throws \DictExceptionMissingString
* @throws \MySQLException
*/
public function RenderContent(WebPage $oPage, $aExtraParams = array())
{
if (!isset($aExtraParams['currentId'])) {
$sId = utils::GetUniqueId(); // Works only if the page is not an Ajax one !
} else {
$sId = $aExtraParams['currentId'];
}
$oPage->AddUiBlock($this->GetRenderContent($oPage, $aExtraParams, $sId));
}
/**
* @param WebPage $oPage
* @param array $aExtraParams
* @param $sId
*
* @return \Combodo\iTop\Application\UI\Base\iUIBlock
* @throws ApplicationException
* @throws CoreException
* @throws CoreWarning
* @throws DictExceptionMissingString
* @throws MySQLException
* @throws Exception
*
* @since 2.7.7 3.0.1 3.1.0 N°3129 add type hinting to $aExtraParams
*/
public function GetRenderContent(WebPage $oPage, array $aExtraParams, string $sId)
{
$sHtml = '';
$oBlock = null;
$this->CheckParams($this->m_sStyle, $aExtraParams);
// Add the extra params into the filter if they make sense for such a filter
$bDoSearch = utils::ReadParam('dosearch', false);
$aQueryParams = array();
if (isset($aExtraParams['query_params'])) {
$aQueryParams = $aExtraParams['query_params'];
} else {
if (isset($aExtraParams['this->id']) && isset($aExtraParams['this->class'])) {
$sClass = $aExtraParams['this->class'];
$iKey = $aExtraParams['this->id'];
$oObj = MetaModel::GetObject($sClass, $iKey);
$aQueryParams = array('this->object()' => $oObj);
}
}
if ($this->m_oSet == null) {
// In case of search, the context filtering is done by the search itself
if (($this->m_sStyle != 'links') && ($this->m_sStyle != static::ENUM_STYLE_SEARCH) && ($this->m_sStyle != static::ENUM_STYLE_LIST_SEARCH)) {
$oAppContext = new ApplicationContext();
$sClass = $this->m_oFilter->GetClass();
$aFilterCodes = MetaModel::GetFiltersList($sClass);
$aCallSpec = array($sClass, 'MapContextParam');
if (is_callable($aCallSpec)) {
foreach ($oAppContext->GetNames() as $sContextParam) {
$sParamCode = call_user_func($aCallSpec, $sContextParam); //Map context parameter to the value/filter code depending on the class
if (!is_null($sParamCode)) {
$sParamValue = $oAppContext->GetCurrentValue($sContextParam, null);
if (!is_null($sParamValue)) {
$aExtraParams[$sParamCode] = $sParamValue;
}
}
}
}
foreach ($aFilterCodes as $sFilterCode) {
$externalFilterValue = utils::ReadParam($sFilterCode, '', false, 'raw_data');
$condition = null;
$bParseSearchString = true;
if (isset($aExtraParams[$sFilterCode])) {
$bParseSearchString = false;
$condition = $aExtraParams[$sFilterCode];
}
if ($bDoSearch && $externalFilterValue != "") {
// Search takes precedence over context params...
$bParseSearchString = true;
unset($aExtraParams[$sFilterCode]);
if (!is_array($externalFilterValue)) {
$condition = trim($externalFilterValue);
} else {
if (count($externalFilterValue) == 1) {
$condition = trim($externalFilterValue[0]);
} else {
$condition = $externalFilterValue;
}
}
}
if (!is_null($condition))
{
$sOpCode = null; // default operator
if (is_array($condition))
{
// Multiple values, add them as AND X IN (v1, v2, v3...)
$sOpCode = 'IN';
}
$this->AddCondition($sFilterCode, $condition, $sOpCode, $bParseSearchString);
}
}
if ($bDoSearch)
{
// Keep the table_id identifying this table if we're performing a search
$sTableId = utils::ReadParam('_table_id_', null, false, utils::ENUM_SANITIZATION_FILTER_ELEMENT_IDENTIFIER);
if ($sTableId != null)
{
$aExtraParams['table_id'] = $sTableId;
}
}
}
$aOrderBy = array();
if (isset($aExtraParams['order_by']))
{
// Convert the string describing the order_by parameter into an array
// The syntax is +attCode1,-attCode2
// attCode1 => ascending, attCode2 => descending
$aTemp = explode(',', $aExtraParams['order_by']);
foreach($aTemp as $sTemp)
{
$aMatches = array();
if (preg_match('/^([+-])?(.+)$/', $sTemp, $aMatches)) {
$bAscending = true;
if ($aMatches[1] == '-') {
$bAscending = false;
}
$aOrderBy[$aMatches[2]] = $bAscending;
}
}
}
$aExtraParams['query_params'] = $this->m_oFilter->GetInternalParams();
$this->m_oSet = new CMDBObjectSet($this->m_oFilter, $aOrderBy, $aQueryParams);
}
$this->m_oSet->SetShowObsoleteData($this->m_bShowObsoleteData);
switch($this->m_sStyle) {
case static::ENUM_STYLE_LIST_SEARCH:
case static::ENUM_STYLE_LIST:
break;
default:
// N°3473: except for 'list_search' and 'list' (which have more granularity, see the other switch below),
// refuse to render if the user is not allowed to see the class.
if (! UserRights::IsActionAllowed($this->m_oSet->GetClass(), UR_ACTION_READ, $this->m_oSet) == UR_ALLOWED_YES) {
$sHtml .= $oPage->GetP(Dict::Format('UI:Error:ReadNotAllowedOn_Class', $this->m_oSet->GetClass()));
return new Html($sHtml);
}
}
switch ($this->m_sStyle) {
case static::ENUM_STYLE_COUNT:
$oBlock = $this->RenderCount($aExtraParams);
break;
case static::ENUM_STYLE_JOIN:
$oBlock = $this->RenderJoin($aExtraParams, $oPage);
break;
case static::ENUM_STYLE_LIST_SEARCH:
$oBlock = $this->RenderListSearch($aExtraParams, $oPage);
break;
case static::ENUM_STYLE_LIST:
case static::ENUM_STYLE_LIST_IN_OBJECT:
$oBlock = $this->RenderList($aExtraParams, $oPage);
break;
case 'links':
$oBlock = $this->RenderLinks($oPage, $aExtraParams);
break;
case static::ENUM_STYLE_ACTIONS:
$oBlock = $this->RenderActions($aExtraParams);
break;
case static::ENUM_STYLE_SUMMARY:
$oBlock = $this->RenderSummary($aExtraParams);
break;
case static::ENUM_STYLE_CSV:
$oBlock = $this->RenderCsv($oAppContext);
break;
case static::ENUM_STYLE_SEARCH:
$oBlock = $this->RenderSearch($oPage, $aExtraParams);
break;
case static::ENUM_STYLE_CHART:
$oBlock = $this->RenderChart($sId, $aQueryParams, $aExtraParams);
break;
case static::ENUM_STYLE_CHART_AJAX:
$oBlock = $this->RenderChartAjax($aExtraParams);
break;
default:
// Unsupported style, do nothing.
$sHtml .= Dict::format('UI:Error:UnsupportedStyleOfBlock', $this->m_sStyle);
}
$bAutoReload = false;
if (isset($aExtraParams['auto_reload']))
{
if ($aExtraParams['auto_reload'] === true)
{
// Note: does not work in the switch (case true) because a positive number evaluates to true!!!
$aExtraParams['auto_reload'] = 'standard';
}
switch($aExtraParams['auto_reload'])
{
case 'fast':
$bAutoReload = true;
$iReloadInterval = MetaModel::GetConfig()->GetFastReloadInterval()*1000;
break;
case 'standard':
case 'true':
$bAutoReload = true;
$iReloadInterval = MetaModel::GetConfig()->GetStandardReloadInterval()*1000;
break;
default:
if (is_numeric($aExtraParams['auto_reload']) && ($aExtraParams['auto_reload'] > 0))
{
$bAutoReload = true;
$iReloadInterval = max(MetaModel::GetConfig()->Get('min_reload_interval'), $aExtraParams['auto_reload'])*1000;
}
else
{
// incorrect config, ignore it
$bAutoReload = false;
}
}
}
if (($bAutoReload) && ($this->m_sStyle != static::ENUM_STYLE_SEARCH)) // Search form do NOT auto-reload
{
// Used either for asynchronous or auto_reload
// does a json_encode twice to get a string usable as function parameter
$sFilterBefore = $this->m_oFilter->serialize();
$sFilter = json_encode($sFilterBefore);
$sExtraParams = json_encode(json_encode($aExtraParams));
$oPage->add_script(
<<<JS
if (typeof window.oAutoReloadBlock == "undefined") {
window.oAutoReloadBlock = {};
}
if (typeof window.oAutoReloadBlock['$sId'] != "undefined") {
clearInterval(window.oAutoReloadBlock['$sId']);
}
window.oAutoReloadBlock['$sId'] = setInterval(function() {
ReloadBlock('$sId', '{$this->m_sStyle}', $sFilter, $sExtraParams);
}, '$iReloadInterval');
JS
);
}
if (!empty($oBlock)) {
return $oBlock;
}
return new Html($sHtml);
}
/**
* Add a condition (restriction) to the current DBSearch on which the display block is based
* taking into account the hierarchical keys for which the condition is based on the 'below' operator
*
* @param string $sFilterCode
* @param array $condition
* @param string $sOpCode
* @param bool $bParseSearchString
*
* @throws \CoreException
* @throws \CoreWarning
* @throws \Exception
*/
protected function AddCondition($sFilterCode, $condition, $sOpCode = null, $bParseSearchString = false)
{
// Workaround to an issue revealed whenever a condition on org_id is applied twice (with a hierarchy of organizations)
// Moreover, it keeps the query as simple as possible
if (isset($this->m_aConditions[$sFilterCode]) && $condition == $this->m_aConditions[$sFilterCode])
{
// Skip
return;
}
$this->m_aConditions[$sFilterCode] = $condition;
$sClass = $this->m_oFilter->GetClass();
$bConditionAdded = false;
// If the condition is an external key with a class having a hierarchy, use a "below" criteria
if (MetaModel::IsValidAttCode($sClass, $sFilterCode))
{
$oAttDef = MetaModel::GetAttributeDef($sClass, $sFilterCode);
if ($oAttDef->IsExternalKey())
{
$sHierarchicalKeyCode = MetaModel::IsHierarchicalClass($oAttDef->GetTargetClass());
if ($sHierarchicalKeyCode !== false)
{
$oFilter = new DBObjectSearch($oAttDef->GetTargetClass());
if (($sOpCode == 'IN') && is_array($condition))
{
$oFilter->AddConditionExpression(self::GetConditionIN($oFilter, 'id', $condition));
}
else
{
$oFilter->AddCondition('id', $condition);
}
$oHKFilter = new DBObjectSearch($oAttDef->GetTargetClass());
$oHKFilter->AddCondition_PointingTo($oFilter, $sHierarchicalKeyCode, TREE_OPERATOR_BELOW); // Use the 'below' operator by default
$this->m_oFilter->AddCondition_PointingTo($oHKFilter, $sFilterCode);
$bConditionAdded = true;
}
else if (($sOpCode == 'IN') && is_array($condition))
{
$this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
$bConditionAdded = true;
}
}
else if (($sOpCode == 'IN') && is_array($condition))
{
$this->m_oFilter->AddConditionExpression(self::GetConditionIN($this->m_oFilter, $sFilterCode, $condition));
$bConditionAdded = true;
}
}
// In all other cases, just add the condition directly
if (!$bConditionAdded)
{
$this->m_oFilter->AddCondition($sFilterCode, $condition, null); // Use the default 'loose' operator
}
}
static protected function GetConditionIN($oFilter, $sFilterCode, $condition)
{
$oField = new FieldExpression($sFilterCode, $oFilter->GetClassAlias());
$sListExpr = '('.implode(', ', CMDBSource::Quote($condition)).')';
$sOQLCondition = $oField->RenderExpression()." IN $sListExpr";
$oNewCondition = Expression::FromOQL($sOQLCondition);
return $oNewCondition;
}
/**
* For the result to be meaningful, this function must be called AFTER GetRenderContent() (or Display())
* @return int
*/
public function GetDisplayedCount()
{
return $this->m_oSet->Count();
}
/**
* @param $aExtraParams
* @param $oGroupByExp
* @param $sGroupByLabel
* @param $aGroupBy
* @param $sAggregationFunction
* @param $sFctVar
* @param $sAggregationAttr
* @param $sSql
*
* @throws \Exception
*/
protected function MakeGroupByQuery(&$aExtraParams, &$oGroupByExp, &$sGroupByLabel, &$aGroupBy, &$sAggregationFunction, &$sFctVar, &$sAggregationAttr, &$sSql)
{
$sAlias = $this->m_oFilter->GetClassAlias();
if (isset($aExtraParams['group_by_label']))
{
$oGroupByExp = Expression::FromOQL($aExtraParams['group_by']);
$sGroupByLabel = $aExtraParams['group_by_label'];
}
else
{
// Backward compatibility: group_by is simply a field id
$oGroupByExp = new FieldExpression($aExtraParams['group_by'], $sAlias);
$sGroupByLabel = MetaModel::GetLabel($this->m_oFilter->GetClass(), $aExtraParams['group_by']);
}
// Security filtering
$aFields = $oGroupByExp->ListRequiredFields();
foreach($aFields as $sFieldAlias)
{
$aMatches = array();
if (preg_match('/^([^.]+)\\.([^.]+)$/', $sFieldAlias, $aMatches))
{
$sFieldClass = $this->m_oFilter->GetClassName($aMatches[1]);
$oAttDef = MetaModel::GetAttributeDef($sFieldClass, $aMatches[2]);
if ($oAttDef instanceof AttributeOneWayPassword)
{
throw new Exception('Grouping on password fields is not supported.');