File: CMapHelper.php

package info (click to toggle)
zabbix 1%3A6.0.14%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 283,384 kB
  • sloc: sql: 868,673; ansic: 322,351; php: 235,311; javascript: 62,116; sh: 5,555; makefile: 2,257; java: 1,397; cpp: 662; xml: 49; perl: 41
file content (717 lines) | stat: -rw-r--r-- 22,317 bytes parent folder | download
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
<?php
/*
** Zabbix
** Copyright (C) 2001-2023 Zabbix SIA
**
** This program 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.
**
** This program 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 this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


class CMapHelper {

	/**
	 * Get map data with resolved element / link states.
	 *
	 * @param array  $sysmapids					Map IDs.
	 * @param array  $options					Options used to retrieve actions.
	 * @param int    $options['severity_min']	Minimum severity.
	 * @param int    $options['unique_id']
	 *
	 * @return array
	 */
	public static function get($sysmapids, array $options = []) {
		$maps = API::Map()->get([
			'output' => ['sysmapid', 'name', 'width', 'height', 'backgroundid', 'label_type', 'label_location',
				'highlight', 'expandproblem', 'markelements', 'show_unack', 'label_format', 'label_type_host',
				'label_type_hostgroup', 'label_type_trigger', 'label_type_map', 'label_type_image', 'label_string_host',
				'label_string_hostgroup', 'label_string_trigger', 'label_string_map', 'label_string_image', 'iconmapid',
				'severity_min', 'show_suppressed'
			],
			'selectShapes' => ['sysmap_shapeid', 'type', 'x', 'y', 'width', 'height', 'text', 'font', 'font_size',
				'font_color', 'text_halign', 'text_valign', 'border_type', 'border_width', 'border_color',
				'background_color', 'zindex'
			],
			'selectLines' => ['sysmap_shapeid', 'x1', 'x2', 'y1', 'y2', 'line_type', 'line_width', 'line_color',
				'zindex'
			],
			'selectSelements' => ['selementid', 'elements', 'elementtype', 'iconid_off', 'iconid_on', 'label',
				'label_location', 'x', 'y', 'iconid_disabled', 'iconid_maintenance', 'elementsubtype', 'areatype',
				'width', 'height', 'viewtype', 'use_iconmap', 'permission', 'evaltype', 'tags'
			],
			'selectLinks' => ['linkid', 'selementid1', 'selementid2', 'drawtype', 'color', 'label', 'linktriggers',
				'permission'
			],
			'sysmapids' => $sysmapids,
			'preservekeys' => true
		]);
		$map = reset($maps);

		$theme = getUserGraphTheme();

		if (!$map) {
			$map = [
				'sysmapid' => -1,
				'width' => 320,
				'height' => 150,
				'backgroundid' => null,
				'severity_min' => 0,
				'show_unack' => EXTACK_OPTION_ALL,
				'label_location' => MAP_LABEL_LOC_BOTTOM,
				'selements' => [],
				'links' => [],
				'shapes' => [[
					'type' => SYSMAP_SHAPE_TYPE_RECTANGLE,
					'x' => 0,
					'y' => 0,
					'width' => 320,
					'height' => 150,
					'font' => 9,
					'font_size' => 11,
					'font_color' => 'FF0000',
					'text' => _('No permissions to referred object or it does not exist!')
				]],
				'aria_label' => ''
			];
		}
		else {
			if (array_key_exists('severity_min', $options)) {
				$map['severity_min'] = $options['severity_min'];
			}
			else {
				$options['severity_min'] = $map['severity_min'];
			}

			// Populate host group elements of subtype 'SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS' with hosts.
			$areas = self::populateHostGroupsWithHosts($map, $theme);

			// Apply inherited label options.
			$map = self::applyMapElementLabelProperties($map);

			// Resolve macros in map element labels.
			$resolve_opt = ['resolve_element_label' => true];
			$map['selements'] = CMacrosResolverHelper::resolveMacrosInMapElements($map['selements'], $resolve_opt);

			self::resolveMapState($map, $areas, $options);
		}

		return [
			'id' => $map['sysmapid'],
			'theme' => $theme,
			'canvas' => [
				'width' => $map['width'],
				'height' => $map['height']
			],
			'refresh' => 'map.php?sysmapid='.$map['sysmapid'].'&severity_min='.$map['severity_min']
				.(array_key_exists('unique_id', $options) ? '&unique_id='.$options['unique_id'] : ''),
			'background' => $map['backgroundid'],
			'label_location' => $map['label_location'],
			'elements' => array_values($map['selements']),
			'links' => array_values($map['links']),
			'shapes' => array_values($map['shapes']),
			'aria_label' => $map['aria_label'],
			'timestamp' => zbx_date2str(DATE_TIME_FORMAT_SECONDS)
		];
	}

	/**
	 * Function applies element labels inherited from map properties.
	 *
	 * @param array  $sysmap                             Map data.
	 * @param array  $sysmap[selements]                  Array of map elements.
	 * @param int    $sysmap[selements][][elementtype]   Map element type.
	 * @param int    $sysmap[label_format]               Map label format property.
	 * @param int    $sysmap[label_type]                 Map label type property.
	 * @param int    $sysmap[label_type_hostgroup]       Map host group element label type.
	 * @param string $sysmap[label_string_hostgroup]     Map host group element custom label.
	 * @param int    $sysmap[label_type_host]            Map host element label type.
	 * @param string $sysmap[label_string_host]          Map host element custom label.
	 * @param int    $sysmap[label_type_trigger]         Map trigger element label type.
	 * @param string $sysmap[label_string_trigger]       Map trigger element custom label.
	 * @param int    $sysmap[label_type_map]             Map submap element label type.
	 * @param string $sysmap[label_string_map]           Map submap element custom label.
	 * @param int    $sysmap[label_type_image]           Map image element label type.
	 * @param string $sysmap[label_string_image]         Map image element custom label.
	 *
	 * @return array
	 */
	public static function applyMapElementLabelProperties(array $sysmap) {
		// Define which $sysmap property holds value for each type of element.
		$label_properties = [
			SYSMAP_ELEMENT_TYPE_HOST_GROUP => [
				'field_label_type' => 'label_type_hostgroup',
				'field_custom_label' => 'label_string_hostgroup'
			],
			SYSMAP_ELEMENT_TYPE_HOST => [
				'field_label_type' => 'label_type_host',
				'field_custom_label' => 'label_string_host'
			],
			SYSMAP_ELEMENT_TYPE_TRIGGER => [
				'field_label_type' => 'label_type_trigger',
				'field_custom_label' => 'label_string_trigger'
			],
			SYSMAP_ELEMENT_TYPE_MAP => [
				'field_label_type' => 'label_type_map',
				'field_custom_label' => 'label_string_map'
			],
			SYSMAP_ELEMENT_TYPE_IMAGE => [
				'field_label_type' => 'label_type_image',
				'field_custom_label' => 'label_string_image'
			]
		];

		// Apply properties to each sysmap element.
		foreach ($sysmap['selements'] as &$selement) {
			$prop = $label_properties[$selement['elementtype']];
			$elmnt_label_type = ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_ON)
				? $sysmap[$prop['field_label_type']]
				: $sysmap['label_type'];
			$inherited_label = null;

			if ($elmnt_label_type == MAP_LABEL_TYPE_NOTHING) {
				$inherited_label = '';
			}
			elseif ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && $elmnt_label_type == MAP_LABEL_TYPE_IP) {
				$inherited_label = '{HOST.IP}';
			}
			elseif ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_ON
					&& $sysmap[$prop['field_label_type']] == MAP_LABEL_TYPE_CUSTOM) {
				$inherited_label = $sysmap[$prop['field_custom_label']];
			}

			$selement['label_type'] = $elmnt_label_type;
			if ($inherited_label !== null) {
				$selement['label'] = $inherited_label;
			}
		}
		unset($selement);

		return $sysmap;
	}

	/**
	 * Resolve map element (selements and links) state.
	 *
	 * @param array  $sysmap                   Map data.
	 * @param array  $areas                    Areas representing array containing host group element IDs and dimension
	 *                                         properties of area.
	 * @param array  $options                  Options used to retrieve actions.
	 * @param int    $options['severity_min']  Minimum severity.
	 * @param int    $options['unique_id']
	 */
	protected static function resolveMapState(array &$sysmap, array $areas, array $options) {
		$map_info = getSelementsInfo($sysmap, ['severity_min' => $options['severity_min']]);
		processAreasCoordinates($sysmap, $areas, $map_info);

		// Adding element names and removing inaccessible triggers from readable elements.
		addElementNames($sysmap['selements']);

		foreach ($sysmap['selements'] as $id => &$element) {
			if ($element['permission'] < PERM_READ) {
				continue;
			}

			switch ($element['elementtype']) {
				case SYSMAP_ELEMENT_TYPE_IMAGE:
					$map_info[$id]['name'] = _('Image');
					break;

				case SYSMAP_ELEMENT_TYPE_TRIGGER:
					// Move the trigger with problem and highest priority to the beginning of the trigger list.
					if (array_key_exists('triggerid', $map_info[$id])) {
						$trigger_pos = 0;

						foreach ($element['elements'] as $i => $trigger) {
							if ($trigger['triggerid'] == $map_info[$id]['triggerid']) {
								$trigger_pos = $i;
								break;
							}
						}

						if ($trigger_pos > 0) {
							$trigger = $element['elements'][$trigger_pos];
							unset($element['elements'][$trigger_pos]);
							array_unshift($element['elements'], $trigger);
						}
					}
					// break; is not missing here

				default:
					$map_info[$id]['name'] = $element['elements'][0]['elementName'];
			}
		}
		unset($element);

		$labels = getMapLabels($sysmap, $map_info);
		$highlights = getMapHighligts($sysmap, $map_info);
		$actions = getActionsBySysmap($sysmap, $options);
		$linktrigger_info = getMapLinkTriggerInfo($sysmap, $options);

		$problems_total = 0;
		$status_problems = [];
		$status_other = [];

		foreach ($sysmap['selements'] as $id => &$element) {
			$element['icon'] = (array_key_exists($id, $map_info) && array_key_exists('iconid', $map_info[$id]))
				? $map_info[$id]['iconid']
				: null;

			unset($element['width'], $element['height']);

			if ($element['permission'] >= PERM_READ) {
				$label = str_replace(['.', ','], ' ', $element['label']);

				if ($map_info[$id]['problems_total'] > 0) {
					$problems_total += $map_info[$id]['problems_total'];
					$problem_desc = str_replace(['.', ','], ' ', $map_info[$id]['aria_label']);
					$status_problems[] = sprintf('%1$s, %2$s, %3$s, %4$s. ',
						sysmap_element_types($element['elementtype']), _('Status problem'), $label, $problem_desc
					);
				}
				else {
					$element_status = _('Status ok');

					if (array_key_exists('info', $map_info[$id])
							&& array_key_exists('maintenance', $map_info[$id]['info'])) {
						$element_status = _('Status maintenance');
					}
					elseif (array_key_exists('info', $map_info[$id])
							&& array_key_exists('status', $map_info[$id]['info'])) {
						$element_status = _('Status disabled');
					}

					$status_other[] = sprintf('%1$s, %2$s, %3$s. ', sysmap_element_types($element['elementtype']),
						$element_status, $label
					);
				}

				$element['highlight'] = $highlights[$id];
				$element['actions'] = $actions[$id];
				$element['label'] = $labels[$id];
			}
			else {
				$element['highlight'] = '';
				$element['actions'] = null;
				$element['label'] = '';
			}

			if ($sysmap['markelements']) {
				$element['latelyChanged'] = $map_info[$id]['latelyChanged'];
			}
		}
		unset($element);

		$sysmap['aria_label'] = str_replace(['.', ','], ' ', $sysmap['name']).', '.
			_n('%1$s of %2$s element in problem state', '%1$s of %2$s elements in problem state',
				count($status_problems), count($sysmap['selements'])).
			', '.
			_n('%1$s problem in total', '%1$s problems in total', $problems_total).
			'. '.
			implode('', array_merge($status_problems, $status_other));

		$sysmap['shapes'] = CMacrosResolverHelper::resolveMapShapeLabelMacros($sysmap['name'], $sysmap['shapes']);
		$sysmap['links'] = CMacrosResolverHelper::resolveMapLinkLabelMacros($sysmap['links']);

		foreach ($sysmap['lines'] as $line) {
			$sysmap['shapes'][] = self::convertLineToShape($line);
		}

		foreach ($sysmap['links'] as &$link) {
			if ($link['permission'] >= PERM_READ) {
				if (empty($link['linktriggers'])) {
					continue;
				}

				$drawtype = $link['drawtype'];
				$color = $link['color'];
				$linktriggers = $link['linktriggers'];
				order_result($linktriggers, 'triggerid');
				$max_severity = $options['severity_min'];

				foreach ($linktriggers as $link_trigger) {
					if ($link_trigger['triggerid'] == 0
							|| !array_key_exists($link_trigger['triggerid'], $linktrigger_info)) {
						continue;
					}

					$trigger = zbx_array_merge($link_trigger, $linktrigger_info[$link_trigger['triggerid']]);

					if ($trigger['status'] == TRIGGER_STATUS_ENABLED
							&& $trigger['value'] == TRIGGER_VALUE_TRUE
							&& $trigger['priority'] >= $max_severity) {
						$drawtype = $trigger['drawtype'];
						$color = $trigger['color'];
						$max_severity = $trigger['priority'];
					}
				}

				$link['color'] = $color;
				$link['drawtype'] = $drawtype;
			}
		}
		unset($link);
	}

	/**
	 * Convert map shape to line (apply mapping to attribute set).
	 *
	 * @param array $shape				Map shape.
	 *
	 * @return array
	 */
	public static function convertShapeToLine($shape) {
		$mapping = [
			'sysmap_shapeid',
			'zindex',
			'x' => 'x1',
			'y' => 'y1',
			'width' => 'x2',
			'height' =>	'y2',
			'border_type' => 'line_type',
			'border_width' => 'line_width',
			'border_color' => 'line_color'
		];

		$line = [];

		foreach ($mapping as $source_key => $target_key) {
			$source_key = (is_numeric($source_key)) ? $target_key : $source_key;

			if (array_key_exists($source_key, $shape)) {
				$line[$target_key] = $shape[$source_key];
			}
		}

		return $line;
	}

	/**
	 * Convert map line to shape (apply mapping to attribute set).
	 *
	 * @param array $line				Map line.
	 *
	 * @return array
	 */
	public static function convertLineToShape($line) {
		$mapping = [
			'sysmap_shapeid',
			'zindex',
			'x1' => 'x',
			'y1' => 'y',
			'x2' => 'width',
			'y2' =>	'height',
			'line_type' => 'border_type',
			'line_width' => 'border_width',
			'line_color' => 'border_color'
		];

		$shape = [];

		foreach ($mapping as $source_key => $target_key) {
			$source_key = (is_numeric($source_key)) ? $target_key : $source_key;

			if (array_key_exists($source_key, $line)) {
				$shape[$target_key] = $line[$source_key];
			}
		}

		$shape['type'] = SYSMAP_SHAPE_TYPE_LINE;

		return $shape;
	}

	/**
	 * Checks that the user has read permissions to objects used in the map elements.
	 *
	 * @param array $selements    selements to check
	 *
	 * @return boolean
	 */
	public static function checkSelementPermissions(array $selements) {
		$groupids = [];
		$hostids = [];
		$triggerids = [];
		$sysmapids = [];

		foreach ($selements as $selement) {
			switch ($selement['elementtype']) {
				case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
					$groupids[$selement['elements'][0]['groupid']] = true;
					break;

				case SYSMAP_ELEMENT_TYPE_HOST:
					$hostids[$selement['elements'][0]['hostid']] = true;
					break;

				case SYSMAP_ELEMENT_TYPE_TRIGGER:
					foreach ($selement['elements'] as $element) {
						$triggerids[$element['triggerid']] = true;
					}
					break;

				case SYSMAP_ELEMENT_TYPE_MAP:
					$sysmapids[$selement['elements'][0]['sysmapid']] = true;
					break;
			}
		}

		return self::checkHostGroupsPermissions(array_keys($groupids))
				&& self::checkHostsPermissions(array_keys($hostids))
				&& self::checkTriggersPermissions(array_keys($triggerids))
				&& self::checkMapsPermissions(array_keys($sysmapids));
	}

	/**
	 * Checks if the current user has access to the given host groups.
	 *
	 * @param array $groupids
	 *
	 * @return boolean
	 */
	private static function checkHostGroupsPermissions(array $groupids) {
		if ($groupids) {
			$count = API::HostGroup()->get([
				'countOutput' => true,
				'groupids' => $groupids
			]);

			return ($count == count($groupids));
		}

		return true;
	}

	/**
	 * Checks if the current user has access to the given hosts.
	 *
	 * @param array $hostids
	 *
	 * @return boolean
	 */
	private static function checkHostsPermissions(array $hostids) {
		if ($hostids) {
			$count = API::Host()->get([
				'countOutput' => true,
				'hostids' => $hostids
			]);

			return ($count == count($hostids));
		}

		return true;
	}

	/**
	 * Checks if the current user has access to the given triggers.
	 *
	 * @param array $triggerids
	 *
	 * @return boolean
	 */
	private static function checkTriggersPermissions(array $triggerids) {
		if ($triggerids) {
			$count = API::Trigger()->get([
				'countOutput' => true,
				'triggerids' => $triggerids
			]);

			return ($count == count($triggerids));
		}

		return true;
	}

	/**
	 * Checks if the current user has access to the given maps.
	 *
	 * @param array $sysmapids
	 *
	 * @return boolean
	 */
	private static function checkMapsPermissions(array $sysmapids) {
		if ($sysmapids) {
			$count = API::Map()->get([
				'countOutput' => true,
				'sysmapids' => $sysmapids
			]);

			return ($count == count($sysmapids));
		}

		return true;
	}

	/**
	 * Replace host groups of subtype = SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP by hosts that belongs to group.
	 *
	 * @param array $sysmap  Map data.
	 * @param array $theme   Theme used to create missing elements (like hostgroup frame).
	 *
	 * @return array         Array representing areas with area coordinates and selementids.
	 */
	protected static function populateHostGroupsWithHosts(array &$sysmap, array $theme) {
		// Collect host groups to populate with hosts.
		$groupids = [];
		foreach ($sysmap['selements'] as &$selement) {
			$selement['selementid_orig'] = $selement['selementid'];
			$selement['elementtype_orig'] = $selement['elementtype'];
			$selement['elementsubtype_orig'] = $selement['elementsubtype'];

			if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP
					&& $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) {
				if ($selement['permission'] >= PERM_READ) {
					$groupids[$selement['elements'][0]['groupid']] = true;
				}
				else {
					// If user has no access to whole host group, always show it as a SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP.
					$selement['elementsubtype'] = SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP;
				}
			}
		}
		unset($selement);

		$areas = [];

		if ($groupids) {
			$groups = API::HostGroup()->get([
				'output' => [],
				'selectHosts' => ['hostid', 'name'],
				'groupids' => array_keys($groupids),
				'preservekeys' => true
			]);

			$new_selementid = (count($sysmap['selements']) > 0)
				? (int) max(zbx_objectValues($sysmap['selements'], 'selementid'))
				: 0;

			$new_linkid = (count($sysmap['links']) > 0) ? (int) max(array_keys($sysmap['links'])) : 0;

			foreach ($sysmap['selements'] as $selement_key => &$selement) {
				if ($selement['elementtype'] != SYSMAP_ELEMENT_TYPE_HOST_GROUP
						|| $selement['elementsubtype'] != SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) {
					continue;
				}

				$groupid = $selement['elements'][0]['groupid'];
				$group = $groups[$groupid];
				$original_selement = $selement;

				// Jump to the next host group if current host group doesn't contain accessible hosts.
				if (!$group['hosts']) {
					continue;
				}

				// Sort hosts by name.
				CArrayHelper::sort($group['hosts'], ['field' => 'name', 'order' => ZBX_SORT_UP]);

				// Define area in which to locate hosts.
				if ($selement['areatype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) {
					$area = [
						'selementids' => [],
						'width' => $selement['width'],
						'height' => $selement['height'],
						'x' => $selement['x'],
						'y' => $selement['y']
					];

					$sysmap['shapes'][] = [
						'sysmap_shapeid' => 'e-'.$selement['selementid'],
						'type' => SYSMAP_SHAPE_TYPE_RECTANGLE,
						'x' => $selement['x'],
						'y' => $selement['y'],
						'width' => $selement['width'],
						'height' => $selement['height'],
						'border_type' => SYSMAP_SHAPE_BORDER_TYPE_SOLID,
						'border_width' => 3,
						'border_color' => $theme['maingridcolor'],
						'background_color' => '',
						'text' => '',
						'zindex' => -1
					];
				}
				else {
					$area = [
						'selementids' => [],
						'width' => $sysmap['width'],
						'height' => $sysmap['height'],
						'x' => 0,
						'y' => 0
					];
				}

				// Add selected hosts as map selements.
				foreach ($group['hosts'] as $host) {
					$new_selementid++;

					$area['selementids'][] = $new_selementid;
					$sysmap['selements'][$new_selementid] = [
						'elementtype' => SYSMAP_ELEMENT_TYPE_HOST,
						'elementsubtype' => SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP,
						'elements' => [
							['hostid' => $host['hostid']]
						],
						'selementid' => $new_selementid
					] + $selement;
				}

				$areas[] = $area;

				// Make links.
				$selements = zbx_toHash($sysmap['selements'], 'selementid');

				foreach ($sysmap['links'] as $link) {
					// Do not multiply links between two areas.
					$id1 = $link['selementid1'];
					$id2 = $link['selementid2'];

					if ($selements[$id1]['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP
							&& $selements[$id1]['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS
							&& $selements[$id2]['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP
							&& $selements[$id2]['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) {
						continue;
					}

					if ($id1 == $original_selement['selementid']) {
						$id_number = 'selementid1';
					}
					elseif ($id2 == $original_selement['selementid']) {
						$id_number = 'selementid2';
					}
					else {
						continue;
					}

					foreach ($area['selementids'] as $selement_id) {
						$new_linkid++;
						$link['linkid'] = -$new_linkid;
						$link[$id_number] = $selement_id;
						$sysmap['links'][$new_linkid] = $link;
					}
				}
			}
		}

		// Remove host group elements that are replaced by hosts.
		$selements = [];
		foreach ($sysmap['selements'] as $key => $element) {
			if ($element['elementtype'] != SYSMAP_ELEMENT_TYPE_HOST_GROUP
					|| $element['elementsubtype'] != SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) {
				$selements[$key] = $element;
			}
		}
		$sysmap['selements'] = $selements;

		return $areas;
	}
}