summaryrefslogtreecommitdiffstats
path: root/frontends/php/include/graphs.inc.php
blob: b597b9876babf57d34bbac2301577865d59d9195 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
<?php
/*
** ZABBIX
** Copyright (C) 2000-2005 SIA Zabbix
**
** 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., 675 Mass Ave, Cambridge, MA 02139, USA.
**/
?>
<?php
/*
 * Function: graph_item_type2str
 *
 * Description:
 *     Represent integer value of graph item type into the string
 *
 * Author:
 *     Eugene Grigorjev 
 *
 */
	function graph_item_type2str($type,$count=null){
		switch($type){
			case GRAPH_ITEM_SUM:	
				$type = S_GRAPH_SUM;
				break;				
			case GRAPH_ITEM_AGGREGATED:	
				$type = S_AGGREGATED.(isset($count) ? '('.$count.')' : '');	
				break;
			case GRAPH_ITEM_SIMPLE:
			default:			
				$type = S_SIMPLE;	
				break;
		}
	return $type;
	}
	
/*
 * Function: graph_item_drawtypes
 *
 * Description:
 *     Return available drawing types for graph item
 *
 * Author:
 *     Eugene Grigorjev 
 *
 */
	function graph_item_drawtypes(){
		return array(
				GRAPH_ITEM_DRAWTYPE_LINE,
				GRAPH_ITEM_DRAWTYPE_FILLED_REGION,
				GRAPH_ITEM_DRAWTYPE_BOLD_LINE,
				GRAPH_ITEM_DRAWTYPE_DOT,
				GRAPH_ITEM_DRAWTYPE_DASHED_LINE
			    );
	}
	
/*
 * Function: graph_item_drawtype2str
 *
 * Description:
 *     Represent integer value of graph item drawing type into the string
 *
 * Author:
 *     Eugene Grigorjev 
 *
 */
	function graph_item_drawtype2str($drawtype,$type=null){
		if($type == GRAPH_ITEM_AGGREGATED) return '-';

		switch($drawtype){
			case GRAPH_ITEM_DRAWTYPE_LINE:			$drawtype = S_LINE;				break;
			case GRAPH_ITEM_DRAWTYPE_FILLED_REGION:	$drawtype = S_FILLED_REGION;	break;
			case GRAPH_ITEM_DRAWTYPE_BOLD_LINE:		$drawtype = S_BOLD_LINE;		break;
			case GRAPH_ITEM_DRAWTYPE_DOT:			$drawtype = S_DOT;				break;
			case GRAPH_ITEM_DRAWTYPE_DASHED_LINE:	$drawtype = S_DASHED_LINE;		break;
			default: $drawtype = S_UNKNOWN;		break;
		}
	return $drawtype;
	}

/*
 * Function: graph_item_calc_fnc2str
 *
 * Description:
 *     Represent integer value of calculation function into the string
 *
 * Author:
 *     Eugene Grigorjev 
 *
 */
	function graph_item_calc_fnc2str($calc_fnc, $type=null){
		if($type == GRAPH_ITEM_AGGREGATED) return '-';
		
		switch($calc_fnc){
			case CALC_FNC_ALL:      $calc_fnc = S_ALL_SMALL;        break;
			case CALC_FNC_MIN:      $calc_fnc = S_MIN_SMALL;        break;
			case CALC_FNC_MAX:      $calc_fnc = S_MAX_SMALL;        break;
			case CALC_FNC_LST:		$calc_fnc = S_LST_SMALL;		break;
			case CALC_FNC_AVG:
			default:		$calc_fnc = S_AVG_SMALL;        break;
		}
	return $calc_fnc;
	}
	
	function get_graph_by_gitemid($gitemid){
		$db_graphs = DBselect('SELECT distinct g.* '.
						' FROM graphs g, graphs_items gi '.
						' WHERE g.graphid=gi.graphid '.
							' AND gi.gitemid='.$gitemid);
			
	return DBfetch($db_graphs);
	}

	function get_graphs_by_hostid($hostid){
		return DBselect('SELECT distinct g.* '.
						' FROM graphs g, graphs_items gi, items i '.
						' WHERE g.graphid=gi.graphid '.
							' AND gi.itemid=i.itemid '.
							' AND i.hostid='.$hostid);
	}

	function get_realhosts_by_graphid($graphid){
		$graph = get_graph_by_graphid($graphid);
		if($graph["templateid"] != 0)
			return get_realhosts_by_graphid($graph["templateid"]);

	return get_hosts_by_graphid($graphid);
	}

	function get_hosts_by_graphid($graphid){	
		return DBselect('SELECT distinct h.* '.
							' FROM graphs_items gi, items i, hosts h'.
							' WHERE h.hostid=i.hostid '.
								' AND gi.itemid=i.itemid '.
								' AND gi.graphid='.$graphid);
	}

	function get_graphitems_by_graphid($graphid){
		return DBselect('SELECT * '.
					' FROM graphs_items '.
					' WHERE graphid='.$graphid.
					' ORDER BY itemid,drawtype,sortorder,color,yaxisside'); 
	}

/*
 * Function: graph_accessible
 *
 * Description:
 *     Checks if graph is accessible to USER
 *
 * Author:
 *     Aly
 *
 */		
	function graph_accessible($graphid){
		global $USER_DETAILS;
		$available_hosts = get_accessible_hosts_by_user($USER_DETAILS, PERM_READ_ONLY, PERM_RES_IDS_ARRAY);
		
		$sql = 	'SELECT g.graphid '.
				' FROM graphs g, graphs_items gi, items i '.
				' WHERE g.graphid='.$graphid.
					' AND g.graphid=gi.graphid '.
					' AND i.itemid=gi.itemid '.
					' AND '.DBcondition('i.hostid',$available_hosts,true);

		if(DBfetch(DBselect($sql,1))){
			return false;
		}
	return true;
	}


/*
 * Function: get_accessible_graphs_by_host
 *
 * Description:
 *     returns string of accessible graphid's
 *
 * Author:
 *     Aly
 *
 */		
	function get_accessible_graphs($perm,$perm_res=null,$nodeid=null,$hostid=null,$cache=1){
		global $USER_DETAILS;
		static $available_graphs;
		
		if(is_null($perm_res)) $perm_res = PERM_RES_STRING_LINE;
		$nodeid_str =(is_array($nodeid))?implode('',$nodeid):strval($nodeid);
		$hostid_str =(is_array($hostid))?implode('',$hostid):strval($hostid);
		
		if($cache && isset($available_graphs[$perm][$perm_res][$nodeid_str][$hostid_str])){
			return $available_graphs[$perm][$perm_res][$nodeid_str][$hostid_str];
		}
		
		$available_hosts = get_accessible_hosts_by_user($USER_DETAILS, $perm, PERM_RES_IDS_ARRAY, $nodeid);

		$denied_graphs = array();
		$result = array();
		
		$sql = 	'SELECT DISTINCT g.graphid '.
				' FROM graphs g, graphs_items gi, items i '.
				' WHERE g.graphid=gi.graphid '.
					(!empty($hostid)?' AND i.hostid='.$hostid:'').
					' AND i.itemid=gi.itemid '.
					' AND '.DBcondition('i.hostid',$available_hosts, true);

		$db_graphs = DBselect($sql);
		while($graph = DBfetch($db_graphs)){
			$denied_graphs[] = $graph['graphid'];
		}

		$sql = 	'SELECT DISTINCT g.graphid '.
				' FROM graphs g, graphs_items gi, items i '.
				' WHERE g.graphid=gi.graphid '.
					(!empty($hostid)?' AND i.hostid='.$hostid:'').
					' AND i.itemid=gi.itemid '.
					' AND i.status='.ITEM_STATUS_ACTIVE.
					(!empty($denied_graphs)?' AND g.graphid NOT IN ('.implode(',',$denied_graphs).')':'');

		$db_graphs = DBselect($sql);
		while($graph = DBfetch($db_graphs)){
			$result[$graph['graphid']] = $graph['graphid'];
		}
		
		if(PERM_RES_STRING_LINE == $perm_res){
			if(count($result) == 0) 
				$result = '-1';
			else
				$result = implode(',',$result);
		}

		$available_graphs[$perm][$perm_res][$nodeid_str][$hostid_str] = $result;

	return $result;
	}

/*
 * Function: get_min_itemclock_by_graphid
 *
 * Description:
 *     Return the time of the 1st apearance of items included in graph in trends
 *
 * Author:
 *     Aly
 *
 */	
	function get_min_itemclock_by_graphid($graphid){
		$min = 0;
		$row = DBfetch(DBselect('SELECT MIN(t.clock) as clock '.
						' FROM graphs_items gi, trends t '.
						' WHERE gi.graphid='.$graphid.
						  ' AND t.itemid = gi.itemid')); 
						  
		if(!empty($row) && $row && $row['clock']) 
			$min = $row['clock'];

		$row = DBfetch(DBselect('SELECT MIN(t.clock) as clock '.
						' FROM graphs_items gi, trends_uint t '.
						' WHERE gi.graphid='.$graphid.
						  ' AND t.itemid = gi.itemid')); 
						  
		if(!empty($row) && $row && $row['clock']) 
			$min = $min == 0 ? $row['clock'] : min($min, $row['clock']);

	return $min;
	}

/*
 * Function: get_min_itemclock_by_itemid
 *
 * Description:
 *     Return the time of the 1st apearance of item in trends
 *
 * Author:
 *     Aly
 *
 */	
	function get_min_itemclock_by_itemid($itemid){
		$min = 0;
		$row = DBfetch(DBselect('SELECT MIN(t.clock) as clock '.
						' FROM trends t '.
						' WHERE t.itemid='.$itemid)); 
						  
		if(!empty($row) && $row && $row['clock']) 
			$min = $row['clock'];

		$row = DBfetch(DBselect('SELECT MIN(t.clock) as clock '.
						' FROM trends_uint t '.
						' WHERE t.itemid='.$itemid)); 
						  
		if(!empty($row) && $row && $row['clock']) 
			$min = $min == 0 ? $row['clock'] : min($min, $row['clock']);

	return $min;
	}
	
// Show History Graph
	function show_history($itemid,$from,$stime,$period){
		$till=date(S_DATE_FORMAT_YMDHMS,time(NULL)-$from*3600);   
		
		show_table_header(S_TILL.SPACE.$till.' ( '.zbx_date2age($stime,$stime+$period).' )');

		$td = new CCol(get_js_sizeable_graph('graph','chart.php?itemid='.$itemid.
				url_param($from,false,'from').
				url_param($stime,false,'stime').
				url_param($period,false,'period')));
		$td->AddOption('align','center');
		
		$tr = new CRow($td);
		$tr->AddOption('bgcolor','#dddddd');
		
		$table = new CTable();
		$table->AddOption('width','100%');
		$table->AddOption('bgcolor','#cccccc');
		$table->AddOption('cellspacing','1');
		$table->AddOption('cellpadding','3');
		
		$table->AddRow($tr);
		
		$table->Show();
		echo SBR;
	}

	function get_graphitem_by_gitemid($gitemid){
		$result=DBselect("SELECT * FROM graphs_items WHERE gitemid=$gitemid");
		$row=DBfetch($result);
		if($row){
			return	$row;
		}
		error("No graph item with gitemid=[$gitemid]");
		
	return	$result;
	}

	function get_graphitem_by_itemid($itemid){
		$result = DBfetch(DBselect('SELECT * FROM graphs_items WHERE itemid='.$itemid));
		$row=DBfetch($result);
		if($row)
		{
			return	$row;
		}
		return	$result;
	}

	function get_graph_by_graphid($graphid){

		$result=DBselect("SELECT * FROM graphs WHERE graphid=$graphid");
		$row=DBfetch($result);
		if($row){
			return	$row;
		}
		error("No graph with graphid=[$graphid]");
		return	false;
	}

	function	get_graphs_by_templateid($templateids){
		zbx_value2array($templateids);
	return DBselect('SELECT * FROM graphs WHERE '.DBcondition('templateid',$templateids));
	}

/*
 * Function: get_same_graphitems_for_host
 *
 * Description:
 *     Replace items for specified host
 *
 * Author:
 *     Eugene Grigorjev 
 *
 * Comments: !!! Don't forget sync code with C !!!
 * Only PHP:
 *		$error= true : rise Error if item doesn't exists(error generated), false: special processing (NO error generated)
 */
	function	get_same_graphitems_for_host($gitems, $dest_hostid, $error=true)
	{
		$result = array();

		foreach($gitems as $gitem)
		{
			$sql = 'SELECT src.itemid '.
							' FROM items src, items dest '.
							' WHERE dest.itemid='.zbx_dbstr($gitem['itemid']).
								' AND src.key_=dest.key_ '.
								' AND src.hostid='.$dest_hostid;
			$db_item = DBfetch(DBselect($sql));
			if (!$db_item && $error){
				$item = get_item_by_itemid($gitem['itemid']);
				$host = get_host_by_hostid($dest_hostid);
				error('Missed key "'.$item['key_'].'" for host "'.$host['host'].'"');
				return false;
			}
			else if(!$db_item){
				continue;
//				$gitem['itemid'] = 0;
			}
			else{
				$gitem['itemid'] = $db_item['itemid'];
			}

			$result[] = $gitem;
		}

		return $result;
	}
	
        /*
         * Function: add_graph
         *
         * Description:
         *     Add graph without items and recursion for templates
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	add_graph($name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d,$templateid=0)
	{
		$graphid = get_dbid("graphs","graphid");

		$result=DBexecute("insert into graphs".
			" (graphid,name,width,height,yaxistype,yaxismin,yaxismax,templateid,show_work_period,show_triggers,graphtype,show_legend,show_3d)".
			" values ($graphid,".zbx_dbstr($name).",$width,$height,$yaxistype,$yaxismin,".
			" $yaxismax,$templateid,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d)");

		return ( $result ? $graphid : $result);
	}

        /*
         * Function: add_graph_with_items
         *
         * Description:
         *     Add graph with items and recursion for templates
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	add_graph_with_items($name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d,$gitems=array(),$templateid=0)
	{
		$result = false;

		if ( !is_array($gitems) || count($gitems) < 1 )
		{
			error('Missed items for graph "'.$name.'"');
			return $result;
		}

		/* check items for template graph */
		unset($new_host_is_template);
		$host_list = array();
		$itemid = array(0);

		foreach($gitems as $gitem)
			$itemid[] = $gitem['itemid'];

		$db_item_hosts = DBselect('select distinct h.hostid,h.host,h.status '.
				' from items i, hosts h where h.hostid=i.hostid and i.itemid in ('.implode(',', $itemid).')');
		while($db_item_host = DBfetch($db_item_hosts))
		{
			$host_list[] = '"'.$db_item_host['host'].'"';

			if ( HOST_STATUS_TEMPLATE ==  $db_item_host['status'] )
				$new_host_is_template = true;
		}

		if ( isset($new_host_is_template) && count($host_list) > 1 )
		{
			error('Graph "'.$name.'" with template host can not contain items from other hosts.');
			return $result;
		}

		if ( ($graphid = add_graph($name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d,$templateid)) )
		{
			$result = true;
			foreach($gitems as $gitem)
			{
				if ( ! ($result = add_item_to_graph(
					$graphid,
					$gitem['itemid'],
					$gitem['color'],
					$gitem['drawtype'],
					$gitem['sortorder'],
					$gitem['yaxisside'],
					$gitem['calc_fnc'],
					$gitem['type'],
					$gitem['periods_cnt'])) )
				{
					break;
				}
			}
		}

		if ( $result ){
			info('Graph "'.$name.'" added to hosts '.implode(',',$host_list));

			/* add graphs for child hosts */
			$tmp_hosts = get_hosts_by_graphid($graphid);
			$host = DBfetch($tmp_hosts);

			$chd_hosts = get_hosts_by_templateid($host['hostid']);
			while($chd_host = DBfetch($chd_hosts)){
				copy_graph_to_host($graphid, $chd_host['hostid'], false);
			}
		}

		if ( !$result && $graphid ){
			delete_graph($graphid);
			$graphid = false;
		}

	return $graphid;
	}

        /*
         * Function: update_graph
         *
         * Description:
         *     Update graph without items and recursion for template
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	update_graph($graphid,$name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d,$templateid=0)
	{
		$g_graph = get_graph_by_graphid($graphid);

		if ( ($result = DBexecute(
				'UPDATE graphs '.
				'SET name='.zbx_dbstr($name).',width='.$width.',height='.$height.
					',yaxistype='.$yaxistype.',yaxismin='.$yaxismin.',yaxismax='.$yaxismax.',templateid='.$templateid.
					',show_work_period='.$showworkperiod.',show_triggers='.$showtriggers.',graphtype='.$graphtype.
					',show_legend='.$legend.',show_3d='.$graph3d.
				' WHERE graphid='.$graphid)) )
		{
			if($g_graph['graphtype'] != $graphtype && $graphtype == GRAPH_TYPE_STACKED)
			{
				$result = DBexecute('UPDATE graphs_items SET calc_fnc='.CALC_FNC_AVG.',drawtype=1,type='.GRAPH_ITEM_SIMPLE.
					' WHERE graphid='.$graphid);
			}
		}
		return $result;
	}
	
        /*
         * Function: update_graph_with_items
         *
         * Description:
         *     Update graph with items and recursion for template
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	update_graph_with_items($graphid,$name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,$showtriggers,$graphtype,$legend,$graph3d,$gitems=array(),$templateid=0)
	{
		$result = false;

		if ( !is_array($gitems) || count($gitems) < 1 )
		{
			error('Missed items for graph "'.$name.'"');
			return $result;
		}

		/* check items for template graph */
		$tmp_hosts = get_hosts_by_graphid($graphid);
		$host = DBfetch($tmp_hosts);
		if ( $host["status"] == HOST_STATUS_TEMPLATE ){
			unset($new_hostid);
			$itemid = array(0);

			foreach($gitems as $gitem)
				$itemid[] = $gitem['itemid'];

			$db_item_hosts = DBselect('select distinct hostid from items where itemid in ('.implode(',', $itemid).')');
			while($db_item = DBfetch($db_item_hosts))
			{
				if ( isset($new_hostid) )
				{
					error('Can not use multiple host items for template graph "'.$name.'"');
					return $result;
				}

				$new_hostid = $db_item['hostid'];
			}

			if ( (bccomp($host['hostid'] ,$new_hostid ) != 0))
			{
				error('You must use items only from host "'.$host['host'].'" for template graph "'.$name.'"');
				return $result;
			}
		}

		/* firstly update child graphs */
		$chd_graphs = get_graphs_by_templateid($graphid);
		while($chd_graph = DBfetch($chd_graphs))
		{
			$tmp_hosts = get_hosts_by_graphid($chd_graph['graphid']);
			$chd_host = DBfetch($tmp_hosts);
			if ( !($new_gitems = get_same_graphitems_for_host($gitems, $chd_host['hostid'])) )
			{ /* skip host with missed items */
				error('Can not update graph "'.$name.'" for host "'.$chd_host['host'].'"');
				return $result;
			}
		
			if ( ! ($result = update_graph_with_items($chd_graph['graphid'], $name, $width, $height,
				$yaxistype, $yaxismin, $yaxismax,
				$showworkperiod, $showtriggers, $graphtype, $legend, $graph3d, $new_gitems, $graphid)) )
			{
				return $result;
			}
		}

		DBexecute('delete from graphs_items where graphid='.$graphid);

		foreach($gitems as $gitem){
			if ( ! ($result = add_item_to_graph(
					$graphid,
					$gitem['itemid'],
					$gitem['color'],
					$gitem['drawtype'],
					$gitem['sortorder'],
					$gitem['yaxisside'],
					$gitem['calc_fnc'],
					$gitem['type'],
					$gitem['periods_cnt'])) )
			{
				return $result;
			}
		}

		if ($result = update_graph($graphid,$name,$width,$height,$yaxistype,$yaxismin,$yaxismax,$showworkperiod,
						$showtriggers,$graphtype,$legend,$graph3d,$templateid))
		{
			$host_list = array();
			$db_hosts = get_hosts_by_graphid($graphid);
			while($db_host = DBfetch($db_hosts)){
				$host_list[] = '"'.$db_host["host"].'"';
			}

			info('Graph "'.$name.'" updated for hosts '.implode(',',$host_list));
		}

		return $result;
	}
	
        /*
         * Function: delete_graph
         *
         * Description:
         *     De;ete graph with templates
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function delete_graph($graphids){
		zbx_value2array($graphids);
		
		$result = true;
		
		$graphs = array();
		$host_lists = array();
		foreach($graphids as $id => $graphid){
			$graphs[] = get_graph_by_graphid($graphid);
	
			$host_list[$graphid] = array();
			$db_hosts = get_hosts_by_graphid($graphid);
			while($db_host = DBfetch($db_hosts)){
				$host_list[$graphid] = '"'.$db_host['host'].'"';
			}
		}		
// firstly remove child graphs 
		$del_chd_graphs = array();
		$chd_graphs = get_graphs_by_templateid($graphids);
		while($chd_graph = DBfetch($chd_graphs)){ /* recursion */
			$del_chd_graphs[$chd_graph['graphid']] = $chd_graph['graphid'];
		}
		if(!empty($del_chd_graphs)){
			$result &= delete_graph($del_chd_graphs);
		}
		
		$result &= DBexecute('DELETE FROM screens_items WHERE '.DBcondition('resourceid',$graphids).' AND resourcetype='.SCREEN_RESOURCE_GRAPH);

		/* delete graph */
		$result &= DBexecute('DELETE FROM graphs_items WHERE '.DBcondition('graphid',$graphids));
		$result &= DBexecute('DELETE FROM graphs WHERE '.DBcondition('graphid',$graphids));
		$result &= DBexecute("DELETE FROM profiles WHERE idx='web.favorite.graphids' AND source='graphid' AND ".DBcondition('value_id',$graphids));
		
		if($result){
			foreach($graphs as $graphid => $graph){
				if(isset($host_list[$graphid]))
					info('Graph "'.$graph['name'].'" deleted from hosts '.implode(',',$host_list[$graphid]));
			}
		}

	return $result;
	}

        /*
         * Function: cmp_graphitems
         *
         * Description:
         *     Compare two graph items
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	cmp_graphitems(&$gitem1, &$gitem2)
	{
		if($gitem1["drawtype"]	!= $gitem2["drawtype"])		return 1;
		if($gitem1["sortorder"] != $gitem2["sortorder"])	return 2;
		if($gitem1["color"]	!= $gitem2["color"])		return 3;
		if($gitem1["yaxisside"] != $gitem2["yaxisside"])	return 4;

		$item1 = get_item_by_itemid($gitem1["itemid"]);
		$item2 = get_item_by_itemid($gitem2["itemid"]);

		if($item1["key_"] != $item2["key_"])			return 5;

		return 0;
	}

        /*
         * Function: add_item_to_graph
         *
         * Description:
         *     Add item to graph
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	add_item_to_graph($graphid,$itemid,$color,$drawtype,$sortorder,$yaxisside,$calc_fnc,$type,$periods_cnt)
	{
		$gitemid = get_dbid('graphs_items','gitemid');

		$result = DBexecute('insert into graphs_items'.
			' (gitemid,graphid,itemid,color,drawtype,sortorder,yaxisside,calc_fnc,type,periods_cnt)'.
			' values ('.$gitemid.','.$graphid.','.$itemid.','.zbx_dbstr($color).','.$drawtype.','.
			$sortorder.','.$yaxisside.','.$calc_fnc.','.$type.','.$periods_cnt.')');

		return ( $result ? $gitemid : $result );
	}
	
/*
 * Function: delete_template_graphs
 *
 * Description:
 *     Delete template graph from specified host
 *
 * Author:
 *     Eugene Grigorjev 
 *
 * Comments: !!! Don't forget sync code with C !!!
 *
 */
	function delete_template_graphs($hostid, $templateids = null /* array format 'arr[id]=name' */, $unlink_mode = false){
		zbx_value2array($templateids);
		
		$db_graphs = get_graphs_by_hostid($hostid);
		while($db_graph = DBfetch($db_graphs)){
			if($db_graph['templateid'] == 0)
				continue;

			if(!is_null($templateids)){
				$tmp_hhosts = get_hosts_by_graphid($db_graph['templateid']);
				$tmp_host = DBfetch($tmp_hhosts);

				if( !uint_in_array($tmp_host['hostid'], $templateids)) continue;
			}

			if($unlink_mode){
				if(DBexecute('UPDATE graphs SET templateid=0 WHERE graphid='.$db_graph['graphid'])){
					info('Graph "'.$db_graph['name'].'" unlinked');
				}	
			}
			else{
				delete_graph($db_graph['graphid']);
			}
		}
	}
	
        /*
         * Function: copy_template_graphs
         *
         * Description:
         *     Copy all graphs to the specified host
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function	copy_template_graphs($hostid, $templateid = null /* array format 'arr[id]=name' */, $copy_mode = false)
	{
		if($templateid == null)
		{
			$templateid = get_templates_by_hostid($hostid);
		}
		
		if(is_array($templateid))
		{
			foreach($templateid as $id => $name)
				copy_template_graphs($hostid, $id, $copy_mode); // attention recursion
			return;
		}

		$db_graphs = get_graphs_by_hostid($templateid);

		while($db_graph = DBfetch($db_graphs)){
			copy_graph_to_host($db_graph["graphid"], $hostid, $copy_mode);
		}
	}

        /*
         * Function: copy_graph_to_host
         *
         * Description:
         *     Copy specified graph to the specified host
         *
         * Author:
         *     Eugene Grigorjev 
         *
         * Comments: !!! Don't forget sync code with C !!!
         *
         */
	function copy_graph_to_host($graphid, $hostid, $copy_mode = false){
		$result = false;

		$gitems = array();

		$db_graph_items = get_graphitems_by_graphid($graphid);
		while( $db_gitem = DBfetch($db_graph_items) ){
			$gitems[] = array(
				'itemid'	=> $db_gitem['itemid'],
				'color'		=> $db_gitem['color'],
				'drawtype'	=> $db_gitem['drawtype'],
				'sortorder'	=> $db_gitem['sortorder'],
				'yaxisside'	=> $db_gitem['yaxisside'],
				'calc_fnc'	=> $db_gitem['calc_fnc'],
				'type'		=> $db_gitem['type'],
				'periods_cnt'	=> $db_gitem['periods_cnt']
				);
		}

		$db_graph = get_graph_by_graphid($graphid);

		if ( ($new_gitems = get_same_graphitems_for_host($gitems, $hostid)) ){
			unset($chd_graphid);
			
			$chd_graphs = get_graphs_by_hostid($hostid);
			while( !isset($chd_graphid) && $chd_graph = DBfetch($chd_graphs)){ 
/* compare graphs */
				if ( $chd_graph['templateid'] != 0 ) continue;

				unset($equal);
				$chd_gitems = get_graphitems_by_graphid($chd_graph["graphid"]);
				while($chd_gitem = DBfetch($chd_gitems)){
					unset($gitem_equal);
					
					foreach($new_gitems as $new_gitem){
						if(cmp_graphitems($new_gitem, $chd_gitem))	continue;

						$gitem_equal = true;
						break;
					}

					if(!isset($gitem_equal)){
						unset($equal);
						break;
					}

					/* founded equal graph item */
					if(!isset($equal))$equal = 0;

					$equal++;
				}

				if(isset($equal) && (count($new_gitems) == $equal)){ 
/* founded equal graph */
					$chd_graphid = $chd_graph["graphid"];
					break;
				}
			}

			if(isset($chd_graphid)){
				$result = update_graph_with_items($chd_graphid, $db_graph['name'], $db_graph['width'], $db_graph['height'],
					$db_graph['yaxistype'], $db_graph['yaxismin'], $db_graph['yaxismax'],
					$db_graph['show_work_period'], $db_graph['show_triggers'], $db_graph['graphtype'],
					$db_graph['show_legend'], $db_graph['show_3d'], $new_gitems, ($copy_mode ? 0: $db_graph['graphid']));
			}
			else{
				$result = add_graph_with_items($db_graph['name'], $db_graph['width'], $db_graph['height'],
					$db_graph['yaxistype'], $db_graph['yaxismin'], $db_graph['yaxismax'],
					$db_graph['show_work_period'], $db_graph['show_triggers'], $db_graph['graphtype'],
					$db_graph['show_legend'], $db_graph['show_3d'], $new_gitems, ($copy_mode ? 0: $db_graph['graphid']));
			}
		}
		else{
			$host = get_host_by_hostid($hostid);
			info('Skipped coping of graph "'.$db_graph["name"].'" to host "'.$host['host'].'"');
		}

	return $result;
	}

	function navigation_bar_calc(){
		if(!isset($_REQUEST["period"]))	$_REQUEST["period"]=ZBX_PERIOD_DEFAULT;
		if(!isset($_REQUEST["from"]))	$_REQUEST["from"]=0;
		if(!isset($_REQUEST["stime"]))	$_REQUEST["stime"]=null;

		if($_REQUEST['period']<ZBX_MIN_PERIOD){
			show_message(S_WARNING.'. '.S_TIME_PERIOD.SPACE.S_MIN_VALUE_SMALL.': '.ZBX_MIN_PERIOD.' ('.(int)(ZBX_MIN_PERIOD/3600).'h)');
			$_REQUEST['period'] = ZBX_MIN_PERIOD;
			
		}
		else if($_REQUEST['period'] > ZBX_MAX_PERIOD){
			show_message(S_WARNING.'. '.S_TIME_PERIOD.SPACE.S_MAX_VALUE_SMALL.': '.ZBX_MAX_PERIOD.' ('.(int)(ZBX_MAX_PERIOD/86400).'d)');
			$_REQUEST['period'] = ZBX_MAX_PERIOD;			
		}

		if(isset($_REQUEST["stime"])){
			$bstime = $_REQUEST['stime'];
			$time = mktime(substr($bstime,8,2),substr($bstime,10,2),0,substr($bstime,4,2),substr($bstime,6,2),substr($bstime,0,4));
			if(($time+$_REQUEST['period']) > time()) unset($_REQUEST['stime']);
		}
		
	return $_REQUEST["period"];
	}

	function navigation_bar($url,$ext_saved_request=NULL){
		$saved_request = array("screenid","itemid","action","from","fullscreen");

		if(is_array($ext_saved_request))
			$saved_request = array_merge($saved_request, $ext_saved_request);
		elseif(is_string($ext_saved_request))
			array_push($saved_request,$ext_saved_request);

		$form = new CForm($url);
		$form->SetMethod('get');	
		
		$form->AddItem(S_PERIOD.SPACE);

		$period = get_request('period',ZBX_PERIOD_DEFAULT);

		if(uint_in_array($period,array(3600,2*3600,4*3600,8*3600,12*3600,24*3600,7*24*3600,31*24*3600,365*24*3600)))
			$custom_per = ZBX_MIN_PERIOD;
		else
			$custom_per = $period;

		$cmbPeriod = new CComboBox("period",$period,"submit()");
		$cmbPeriod->AddItem($custom_per,"custom");
		$cmbPeriod->AddItem(3600,"1h");
		$cmbPeriod->AddItem(2*3600,"2h");
		$cmbPeriod->AddItem(4*3600,"4h");
		$cmbPeriod->AddItem(8*3600,"8h");
		$cmbPeriod->AddItem(12*3600,"12h");
		$cmbPeriod->AddItem(24*3600,"24h");
		$cmbPeriod->AddItem(7*24*3600,"week");
		$cmbPeriod->AddItem(31*24*3600,"month");
		$cmbPeriod->AddItem(365*24*3600,"year");
		$form->AddItem($cmbPeriod);

		$cmbDec = new CComboBox("dec",0,"submit()");
		$cmbDec->AddItem(0,S_DECREASE);
		$cmbDec->AddItem(3600,"-1h");
		$cmbDec->AddItem(4*3600,"-4h");
		$cmbDec->AddItem(24*3600,"-24h");
		$cmbDec->AddItem(7*24*3600,"-week");
		$cmbDec->AddItem(31*24*3600,"-month");
		$cmbDec->AddItem(365*24*3600,"-year");
		$form->AddItem($cmbDec);

		$cmbInc = new CComboBox("inc",0,"submit()");
		$cmbInc->AddItem(0,S_INCREASE);
		$cmbInc->AddItem(3600,"+1h");
		$cmbInc->AddItem(4*3600,"+4h");
		$cmbInc->AddItem(24*3600,"+24h");
		$cmbInc->AddItem(7*24*3600,"+week");
		$cmbInc->AddItem(31*24*3600,"+month");
		$cmbInc->AddItem(365*24*3600,"+year");
		$form->AddItem($cmbInc);

		$form->AddItem(SPACE.S_MOVE.SPACE);

		$cmbLeft = new CComboBox("left",0,"submit()");
		$cmbLeft->AddItem(0,S_LEFT_DIR);
		$cmbLeft->AddItem(1,"-1h");
		$cmbLeft->AddItem(4,"-4h");
		$cmbLeft->AddItem(24,"-24h");
		$cmbLeft->AddItem(7*24,"-week");
		$cmbLeft->AddItem(31*24,"-month");
		$cmbLeft->AddItem(365*24,"-year");
		$form->AddItem($cmbLeft);

		$cmbRight = new CComboBox("right",0,"submit()");
		$cmbRight->AddItem(0,S_RIGHT_DIR);
		$cmbRight->AddItem(1,"+1h");
		$cmbRight->AddItem(4,"+4h");
		$cmbRight->AddItem(24,"+24h");
		$cmbRight->AddItem(7*24,"+week");
		$cmbRight->AddItem(31*24,"+month");
		$cmbRight->AddItem(365*24,"+year");
		$form->AddItem($cmbRight);

		$form->AddItem(array(SPACE,
			new CTextBox("stime","yyyymmddhhmm",12),SPACE,
			new CButton("action","go"),
			new CButton("reset","reset")));

		foreach($saved_request as $item)
			if(isset($_REQUEST[$item]))
				$form->AddVar($item,$_REQUEST[$item]);

		show_table_header(
			S_NAVIGATE,
			$form);

		return;
	}
	
	/*
	 * Function: 
	 *		make_array_from_gitems
	 *
	 * Description:
	 *     Creates array with items params for preapare_url function
	 *
	 * Author:
	 *     Aly
	 *
	 * Comments
	 *	
	 */	
	function make_url_from_gitems($gitems){

		$gurl=array();
		$ifields = array(
						'itemid'	=> 1,
						'drawtype'	=> 1,
						'sortorder'	=> 1,
						'color'		=> 1,
						'yaxisside'	=> 1,
						'calc_fnc'	=> 1,
						'type'		=> 1,
						'periods_cnt'=>1
					);

		foreach($gitems as $gitem){
			foreach($gitem as $name => $value){
				if(isset($ifields[$name])){
					$gurl['items['.$gitem['itemid'].']['.$name.']']=$value;
				}
			}
		}
		
	return prepare_url($gurl);
	}
	
	/*
	 * Function: 
	 *		make_array_from_graphid
	 *
	 * Description:
	 *     Creates array with graph params for preapare_url function
	 *
	 * Author:
	 *     Aly
	 *
	 * Comments
	 *	$full= false: for screens(WITHOUT width && height), true=all params
	 */	
	function make_url_from_graphid($graphid,$full=false){

		$gurl=array();
		if($full){
			$gparams = array();
		}
		else{
			$gparams = array(
						'height'=> 1,
						'width'	=> 1
					);
		}
		
		$graph=get_graph_by_graphid($graphid);
		if($graph){
			foreach($graph as $name => $value){
				if(!is_numeric($name) && !isset($gparams[$name])) $gurl[$name]=$value;
			}
		}

		$url = prepare_url($gurl);
		if(!empty($url)){
			$url=((($gurl['graphtype']==GRAPH_TYPE_PIE) || ($gurl['graphtype']==GRAPH_TYPE_EXPLODED))?'chart7.php?':'chart3.php?').trim($url,'&');
		}
	return $url;
	}
?>