forked from Cacti/plugin_gexport
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
1811 lines (1467 loc) · 62.1 KB
/
functions.php
File metadata and controls
1811 lines (1467 loc) · 62.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 (C) 2004-2017 The Cacti Group |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
function gexport_calc_next_start($export, $start_time = 0) {
if ($start_time == 0) $start_time = time();
$poller_interval = read_config_option('poller_interval');
if ($export['export_timing'] == 'periodic') {
$now = date('Y-m-d H:i:00', time());
$next_run = strtotime($now) + $export['export_skip'] * $poller_interval;
$next_start = date('Y-m-d H:i:s', $next_run);
}else{
switch($export['export_timing']) {
case 'hourly':
$next_start = date('Y-m-d H:' . $export['export_hourly'] . ':00', $start_time);
$now_time = strtotime(date('Y-m-d H:i:00', $start_time));
$next_run = strtotime($next_start);
if ($next_run <= $now_time) {
$next_run += 3600;
}
$next_start = date('Y-m-d H:i:00', $next_run);
break;
case 'daily':
$next_start = date('Y-m-d ' . $export['export_daily'] . ':00', $start_time);
$now_time = strtotime(date('Y-m-d H:i:00', $start_time));
$next_run = strtotime($next_start);
if ($next_run <= $now_time) {
$next_run += 86400;
}
$next_start = date('Y-m-d H:i:00', $next_run);
break;
}
}
return $next_start;
}
/* graph_export - a function that determines, for each export definition
if it's time to run or not. this function is currently single threaded
and some thought should be given to making multi-threaded.
@arg $id - the id of the export to check, '0' for all export definitions.
@arg $force - force the export to run no regardless of it's timing settings. */
function graph_export($id = 0, $force = false) {
global $debug, $start;
/* take time to log performance data */
$start = microtime(true);
$start_time = time();
$poller_interval = read_config_option('poller_interval');
$runnow = false;
$sql_where = '';
$started_exports = 0;
if ($force) {
export_debug('This is a forced run');
}
/* force run */
if ($id > 0) {
$sql_where = ' AND id=' . $id;
}
$exports = db_fetch_assoc('SELECT *
FROM graph_exports
WHERE enabled="on"' . $sql_where);
if (sizeof($exports)) {
foreach($exports as $export) {
export_debug("Checking export '" . $export['name'] . "' to determine if it's time to run.");
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_checked = NOW()
WHERE id = ?',
array($export['id']));
$runnow = false;
if (!$force) {
if (strtotime($export['next_start']) < $start_time) {
$runnow = true;
$next_start = gexport_calc_next_start($export);
db_execute_prepared('UPDATE graph_exports
SET next_start = ? WHERE id = ?',
array($next_start, $export['id']));
}
}else{
$runnow = true;
}
if ($runnow) {
$started_exports++;
export_debug('Running Export for id ' . $export['id']);
run_export($export);
}
}
}
$end = microtime(true);
$export_stats = sprintf('Time:%01.2f Exports:%s Exported:%s', $end - $start, sizeof($exports), $started_exports);
cacti_log('MASTER STATS: ' . $export_stats, true, 'EXPORT');
}
/* run_export - a function the pre-processes the export structure and
then executes the required functions to export graphs, html and
config, to sanitize directories, and transfer data to the remote
host(s).
@arg $export - the export item structure. */
function run_export(&$export) {
global $config, $export_path;
$exported = 0;
if (!empty($export['export_pid'])) {
cacti_log('WARNING: Previous run of the following Graph Export ended in an unclean state Export:' . $export['name']);
if (posix_kill($export['export_pid'], 0) !== false) {
cacti_log('WARNING: Can not start the following Graph Export:' . $export['name'] . ' is still running');
return;
}
}
db_execute_prepared('UPDATE graph_exports
SET export_pid = ?, status = 1, last_started=NOW()
WHERE id = ?',
array(getmypid(), $export['id']));
switch ($export['export_type']) {
case 'local':
export_debug("Export Type is 'local'");
$export_path = $export['export_directory'];
$exported = exporter($export, $export_path);
break;
case 'sftp':
export_debug("Export Type is 'sftp_php'");
if (!function_exists('ftp_ssl_connect')) {
export_fatal($export, 'Secure FTP Function does not exist. Export can not continue.');
}
case 'ftp':
export_debug("Export Type is 'ftp'");
/* set the temp directory */
if (strlen($export['export_temp_directory']) == 0) {
$stExportDir = getenv('TEMP') . '/cacti-ftp-temp-' . $export['id'];
}else{
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-ftp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_pre_ftp_upload($export, $stExportDir);
export_log('Using PHP built-in FTP functions.');
export_ftp_php_execute($export, $stExportDir);
export_post_ftp_upload($export, $stExportDir);
break;
case 'ftp_nc':
export_debug("Export Type is 'ftp_nc'");
if (strstr(PHP_OS, 'WIN')) export_fatal($export, 'ncftpput only available in unix environment! Export can not continue.');
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-ftp-temp-' . $export['id'];
}else{
$stExportDir = '/tmp/cacti-ftp-temp-' . $export['id'];
}
}else{
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-ftp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_pre_ftp_upload($export, $stExportDir);
export_log('Using ncftpput.');
export_ftp_ncftpput_execute($export, $stExportDir);
export_post_ftp_upload($export, $stExportDir);
break;
case 'rsync':
export_debug("Export Type is 'rsync'");
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-rsync-temp-' . $export['id'];
}else{
$stExportDir = '/tmp/cacti-rsync-temp-' . $export['id'];
}
}else{
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\t") . '/cacti-rsync-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_rsync_execute($export, $stExportDir);
break;
case 'scp':
export_debug("Export Type is 'scp'");
/* set the temp directory */
if (trim($export['export_temp_directory']) == '') {
if ($config['cacti_server_os'] == 'win32') {
$stExportDir = getenv('TEMP') . '/cacti-scp-temp-' . $export['id'];
}else{
$stExportDir = '/tmp/cacti-scp-temp-' . $export['id'];
}
}else{
$stExportDir = rtrim($export['export_temp_directory'], "/ \n\r") . '/cacti-scp-temp-' . $export['id'];
}
$exported = exporter($export, $stExportDir);
export_scp_execute($export, $stExportDir);
break;
default:
export_fatal($export, 'Export method not specified. Exporting can not continue. Please set method properly in Cacti configuration.');
}
db_execute_prepared('UPDATE graph_exports SET export_pid = 0 WHERE id = ?', array($export['id']));
config_export_stats($export, $exported);
}
function export_rsync_execute(&$export, $stExportDir) {
$keyopt = '';
$user = $export['export_user'];
$port = $export['export_port'];
$host = $export['export_host'];
$output = '';
$prune = '';
$retvar = 0;
if ($export['export_private_key_path'] != '') {
if (file_exists($export['export_private_key_path'])) {
if (is_readable($export['export_private_key_path'])) {
$keyopt = ' -e \'ssh -i "' . $export['export_private_key_path'] . '"\'';
}else{
export_fatal($export, 'ssh Private Key file is not readable.');
}
}else{
export_fatal($export, 'ssh Private Key file does not exist.');
}
}
if (gethostbyname($host) == $host) {
export_fatal($export, "Hostname '" . $host . "' can not be resolved to an IP Address.");
}
if ($port != '') {
if (!is_numeric($port)) {
export_fatal($export, "SSH port '" . $port . "' must be numeric.");
}else{
$keyopt .= " -e 'ssh -p " . $port . "'";
}
}elseif ($keyopt != '') {
$keyopt .= " ";
}
if ($export['export_sanitize_remote'] == 'on') {
$prune = '--delete-delay --prune-empty-dirs';
}
exec('rsync -zav ' . $prune . $keyopt . ' ' . $stExportDir . '/. ' . ($user != '' ? "$user@":'') . $host . ':' . $export['export_directory'], $output, $retvar);
if ($retvar != 0) {
export_fatal($export, "RSYNC FAILED! Return Code was '$retvar' with message '" . trim($output) . "'");
}
}
function export_scp_execute(&$export, $stExportDir) {
$keyopt = '';
$user = $export['export_user'];
$port = $export['export_port'];
$host = $export['export_host'];
$output = '';
$retvar = 0;
if ($export['export_private_key_path'] != '') {
if (file_exists($export['export_private_key_path'])) {
if (is_readable($export['export_private_key_path'])) {
$keyopt = ' -i "' . $export['export_private_key_path'] . '"';
}else{
export_fatal($export, 'ssh Private Key file is not readable.');
}
}else{
export_fatal($export, 'ssh Private Key file does not exist.');
}
}
if (gethostbyname($host) == $host) {
export_fatal($export, "Hostname '" . $host . "' can not be resolved to an IP Address.");
}
if ($port != '' && !is_numeric($port)) {
export_fatal($export, "SCP port '" . $port . "' must be numeric.");
}
exec('scp -rp ' . $keyopt . ($port != '' ? ' -P ' . "$port ":"") . $stExportDir . '/. ' . ($user != '' ? "$user@":'') . $host . ':' . $export['export_directory'], $output, $retvar);
if ($retvar != 0) {
export_fatal($export, "SCP FAILED! Return Code was '$retvar' with message '" . trim(implode(',', $output)) . "'");
}
}
/* exporter - a wrapper function that reduces clutter in the run_export
function.
@arg $export - the export item structure.
@arg $export_path - the location to storage export output. */
function exporter(&$export, $export_path) {
global $config;
$root_path = $config['base_path'];
$exported = 0;
create_export_directory_structure($export, $root_path, $export_path);
$exported = export_graphs($export, $export_path);
tree_site_export($export, $export_path);
return $exported;
}
/* config_export_stats - a function to export stats to the Cacti system for information
and possible graphing. It uses a global variable to get the start time of the
export process.
@arg $export - the export item structure
@arg $exported - the number of graphs exported. */
function config_export_stats(&$export, $exported) {
global $start;
/* take time to log performance data */
$end = microtime(true);
$export_stats = sprintf(
'ExportID:%s ExportDate:%s ExportDuration:%01.2f TotalGraphsExported:%s',
$export['id'], date('Y-m-d_G:i:s'), $end - $start, $exported);
cacti_log('STATS: ' . $export_stats, true, 'EXPORT');
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_runtime = ?, total_graphs = ?, last_ended=NOW(), status=0
WHERE id = ?',
array($end - $start, $exported, $export['id']));
db_execute_prepared(sprintf("REPLACE INTO settings (name,value) values ('stats_export_%s', ?)", $export['id']), array($export_stats));
}
/* export_fatal - a simple export logging function that indicates a
fatal condition for developers and users.
@arg $export - the export item structure
@arg $stMessage - the debug message. */
function export_fatal(&$export, $stMessage) {
cacti_log('FATAL ERROR: ' . $stMessage, true, 'EXPORT');
/* insert poller stats into the settings table */
db_execute_prepared('UPDATE graph_exports
SET last_error = ?, last_ended=NOW(), last_errored=NOW(), status=2
WHERE id = ?',
array($stMessage, $export['id']));
export_debug($stMessage);
exit;
}
/* export_log - a simple export logging function that also logs to stdout
for developers.
@arg $message - the debug message. */
function export_log($stMessage) {
cacti_log($stMessage, true, 'EXPORT', POLLER_VERBOSITY_HIGH);
export_debug($stMessage);
}
/* export_debug - a common cli debug level output for developers.
@arg $message - the debug message. */
function export_debug($message) {
global $debug;
if ($debug) {
print 'MEMUSE: ' . number_format_i18n(memory_get_usage()) . ', MESSAGE: ' . rtrim($message) . "\n";
}
}
/* export_pre_ftp_upload - this function creates a global variable
of your pre-checked ftp credentials and settings that will be used
for the actual ftp transfer.
@arg $export - the export item structure */
function export_pre_ftp_upload(&$export) {
global $config, $aFtpExport;
$aFtpExport['server'] = $export['export_host'];
if (empty($aFtpExport['server'])) {
export_fatal($export, 'FTP Hostname is not expected to be blank!');
}
$aFtpExport['remotedir'] = $export['export_directory'];
if (empty($aFtpExport['remotedir'])) {
export_fatal($export, 'FTP Remote export path is not expected to be blank!');
}
$aFtpExport['port'] = $export['export_port'];
$aFtpExport['port'] = empty($aFtpExport['port']) ? '21' : $aFtpExport['port'];
$aFtpExport['username'] = $export['export_user'];
$aFtpExport['password'] = $export['export_password'];
if (empty($aFtpExport['username'])) {
$aFtpExport['username'] = 'Anonymous';
$aFtpExport['password'] = '';
export_log('Using Anonymous transfer method.');
}
if ($export['export_passive'] == 'on') {
$aFtpExport['passive'] = TRUE;
export_log('Using passive transfer method.');
}else {
$aFtpExport['passive'] = FALSE;
export_log('Using active transfer method.');
}
}
/* check_cacti_paths - this function is looking for bad export paths that
can potentially get the user in trouble. We avoid paths that can
get erased by accident.
@arg $export - the export item structure
@arg $export_path - the directory holding the export contents. */
function check_cacti_paths(&$export, $export_path) {
global $config;
$root_path = $config['base_path'];
/* check for bad directories within the cacti path */
if (strcasecmp($root_path, $export_path) < 0) {
$cacti_system_paths = array(
'include',
'lib',
'install',
'rra',
'log',
'scripts',
'plugins',
'images',
'resource');
foreach($cacti_system_paths as $cacti_system_path) {
if (substr_count(strtolower($export_path), strtolower($cacti_system_path)) > 0) {
export_fatal($export, "Export path '" . $export_path . "' is potentially within a Cacti system path '" . $cacti_system_path . "'. Can not continue.");
}
}
}
/* can not be the web root */
if ((strcasecmp($root_path, $export_path) == 0) &&
(read_config_option('export_type') == 'local')) {
export_fatal($export, "Export path '" . $export_path . "' is the Cacti web root. Can not continue.");
}
/* can not be a parent of the Cacti web root */
if (strncasecmp($root_path, $export_path, strlen($export_path))== 0) {
export_fatal($export, "Export path '" . $export_path . "' is a parent folder from the Cacti web root. Can not continue.");
}
}
function check_system_paths(&$export, $export_path) {
/* don't allow to export to system paths */
$system_paths = array(
'/boot',
'/lib',
'/usr',
'/usr/bin',
'/bin',
'/sbin',
'/usr/sbin',
'/usr/lib',
'/var/lib',
'/var/log',
'/root',
'/etc',
'windows',
'winnt',
'program files');
foreach($system_paths as $system_path) {
if (substr($system_path, 0, 1) == '/') {
if ($system_path == substr($export_path, 0, strlen($system_path))) {
export_fatal($export, "Export path '" . $export_path . "' is within a system path '" . $system_path . "'. Can not continue.");
}
}elseif (substr_count(strtolower($export_path), strtolower($system_path)) > 0) {
export_fatal($export, "Export path '" . $export_path . "' is within a system path '" . $system_path . "'. Can not continue.");
}
}
}
/* export_graphs - this function exports all the graphs and some html for
mgtg view data. these are all the graphs that are in scope for the export
be it a tree export, or a site export.
@arg $export - the export item structure
@arg $export_path - the directory holding the export contents. */
function export_graphs(&$export, $export_path) {
global $config;
/* check for bad directories */
check_cacti_paths($export, $export_path);
check_system_paths($export, $export_path);
/* if the path is not a directory, don't continue */
if (!is_dir($export_path)) {
if (!mkdir($export_path)) {
export_fatal($export, "Unable to create path '" . $export_path . "'! Export can not continue.");
}
}
if (!is_dir($export_path . '/graphs')) {
if (!mkdir($export_path . '/graphs')) {
export_fatal($export, "Unable to create path '" . $export_path . "/graphs'! Export can not continue.");
}
}
if (!is_writable($export_path)) {
export_fatal($export, "Unable to write to path '" . $export_path . "'! Export can not continue.");
}
if (!is_writable($export_path . '/graphs')) {
export_fatal($export, "Unable to write to path '" . $export_path . "/graphs'! Export can not continue.");
}
/* blank paths are not good */
if (strlen($export_path) == 0) {
export_fatal($export, 'Export path is null! Export can not continue.');
}
export_log('Running graph export');
$user = $export['export_effective_user'];
$trees = $export['graph_tree'];
$sites = $export['graph_site'];
$ntree = array();
$graphs = array();
$ngraph = array();
$limit = 1000;
$sql_where = '';
$hosts = '';
$total_rows = 0;
$exported = 0;
$metadata = array();
if ($user == 0) {
$user = -1;
}
if ($export['export_presentation'] == 'tree') {
if ($trees != '0') {
$sql_where = 'gt.id IN(' . $trees . ')';
}
$trees = get_allowed_trees(false, false, $sql_where, 'name', '', $total_rows, $user);
export_debug('There are ' . sizeof($trees) . ' to export');
if (sizeof($trees)) {
foreach($trees as $tree) {
$ntree[] = $tree['id'];
}
}
if (sizeof($ntree)) {
$graphs = array_rekey(
db_fetch_assoc('SELECT DISTINCT local_graph_id
FROM graph_tree_items
WHERE local_graph_id > 0
AND graph_tree_id IN(' . implode(', ', $ntree) . ')'),
'local_graph_id', 'local_graph_id'
);
export_debug('There are ' . sizeof($graphs) . ' to export for all trees.');
if (sizeof($graphs)) {
foreach($graphs as $local_graph_id) {
if (is_graph_allowed($local_graph_id, $user)) {
$ngraph[$local_graph_id] = $local_graph_id;
}
}
}
$hosts = db_fetch_cell_prepared('SELECT GROUP_CONCAT(DISTINCT host_id)
FROM graph_tree_items
WHERE graph_tree_id IN(?)',
array(implode(', ', $ntree)));
if ($hosts != '') {
$sql_where = 'gl.host_id IN(' . $hosts . ')';
$graphs = get_allowed_graphs($sql_where, 'gtg.title_cache', '', $total_rows, $user);
if (sizeof($graphs)) {
foreach($graphs as $graph) {
if (is_graph_allowed($graph['local_graph_id'], $user)) {
$ngraph[$graph['local_graph_id']] = $graph['local_graph_id'];
}
}
}
}
}
}else{
if ($sites != '0') {
$hosts = db_fetch_cell('SELECT GROUP_CONCAT(id) FROM host WHERE site_id IN(' . $sites . ')');
}
if ($hosts != '') {
$sql_where = 'gl.host_id IN(' . $hosts . ')';
}
$graphs = get_allowed_graphs($sql_where, 'gtg.title_cache', '', $total_rows, $user);
if (sizeof($graphs)) {
foreach($graphs as $graph) {
if (is_graph_allowed($graph['local_graph_id'], $user)) {
$ngraph[$graph['local_graph_id']] = $graph['local_graph_id'];
}
}
}
}
if (sizeof($ngraph)) {
/* open a pipe to rrdtool for writing */
$rrdtool_pipe = rrd_init();
foreach($ngraph as $local_graph_id) {
export_debug('Exporting Graph ID: ' . $local_graph_id);
/* settings for preview graphs */
$graph_data_array['export_filename'] = $export_path . '/graphs/thumb_' . $local_graph_id . '.png';
$graph_data_array['graph_height'] = $export['graph_height'];
$graph_data_array['graph_width'] = $export['graph_width'];
$graph_data_array['graph_nolegend'] = true;
$graph_data_array['export'] = true;
check_remove($graph_data_array['export_filename']);
check_remove($export_path . '/graph_' . $local_graph_id . '.html');
export_log("Creating Graph '" . $graph_data_array['export_filename'] . "'");
rrdtool_function_graph($local_graph_id, 0, $graph_data_array, $rrdtool_pipe, $metadata, $user);
unset($graph_data_array);
/* settings for preview graphs */
$graph_data_array['export_filename'] = $export_path . '/graphs/graph_' . $local_graph_id . '.png';
$graph_data_array['export'] = true;
check_remove($graph_data_array['export_filename']);
export_log("Creating Graph '" . $graph_data_array['export_filename'] . "'");
rrdtool_function_graph($local_graph_id, 0, $graph_data_array, $rrdtool_pipe, $metadata, $user);
unset($graph_data_array);
$exported++;
/* generate html files for each graph */
export_log("Creating File '" . $export_path . '/graph_' . $local_graph_id . '.html');
$fp_graph_index = fopen($export_path . '/graph_' . $local_graph_id . '.html', 'w');
if (is_resource($fp_graph_index)) {
fwrite($fp_graph_index, '<table class="center"><tr><td class="center"><strong>Graph - ' . get_graph_title($local_graph_id) . '</strong></td></tr>');
$rras = get_associated_rras($local_graph_id, ' AND dspr.id IS NOT NULL');
/* generate graphs for each rra */
if (sizeof($rras)) {
foreach ($rras as $rra) {
$graph_data_array['export_filename'] = $export_path . '/graphs/graph_' . $local_graph_id . '_' . $rra['id'] . '.png';
$graph_data_array['export'] = true;
$graph_data_array['graph_end'] = time() - read_config_option('poller_interval');
$graph_data_array['graph_start'] = time() - ($rra['rows'] * $rra['step'] * $rra['steps']);
check_remove($graph_data_array['export_filename']);
export_log("Creating Graph '" . $graph_data_array['export_filename'] . "'");
rrdtool_function_graph($local_graph_id, $rra['id'], $graph_data_array, $rrdtool_pipe, $metadata, $user);
unset($graph_data_array);
fwrite($fp_graph_index, "<tr><td class='center'><div><img src='graphs/graph_" . $local_graph_id . '_' . $rra['id'] . ".png'></div></td></tr>\n");
fwrite($fp_graph_index, "<tr><td class='center'><div><strong>" . $rra['name'] . '</strong></div></td></tr>');
}
fwrite($fp_graph_index, '</table>');
fclose($fp_graph_index);
}
}else{
cacti_log('WARNING: Unable to write to file ' . $export_path . '/graph_' . $local_graph_id . '.html');
}
if ($exported >= $export['graph_max']) {
db_execute_prepared('UPDATE graph_exports
SET last_error="WARNING: Max number of Graphs ' . $export['graph_max'] . ' reached",
last_errored=NOW()
WHERE id = ?',
array($export['id']));
break;
}
}
/* close the rrdtool pipe */
rrd_close($rrdtool_pipe);
}
return $exported;
}
/* export_ftp_php_execute - this function creates the ftp connection object,
optionally sanitizes the destination and then calls the function to copy
data to the remote host.
@arg $export - the export item structure
@arg $stExportDir - the temporary data holding the staged export contents.
@arg $stFtpType - the type of ftp transfer, secure or unsecure. */
function export_ftp_php_execute(&$export, $stExportDir, $stFtpType = 'ftp') {
global $aFtpExport;
/* connect to foreign system */
switch($stFtpType) {
case 'ftp':
$oFtpConnection = ftp_connect($aFtpExport['server'], $aFtpExport['port']);
if (!$oFtpConnection) {
export_fatal($export, 'FTP Connection failed! Check hostname and port. Export can not continue.');
}else {
export_log('Conection to remote server was successful.');
}
break;
case 'sftp':
$oFtpConnection = ftp_ssl_connect($aFtpExport['server'], $aFtpExport['port']);
if (!$oFtpConnection) {
export_fatal($export, 'SFTP Connection failed! Check hostname and port. Export can not continue.');
}else {
export_log('Conection to remote server was successful.');
}
break;
}
/* login to foreign system */
if (!ftp_login($oFtpConnection, $aFtpExport['username'], $aFtpExport['password'])) {
ftp_close($oFtpConnection);
export_fatal($export, 'FTP Login failed! Check username and password. Export can not continue.');
}else {
export_log('Remote login was successful.');
}
/* set connection type */
if ($aFtpExport['passive']) {
ftp_pasv($oFtpConnection, TRUE);
}else {
ftp_pasv($oFtpConnection, FALSE);
}
/* change directories into the remote upload directory */
if (!@ftp_chdir($oFtpConnection, $aFtpExport['remotedir'])) {
ftp_close($oFtpConnection);
export_fatal($export, "FTP Remote directory '" . $aFtpExport['remotedir'] . "' does not exist!. Export can not continue.");
}
/* sanitize the remote location if the user has asked so */
if ($export['export_sanitize_remote'] == 'on') {
export_log('Deleting remote files.');
/* get rid of the files first */
$aFtpRemoteFiles = ftp_nlist($oFtpConnection, $aFtpExport['remotedir']);
if (is_array($aFtpRemoteFiles)) {
foreach ($aFtpRemoteFiles as $stFile) {
export_log("Deleting remote file '" . $stFile . "'");
@ftp_delete($oFtpConnection, $stFile);
}
}
/* if the presentation is tree, you will have some directories too */
if ($export['export_presentation'] == 'tree') {
$aFtpRemoteDirs = ftp_nlist($oFtpConnection, $aFtpExport['remotedir']);
foreach ($aFtpRemoteDirs as $remote_dir) {
if (ftp_chdir($oFtpConnection, addslashes($remote_dir))) {
$aFtpRemoteFiles = ftp_nlist($oFtpConnection, '.');
if (is_array($aFtpRemoteFiles)) {
foreach ($aFtpRemoteFiles as $stFile) {
export_log("Deleting Remote File '" . $stFile . "'");
ftp_delete($oFtpConnection, $stFile);
}
}
ftp_chdir($oFtpConnection, '..');
export_log("Removing Remote Directory '" . $remote_dir . "'");
ftp_rmdir($oFtpConnection, $remote_dir);
}else{
ftp_close($oFtpConnection);
export_fatal($export, 'Unable to cd on remote system');
}
}
}
$aFtpRemoteFiles = ftp_nlist($oFtpConnection, $aFtpExport['remotedir']);
if (sizeof($aFtpRemoteFiles) > 0) {
ftp_close($oFtpConnection);
export_fatal($export, 'Problem sanitizing remote ftp location, must exit.');
}
}
/* upload files to remote system */
export_log('Uploading files to remote location.');
ftp_chdir($oFtpConnection, $aFtpExport['remotedir']);
export_ftp_php_uploaddir($stExportDir,$oFtpConnection);
/* end connection */
export_log('Closing ftp connection.');
ftp_close($oFtpConnection);
}
/* export_ftp_php_uploaddir - this function performs the transfer of the exported
data to the remote host.
@arg $dir - the directory to transfer to the remote host.
@arge $oFtpConnection - the ftp connection object created previously. */
function export_ftp_php_uploaddir($dir, $oFtpConnection) {
global $aFtpExport;
export_log("Uploading directory: '$dir' to remote location.");
if($dh = opendir($dir)) {
export_log('Uploading files to remote location.');
while(($file = readdir($dh)) !== false) {
$filePath = $dir . '/' . $file;
if($file != '.' && $file != '..' && !is_dir($filePath)) {
if(!ftp_put($oFtpConnection, $file, $filePath, FTP_BINARY)) {
export_log("Failed to upload '$file'.");
}
}
if (($file != '.') &&
($file != '..') &&
(is_dir($filePath))) {
export_log("Create remote directory: '$file'.");
ftp_mkdir($oFtpConnection,$file);
export_log("Change remote directory to: '$file'.");
ftp_chdir($oFtpConnection,$file);
export_ftp_php_uploaddir($filePath,$oFtpConnection);
export_log('Change remote directory: one up.');
ftp_cdup($oFtpConnection);
}
}
closedir($dh);
}
}
/* export_ftp_ncftpput_execute - this function performs the transfer of the exported
data to the remote host.
@arg $stExportDir - the directory to transfer to the remote host. */
function export_ftp_ncftpput_execute($stExportDir) {
global $aFtpExport;
chdir($stExportDir);
/* set the initial command structure */
$stExecute = 'ncftpput -R -V -r 1 -u ' . cacti_escapeshellarg($aFtpExport['username']) . ' -p ' . cacti_escapeshellarg($aFtpExport['password']);
/* if the user requested passive mode, use it */
if ($aFtpExport['passive']) {
$stExecute .= ' -F ';
}
/* setup the port, server, remote directory and all files */
$stExecute .= ' -P ' . cacti_escapeshellarg($aFtpExport['port']) . ' ' . cacti_escapeshellarg($aFtpExport['server']) . ' ' . cacti_escapeshellarg($aFtpExport['remotedir']) . '.';
/* run the command */
$iExecuteReturns = 0;
system($stExecute, $iExecuteReturns);
$aNcftpputStatusCodes = array (
'Success.',
'Could not connect to remote host.',
'Could not connect to remote host - timed out.',
'Transfer failed.',
'Transfer failed - timed out.',
'Directory change failed.',
'Directory change failed - timed out.',
'Malformed URL.',
'Usage error.',
'Error in login configuration file.',
'Library initialization failed.',
'Session initialization failed.');
export_log('Ncftpput returned: ' . $aNcftpputStatusCodes[$iExecuteReturns]);
}
/* export_post_ftp_upload - this function clean's up the local temporary
directory after the data transfer has completed.
@arg $export - the export structure
@arg $stExportDir - the temporary directory where files were staged. */
function export_post_ftp_upload(&$export, $stExportDir) {
/* clean-up after ftp-put */
if ($dh = opendir($stExportDir)) {
while (($file = readdir($dh)) !== false) {
$filePath = $stExportDir . '/' . $file;
if ($file != '.' && $file != '..' && !is_dir($filePath)) {
export_log("Removing Local File '" . $file . "'");
unlink($filePath);
}
/* if the directory turns out to be a sub-directory, delete it too */
if ($file != '.' && $file != '..' && is_dir($filePath)) {
export_log("Removing Local Directory '" . $filePath . "'");
export_post_ftp_upload($export, $filePath);
}
}
closedir($dh);
/* don't delete the root of the temporary export directory */
if ($export['export_temp_directory'] != $stExportDir) {
rmdir($stExportDir);
}
}
}
/* write_branch_conf - this function writes a json array of all graphs
that lie on a branch within a tree.
@arg $tree_site_id - the tree or site id of the branch
@arg $branch_id - the branch id of the branch
@arg $type - the type of conf file including tree, branch, host, host_gt, host_dq, and host_dqi
@arg $host_id - the host id of any host level tree objects
@arg $sub_id - the sub id of the object passed. This is either a numeric data point, or a hybrid
the case of the host_dqi object.
@arg $user - the effective user to use for export, -1 indicates no permission check
@arg $export_path - the location to store the json array configuration file */
function write_branch_conf($tree_site_id, $branch_id, $type, $host_id, $sub_id, $user, $export_path) {
static $json_files = array();
$total_rows = 0;
$graph_array = array();
if ($type == 'branch') {
$json_file = $export_path . '/tree_' . $tree_site_id . '_branch_' . $branch_id . '.json';
if (isset($json_files[$json_file])) return;
$graphs = db_fetch_assoc_prepared('SELECT DISTINCT local_graph_id
FROM graph_tree_items
WHERE graph_tree_id = ?
AND parent = ?
AND local_graph_id > 0
ORDER BY position', array($tree_site_id, $branch_id));
}elseif ($type == 'gtbranch') {
$json_file = $export_path . '/site_' . $tree_site_id . '_gtbranch_0.json';
if (isset($json_files[$json_file])) return;
$graphs = array();
}elseif ($type == 'dqbranch') {