From 995148cde2b39125b1fb0dc0879679d069e605a1 Mon Sep 17 00:00:00 2001 From: mattf Date: Tue, 16 May 2023 22:05:41 +0000 Subject: [PATCH] Added Latency Gaps logging Added Demographic Quotas campaign features Added more logging for campaign test calls git-svn-id: svn://192.168.202.10@3723 3d104415-ff17-0410-8863-d5cf3c621b8a --- UPGRADE | 7 +- bin/ADMIN_archive_log_tables.pl | 55 +- bin/ADMIN_keepalive_ALL.pl | 55 +- bin/AST_VDdemographic_quotas.pl | 1659 +++ bin/AST_VDhopper.pl | 51 +- bin/AST_VDremote_agents.pl | 4 +- bin/AST_latency_gaps.pl | 1178 ++ docs/AGENT_SCREEN_LOGGING.txt | 51 +- docs/DEMOGRAPHIC_QUOTAS.txt | 276 + docs/conf_examples/extensions.conf.sample-18 | 666 + extras/MySQL_AST_CREATE_tables.sql | 55 +- extras/upgrade_2.14.sql | 55 + install.pl | 24 +- www/agc/DQ_dispo.php | 371 + www/vicidial/AST_latency_gaps_report.php | 486 + www/vicidial/admin.php | 163 +- www/vicidial/demographic_quotas_report.php | 464 + www/vicidial/dygraph.css | 121 + www/vicidial/dygraph.js | 11502 +++++++++++++++++ www/vicidial/dygraph_functions.php | 356 + www/vicidial/help_documentation.txt | 9 +- www/vicidial/user_latency_report.php | 222 +- 22 files changed, 17768 insertions(+), 62 deletions(-) create mode 100644 bin/AST_VDdemographic_quotas.pl create mode 100644 bin/AST_latency_gaps.pl create mode 100644 docs/DEMOGRAPHIC_QUOTAS.txt create mode 100644 docs/conf_examples/extensions.conf.sample-18 create mode 100644 www/agc/DQ_dispo.php create mode 100644 www/vicidial/AST_latency_gaps_report.php create mode 100644 www/vicidial/demographic_quotas_report.php create mode 100644 www/vicidial/dygraph.css create mode 100644 www/vicidial/dygraph.js create mode 100644 www/vicidial/dygraph_functions.php diff --git a/UPGRADE b/UPGRADE index 09628020..8a82c39e 100644 --- a/UPGRADE +++ b/UPGRADE @@ -790,7 +790,12 @@ OTHER CHANGES: of calls with no audio data. This is a campaign feature. 222. Added agent screen latency logging, viewable in the Real-Time Report and - the new Agent Latency Report. + the new Agent Latency Report and Latency Gaps Report. + +223. Added Demographic Quotas, allowing for setting of quota goals for leads + based upon lead field values for demographic parameters like: gender, + age-group, political-party, etc... For more information on this set of + features, read the DEMOGRAPHIC_QUOTAS.txt document. diff --git a/bin/ADMIN_archive_log_tables.pl b/bin/ADMIN_archive_log_tables.pl index 4c71b9cb..34faa4e7 100644 --- a/bin/ADMIN_archive_log_tables.pl +++ b/bin/ADMIN_archive_log_tables.pl @@ -67,6 +67,7 @@ # 220312-0859 - Added vicidial_dial_cid_log table archiving, same as vicidial_dial_log # 230418-1341 - Added vicidial_user_dial_log archiving, same as vicidial_dial_log # 230421-0057 - Added vicidial_agent_latency_summary_log archiving +# 230507-0804 - Added vicidial_latency_gaps archiving # $CALC_TEST=0; @@ -3237,7 +3238,7 @@ if (!$T) if ($wipe_all > 0) {$stmtA = "DELETE FROM vicidial_agent_latency_summary_log;";} else - {$stmtA = "DELETE FROM vicidial_agent_latency_summary_log WHERE db_time < '$del_time';";} + {$stmtA = "DELETE FROM vicidial_agent_latency_summary_log WHERE log_date < '$del_time';";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; $sthArows = $sthA->rows; @@ -3253,6 +3254,58 @@ if (!$T) } + ##### vicidial_latency_gaps + $stmtA = "SELECT count(*) from vicidial_latency_gaps;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $vicidial_latency_gaps_count = $aryA[0]; + } + $sthA->finish(); + + $stmtA = "SELECT count(*) from vicidial_latency_gaps_archive;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $vicidial_latency_gaps_archive_count = $aryA[0]; + } + $sthA->finish(); + + if (!$Q) {print "\nProcessing vicidial_latency_gaps table... ($vicidial_latency_gaps_count|$vicidial_latency_gaps_archive_count)\n";} + $stmtA = "INSERT IGNORE INTO vicidial_latency_gaps_archive SELECT * from vicidial_latency_gaps;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows = $sthA->rows; + if (!$Q) {print "$sthArows rows inserted into vicidial_latency_gaps_archive table \n";} + + $rv = $sthA->err(); + if (!$rv) + { + if ($wipe_all > 0) + {$stmtA = "DELETE FROM vicidial_latency_gaps;";} + else + {$stmtA = "DELETE FROM vicidial_latency_gaps WHERE gap_date < '$del_time';";} + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows = $sthA->rows; + if (!$Q) {print "$sthArows rows deleted from vicidial_latency_gaps table \n";} + + $stmtA = "optimize table vicidial_latency_gaps;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + + $stmtA = "optimize table vicidial_latency_gaps_archive;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + } + + ##### vicidial_carrier_log $stmtA = "SELECT count(*) from vicidial_carrier_log;"; $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; diff --git a/bin/ADMIN_keepalive_ALL.pl b/bin/ADMIN_keepalive_ALL.pl index eacd62c1..77eb8ad1 100644 --- a/bin/ADMIN_keepalive_ALL.pl +++ b/bin/ADMIN_keepalive_ALL.pl @@ -163,9 +163,10 @@ # 230331-2155 - Fix for issue #1458 # 230412-1405 - Added daily rolling of vicidial_agent_notifications table, truncating of vicidial_agent_notifications_queue table # 230420-2321 - Added latency live agent detail updates and log rolling nightly +# 230511-0825 - Added log_latency_gaps trigger, demographic_quotas trigger # -$build = '230420-2321'; +$build = '230511-0825'; $DB=0; # Debug flag $teodDB=0; # flag to log Timeclock End of Day processes to log file @@ -460,7 +461,7 @@ $dbhA = DBI->connect("DBI:mysql:$VARDB_database:$VARDB_server:$VARDB_port", "$VA ##### Get the settings from system_settings ##### -$stmtA = "SELECT sounds_central_control_active,active_voicemail_server,custom_dialplan_entry,default_codecs,generate_cross_server_exten,voicemail_timezones,default_voicemail_timezone,call_menu_qualify_enabled,allow_voicemail_greeting,reload_timestamp,meetme_enter_login_filename,meetme_enter_leave3way_filename,allow_chats,enable_auto_reports,enable_drop_lists,expired_lists_inactive,sip_event_logging,call_quota_lead_ranking,inbound_answer_config FROM system_settings;"; +$stmtA = "SELECT sounds_central_control_active,active_voicemail_server,custom_dialplan_entry,default_codecs,generate_cross_server_exten,voicemail_timezones,default_voicemail_timezone,call_menu_qualify_enabled,allow_voicemail_greeting,reload_timestamp,meetme_enter_login_filename,meetme_enter_leave3way_filename,allow_chats,enable_auto_reports,enable_drop_lists,expired_lists_inactive,sip_event_logging,call_quota_lead_ranking,inbound_answer_config,log_latency_gaps,demographic_quotas FROM system_settings;"; # print "$stmtA\n"; $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -487,6 +488,8 @@ if ($sthArows > 0) $SSsip_event_logging = $aryA[16]; $SScall_quota_lead_ranking = $aryA[17]; $SSinbound_answer_config = $aryA[18]; + $SSlog_latency_gaps = $aryA[19]; + $SSdemographic_quotas = $aryA[20]; } $sthA->finish(); if ($DBXXX > 0) {print "SYSTEM SETTINGS: $sounds_central_control_active|$active_voicemail_server|$SScustom_dialplan_entry|$SSdefault_codecs\n";} @@ -5557,6 +5560,16 @@ if ( ($active_voicemail_server =~ /$server_ip/) && ((length($active_voicemail_se } $i++; } + + # trigger the latency gaps logging process if enabled + if ($SSlog_latency_gaps > 0) + { + $LL_email=''; + if ($SSlog_latency_gaps < 2) + {$LL_email='--email-gaps-notice';} + if ($DB) {print "running agent latency gaps logging process...\n";} + `/usr/bin/screen -d -m -S Gaps$reset_test $PATHhome/AST_latency_gaps.pl -q --container=AGENT_LATENCY_LOGGING --live $LL_email 2>/dev/null 1>&2`; + } } ################################################################################ ##### END latency log live agent details updates @@ -5565,6 +5578,44 @@ if ( ($active_voicemail_server =~ /$server_ip/) && ((length($active_voicemail_se +################################################################################ +##### START launch Demographic Quotas process, if enabled on any active campaigns +################################################################################ +# only run this on active voicemail server +if ( ($active_voicemail_server =~ /$server_ip/) && ((length($active_voicemail_server)) eq (length($server_ip))) && ($SSdemographic_quotas > 0) ) + { + ##### look for active campaigns with DQ enabled on them ##### + $demographic_quotas=0; + $stmtA = "SELECT count(*) FROM vicidial_campaigns where active='Y' and demographic_quotas='ENABLED';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $demographic_quotas = $aryA[0]; + } + $sthA->finish(); + + if ($demographic_quotas > 0) + { + if ($DB) {print "Demographic Quotas campaigns enabled on this system, launching process: $demographic_quotas \n";} + `/usr/bin/screen -d -m -S DQrun$reset_test $PATHhome/AST_VDdemographic_quotas.pl 2>/dev/null 1>&2`; + } + else + { + if ($DB) {print "No Demographic Quotas campaigns enabled on this system: $demographic_quotas \n";} + } + } +################################################################################ +##### START launch Demographic Quotas process, if enabled on any active campaigns +################################################################################ + + + + + ################################################################################ ##### BEGIN Audio Store sync ################################################################################ diff --git a/bin/AST_VDdemographic_quotas.pl b/bin/AST_VDdemographic_quotas.pl new file mode 100644 index 00000000..97fc3a01 --- /dev/null +++ b/bin/AST_VDdemographic_quotas.pl @@ -0,0 +1,1659 @@ +#!/usr/bin/perl +# +# AST_VDdemographic_quotas.pl version 2.14 +# +# DESCRIPTION: +# Operates the campaign Demographic Quotas features +# +# SUMMARY: +# For VICIDIAL outbound dialing, this program is triggered by another program +# +# Copyright (C) 2023 Matt Florell LICENSE: AGPLv2 +# +# CHANGELOG +# 230427-1424 - First build +# + +# constants +$build = '230427-1424'; +$script='demo_quota'; +$DB=0; # Debug flag, set to 0 for no debug messages. Can be overriden with CLI --debug flag +$US='__'; +$MT[0]=''; +$force_rerank=0; + +### gather date and time +$secT = time(); +$secX = time(); +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); +$year = ($year + 1900); +$mon++; +$wtoday = $wday; +if ($mon < 10) {$mon = "0$mon";} +if ($mday < 10) {$mday = "0$mday";} +if ($hour < 10) {$hour = "0$hour";} +if ($min < 10) {$min = "0$min";} +if ($sec < 10) {$sec = "0$sec";} +$file_date = "$year-$mon-$mday"; +$now_date = "$year-$mon-$mday $hour:$min:$sec"; +$VDL_date = "$year-$mon-$mday 00:00:01"; +$YMD = "$year-$mon-$mday"; +$reset_test = "$hour$min"; + +### get date-time of one hour ago ### +$VDL_hour = ($secX - (60 * 60)); +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_hour); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +$VDL_hour = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +### get date-time of half hour ago ### +$VDL_halfhour = ($secX - (30 * 60)); +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_halfhour); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +$VDL_halfhour = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +### get date-time of five minutes ago ### +$VDL_five = ($secX - (5 * 60)); +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_five); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +$VDL_five = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +### get date-time of one minute ago ### +$VDL_one = ($secX - (1 * 60)); +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_one); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +$VDL_one = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +### get date-time of 10 seconds ago ### +$VDL_tensec = ($secX - 10); +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_tensec); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +$VDL_tensec = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +### begin parsing CLI run-time options ### +if (length($ARGV[0])>1) + { + $i=0; + $allow_inactive_list_leads=0; + while ($#ARGV >= $i) + { + $args = "$args $ARGV[$i]"; + $i++; + } + + if ($args =~ /--help/i) + { + print "allowed run time options(must stay in this order):\n"; + print " [--test] = test\n"; + print " [--help] = this screen\n"; + print " [--version] = print version of this script, then exit\n"; + print " [--count-only] = only display the number of leads in the hopper, then exit\n"; + print " [--force-rerank] = will force re-ranking of leads for this run\n"; + print " [--rerank-limit=XXX] = force a re-rank limit of XXX\n"; + print " [--debug] = debug\n"; + print " [--debugX] = super debug\n"; + print " [--container=XXX] = force a container_id of XXX\n"; + print " [--campaign=XXX] = run for campaign XXX only(or more campaigns if separated by triple dash ---)\n"; + print "\n"; + exit; + } + else + { + if ($args =~ /--version/i) + { + print "version: $build\n"; + exit; + } + if ($args =~ /--campaign=/i) + { + # print "\n|$ARGS|\n\n"; + @data_in = split(/--campaign=/,$args); + $CLIcampaign = $data_in[1]; + $CLIcampaign =~ s/ .*$//gi; + if ($CLIcampaign =~ /---/) + { + $CLIcampaign =~ s/---/','/gi; + } + } + else + {$CLIcampaign = '';} + if ($args =~ /--container=/i) + { + @data_in = split(/--container=/,$args); + $CLIcontainer = $data_in[1]; + $CLIcontainer =~ s/ .*$//gi; + print "\n----- CONTAINER OVERRIDE: $CLIcontainer -----\n\n"; + } + else + {$CLIcontainer = '';} + if ($args =~ /--rerank-limit=/i) + { + @data_in = split(/--rerank-limit=/,$args); + $CLIrerank_limit = $data_in[1]; + $CLIrerank_limit =~ s/ .*$//gi; + $CLIrerank_limit =~ s/\D//gi; + print "\n----- RE-RANK LIMIT OVERRIDE: $CLIrerank_limit -----\n\n"; + } + else + {$CLIrerank_limit = '';} + if ($args =~ /--debug/i) + { + $DB=1; + print "\n----- DEBUG -----\n\n"; + } + if ($args =~ /--debugX/i) + { + $DBX=1; + print "\n----- SUPER DEBUG -----\n\n"; + } + if ($args =~ /--test/i) + { + $T=1; $TEST=1; + print "\n-----TESTING -----\n\n"; + } + if ($args =~ /--count-only/i) + { + $count_only=1; + } + if ($args =~ /--force-rerank/i) + { + $force_rerank=1; + } + } + } +else + { + print "no command line options set\n"; + } + +# default path to astguiclient configuration file: +$PATHconf = '/etc/astguiclient.conf'; + +open(conf, "$PATHconf") || die "can't open $PATHconf: $!\n"; +@conf = ; +close(conf); +$i=0; +foreach(@conf) + { + $line = $conf[$i]; + $line =~ s/ |>|\n|\r|\t|\#.*|;.*//gi; + if ( ($line =~ /^PATHhome/) && ($CLIhome < 1) ) + {$PATHhome = $line; $PATHhome =~ s/.*=//gi;} + if ( ($line =~ /^PATHlogs/) && ($CLIlogs < 1) ) + {$PATHlogs = $line; $PATHlogs =~ s/.*=//gi;} + if ( ($line =~ /^PATHagi/) && ($CLIagi < 1) ) + {$PATHagi = $line; $PATHagi =~ s/.*=//gi;} + if ( ($line =~ /^PATHweb/) && ($CLIweb < 1) ) + {$PATHweb = $line; $PATHweb =~ s/.*=//gi;} + if ( ($line =~ /^PATHsounds/) && ($CLIsounds < 1) ) + {$PATHsounds = $line; $PATHsounds =~ s/.*=//gi;} + if ( ($line =~ /^PATHmonitor/) && ($CLImonitor < 1) ) + {$PATHmonitor = $line; $PATHmonitor =~ s/.*=//gi;} + if ( ($line =~ /^VARserver_ip/) && ($CLIserver_ip < 1) ) + {$VARserver_ip = $line; $VARserver_ip =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_server/) && ($CLIDB_server < 1) ) + {$VARDB_server = $line; $VARDB_server =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_database/) && ($CLIDB_database < 1) ) + {$VARDB_database = $line; $VARDB_database =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_user/) && ($CLIDB_user < 1) ) + {$VARDB_user = $line; $VARDB_user =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_pass/) && ($CLIDB_pass < 1) ) + {$VARDB_pass = $line; $VARDB_pass =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_port/) && ($CLIDB_port < 1) ) + {$VARDB_port = $line; $VARDB_port =~ s/.*=//gi;} + $i++; + } + +if (!$DQLOGfile) {$DQLOGfile = "$PATHlogs/demographic_quotas.$year-$mon-$mday";} +if (!$VARDB_port) {$VARDB_port='3306';} + +use DBI; + +$dbhA = DBI->connect("DBI:mysql:$VARDB_database:$VARDB_server:$VARDB_port", "$VARDB_user", "$VARDB_pass") + or die "Couldn't connect to database: " . DBI->errstr; + + +### Grab system_settings values from the database +$stmtA = "SELECT demographic_quotas,UNIX_TIMESTAMP(NOW()) FROM system_settings;"; +$sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; +$sthA->execute or die "executing: $stmtA ", $dbhA->errstr; +$sthArows=$sthA->rows; +if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $SSdemographic_quotas = $aryA[0]; + $SSdb_now = $aryA[1]; + } +$sthA->finish(); + +### Grab Server values from the database +$stmtA = "SELECT vd_server_logs,local_gmt FROM servers where server_ip = '$VARserver_ip';"; +$sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; +$sthA->execute or die "executing: $stmtA ", $dbhA->errstr; +$sthArows=$sthA->rows; +if ($sthArows==0) {die "Server IP $VARserver_ip does not have an entry in the servers table\n\n";} +if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $DBvd_server_logs = $aryA[0]; + $DBSERVER_GMT = $aryA[1]; + if ($DBvd_server_logs =~ /Y/) {$SYSLOG = '1';} + else {$SYSLOG = '0';} + if (length($DBSERVER_GMT)>0) {$SERVER_GMT = $DBSERVER_GMT;} + } +$sthA->finish(); + +if ($non_latin > 0) + { + $stmtA = "SET NAMES 'UTF8';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthA->finish(); + } + +$stmtA = "INSERT IGNORE into vicidial_campaign_stats_debug (campaign_id,server_ip) select campaign_id,'DEMO_QUOTAS' from vicidial_campaigns;"; +$sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; +$sthA->execute or die "executing: $stmtA ", $dbhA->errstr; +$sthA->finish(); + +### Grab container override details, if defined +if (length($CLIcontainer) > 0) + { + $dq_container_stmt="select container_entry from vicidial_settings_containers where container_id='$CLIcontainer' and container_entry!=''"; + if ($DBX) {print "$dq_container_stmt\n";} + $dq_container_rslt=$dbhA->prepare($dq_container_stmt); + $dq_container_rslt->execute(); + if ($dq_container_rslt->rows < 1) + { + print "Container Override does not exist: $CLIcontainer\n"; + exit; + } + $dq_container_rslt->finish; + } + +$secX = time(); +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($secX); +$LOCAL_GMT_OFF = $SERVER_GMT; +$LOCAL_GMT_OFF_STD = $SERVER_GMT; +if ($isdst) {$LOCAL_GMT_OFF++;} + +$GMT_now = ($secX - ($LOCAL_GMT_OFF * 3600)); +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($GMT_now); +$mon++; +$year = ($year + 1900); +if ($mon < 10) {$mon = "0$mon";} +if ($mday < 10) {$mday = "0$mday";} +if ($hour < 10) {$hour = "0$hour";} +if ($min < 10) {$min = "0$min";} +if ($sec < 10) {$sec = "0$sec";} + +if ($DB) {print "TIME DEBUG: $LOCAL_GMT_OFF_STD|$LOCAL_GMT_OFF|$isdst| GMT: $hour:$min\n";} + +### check if demographic_quotas is enabled in the system +if ($SSdemographic_quotas < 1) + { + print "Demographic Quotas disabled: $SSdemographic_quotas exiting...\n"; + exit; + } + +$run_check=1; +### concurrency check (SCREEN uses script path, so check for more than 2 entries) +if ($run_check > 0) + { + my $grepout = `/bin/ps ax | grep $0 | grep -v grep | grep -v '/bin/sh'`; + my $grepnum=0; + $grepnum++ while ($grepout =~ m/\n/g); + if ($grepnum > 2) + { + if ($DB) {print "I am not alone! Another $0 is running! Exiting...\n";} + $event_string = "I am not alone! Another $0 is running! Exiting..."; + &event_logger; + exit; + } + } + +### Count only process +if ($count_only) + { + if (length($CLIcampaign)>0) + { + $stmtA = "SELECT count(*) from vicidial_demographic_quotas_goals where campaign_id IN('$CLIcampaign');"; + } + else + { + $stmtA = "SELECT count(*) from vicidial_demographic_quotas_goals;"; + } + $dq_count_only=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $dq_count_only = $aryA[0]; + } + $sthA->finish(); + if ($DB) + {print "Demographic Quota Goals count: $dq_count_only|$stmtA|\n";} + else + {print "Demographic Quota Goals count: $dq_count_only\n";} + $event_string = "|DEMOGRAPHIC QUOTA GOALS COUNT: $dq_count_only|"; + &event_logger; + + exit; + } + + +##### BEGIN check for active campaigns that need the hopper run for them +@campaign_id=@MT; +$ANY_hopper_vlc_dup_check='N'; + +if (length($CLIcampaign)>1) + { + $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,dial_method,dial_statuses,call_count_limit,call_quota_lead_ranking,demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets,dispo_call_url,demographic_quotas_last_rerank from vicidial_campaigns where campaign_id IN('$CLIcampaign') and active='Y' and demographic_quotas IN('ENABLED','COMPLETE');"; + } +else + { + $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,dial_method,dial_statuses,call_count_limit,call_quota_lead_ranking,demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets,dispo_call_url,demographic_quotas_last_rerank from vicidial_campaigns where active='Y' and demographic_quotas IN('ENABLED','COMPLETE');"; + } +$sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; +$sthA->execute or die "executing: $stmtA ", $dbhA->errstr; +$sthArows=$sthA->rows; +$rec_count=0; +while ($sthArows > $rec_count) + { + @aryA = $sthA->fetchrow_array; + $campaign_id[$rec_count] = $aryA[0]; + $lead_order[$rec_count] = $aryA[1]; + $hopper_level[$rec_count] = $aryA[2]; + $auto_dial_level[$rec_count] = $aryA[3]; + $local_call_time[$rec_count] = $aryA[4]; + $dial_method[$rec_count] = $aryA[5]; + $dial_statuses[$rec_count] = $aryA[6]; + $call_count_limit[$rec_count] = $aryA[7]; + $call_quota_lead_ranking[$rec_count] = $aryA[8]; + $demographic_quotas[$rec_count] = $aryA[9]; + if (length($CLIcontainer) < 1) + {$demographic_quotas_container[$rec_count] = $aryA[10];} + else + {$demographic_quotas_container[$rec_count] = "$CLIcontainer";} + $demographic_quotas_rerank[$rec_count] = $aryA[11]; + $demographic_quotas_list_resets[$rec_count] = $aryA[12]; + $dispo_call_url[$rec_count] = $aryA[13]; + $demographic_quotas_last_rerank[$rec_count] = $aryA[14]; + $ranking_limit[$rec_count] = 999999; + if ($demographic_quotas_rerank[$rec_count] =~ /MINUTE/) {$ranking_limit[$rec_count] = ($hopper_level[$rec_count] * 6);} + if ($demographic_quotas_rerank[$rec_count] =~ /HOUR/) {$ranking_limit[$rec_count] = ($hopper_level[$rec_count] * 130);} + if (length($CLIrerank_limit) > 0) + { + if ($DBX) {print "Re-rank limit override: |new: $CLIrerank_limit|old: $ranking_limit[$rec_count]|\n";} + $ranking_limit[$rec_count] = $CLIrerank_limit; + } + + ### Find the number of agents + $stmtB = "SELECT COUNT(*) FROM vicidial_live_agents WHERE ( (campaign_id='$campaign_id[$rec_count]') or (dial_campaign_id='$campaign_id[$rec_count]') ) and status IN ('READY','QUEUE','INCALL','CLOSER','PAUSED') and last_update_time >= '$VDL_tensec'"; + $sthB = $dbhA->prepare($stmtB) or die "preparing: ",$dbhA->errstr; + $sthB->execute or die "executing: $stmtB ", $dbhA->errstr; + @aryAgent = $sthB->fetchrow_array; + $num_agents = $aryAgent[0]; + $sthB->finish(); + + $rec_count++; + } +$sthA->finish(); +if ($DB) {print "CAMPAIGNS TO PROCESS DEMOGRAPHIC QUOTAS FOR: $rec_count|$#campaign_id\n";} +##### END check for active campaigns that need the hopper run for them + + + + + +##### LOOP THROUGH EACH CAMPAIGN AND PROCESS THE DEMOGRAPHIC QUOTAS ##### +$i=0; +foreach(@campaign_id) + { + $secC[$i] = time(); + $RUNgoals=1; + $finished_statusesSQL=''; + $field_valueSQL=''; + @demo_fields=@MT; + @demo_fields_values=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + @demo_fields_goals=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + @demo_fields_leads_total=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + @demo_fields_leads_active=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + @demo_fields_quota_count=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + @demo_fields_quota_status=([('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11], [('') x 11]); + $fields_count=0; + $fields_values_count=0; + $total_filled_count=0; + $newly_filled_count=0; + $quota_status_active_count=0; + $longest_query_time=0; + $newly_filledSQL=''; + $existing_filledSQL=''; + $active_demosSQL=''; + $ranked_leads=0; + $rerank_output=''; + + $stmtA = "SELECT container_entry FROM vicidial_settings_containers where container_id='$demographic_quotas_container[$i]';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthSCrows=$sthA->rows; + if ($DB) {print "Checking for $campaign_id[$i] Call Quota settings container: |$sthSCrows|$stmtA|\n";} + $hopper_begin_output = "Campaign $campaign_id[$i] Demographic Quota Container check: $demographic_quotas_container[$i]\n"; + if ($sthSCrows > 0) + { + @aryA = $sthA->fetchrow_array; + $TEMPcontainer_entry = $aryA[0]; + $TEMPcontainer_entry =~ s/\\//gi; + if (length($TEMPcontainer_entry) > 5) + { + @container_lines = split(/\n/,$TEMPcontainer_entry); + $c=0; + foreach(@container_lines) + { + $container_lines[$c] =~ s/;.*|\r|\t//gi; + if (length($container_lines[$c]) > 10) + { + # define finished_statuses + if ($container_lines[$c] =~ /^finished_statuses/i) + { + $finished_statuses = $container_lines[$c]; + $finished_statuses =~ s/finished_statuses=>|finished_statuses => //gi; + if ( (length($finished_statuses) > 0) && (length($finished_statuses) <= 70) ) + { + $TEMPfinished_statuses = $finished_statuses; + $TEMPfinished_statuses =~ s/,/','/gi; + $finished_statusesSQL = "'$TEMPfinished_statuses'"; + if ($DBX) {print "Demographic Quota DEBUG: finished_statuses defined - $finished_statuses|$finished_statusesSQL|\n";} + $hopper_begin_output .= "finished_statuses defined - $finished_statuses|$finished_statusesSQL|\n"; + } + } + # define demo fields and values + if ($container_lines[$c] =~ /^demo\d\d_field/i) + { + $demo_field_line = $container_lines[$c]; + $demo_field_line =~ s/^demo\d\d_field=>|^demo\d\d_field => //gi; + $demo_field_line_number = $container_lines[$c]; + $demo_field_line_number =~ s/^demo|_field.*//gi; + $demo_field_line_number = ($demo_field_line_number + 0); + if ( (length($demo_field_line) > 2) && (length($demo_field_line_number) > 0) ) + { + $fields_count++; + $demo_fields[$demo_field_line_number] = $demo_field_line; + if ($DBX) {print "Demographic Quota DEBUG: field number $demo_field_line_number defined - $demo_field_line|$fields_count|\n";} + $hopper_begin_output .= "field $demo_value_line_number defined - $demo_field_line|$fields_count|\n"; + } + } + if ($container_lines[$c] =~ /^demo\d\d_value\d\d/i) + { + $demo_value_line = $container_lines[$c]; + $demo_value_line =~ s/^demo\d\d_value\d\d=>|^demo\d\d_value\d\d => //gi; + @demo_value_lineARY = split(/,/,$demo_value_line); + + $demo_value_line_number = $container_lines[$c]; + $demo_value_line_number =~ s/^demo|_value.*//gi; + $demo_value_line_number = ($demo_value_line_number + 0); + $demo_value_line_valnum = $container_lines[$c]; + $demo_value_line_valnum =~ s/^demo\d\d_value| => .*|=>.*//gi; + $demo_value_line_valnum = ($demo_value_line_valnum + 0); + if ( (length($demo_value_line) > 2) && (length($demo_value_line_number) > 0) && (length($demo_value_line_valnum) > 0) ) + { + $fields_values_count++; + $demo_fields_values[$demo_value_line_number][$demo_value_line_valnum] = $demo_value_lineARY[0]; + $demo_fields_goals[$demo_value_line_number][$demo_value_line_valnum] = $demo_value_lineARY[1]; + if ($DBX) {print "Demographic Quota DEBUG: field number $demo_value_line_number value/goal defined - |$demo_value_lineARY[0]|$demo_value_lineARY[1]|$fields_values_count|\n";} + $hopper_begin_output .= "field $demo_value_line_number value/goal defined - |$demo_value_lineARY[0]|$demo_value_lineARY[1]|$fields_values_count|\n"; + } + } + } + $c++; + } + } + else + { + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "Campaign $campaign_id[$i] Demographic Quota Container is empty: $demographic_quotas_container[$i]|$affected_rowsC \n";} + $hopper_begin_output .= "Campaign $campaign_id[$i] Demographic Quota Container is empty: $demographic_quotas_container[$i]|$affected_rowsC \n"; + $RUNgoals=0; + } + } + else + { + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "Campaign $campaign_id[$i] Demographic Quota Container does not exist: $demographic_quotas_container[$i]|$affected_rowsC \n";} + $hopper_begin_output .= "Campaign $campaign_id[$i] Demographic Quota Container does not exist: $demographic_quotas_container[$i]|$affected_rowsC \n"; + $RUNgoals=0; + } + $sthA->finish(); + + if ($DB) {print "DQ DEBUG: Fields defined: $fields_count, Values defined: $fields_values_count\n";} + + if (length($finished_statusesSQL) < 3) + { + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "Campaign $campaign_id[$i] Demographic Quota Container does not define statuses: $demographic_quotas_container[$i]|$finished_statusesSQL|$affected_rowsC \n";} + $hopper_begin_output .= "Campaign $campaign_id[$i] Demographic Quota Container does not define statuses: $demographic_quotas_container[$i]|$finished_statusesSQL|$affected_rowsC \n"; + $RUNgoals=0; + } + + if ( ($fields_count < 1) || ($fields_values_count < 1) ) + { + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "Campaign $campaign_id[$i] Demographic Quota Container is invalid: $demographic_quotas_container[$i]|$fields_count|$fields_values_count|$affected_rowsC \n";} + $hopper_begin_output .= "Campaign $campaign_id[$i] Demographic Quota Container is invalid: $demographic_quotas_container[$i]|$fields_count|$fields_values_count|$affected_rowsC \n"; + $RUNgoals=0; + } + + $stmtA = "SELECT list_id FROM vicidial_lists where ( ( (active='N') or ( (active='Y') and (expiration_date < \"$file_date\") ) ) and (campaign_id='$campaign_id[$i]') );"; + if ($DB) {print $stmtA;} + $inactive_lists=''; + $inactive_lists_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + while ($sthArows > $inactive_lists_count) + { + @aryA = $sthA->fetchrow_array; + $inactive_list = $aryA[0]; + $inactive_lists .= "'$inactive_list',"; + $inactive_lists_count++; + } + $sthA->finish(); + if (length($inactive_lists) > 3) {$inactive_lists =~ s/,$//gi;} + if ($DB) {print "Inactive Lists: $inactive_lists_count |$inactive_lists|\n";} + + $stmtA = "SELECT list_id FROM vicidial_lists where ( (active='Y') and (expiration_date >= \"$file_date\") and (campaign_id='$campaign_id[$i]') );"; + if ($DB) {print $stmtA;} + $active_lists=''; + $active_lists_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + while ($sthArows > $active_lists_count) + { + @aryA = $sthA->fetchrow_array; + $active_list = $aryA[0]; + $active_lists .= "'$active_list',"; + $active_lists_count++; + } + $sthA->finish(); + if (length($active_lists) > 3) {$active_lists =~ s/,$//gi;} + if ($DB) {print "Active Lists: $active_lists_count |$active_lists|\n";} + + + ### If Call Quota Lead Ranking is enabled on this campaign, set Demographic Quotas to INVALID + if ( ($call_quota_lead_ranking[$i] !~ /^DISABLED$/) && (length($call_quota_lead_ranking[$i]) > 0) ) + { + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "Campaign $campaign_id[$i] Call Quota Lead Ranking enabled: $call_quota_lead_ranking[$i]|$affected_rowsC \n";} + $hopper_begin_output .= "Campaign $campaign_id[$i] Call Quota Lead Ranking enabled: $call_quota_lead_ranking[$i]|$affected_rowsC \n"; + $RUNgoals=0; + } + + + ##### BEGIN check if Dispo Call URL is set up properly in campaign ##### + if ($dispo_call_url[$i] =~ /^ALT$/) + { + # looking up alternate dispo call url entry to confirm DQ_dispo.php is present and configured properly + $DQ_dispo_url=''; + $stmtA = "SELECT url_address FROM vicidial_url_multi where (campaign_id='$campaign_id[$i]') and (entry_type='CAMPAIGN') and (active='Y') and (url_type='dispo');"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "$sthArows|$stmtA|\n";} + $vum=0; + while ($sthArows > $vum) + { + @aryA = $sthA->fetchrow_array; + if ($aryA[0] =~ /DQ_dispo.php/) + {$DQ_dispo_url = $aryA[0];} + $vum++; + } + $sthA->finish(); + } + else + {$DQ_dispo_url = $dispo_call_url[$i];} + + $campCLItest = "campaign_id=$campaign_id[$i]"; + if ( ($DQ_dispo_url =~ /DQ_dispo.php/) && ($DQ_dispo_url =~ /dispo=--A--dispo--B--/) && ($DQ_dispo_url =~ /$campCLItest/i) ) + { + if ($DB) {print "DQ_dispo Dispo Call URL is configured on this campaign: $campaign_id[$i]|$DQ_dispo_url| \n";} + $hopper_begin_output .= "DQ_dispo Dispo Call URL is configured on this campaign: $campaign_id[$i]|$DQ_dispo_url| \n"; + } + else + { + $Dmessage=''; + if ($DQ_dispo_url !~ /DQ_dispo.php/) {$Dmessage .= ", Missing 'DQ_dispo.php'";} + if ($DQ_dispo_url !~ /dispo=--A--dispo--B--/) {$Dmessage .= ", Missing 'dispo=--A--dispo--B--'";} + if ($DQ_dispo_url !~ /$campCLItest/) {$Dmessage .= ", Missing '$campCLItest'";} + + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='INVALID' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + if ($DB) {print "DQ_dispo Dispo Call URL is NOT configured on this campaign, disabling DQ: $campaign_id[$i]|$DQ_dispo_url|$affected_rowsC|$Dmessage| \n";} + $hopper_begin_output .= "DQ_dispo Dispo Call URL is NOT configured on this campaign, disabling DQ: $campaign_id[$i]|$DQ_dispo_url|$affected_rowsC|$Dmessage| \n"; + $RUNgoals=0; + } + ##### END check if Dispo Call URL is set up properly in campaign ##### + + + + ##### Go through the demographic quota goals and update settings and counts, and assign ranks to leads in active lists + if ($RUNgoals > 0) + { + $vicidial_log = 'vicidial_log'; + + $dial_statuses[$i] =~ s/ -$//gi; + @Dstatuses = split(/ /,$dial_statuses[$i]); + $Ds_to_print = (($#Dstatuses) + 0); + $STATUSsql[$i]=''; + $o=0; + while ($Ds_to_print > $o) + { + $o++; + $STATUSsql[$i] .= "'$Dstatuses[$o]',"; + } + if (length($STATUSsql[$i])<3) {$STATUSsql[$i]="''";} + else {chop($STATUSsql[$i]);} + + $VCSdialable_leads[$i]=0; + ### BEGIN - GATHER STATS FROM THE vicidial_campaign_stats TABLE ### + $stmtA = "SELECT dialable_leads from vicidial_campaign_stats where campaign_id='$campaign_id[$i]';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + $rec_count=0; + while ($sthArows > $rec_count) + { + @aryA = $sthA->fetchrow_array; + $VCSdialable_leads[$i] = $aryA[0]; + $rec_count++; + } + $sthA->finish(); + ### END - GATHER STATS FROM THE vicidial_campaign_stats TABLE ### + + if ($DB) {print "\nStarting quota run for $campaign_id[$i] campaign- GMT: $local_call_time[$i] HOPPER LEVEL: $hopper_level[$i] RANKING LIMIT: $ranking_limit[$i] ($demographic_quotas_rerank[$i]) \n";} + + $hopper_begin_output .= "Starting quota run for $campaign_id[$i] campaign- GMT: $local_call_time[$i] HOPPER LEVEL: $hopper_level[$i] RANKING LIMIT: $ranking_limit[$i] ($demographic_quotas_rerank[$i]) \n"; + + ### Set all filled vicidial_demographic_quotas_goals records for this campaign to FPENDING status ahead of updates + $stmtA = "UPDATE vicidial_demographic_quotas_goals SET quota_status='FPENDING' where campaign_id='$campaign_id[$i]' and quota_status='FILLED';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "Setting all filled vicidial_demographic_quotas_goals records for this campaign to FPENDING status: $affected_rows\n"; + + ### Set all non-filled vicidial_demographic_quotas_goals records for this campaign to PENDING status ahead of updates + $stmtA = "UPDATE vicidial_demographic_quotas_goals SET quota_status='PENDING' where campaign_id='$campaign_id[$i]' and quota_status NOT IN('FPENDING','ARCHIVE');"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "Setting all non-filled vicidial_demographic_quotas_goals records for this campaign to PENDING status: $affected_rows\n"; + + if (length($active_lists) > 2) + {$all_listsSQL = $active_lists;} + if (length($inactive_lists) > 2) + { + if (length($all_listsSQL) > 2) {$all_listsSQL .= ",";} + $all_listsSQL .= "$inactive_lists"; + } + + $g=1; + while ($g <= 10) + { + $v=1; + while ($v <= 10) + { + if ( (length($demo_fields_values[$g][$v]) > 0) && (length($demo_fields_goals[$g][$v]) > 0) ) + { + if ($DBX) {print "DQ DEBUG: Field $g Value $v: |val: $demo_fields_values[$g][$v]| |goal: $demo_fields_goals[$g][$v]|\n";} + + ### BEGIN - GATHER STATS FROM THE vicidial_campaign_stats TABLE ### + $demo_fields_leads_total[$g][$v]=0; + $demo_fields_leads_active[$g][$v]=0; + $demo_fields_quota_count[$g][$v]=0; + $demo_fields_quota_status[$g][$v]='ACTIVE'; + if (length($active_lists) > 2) + { + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_list where list_id IN($active_lists) and $demo_fields[$g]=\"$demo_fields_values[$g][$v]\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $demo_fields_leads_active[$g][$v] = $aryA[0]; + } + $sthA->finish(); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + } + if (length($inactive_lists) > 2) + { + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_list where list_id IN($inactive_lists) and $demo_fields[$g]=\"$demo_fields_values[$g][$v]\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $demo_fields_leads_total[$g][$v] = ($demo_fields_leads_active[$g][$v] + $aryA[0]); + } + else + {$demo_fields_leads_total[$g][$v] = $demo_fields_leads_active[$g][$v];} + $sthA->finish(); + + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + } + else + {$demo_fields_leads_total[$g][$v] = $demo_fields_leads_active[$g][$v];} + + if (length($all_listsSQL) > 2) + { + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_list where list_id IN($all_listsSQL) and $demo_fields[$g]=\"$demo_fields_values[$g][$v]\" and status IN($finished_statusesSQL);"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $demo_fields_quota_count[$g][$v] = $aryA[0]; + } + $sthA->finish(); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + } + + if ($demo_fields_quota_count[$g][$v] >= $demo_fields_goals[$g][$v]) + { + $total_filled_count++; + $demo_fields_quota_status[$g][$v]='FILLED'; + $quota_status_already_filled=0; + $stmtA = "SELECT count(*) from vicidial_demographic_quotas_goals where campaign_id='$campaign_id[$i]' and demographic_quotas_container='$demographic_quotas_container[$i]' and quota_field='$demo_fields[$g]' and quota_field_order='$g' and quota_value=\"$demo_fields_values[$g][$v]\" and quota_value_order='$v' and quota_status='FPENDING';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $quota_status_already_filled = $aryA[0]; + } + $sthA->finish(); + if ($quota_status_already_filled < 1) + { + $newly_filled_count++; + $demo_fields_quota_status[$g][$v]='NEW_FILLED'; + if (length($newly_filledSQL) < 1) {$newly_filledSQL .= "and ( ";} + else {$newly_filledSQL .= " or ";} + $newly_filledSQL .= "($demo_fields[$g]=\"$demo_fields_values[$g][$v]\")"; + } + else + { + if (length($existing_filledSQL) < 1) {$existing_filledSQL .= "and ( ";} + else {$existing_filledSQL .= " or ";} + $existing_filledSQL .= "($demo_fields[$g]=\"$demo_fields_values[$g][$v]\")"; + } + } + else + { + $active_demosSQL .= " and $demo_fields[$g]='$demo_fields_values[$g][$v]'"; + } + + ### Insert/Update the vicidial_demographic_quotas_goals record for this field/value + $stmtA = "INSERT IGNORE INTO vicidial_demographic_quotas_goals SET campaign_id='$campaign_id[$i]',demographic_quotas_container='$demographic_quotas_container[$i]',quota_field='$demo_fields[$g]',quota_field_order='$g',quota_value=\"$demo_fields_values[$g][$v]\",quota_value_order='$v',quota_goal='$demo_fields_goals[$g][$v]',quota_count='$demo_fields_quota_count[$g][$v]',quota_leads_total='$demo_fields_leads_total[$g][$v]',quota_leads_active='$demo_fields_leads_active[$g][$v]',quota_status='$demo_fields_quota_status[$g][$v]',quota_modify_date=NOW(),last_call_date='2000-01-01 00:00:00' ON DUPLICATE KEY UPDATE quota_goal='$demo_fields_goals[$g][$v]',quota_leads_total='$demo_fields_leads_total[$g][$v]',quota_leads_active='$demo_fields_leads_active[$g][$v]',quota_status='$demo_fields_quota_status[$g][$v]',quota_modify_date=NOW(),quota_count='$demo_fields_quota_count[$g][$v]';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + } + $v++; + } + $g++; + } + + $stmtA = "SELECT count(*) from vicidial_demographic_quotas_goals where campaign_id='$campaign_id[$i]' and quota_status='ACTIVE';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $quota_status_active_count = $aryA[0]; + } + $sthA->finish(); + + $hopper_begin_output .= " quota fields: $fields_count \n"; + $hopper_begin_output .= " quota values: $fields_values_count \n"; + $hopper_begin_output .= " total filled: $total_filled_count newly filled: $newly_filled_count \n"; + $hopper_begin_output .= " total active: $quota_status_active_count \n"; + + ### archive inactive vicidial_demographic_quotas_goals records for this campaign + $stmtA = "UPDATE vicidial_demographic_quotas_goals SET quota_status='ARCHIVE' where campaign_id='$campaign_id[$i]' and quota_status IN('FPENDING','PENDING');"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "Archiving inactive vicidial_demographic_quotas_goals records for this campaign: $affected_rows\n"; + + ### Update all newly filled demos in vicidial_list to rank = -9999 + if (length($newly_filledSQL) > 10) + { + $newly_filledSQL .= " )"; + $temp_start_time = time(); + $stmtA = "UPDATE vicidial_list SET rank='-9999' where list_id IN($all_listsSQL) $newly_filledSQL;"; + $affected_rows = $dbhA->do($stmtA); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "Newly filled demographics leads set to low rank: $affected_rows\n"; + + ### set NEW_FILLED vicidial_demographic_quotas_goals records to FILLED for this campaign + $stmtA = "UPDATE vicidial_demographic_quotas_goals SET quota_status='FILLED' where campaign_id='$campaign_id[$i]' and quota_status IN('NEW_FILLED');"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "set NEW_FILLED vicidial_demographic_quotas_goals records to FILLED for this campaign: $affected_rows\n"; + } + + if ($DBX) {print "DQ DEBUG: Re-Rank tests: |$force_rerank|$newly_filled_count|$demographic_quotas_rerank[$i]|$min|\n";} + + if ( ($force_rerank > 0) || ($newly_filled_count > 0) || ($demographic_quotas_rerank[$i] =~ /MINUTE|NOW/) || ( ($demographic_quotas_rerank[$i] =~ /HOUR/) && ($min < 1) ) || ($demographic_quotas_last_rerank[$i] eq '2000-01-01 00:00:00') ) + { + $rerank_output .= "STARTING LEAD RE-RANKING: $demographic_quotas_rerank[$i] $now_date\n"; + + ### Update all existing filled demos in vicidial_list to rank = -9999 + if (length($existing_filledSQL) > 10) + { + $existing_filledSQL .= " )"; + $temp_start_time = time(); + $stmtA = "UPDATE vicidial_list SET rank='-9999' where list_id IN($all_listsSQL) $existing_filledSQL;"; + $affected_rows = $dbhA->do($stmtA); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + if ($DBX) {print "DQ DEBUG: $affected_rows|$stmtA|\n";} + $hopper_begin_output .= "Existing filled demographics leads set to low rank: $affected_rows\n"; + $rerank_output .= "Existing filled demographics leads set to low rank: $affected_rows\n"; + } + + ##### BEGIN loop through the ACTIVE vicidial_demographic_quotas_goals and update the vicidial_list ranks for the leads in this campaign + $stmtA = "SELECT quota_field,quota_field_order,quota_value,quota_value_order,quota_goal,quota_count,quota_leads_total,quota_leads_active from vicidial_demographic_quotas_goals where campaign_id='$campaign_id[$i]' and quota_status='ACTIVE' order by quota_field_order,quota_value_order;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsT=$sthA->rows; + $qt=0; + $field_levels='|'; + $field_val_levels='|'; + $field_levels_ct=0; + while ($sthArowsT > $qt) + { + @aryA = $sthA->fetchrow_array; + $Tquota_field[$qt] = $aryA[0]; + $Tquota_field_order[$qt] = $aryA[1]; + $Tquota_value[$qt] = $aryA[2]; + $Tquota_value_order[$qt] = $aryA[3]; + $Tquota_goal[$qt] = $aryA[4]; + $Tquota_count[$qt] = $aryA[5]; + $Tquota_leads_total[$qt] = $aryA[6]; + $Tquota_leads_active[$qt] = $aryA[7]; + if ($qt < 1) + { + $field_levels.="$Tquota_field_order[$qt]|"; + $field_val_levels.="$Tquota_field_order[$qt]x$Tquota_value_order[$qt]|"; + $field_levels_ct++; + } + else + { + if ($field_levels !~ /\|$Tquota_field_order[$qt]\|/) + { + $field_levels.="$Tquota_field_order[$qt]|"; + $field_val_levels.="$Tquota_field_order[$qt]x$Tquota_value_order[$qt]|"; + $field_levels_ct++; + } + } + $rerank_output .= " Re-Rank Debug - Active goal $qt: $Tquota_field[$qt]|$Tquota_value[$qt]|$Tquota_goal[$qt]|$Tquota_count[$qt]|$field_levels_ct|\n"; + $qt++; + } + $sthA->finish(); + + $rs=0; + $end_of_queries=0; + $last_firstSQL=''; + @rankingSQL_ary = @MT; + + # if only one field (level) is active, then don't include next level in SQL queries + if ($field_levels_ct <= 1) + { + $rerank_output .= " Re-Rank Debug - rank SQL only 1 field level: |$field_levels_ct|\n"; + $qt=0; + $first_sort_field_rank=0; + $first_sort_value_rank=0; + $temp_firstSQL=''; + + while ($sthArowsT > $qt) + { + if ($Tquota_field_order[$qt] > 0) + { + $rankingSQL_ary[$rs] = "and ($Tquota_field[$qt]=\"$Tquota_value[$qt]\")"; + $rerank_output .= " Re-Rank Debug - rank SQL $rs: |$rankingSQL_ary[$rs]|\n"; + $rs++; + } + $qt++; + } + } + else + { + # More than one field (level) is active, then include next level in SQL queries + $rerank_output .= " Re-Rank Debug - rank SQL multiple field levels: |$field_levels_ct|\n"; + while ($end_of_queries < 10) + { + $qt=0; + $first_sort_field_rank=0; + $first_sort_value_rank=0; + $temp_firstSQL=''; + $field_val_rs='|'; + + while ($sthArowsT > $qt) + { + if ($first_sort_field_rank < 1) + { + if ($Tquota_field_order[$qt] > 0) + { + $first_sort_field_rank = $Tquota_field_order[$qt]; + $first_sort_value_rank = $Tquota_value_order[$qt]; + $temp_firstSQL = "and ($Tquota_field[$qt]=\"$Tquota_value[$qt]\")"; + $Tquota_field_order[$qt]=0; + } + } + else + { + if ($Tquota_field_order[$qt] > $first_sort_field_rank) + { + $rankingSQL_ary[$rs] = "$temp_firstSQL and ($Tquota_field[$qt]=\"$Tquota_value[$qt]\")"; + $rerank_output .= " Re-Rank Debug - rank SQL $rs: |$rankingSQL_ary[$rs]|\n"; + $rs++; + } + } + $qt++; + } + + $end_of_queries++; + } + } + + $temp_rank=3000; + $to=0; + while ( ($rs > $to) && ($ranked_leads < $ranking_limit[$i]) ) + { + $temp_rank = ($temp_rank - 1); + print "$to $rankingSQL_ary[$to] \n"; + + $temp_start_time = time(); + $stmtA = "UPDATE vicidial_list SET rank='$temp_rank' where list_id IN($all_listsSQL) and (rank < $temp_rank) $rankingSQL_ary[$to];"; + $affected_rows = $dbhA->do($stmtA); + $ranked_leads = ($ranked_leads + $affected_rows); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + if ($DBX) {print "DQ DEBUG: $affected_rows|$ranked_leads|$stmtA|\n";} + $hopper_begin_output .= "ORDER LEVEL $to: leads set to rank $temp_rank: $affected_rows |$ranked_leads|$rankingSQL_ary[$to]|\n"; + $rerank_output .= "ORDER LEVEL $to: leads set to rank $temp_rank: $affected_rows |$ranked_leads|$rankingSQL_ary[$to]|\n"; + + $to++; + } + if ($ranked_leads >= $ranking_limit[$i]) + { + if ($DBX) {print "DQ DEBUG: REACHED LEAD RANK LIMIT FOR $demographic_quotas_rerank[$i]: ($ranked_leads >= $ranking_limit[$i]) \n";} + $hopper_begin_output .= " REACHED LEAD RANK LIMIT FOR $demographic_quotas_rerank[$i]: ($ranked_leads >= $ranking_limit[$i]) \n"; + $rerank_output .= " REACHED LEAD RANK LIMIT FOR $demographic_quotas_rerank[$i]: ($ranked_leads >= $ranking_limit[$i]) \n"; + } + ##### END loop through the ACTIVE vicidial_demographic_quotas_goals and update the vicidial_list ranks for the leads in this campaign + + $campaign_updated=0; + if ($demographic_quotas_rerank[$i] =~ /NOW_HOUR/) + { + # set demographic_quotas_rerank back to HOUR if set to NOW_HOUR + $demographic_quotas_rerank[$i]='HOUR'; + $stmtA = "UPDATE vicidial_campaigns SET demographic_quotas_rerank='HOUR',demographic_quotas_last_rerank=NOW() where campaign_id='$campaign_id[$i]' and demographic_quotas_rerank='NOW_HOUR';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: Re-Rank set back to HOUR: |$affected_rows|$stmtA| \n";} + $campaign_updated++; + } + if ($demographic_quotas_rerank[$i] =~ /NOW/) + { + # set demographic_quotas_rerank back to NO if set to NOW + $demographic_quotas_rerank[$i]='NO'; + $stmtA = "UPDATE vicidial_campaigns SET demographic_quotas_rerank='NO',demographic_quotas_last_rerank=NOW() where campaign_id='$campaign_id[$i]' and demographic_quotas_rerank='NOW';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: Re-Rank set back to N: |$affected_rows|$stmtA| \n";} + $campaign_updated++; + } + if ($campaign_updated < 1) + { + # set demographic_quotas_rerank back to NO if set to NOW + $demographic_quotas_rerank[$i]='NO'; + $stmtA = "UPDATE vicidial_campaigns SET demographic_quotas_last_rerank=NOW() where campaign_id='$campaign_id[$i]';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: Last Re-Rank date updated: |$affected_rows|$stmtA| \n";} + $campaign_updated++; + } + } + } + + + + ##### BEGIN auto-list-reset process ##### + if ( ($demographic_quotas_list_resets[$i] eq 'AUTO') && ($RUNgoals > 0) ) + { + if ($DBX) {print "DQ List AUTO Resets enabled, checking hopper count: $demographic_quotas_list_resets[$i] \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, checking hopper count: $demographic_quotas_list_resets[$i] \n"; + $hopper_leads=0; + $stmtA="SELECT count(*) FROM vicidial_hopper where campaign_id='$campaign_id[$i]' and status IN('READY');"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $hopper_leads = $aryA[0]; + } + $sthA->finish(); + + if ($hopper_leads < 1) + { + if ($DBX) {print "DQ List AUTO Resets enabled, hopper empty, checking for dialable leads next: $hopper_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, hopper empty, checking for dialable leads next: $hopper_leads \n"; + $dialable_leads=0; + $stmtA = "SELECT dialable_leads from vicidial_campaign_stats where campaign_id='$campaign_id[$i]';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $dialable_leads = $aryA[0]; + } + $sthA->finish(); + + if ($dialable_leads < 1) + { + if ($DBX) {print "DQ List AUTO Resets enabled, no dialable leads, checking for active lists next: $dialable_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, no dialable leads, checking for active lists next: $dialable_leads \n"; + + if (length($active_lists) > 2) + { + if ($DBX) {print "DQ List AUTO Resets enabled, active lists set, checking for list resets in last 5 minutes next: $active_lists \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, active lists set, checking for list resets in last 5 minutes next: $active_lists \n"; + $recent_resets=0; + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_admin_log where event_section='LISTS' and event_type='RESET' and record_id IN($all_listsSQL) and event_date > NOW()-INTERVAL 5 MINUTE;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $recent_resets = $aryA[0]; + } + $sthA->finish(); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + + if ($recent_resets < 1) + { + if ($DBX) {print "DQ List AUTO Resets enabled, no recent resets, checking for dialable leads within timezones next: $recent_resets $temp_query_time sec \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, no recent resets, checking for dialable leads within timezones next: $recent_resets $temp_query_time sec \n"; + + ##### BEGIN calculate what gmt_offset_now values are within the allowed local_call_time setting ### + $g=0; + $p='13'; + $GMT_gmt[0] = ''; + $GMT_hour[0] = ''; + $GMT_day[0] = ''; + if ($DBX) {print "\n |GMT-DAY-HOUR| ";} + while ($p > -13) + { + $pzone = ($GMT_now + ($p * 3600)); + ($psec,$pmin,$phour,$pmday,$pmon,$pyear,$pday,$pyday,$pisdst) = localtime($pzone); + $phour=($phour * 100); + $tz = sprintf("%.2f", $p); + $GMT_gmt[$g] = "$tz"; + $GMT_day[$g] = "$pday"; + $GMT_hour[$g] = ($phour + $pmin); + $p = ($p - 0.25); + if ($DBX) {print "|$GMT_gmt[$g]-$GMT_day[$g]-$GMT_hour[$g]|";} + $g++; + } + if ($DBX) {print "\n";} + + $stmtA = "SELECT call_time_id,call_time_name,call_time_comments,ct_default_start,ct_default_stop,ct_sunday_start,ct_sunday_stop,ct_monday_start,ct_monday_stop,ct_tuesday_start,ct_tuesday_stop,ct_wednesday_start,ct_wednesday_stop,ct_thursday_start,ct_thursday_stop,ct_friday_start,ct_friday_stop,ct_saturday_start,ct_saturday_stop,ct_state_call_times,ct_holidays FROM vicidial_call_times where call_time_id='$local_call_time[$i]';"; + if ($DBX) {print " |$stmtA|\n";} + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + $rec_count=0; + while ($sthArows > $rec_count) + { + @aryA = $sthA->fetchrow_array; + $Gct_default_start = $aryA[3]; + $Gct_default_stop = $aryA[4]; + $Gct_sunday_start = $aryA[5]; + $Gct_sunday_stop = $aryA[6]; + $Gct_monday_start = $aryA[7]; + $Gct_monday_stop = $aryA[8]; + $Gct_tuesday_start = $aryA[9]; + $Gct_tuesday_stop = $aryA[10]; + $Gct_wednesday_start = $aryA[11]; + $Gct_wednesday_stop = $aryA[12]; + $Gct_thursday_start = $aryA[13]; + $Gct_thursday_stop = $aryA[14]; + $Gct_friday_start = $aryA[15]; + $Gct_friday_stop = $aryA[16]; + $Gct_saturday_start = $aryA[17]; + $Gct_saturday_stop = $aryA[18]; + $Gct_state_call_times = $aryA[19]; + $Gct_holidays = $aryA[20]; + $rec_count++; + } + $sthA->finish(); + ### BEGIN Check for outbound call time holiday ### + $holiday_id = ''; + if (length($Gct_holidays)>2) + { + $Gct_holidaysSQL = $Gct_holidays; + $Gct_holidaysSQL =~ s/^\||\|$//gi; + $Gct_holidaysSQL =~ s/\|/','/gi; + $Gct_holidaysSQL = "'$Gct_holidaysSQL'"; + + $stmtC = "SELECT holiday_id,holiday_date,holiday_name,ct_default_start,ct_default_stop from vicidial_call_time_holidays where holiday_id IN($Gct_holidaysSQL) and holiday_status='ACTIVE' and holiday_date='$YMD' order by holiday_id;"; + if ($DBX) {print " |$stmtC|\n";} + $sthC = $dbhA->prepare($stmtC) or die "preparing: ",$dbhA->errstr; + $sthC->execute or die "executing: $stmtC ", $dbhA->errstr; + $sthCrows=$sthC->rows; + if ($sthCrows > 0) + { + @aryC = $sthC->fetchrow_array; + $holiday_id = $aryC[0]; + $holiday_date = $aryC[1]; + $holiday_name = $aryC[2]; + if ( ($Gct_default_start < $aryC[3]) && ($Gct_default_stop > 0) ) {$Gct_default_start = $aryC[3];} + if ( ($Gct_default_stop > $aryC[4]) && ($Gct_default_stop > 0) ) {$Gct_default_stop = $aryC[4];} + if ( ($Gct_sunday_start < $aryC[3]) && ($Gct_sunday_stop > 0) ) {$Gct_sunday_start = $aryC[3];} + if ( ($Gct_sunday_stop > $aryC[4]) && ($Gct_sunday_stop > 0) ) {$Gct_sunday_stop = $aryC[4];} + if ( ($Gct_monday_start < $aryC[3]) && ($Gct_monday_stop > 0) ) {$Gct_monday_start = $aryC[3];} + if ( ($Gct_monday_stop > $aryC[4]) && ($Gct_monday_stop > 0) ) {$Gct_monday_stop = $aryC[4];} + if ( ($Gct_tuesday_start < $aryC[3]) && ($Gct_tuesday_stop > 0) ) {$Gct_tuesday_start = $aryC[3];} + if ( ($Gct_tuesday_stop > $aryC[4]) && ($Gct_tuesday_stop > 0) ) {$Gct_tuesday_stop = $aryC[4];} + if ( ($Gct_wednesday_start < $aryC[3]) && ($Gct_wednesday_stop > 0) ) {$Gct_wednesday_start = $aryC[3];} + if ( ($Gct_wednesday_stop > $aryC[4]) && ($Gct_wednesday_stop > 0) ) {$Gct_wednesday_stop = $aryC[4];} + if ( ($Gct_thursday_start < $aryC[3]) && ($Gct_thursday_stop > 0) ) {$Gct_thursday_start = $aryC[3];} + if ( ($Gct_thursday_stop > $aryC[4]) && ($Gct_thursday_stop > 0) ) {$Gct_thursday_stop = $aryC[4];} + if ( ($Gct_friday_start < $aryC[3]) && ($Gct_friday_stop > 0) ) {$Gct_friday_start = $aryC[3];} + if ( ($Gct_friday_stop > $aryC[4]) && ($Gct_friday_stop > 0) ) {$Gct_friday_stop = $aryC[4];} + if ( ($Gct_saturday_start < $aryC[3]) && ($Gct_saturday_stop > 0) ) {$Gct_saturday_start = $aryC[3];} + if ( ($Gct_saturday_stop > $aryC[4]) && ($Gct_saturday_stop > 0) ) {$Gct_saturday_stop = $aryC[4];} + if ($DB) {print " CALL TIME HOLIDAY FOUND! $local_call_time[$i]|$holiday_id|$holiday_date|$holiday_name|$Gct_default_start|$Gct_default_stop|\n";} + $hopper_begin_output .= " CALL TIME HOLIDAY FOUND! $local_call_time[$i]|$holiday_id|$holiday_date|$holiday_name|$Gct_default_start|$Gct_default_stop|\n"; + } + $sthC->finish(); + } + ### END Check for outbound call time holiday ### + + $r=0; + @default_gmt_ARY=@MT; + $dgA=0; + $default_gmt=''; + while($r < $g) + { + if ($GMT_day[$r]==0) #### Sunday local time + { + if (($Gct_sunday_start==0) && ($Gct_sunday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_sunday_start) && ($GMT_hour[$r]<$Gct_sunday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==1) #### Monday local time + { + if (($Gct_monday_start==0) && ($Gct_monday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_monday_start) && ($GMT_hour[$r]<$Gct_monday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==2) #### Tuesday local time + { + if (($Gct_tuesday_start==0) && ($Gct_tuesday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_tuesday_start) && ($GMT_hour[$r]<$Gct_tuesday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==3) #### Wednesday local time + { + if (($Gct_wednesday_start==0) && ($Gct_wednesday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_wednesday_start) && ($GMT_hour[$r]<$Gct_wednesday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==4) #### Thursday local time + { + if (($Gct_thursday_start==0) && ($Gct_thursday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_thursday_start) && ($GMT_hour[$r]<$Gct_thursday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==5) #### Friday local time + { + if (($Gct_friday_start==0) && ($Gct_friday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_friday_start) && ($GMT_hour[$r]<$Gct_friday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + if ($GMT_day[$r]==6) #### Saturday local time + { + if (($Gct_saturday_start==0) && ($Gct_saturday_stop==0)) + { + if ( ($GMT_hour[$r]>=$Gct_default_start) && ($GMT_hour[$r]<$Gct_default_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + else + { + if ( ($GMT_hour[$r]>=$Gct_saturday_start) && ($GMT_hour[$r]<$Gct_saturday_stop) ) + {$default_gmt.="'$GMT_gmt[$r]',"; $default_gmt_ARY[$dgA] = "$GMT_gmt[$r]"; $dgA++;} + } + } + $r++; + } + + $default_gmt = "$default_gmt'99'"; + $all_gmtSQL[$i] = "(gmt_offset_now IN($default_gmt))"; + # $del_gmtSQL[$i] = "(gmt_offset_now NOT IN($default_gmt)"; + + ##### END calculate what gmt_offset_now values are within the allowed local_call_time setting ### + + $dial_statuses[$i] =~ s/ -$//gi; + @Dstatuses = split(/ /,$dial_statuses[$i]); + $Ds_to_print = (($#Dstatuses) + 0); + $STATUSsql[$i]=''; + $o=0; + while ($Ds_to_print > $o) + { + $o++; + $STATUSsql[$i] .= "'$Dstatuses[$o]',"; + } + if (length($STATUSsql[$i])<3) {$STATUSsql[$i]="''";} + else {chop($STATUSsql[$i]);} + + $CCLsql[$i]=''; + if ($call_count_limit[$i] > 0) + { + $CCLsql[$i] = "and (called_count < $call_count_limit[$i])"; + if ($DB) {print " total call count limit $call_count_limit[$i] defined for $campaign_id[$i]\n";} + if ($DBX) {print " |$CCLsql[$i]|\n";} + $hopper_begin_output .= " total call count limit $call_count_limit[$i] defined for $campaign_id[$i] \n"; + } + + $time_callable_leads=0; + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_list where list_id IN($active_lists) and status IN($STATUSsql[$i]) and ($all_gmtSQL[$i]) and (rank != '-9999') $CCLsql[$i];"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $time_callable_leads = $aryA[0]; + } + $sthA->finish(); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + $hopper_begin_output .= " DQ DEBUG: $time_callable_leads|$stmtA| $temp_query_time sec \n"; + + if ($time_callable_leads > 0) + { + if ($DBX) {print "DQ List AUTO Resets enabled, time-callable leads available, resetting lists next: $time_callable_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, time-callable leads available, resetting lists next: $time_callable_leads \n"; + + # gather active lists in this campaign that can still be reset + $stmtA = "SELECT list_id FROM vicidial_lists where ( (active='Y') and (expiration_date >= \"$file_date\") ) and (campaign_id='$campaign_id[$i]') and ( (resets_today < daily_reset_limit) or (daily_reset_limit < 0) ) and (resets_today < 4);"; + $resetable_lists[0]=''; + $resetable_lists_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "$sthArows|$stmtA|\n";} + while ($sthArows > $resetable_lists_count) + { + @aryA = $sthA->fetchrow_array; + $resetable_lists[$resetable_lists_count] = $aryA[0]; + $resetable_lists_count++; + } + $sthA->finish(); + + if ($resetable_lists_count > 0) + { + if ($DB) {print "DQ List AUTO Reset, checking each list for resets within 3 hours: $resetable_lists_count \n";} + $hopper_begin_output .= "DQ List AUTO Reset, checking each list for resets within 3 hours: $resetable_lists_count \n"; + $tlc=0; + $lists_reset=0; + while ($tlc < $resetable_lists_count) + { + $reset_3_hours_ago=0; + $temp_start_time = time(); + $stmtA = "SELECT count(*) from vicidial_admin_log where event_section='LISTS' and event_type='RESET' and record_id='$resetable_lists[$tlc]' and event_date > NOW()-INTERVAL 3 HOUR;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $reset_3_hours_ago = $aryA[0]; + } + $sthA->finish(); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + + $hopper_begin_output .= " DQ DEBUG - list $resetable_lists[$tlc]: $reset_3_hours_ago|$stmtA|\n"; + + if ($reset_3_hours_ago < 1) + { + if ($DBX) {print "DQ List AUTO Reset, no recent reset for list $resetable_lists[$tlc], resetting this list: $reset_3_hours_ago $temp_query_time \n";} + $hopper_begin_output .= "DQ List AUTO Reset, no recent reset for list $resetable_lists[$tlc], resetting this list: $reset_3_hours_ago $temp_query_time \n"; + + $stmtA="UPDATE vicidial_lists set resets_today=(resets_today + 1) where list_id='$resetable_lists[$tlc]';"; + $affected_rows = $dbhA->do($stmtA); + + $temp_start_time = time(); + $stmtB="UPDATE vicidial_list set called_since_last_reset='N' where list_id='$resetable_lists[$tlc]';"; + $affected_rowsB = $dbhA->do($stmtB); + $temp_end_time = time(); + $temp_query_time = ($temp_end_time - $temp_start_time); + if ($temp_query_time > $longest_query_time) + {$longest_query_time = $temp_query_time;} + + $SQL_log = "$stmtA|$stmtB|"; + $SQL_log =~ s/;|\\|\'|\"//gi; + + if ($DB) {print "List Reset DONE: $resetable_lists[$tlc]($affected_rows|$affected_rowsB) $temp_query_time sec \n";} + + $stmtA="INSERT INTO vicidial_admin_log set event_date='$now_date', user='VDAD', ip_address='1.1.1.1', event_section='LISTS', event_type='RESET', record_id='$resetable_lists[$tlc]', event_code='ADMIN DQ RESET LIST', event_sql=\"$SQL_log\", event_notes='$affected_rowsB leads reset, resets count updated $affected_rows';"; + $Iaffected_rows = $dbhA->do($stmtA); + if ($DB) {print "FINISHED: $affected_rows|$Iaffected_rows|$stmtA";} + + $lists_reset++; + } + $tlc++; + } + if ( ($lists_reset > 0) && ($demographic_quotas_rerank[$i] !~ /MINUTE|NOW/) ) + { + $temp_rerank='NOW'; + if ($demographic_quotas_rerank[$i] =~ /HOUR/) {$temp_rerank='NOW_HOUR';} + $stmtA = "UPDATE vicidial_campaigns SET demographic_quotas_rerank='$temp_rerank' where campaign_id='$campaign_id[$i]';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "DQ DEBUG: Force Re-Rank set for campaign: |$affected_rows|$stmtA| \n";} + $hopper_begin_output .= "DQ DEBUG: Force Re-Rank set for campaign: |$affected_rows|$stmtA| \n"; + } + if ($DB) {print "DQ Lists Reset for campaign: $lists_reset|$campaign_id[$i] \n";} + $hopper_begin_output .= "DQ Lists Reset for campaign: $lists_reset|$campaign_id[$i] \n"; + } + else + { + if ($DB) {print "DQ List AUTO Reset, no resettable lists available: $resetable_lists_count \n";} + $hopper_begin_output .= "DQ List AUTO Reset, no resettable lists available: $resetable_lists_count \n"; + } + } + else + { + if ($DBX) {print "DQ List AUTO Resets enabled, time-callable leads not available: $time_callable_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, time-callable leads not available: $time_callable_leads \n"; + } + } + else + { + if ($DBX) {print "DQ List AUTO Resets enabled, recent list resets: $recent_resets $temp_query_time sec \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, recent list resets: $recent_resets $temp_query_time sec \n"; + } + } + else + { + if ($DBX) {print "DQ List AUTO Resets enabled, no active lists present: $active_lists \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, no active lists present: $active_lists \n"; + } + } + else + { + if ($DBX) {print "DQ List AUTO Resets enabled, dialable leads present: $dialable_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, dialable leads present: $dialable_leads \n"; + } + } + else + { + if ($DBX) {print "DQ List AUTO Resets enabled, hopper has leads: $hopper_leads \n";} + $hopper_begin_output .= "DQ List AUTO Resets enabled, hopper has leads: $hopper_leads \n"; + } + } + ##### END auto-list-reset process ##### + + + + ##### BEGIN if leads have been ranked, wipe the hopper and force a new hopper load now for this campaign + if ($ranked_leads > 0) + { + $hopper_leads=0; + $stmtA="SELECT count(*) FROM vicidial_hopper where campaign_id='$campaign_id[$i]' and status IN('READY');"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $hopper_leads = $aryA[0]; + } + $sthA->finish(); + + if ($hopper_leads > 0) + { + $run_hopper_loop=0; + while ($run_hopper_loop < 60) + { + my $grepout = `/bin/ps ax | grep AST_VDhopper.pl | grep -v grep | grep -v '/bin/sh'`; + my $grepnum=0; + $grepnum++ while ($grepout =~ m/\n/g); + if ($grepnum > 0) + { + if ($DB) {print "hopper running, waiting $run_hopper_loop";} + $hopper_begin_output .= "hopper running, waiting $run_hopper_loop"; + sleep(1); + } + else + { + $stmtB="DELETE FROM vicidial_hopper WHERE campaign_id='$campaign_id[$i]';"; + $affected_rowsB = $dbhA->do($stmtB); + if ($DB) {print "\nHopper Reset DONE, launching hopper in screen next: $affected_rowsB $campaign_id[$i] \n";} + $hopper_begin_output .= "\nHopper Reset DONE, launching hopper in screen next: $affected_rowsB $campaign_id[$i] \n"; + + # gather hopper run flags + $hopper_flags=''; + $stmtA="SELECT container_entry FROM vicidial_settings_containers where container_id='HOPPER_CLI_FLAGS';"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "DQ DEBUG: |$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $hopper_flags = $aryA[0]; + $hopper_flags =~ s/[^a-zA-Z0-9 _-]//gi; + } + $sthA->finish(); + + $hopper_command = "/usr/bin/screen -d -m -S DQ$reset_test$campaign_id[$i] $PATHhome/AST_VDhopper.pl --debugX --campaign=$campaign_id[$i] $hopper_flags "; + `$hopper_command`; + if ($DB) {print "Hopper run triggered: |$hopper_command|\n";} + $hopper_begin_output .= "Hopper run triggered: |$hopper_command|\n"; + $run_hopper_loop=61; + } + $run_hopper_loop++; + } + } + } + ##### END if leads have been ranked, wipe the hopper and force a new hopper load now for this campaign + + +# $hopper_begin_output .= " DQ DEBUG, COMPLETE check: |$newly_filled_count|$demographic_quotas[$i]|$total_filled_count|$quota_status_active_count|\n"; + + ##### BEGIN set all leads in active campaign lists to rank=-9999 if all quota goals newly filled + if ( ( ($newly_filled_count > 0) || ( ($demographic_quotas[$i] =~ /ENABLED/) && ($total_filled_count > 0) ) ) && ($quota_status_active_count < 1) ) + { + $stmtB = "UPDATE vicidial_list SET rank='-9999',called_since_last_reset='Y' where list_id IN($active_lists) and (rank != '-9999');"; + $affected_rowsB = $dbhA->do($stmtB); + + $stmtB = "UPDATE vicidial_campaigns SET demographic_quotas='COMPLETE' where campaign_id='$campaign_id[$i]';"; + $affected_rowsC = $dbhA->do($stmtB); + + $stmtB = "DELETE FROM vicidial_hopper WHERE campaign_id='$campaign_id[$i]';"; + $affected_rowsH = $dbhA->do($stmtB); + + if ($DB) {print "Quota Goals Complete, all active leads set to called with -9999 rank: $affected_rowsB $affected_rowsC $campaign_id[$i] \n";} + $hopper_begin_output .= "Quota Goals Complete, all active leads set to called with -9999 rank: $affected_rowsB $affected_rowsC $affected_rowsH $campaign_id[$i] \n"; + } + ##### END set all leads in active campaign lists to rank=-9999 if all quota goals newly filled + + + $secCF[$i] = time(); + $camp_run_time = ($secCF[$i] - $secC[$i]); + $hopper_begin_output .= "DQ Campaign run time: $camp_run_time seconds longest query time: $longest_query_time \n"; + + # update debug output + $hopper_begin_output =~ s/"/'/gi; + $rerank_output =~ s/"/'/gi; + $rerank_outputSQL=''; + if (length($rerank_output) > 10) + {$rerank_outputSQL = ",adapt_output=\"$rerank_output\"";} + $stmtA = "UPDATE vicidial_campaign_stats_debug SET entry_time='$now_date',debug_output=\"$hopper_begin_output\"$rerank_outputSQL where campaign_id='$campaign_id[$i]' and server_ip='DEMO_QUOTAS';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "vicidial_campaign_stats_debug UPDATE: $affected_rows|$stmtA|\n";} + + $event_string = $hopper_begin_output; + &event_logger; + + $i++; + } + + +$dbhA->disconnect(); + +if($DB) + { + if (length($ENDoutput) > 10) + { + print "\n"; + print "SUMMARY: $i campaigns\n"; + print "$ENDoutput"; + } + ### calculate time to run script ### + $secY = time(); + $secZ = ($secY - $secT); + + if (!$q) {print "DONE. Script execution time in seconds: $secZ\n";} + } +exit; + + +##### SUBROUTINES ##### +sub event_logger + { + if ($SYSLOG) + { + ### open the log file for writing ### + open(Lout, ">>$DQLOGfile") + || die "Can't open $DQLOGfile: $!\n"; + print Lout "$now_date|$event_string|\n"; + close(Lout); + } + $event_string=''; + } diff --git a/bin/AST_VDhopper.pl b/bin/AST_VDhopper.pl index 0b16add9..23d260a8 100644 --- a/bin/AST_VDhopper.pl +++ b/bin/AST_VDhopper.pl @@ -106,10 +106,11 @@ # 210718-0343 - Fixes for 24-Hour Call Count Limits with standard Auto-Alt-Dialing # 210719-1519 - Added additional state override methods for call_limit_24hour # 220822-0938 - Change DNC check queries to put phone_number in double-quotes instead of single-quotes +# 230428-2017 - Added demographic_quotas code # # constants -$build = '220822-0938'; +$build = '230428-2017'; $script='AST_VDhopper'; $DB=0; # Debug flag, set to 0 for no debug messages. Can be overriden with CLI --debug flag $US='__'; @@ -117,6 +118,7 @@ $MT[0]=''; #$vicidial_hopper='TEST_vicidial_hopper'; # for testing only $vicidial_hopper='vicidial_hopper'; $count_only=0; +$run_check=0; # options $insert_auto_CB_to_hopper = 1; # set to 1 to automatically insert ANYONE callbacks into the hopper, default = 1 @@ -202,6 +204,7 @@ if (length($ARGV[0])>1) print " [--help] = this screen\n"; print " [--version] = print version of this script, then exit\n"; print " [--count-only] = only display the number of leads in the hopper, then exit\n"; + print " [--run-check] = concurrency check, exit if already running\n"; print " [--debug] = debug\n"; print " [--debugX] = super debug\n"; print " [--dbgmt] = show GMT offset of records as they are inserted into hopper\n"; @@ -281,6 +284,11 @@ if (length($ARGV[0])>1) { $count_only=1; } + if ($args =~ /--run-check/i) + { + $run_check=1; + if ($DB) {print "\n----- CONCURRENCY CHECK -----\n\n";} + } } } else @@ -288,6 +296,21 @@ else print "no command line options set\n"; } +### concurrency check (hopper runs should be unique) +if ($run_check > 0) + { + my $grepout = `/bin/ps ax | grep $0 | grep -v grep | grep -v '/bin/sh'`; + my $grepnum=0; + $grepnum++ while ($grepout =~ m/\n/g); + if ($grepnum > 1) + { + if ($DB) {print "I am not alone! Another $0 is running! Exiting...\n";} + $event_string = "I am not alone! Another $0 is running! Exiting..."; + &event_logger; + exit 1; + } + } + # default path to astguiclient configuration file: $PATHconf = '/etc/astguiclient.conf'; @@ -1254,11 +1277,11 @@ $ANY_hopper_vlc_dup_check='N'; if (length($CLIcampaign)>1) { - $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,lead_filter_id,use_internal_dnc,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,dial_statuses,list_order_mix,use_campaign_dnc,drop_lockout_time,no_hopper_dialing,auto_alt_dial_statuses,dial_timeout,auto_hopper_multi,use_auto_hopper,auto_trim_hopper,lead_order_randomize,lead_order_secondary,call_count_limit,hopper_vlc_dup_check,use_other_campaign_dnc,callback_dnc,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override from vicidial_campaigns where campaign_id IN('$CLIcampaign');"; + $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,lead_filter_id,use_internal_dnc,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,dial_statuses,list_order_mix,use_campaign_dnc,drop_lockout_time,no_hopper_dialing,auto_alt_dial_statuses,dial_timeout,auto_hopper_multi,use_auto_hopper,auto_trim_hopper,lead_order_randomize,lead_order_secondary,call_count_limit,hopper_vlc_dup_check,use_other_campaign_dnc,callback_dnc,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,demographic_quotas,demographic_quotas_container from vicidial_campaigns where campaign_id IN('$CLIcampaign');"; } else { - $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,lead_filter_id,use_internal_dnc,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,dial_statuses,list_order_mix,use_campaign_dnc,drop_lockout_time,no_hopper_dialing,auto_alt_dial_statuses,dial_timeout,auto_hopper_multi,use_auto_hopper,auto_trim_hopper,lead_order_randomize,lead_order_secondary,call_count_limit,hopper_vlc_dup_check,use_other_campaign_dnc,callback_dnc,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override from vicidial_campaigns where active='Y';"; + $stmtA = "SELECT campaign_id,lead_order,hopper_level,auto_dial_level,local_call_time,lead_filter_id,use_internal_dnc,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,dial_statuses,list_order_mix,use_campaign_dnc,drop_lockout_time,no_hopper_dialing,auto_alt_dial_statuses,dial_timeout,auto_hopper_multi,use_auto_hopper,auto_trim_hopper,lead_order_randomize,lead_order_secondary,call_count_limit,hopper_vlc_dup_check,use_other_campaign_dnc,callback_dnc,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,demographic_quotas,demographic_quotas_container from vicidial_campaigns where active='Y';"; } $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -1304,8 +1327,12 @@ while ($sthArows > $rec_count) $call_limit_24hour_scope[$rec_count] = $aryA[31]; $call_limit_24hour[$rec_count] = $aryA[32]; $call_limit_24hour_override[$rec_count] = $aryA[33]; + $demographic_quotas[$rec_count] = $aryA[34]; + $demographic_quotas_container[$rec_count] = $aryA[35]; + $demographic_quotasSQL[$rec_count] = ''; - + if ( ($demographic_quotas[$rec_count] =~ /ENABLED|COMPLETE/) && ( (length($demographic_quotas_container[$rec_count]) > 0) && ($demographic_quotas_container[$rec_count] !~ /DISABLED/) ) ) + {$demographic_quotasSQL[$rec_count] = "and rank!='-9999'";} if ($hopper_vlc_dup_check[$rec_count] =~ /Y/) {$ANY_hopper_vlc_dup_check = 'Y';} @@ -2903,12 +2930,12 @@ foreach(@campaign_id) ##### Get count of leads that are dialable ##### if ($list_order_mix[$i] =~ /DISABLED/) { - $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL status IN($STATUSsql[$i]) and ($list_id_sql[$i]) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i] $CCLsql[$i];"; + $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL status IN($STATUSsql[$i]) and ($list_id_sql[$i]) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i] $CCLsql[$i] $demographic_quotasSQL[$i];"; } else { if (length($list_mix_dialableSQL)<3) {$list_mix_dialableSQL="called_count < 0";} - $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL ($list_mix_dialableSQL) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i] $CCLsql[$i];"; + $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL ($list_mix_dialableSQL) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i] $CCLsql[$i] $demographic_quotasSQL[$i];"; } if ($DBX) {print " |$stmtA|\n";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; @@ -2926,7 +2953,7 @@ foreach(@campaign_id) if ( ($lead_order[$i] =~ / 2nd NEW$| 3rd NEW$| 4th NEW$| 5th NEW$| 6th NEW$/) && ($list_order_mix[$i] =~ /DISABLED/) ) { - $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL status IN('NEW') and ($list_id_sql[$i]) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i];"; + $stmtA = "SELECT count(*) FROM vicidial_list $VLforce_index where $cslrSQL status IN('NEW') and ($list_id_sql[$i]) and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $DLTsql[$i] $demographic_quotasSQL[$i];"; $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; $sthArows=$sthA->rows; @@ -3074,7 +3101,7 @@ foreach(@campaign_id) if ($hopper_vlc_dup_check[$i] =~ /Y/) {$vlc_dup_check_SQL = "and vendor_lead_code NOT IN($live_vlc$vlc_lists)";} - $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $recycle_SQL[$i] and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $dnc_blocked_lists_SQL $order_stmt limit $hopper_level[$i];"; + $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $recycle_SQL[$i] and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $demographic_quotasSQL[$i] $dnc_blocked_lists_SQL $order_stmt limit $hopper_level[$i];"; if ($DBX) {print " |$stmtA|\n";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -3135,7 +3162,7 @@ foreach(@campaign_id) if ($hopper_vlc_dup_check[$i] =~ /Y/) {$vlc_dup_check_SQL = "and vendor_lead_code NOT IN($live_vlc$vlc_lists)";} - $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL status IN('NEW') and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $dnc_blocked_lists_SQL $order_stmt limit $NEW_level;"; + $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL status IN('NEW') and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $demographic_quotasSQL[$i] $dnc_blocked_lists_SQL $order_stmt limit $NEW_level;"; if ($DBX) {print " |$stmtA|\n";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -3194,7 +3221,7 @@ foreach(@campaign_id) if ($list_order_mix[$i] =~ /DISABLED/) { - $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL status IN($STATUSsql[$i]) and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $dnc_blocked_lists_SQL $order_stmt limit $OTHER_level;"; + $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL status IN($STATUSsql[$i]) and ($list_id_sql[$i]) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $demographic_quotasSQL[$i] $dnc_blocked_lists_SQL $order_stmt limit $OTHER_level;"; if ($DBX) {print " |$stmtA|\n";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -3303,7 +3330,7 @@ foreach(@campaign_id) if ($hopper_vlc_dup_check[$i] =~ /Y/) {$vlc_dup_check_SQL = "and vendor_lead_code NOT IN($live_vlc$vlc_lists)";} - $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL ($list_mix_dialableSQL) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $dnc_blocked_lists_SQL $order_stmt limit $LM_step_goal[$x];"; + $stmtA = "SELECT lead_id,list_id,gmt_offset_now,phone_number,state,status,modify_date,user,vendor_lead_code,phone_code,postal_code FROM vicidial_list $VLforce_index where $cslrSQL ($list_mix_dialableSQL) and lead_id NOT IN($lead_id_lists) $vlc_dup_check_SQL and ($all_gmtSQL[$i]) $lead_filter_sql[$i] $CCLsql[$i] $DLTsql[$i] $demographic_quotasSQL[$i] $dnc_blocked_lists_SQL $order_stmt limit $LM_step_goal[$x];"; if ($DBX) {print " |$stmtA|\n";} $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; @@ -3673,7 +3700,7 @@ if($DB) if (!$q) {print "DONE. Script execution time in seconds: $secZ\n";} } -exit; +exit 0; ##### SUBROUTINES ##### diff --git a/bin/AST_VDremote_agents.pl b/bin/AST_VDremote_agents.pl index f17f7bcd..7ca38c56 100644 --- a/bin/AST_VDremote_agents.pl +++ b/bin/AST_VDremote_agents.pl @@ -812,7 +812,7 @@ while($one_day_interval > 0) } $sthA->finish(); - $stmtA = "INSERT INTO vicidial_live_agents (user,server_ip,conf_exten,extension,status,campaign_id,random_id,last_call_time,last_update_time,last_call_finish,closer_campaigns,channel,uniqueid,callerid,user_level,comments,last_state_change,outbound_autodial,ra_user,on_hook_agent,on_hook_ring_time,last_inbound_call_time,last_inbound_call_finish) values('$DBremote_user[$h]','$server_ip','$DBremote_conf_exten[$h]','R/$DBremote_user[$h]','READY','$DBremote_campaign[$h]','$DBremote_random[$h]','$SQLdate','$FDtsSQLdate','$SQLdate','$DBremote_closer[$h]','','','','$DBuser_level[$h]','REMOTE','$SQLdate','$CAMPAIGN_autodial[$h]','$DBuser_start[$h]','$DBon_hook_agent[$h]','$DBon_hook_ring_time[$h]','$SQLdate','$SQLdate');"; + $stmtA = "INSERT INTO vicidial_live_agents (user,server_ip,conf_exten,extension,status,campaign_id,random_id,last_call_time,last_update_time,last_call_finish,closer_campaigns,channel,uniqueid,callerid,user_level,comments,last_state_change,outbound_autodial,ra_user,on_hook_agent,on_hook_ring_time,last_inbound_call_time,last_inbound_call_finish,lead_id) values('$DBremote_user[$h]','$server_ip','$DBremote_conf_exten[$h]','R/$DBremote_user[$h]','READY','$DBremote_campaign[$h]','$DBremote_random[$h]','$SQLdate','$FDtsSQLdate','$SQLdate','$DBremote_closer[$h]','','','','$DBuser_level[$h]','REMOTE','$SQLdate','$CAMPAIGN_autodial[$h]','$DBuser_start[$h]','$DBon_hook_agent[$h]','$DBon_hook_ring_time[$h]','$SQLdate','$SQLdate','0');"; $affected_rows = $dbhA->do($stmtA); if ($DBX) {print STDERR "$DBremote_user[$h] NEW INSERT\n";} if ($TESTrun > 0) @@ -831,7 +831,7 @@ while($one_day_interval > 0) if ($number_of_lines > $LSC_count) { $SIqueryCID = "T$CIDdate$DBremote_conf_exten[$h]"; - $stmtA="INSERT INTO vicidial_manager values('','','$SQLdate','NEW','N','$server_ip','','Originate','$SIqueryCID','Channel: $local_DEF$DBremote_conf_exten[$h]$local_AMP$ext_context','Context: $ext_context','Exten: 999999999999','Priority: 1','Callerid: $SIqueryCID','','','','','');"; + $stmtA="INSERT INTO vicidial_manager set uniqueid = '', entry_date = '$SQLdate', status = 'NEW', response = 'N', server_ip = '$server_ip', channel = '', action = 'Originate', callerid = '$SIqueryCID', cmd_line_b = 'Channel: $local_DEF$DBremote_conf_exten[$h]$local_AMP$ext_context', cmd_line_c = 'Context: $ext_context', cmd_line_d = 'Exten: 999999999999', cmd_line_e = 'Priority: 1', cmd_line_f = 'Callerid: $SIqueryCID', cmd_line_g = '', cmd_line_h = '', cmd_line_i = '', cmd_line_j = '', cmd_line_k = '';"; $affected_rows = $dbhA->do($stmtA); if ($DBX) {print STDERR " TESTrun CALL PLACED: 999999999999 $DBremote_conf_exten[$h] $DBremote_user[$h] NEW INSERT: |$affected_rows|\n";} } diff --git a/bin/AST_latency_gaps.pl b/bin/AST_latency_gaps.pl new file mode 100644 index 00000000..9f3d625d --- /dev/null +++ b/bin/AST_latency_gaps.pl @@ -0,0 +1,1178 @@ +#!/usr/bin/perl +# +# AST_latency_gaps.pl version 2.12 +# +# DESCRIPTION: +# - checks for latency gaps in agent screen logs +# +# This script can be run manually as needed, or put into the crontab on one server +# +# Latency connection problem detector program: +# - Live-Mode: check on vicidial_live_agents agents, check for the last minute of latency log records, count number, if less than 55 then run deeper analysis +# - Recent-Mode: check on 30 seconds ago to 90 seconds ago, if less than 55 records then run deeper analysis +# - Long-Recent-Mode: check on agents that were logged in 1 minute ago to 62 minutes ago, if less than X records, run further analysis +# - 24-hour-Mode: run at TEOD check for each agent LOGIN to LOGOUT, count number records comparing against number of seconds logged in +# +# Settings Container settings: +# minimum_gap => 10 +# email_sender => info@vicidial.com +# email_list => info@vicidial.com,test@vicidial.com +# email_subject => Agent Latency Gap Detected +# +# Copyright (C) 2023 Matt Florell LICENSE: AGPLv2 +# +# CHANGES +# 230430-0800 - First build +# + +$build = '230430-0800'; +$MT[0]=''; +$minimum_gap=10; +$CLIminimum_gap=''; +$check_user_sessions=0; +$vicidial_agent_latency_log = 'vicidial_agent_latency_log'; +$gaps_found=0; +$email_gaps_notice=0; +$email_message=''; +$day_end_report=0; +$day_end_hours=18; +$day_end_groups=''; +$group_groups[0]=''; +$group_email[0]=''; +$group_email_message[0]=''; +$group_group_count=0; +$group_group_list='|'; + +use Time::Local; + +### begin parsing run-time options ### +if (length($ARGV[0])>1) + { + $i=0; + while ($#ARGV >= $i) + { + $args = "$args $ARGV[$i]"; + $i++; + } + + if ($args =~ /--version/i) + { + print "build: $build\n"; + + exit; + } + if ($args =~ /--help/i) + { + print "allowed run time options:\n"; + print " [-q] = quiet\n"; + print " [-t] = test\n"; + print " [--version] = show version of this script\n"; + print " [--help] = this screen\n"; + print " [--debug] = debugging messages\n"; + print " [--debugX] = Extra debugging messages\n"; + print " [--container=XXX] = REQUIRED, the specifications to run these checks with\n"; + print " [--live] = check current logged-in agents only for the last 2 minutes\n"; + print " [--fresh] = check agent records for 30-150 seconds ago\n"; + print " [--recent] = check agent records for 1-63 minutes ago\n"; + print " [--24-hours] = check agent records for the last 24 hours(until last timeclock-end-of-day)\n"; + print " [--date=XXX] = check agent records for this specific date YYYY-MM-DD\n"; + print " [--minimum-gap=XXX] = override settings container with this gap seconds\n"; + print " [--check-user-sessions] = check by all user sessions (recommended only for --date=X or --24-hours runs)\n"; + print " [--email-gaps-notice] = if gaps are found, send email using container settings\n"; + print " [--day-end-report] = only run day-end report, now\n"; + print "\n"; + + exit; + } + else + { + if ($args =~ /-q/i) + { + $q=1; $Q=1; + } + if ($args =~ /--debug/i) + { + $DB=1; + print "\n----- DEBUGGING -----\n\n"; + } + if ($args =~ /--debugX/i) + { + $DBX=1; + print "\n----- EXTRA DEBUGGING -----\n\n"; + } + if ($args =~ /-t|--test/i) + { + $T=1; $TEST=1; + print "\n----- TESTING -----\n\n"; + } + if ($args =~ /--container=/i) + { + @data_in = split(/--container=/,$args); + $container = $data_in[1]; + $container =~ s/ .*$//gi; + if ($Q < 1) + {print "\n----- SETTINGS CONTAINER: $container -----\n\n";} + } + if (length($container) < 1) + { + print "ERROR! Invalid Settings Container: $container Exiting...\n"; + exit; + } + if ($args =~ /--date=/i) + { + @data_in = split(/--date=/,$args); + $date = $data_in[1]; + $date =~ s/ .*$//gi; + if ($Q < 1) + {print "\n----- DATE SET: $date -----\n\n";} + } + if ($args =~ /--minimum-gap=/i) + { + @data_in = split(/--minimum-gap=/,$args); + $CLIminimum_gap = $data_in[1]; + $CLIminimum_gap =~ s/ .*$//gi; + $CLIminimum_gap =~ s/\D//gi; + if ($Q < 1) + {print "\n----- MINIMUM GAP OVERRIDE SET: $CLIminimum_gap -----\n\n";} + } + if ($args =~ /--live/i) + { + $check_live=1; + if ($Q < 1) + {print "\n----- LIVE CHECK -----\n\n";} + } + if ($args =~ /--fresh/i) + { + $check_fresh=1; + if ($Q < 1) + {print "\n----- FRESH CHECK -----\n\n";} + } + if ($args =~ /--recent/i) + { + $check_recent=1; + if ($Q < 1) + {print "\n----- RECENT CHECK -----\n\n";} + } + if ($args =~ /--24-hours/i) + { + $check_oneday=1; + if ($Q < 1) + {print "\n----- 24-HOUR CHECK -----\n\n";} + } + if ($args =~ /--check-user-sessions/i) + { + $check_user_sessions=1; + if ($Q < 1) + {print "\n----- CHECK BY USER SESSIONS: $check_user_sessions -----\n\n";} + } + if ($args =~ /--email-gaps-notice/i) + { + $email_gaps_notice=1; + if ($Q < 1) + {print "\n----- EMAIL GAPS NOTICE: $email_gaps_notice -----\n\n";} + } + if ($args =~ /--day-end-report/i) + { + $day_end_report=1; + if ($Q < 1) + {print "\n----- DAY END REPORT: $day_end_report -----\n\n";} + } + } + } +else + { + print "no command line options set Exiting...\n"; + } +### end parsing run-time options ### + +$secX = time(); +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); +$year = ($year + 1900); +$yy = $year; $yy =~ s/^..//gi; +$mon++; +if ($mon < 10) {$mon = "0$mon";} +if ($mday < 10) {$mday = "0$mday";} +if ($hour < 10) {$hour = "0$hour";} +if ($min < 10) {$min = "0$min";} +if ($sec < 10) {$sec = "0$sec";} +$SQLdate_NOW="$year-$mon-$mday $hour:$min:$sec"; +$SQLdate_MIDNIGHT="$year-$mon-$mday 00:00:00"; + +### get date-time of 24 hours ago ### +$VDL_one = ($secX - (60 * 1440)); +($Dsec,$Dmin,$Dhour,$Dmday,$Dmon,$Dyear,$Dwday,$Dyday,$Disdst) = localtime($VDL_one); +$Dyear = ($Dyear + 1900); +$Dmon++; +if ($Dmon < 10) {$Dmon = "0$Dmon";} +if ($Dmday < 10) {$Dmday = "0$Dmday";} +if ($Dhour < 10) {$Dhour = "0$Dhour";} +if ($Dmin < 10) {$Dmin = "0$Dmin";} +if ($Dsec < 10) {$Dsec = "0$Dsec";} +$VDL_day = "$Dyear-$Dmon-$Dmday $Dhour:$Dmin:$Dsec"; + +### get date-time of one hour ago ### +if ($check_live > 0) + { + $VDL_secBEGIN = ($secX - 0); + $VDL_secEND = ($secX - 120); + $query_length_check = ($VDL_secBEGIN - $VDL_secEND); + } +if ($check_fresh > 0) + { + $VDL_secBEGIN = ($secX - 30); + $VDL_secEND = ($secX - 150); + $query_length_check = ($VDL_secBEGIN - $VDL_secEND); + } +if ($check_recent > 0) + { + $VDL_secBEGIN = ($secX - (60 * 1)); + $VDL_secEND = ($secX - (60 * 63)); + $query_length_check = ($VDL_secBEGIN - $VDL_secEND); + } +if ($check_oneday > 0) + { + $VDL_secBEGIN = ($secX - (60 * 1)); + $VDL_secEND = ($secX - (60 * 1441)); + $query_length_check = ($VDL_secBEGIN - $VDL_secEND); + } +if (length($date) > 9) + { + $vicidial_agent_latency_log = 'vicidial_agent_latency_log_archive'; + $query_length_check = 86400; + $VDL_hourEND = "$date 00:00:00"; + @cli_dateB = split("-",$date); + $cli_dateB[1] = ($cli_dateB[1] - 1); + $VDL_secEND = timelocal(0,0,0,$cli_dateB[2],$cli_dateB[1],$cli_dateB[0]); + $XDL_hourBEGIN = "$date 23:59:59"; + $VDL_secBEGIN = timelocal(59,59,23,$cli_dateB[2],$cli_dateB[1],$cli_dateB[0]); + $VDL_day = $VDL_hourEND; + } + +# generate begin date/time +($Vsec,$Vmin,$Vhour,$Vmday,$Vmon,$Vyear,$Vwday,$Vyday,$Visdst) = localtime($VDL_secBEGIN); +$Vyear = ($Vyear + 1900); +$Vmon++; +if ($Vmon < 10) {$Vmon = "0$Vmon";} +if ($Vmday < 10) {$Vmday = "0$Vmday";} +if ($Vhour < 10) {$Vhour = "0$Vhour";} +if ($Vmin < 10) {$Vmin = "0$Vmin";} +if ($Vsec < 10) {$Vsec = "0$Vsec";} +$VDL_hourBEGIN = "$Vyear-$Vmon-$Vmday $Vhour:$Vmin:$Vsec"; + +# generate end date/time +($Xsec,$Xmin,$Xhour,$Xmday,$Xmon,$Xyear,$Xwday,$Xyday,$Xisdst) = localtime($VDL_secEND); +$Xyear = ($Xyear + 1900); +$Xmon++; +if ($Xmon < 10) {$Xmon = "0$Xmon";} +if ($Xmday < 10) {$Xmday = "0$Xmday";} +if ($Xhour < 10) {$Xhour = "0$Xhour";} +if ($Xmin < 10) {$Xmin = "0$Xmin";} +if ($Xsec < 10) {$Xsec = "0$Xsec";} +$XDL_hourEND = "$Xyear-$Xmon-$Xmday $Xhour:$Xmin:$Xsec"; + + +if (!$Q) {print "TEST\n\n";} +if (!$Q) {print "NOW DATETIME: $SQLdate_NOW\n";} +if (!$Q) {print "ANALYSIS DATE RANGE: $VDL_hourBEGIN - $XDL_hourEND\n";} + +# default path to astguiclient configuration file: +$PATHconf = '/etc/astguiclient.conf'; + +open(conf, "$PATHconf") || die "can't open $PATHconf: $!\n"; +@conf = ; +close(conf); +$i=0; +foreach(@conf) + { + $line = $conf[$i]; + $line =~ s/ |>|\n|\r|\t|\#.*|;.*//gi; + if ( ($line =~ /^PATHhome/) && ($CLIhome < 1) ) + {$PATHhome = $line; $PATHhome =~ s/.*=//gi;} + if ( ($line =~ /^PATHlogs/) && ($CLIlogs < 1) ) + {$PATHlogs = $line; $PATHlogs =~ s/.*=//gi;} + if ( ($line =~ /^PATHagi/) && ($CLIagi < 1) ) + {$PATHagi = $line; $PATHagi =~ s/.*=//gi;} + if ( ($line =~ /^PATHweb/) && ($CLIweb < 1) ) + {$PATHweb = $line; $PATHweb =~ s/.*=//gi;} + if ( ($line =~ /^PATHsounds/) && ($CLIsounds < 1) ) + {$PATHsounds = $line; $PATHsounds =~ s/.*=//gi;} + if ( ($line =~ /^PATHmonitor/) && ($CLImonitor < 1) ) + {$PATHmonitor = $line; $PATHmonitor =~ s/.*=//gi;} + if ( ($line =~ /^VARserver_ip/) && ($CLIserver_ip < 1) ) + {$VARserver_ip = $line; $VARserver_ip =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_server/) && ($CLIDB_server < 1) ) + {$VARDB_server = $line; $VARDB_server =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_database/) && ($CLIDB_database < 1) ) + {$VARDB_database = $line; $VARDB_database =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_user/) && ($CLIDB_user < 1) ) + {$VARDB_user = $line; $VARDB_user =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_pass/) && ($CLIDB_pass < 1) ) + {$VARDB_pass = $line; $VARDB_pass =~ s/.*=//gi;} + if ( ($line =~ /^VARDB_port/) && ($CLIDB_port < 1) ) + {$VARDB_port = $line; $VARDB_port =~ s/.*=//gi;} + $i++; + } + +# Customized Variables +$server_ip = $VARserver_ip; # Asterisk server IP + +if (!$VARDB_port) {$VARDB_port='3306';} + +use DBI; + +$dbhA = DBI->connect("DBI:mysql:$VARDB_database:$VARDB_server:$VARDB_port", "$VARDB_user", "$VARDB_pass", {PrintError => 0, RaiseError => 0}) + or die "Couldn't connect to database: " . DBI->errstr; + +### Grab container content from the database +$container_sql=''; +$stmtA = "SELECT container_entry FROM vicidial_settings_containers where container_id = '$container';"; +$sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; +$sthA->execute or die "executing: $stmtA ", $dbhA->errstr; +$sthArows=$sthA->rows; +if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $container_sql = $aryA[0]; + } +$sthA->finish(); + +if (length($container_sql)>5) + { + @container_lines = split(/\n/,$container_sql); + $i=0; + foreach(@container_lines) + { + $container_lines[$i] =~ s/;.*//gi; + if (length($container_lines[$i])>5) + { + if ($container_lines[$i] =~ /^minimum_gap/i) + { + $minimum_gap = $container_lines[$i]; + $minimum_gap =~ s/minimum_gap=>|minimum_gap => //gi; + $minimum_gap =~ s/\D//gi; + if($DBX){print "Minimum Gap set: $minimum_gap \n";} + } + if ($container_lines[$i] =~ /^email_sender/i) + { + $email_sender = $container_lines[$i]; + $email_sender =~ s/email_sender=>|email_sender => //gi; + $email_sender =~ s/\n|\r|\t//gi; + if($DBX){print "Email Sender set: $email_sender \n";} + } + if ($container_lines[$i] =~ /^email_list/i) + { + $email_list = $container_lines[$i]; + $email_list =~ s/email_list=>|email_list => //gi; + $email_list =~ s/\n|\r|\t//gi; + if($DBX){print "Email List set: $email_list \n";} + } + if ($container_lines[$i] =~ /^email_subject/i) + { + $email_subject = $container_lines[$i]; + $email_subject =~ s/email_subject=>|email_subject => //gi; + $email_subject =~ s/\n|\r|\t//gi; + if($DBX){print "Email Subject set: $email_subject \n";} + } + + if ( ($container_lines[$i] =~ /^day_end_minimum_gap/i) && ($day_end_report > 0) ) + { + $minimum_gap = $container_lines[$i]; + $minimum_gap =~ s/day_end_minimum_gap=>|day_end_minimum_gap => //gi; + $minimum_gap =~ s/\D//gi; + if($DBX){print "Day End Minimum Gap set: $minimum_gap \n";} + } + if ( ($container_lines[$i] =~ /^day_end_email_list/i) && ($day_end_report > 0) ) + { + $email_list = $container_lines[$i]; + $email_list =~ s/day_end_email_list=>|day_end_email_list => //gi; + $email_list =~ s/\n|\r|\t//gi; + if($DBX){print "Day End Email List set: $email_list \n";} + } + if ( ($container_lines[$i] =~ /^day_end_email_subject/i) && ($day_end_report > 0) ) + { + $email_subject = $container_lines[$i]; + $email_subject =~ s/day_end_email_subject=>|day_end_email_subject => //gi; + $email_subject =~ s/\n|\r|\t//gi; + if($DBX){print "Day End Email Subject set: $email_subject \n";} + } + if ( ($container_lines[$i] =~ /^day_end_hours/i) && ($day_end_report > 0) ) + { + $day_end_hours = $container_lines[$i]; + $day_end_hours =~ s/day_end_hours=>|day_end_hours => //gi; + $day_end_hours =~ s/\n|\r|\t//gi; + if($DBX){print "Day End Hours set: $day_end_hours \n";} + } + if ( ($container_lines[$i] =~ /^day_end_groups/i) && ($day_end_report > 0) ) + { + $day_end_groups = $container_lines[$i]; + $day_end_groups =~ s/day_end_groups=>|day_end_groups => //gi; + $day_end_groups =~ s/\n|\r|\t//gi; + if($DBX){print "Day End User Groups set: $day_end_groups \n";} + } + if ($container_lines[$i] =~ /^group\d\d_groups/i) + { + $temp_group_groups = $container_lines[$i]; + $temp_group_groups =~ s/^group\d\d_groups=>|^group\d\d_groups => //gi; + $temp_group_groups =~ s/\n|\r|\t//gi; + $temp_group_groups_num = $container_lines[$i]; + $temp_group_groups_num =~ s/^group|_groups.*//gi; + $temp_group_groups_num = ($temp_group_groups_num - 1); + $group_groups[$temp_group_groups_num] = ",$temp_group_groups,"; + $group_email_message[$temp_group_groups_num]=''; + if ($group_group_list !~ /\|$temp_group_groups\|/) + { + $group_group_list .= "$temp_group_groups|"; + $group_group_count++; + } + if($DBX){print "User Group Email User Group Restriction set: $temp_group_groups_num|$group_groups[$temp_group_groups_num]|$group_group_count| \n";} + } + if ($container_lines[$i] =~ /^group\d\d_email/i) + { + $temp_group_email = $container_lines[$i]; + $temp_group_email =~ s/^group\d\d_email=>|^group\d\d_email => //gi; + $temp_group_email =~ s/\n|\r|\t//gi; + $temp_group_email_num = $container_lines[$i]; + $temp_group_email_num =~ s/^group|_email.*//gi; + $temp_group_email_num = ($temp_group_email_num - 1); + $group_email[$temp_group_email_num] = $temp_group_email; + if($DBX){print "User Group Email Group set: $temp_group_email_num|$group_email[$temp_group_email_num]| \n";} + } + } + $i++; + } + } +else + { + if ($Q < 1) + {print "ERROR: SETTINGS CONTAINER EMPTY: $container $container_sql\n";} + } + +if (length($CLIminimum_gap) > 0) + {$minimum_gap = $CLIminimum_gap;} + +$query_length_check_net = ($query_length_check - $minimum_gap); +if ($DB) {print "Net check seconds: $query_length_check_net = ($query_length_check - $minimum_gap)\n";} + +$VDL_secBEGIN_master = $VDL_secBEGIN; +$VDL_hourBEGIN_master = $VDL_hourBEGIN; +$VDL_secEND_master = $VDL_secEND; +$XDL_hourEND_master = $XDL_hourEND; + + + +##### BEGIN run the Day End Report ##### +if ($day_end_report > 0) + { + ### get date-time of X hours ago ### + $DE_sec = ($secX - (60 * 60 * $day_end_hours)); + ($Dsec,$Dmin,$Dhour,$Dmday,$Dmon,$Dyear,$Dwday,$Dyday,$Disdst) = localtime($DE_sec); + $Dyear = ($Dyear + 1900); + $Dmon++; + if ($Dmon < 10) {$Dmon = "0$Dmon";} + if ($Dmday < 10) {$Dmday = "0$Dmday";} + if ($Dhour < 10) {$Dhour = "0$Dhour";} + if ($Dmin < 10) {$Dmin = "0$Dmin";} + if ($Dsec < 10) {$Dsec = "0$Dsec";} + $DE_date = "$Dyear-$Dmon-$Dmday $Dhour:$Dmin:$Dsec"; + + $day_end_groupsSQL=''; + if (length($day_end_groups) > 0) + { + $day_end_groupsSQL = $day_end_groups; + $day_end_groupsSQL =~ s/,|\|/','/gi; + $day_end_groupsSQL = "and user_group IN('$day_end_groupsSQL')"; + } + if ($DB) {print "Running the day-end report, for $day_end_hours hours ($day_end_groupsSQL) \n";} + + $stmtA = "SELECT user,user_ip,gap_date,gap_length FROM vicidial_latency_gaps where gap_date > \"$DE_date\" and (gap_length >= $minimum_gap) order by gap_date limit 1000;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "|$sthArows|$stmtA|\n";} + $ug=0; + while ($sthArows > $ug) + { + @aryA = $sthA->fetchrow_array; + $DEuser[$ug] = $aryA[0]; + $DEuser_ip[$ug] = $aryA[1]; + $DEgap_date[$ug] = $aryA[2]; + $DEgap_length[$ug] = $aryA[3]; + $ug++; + } + $sthA->finish(); + if ($DB) {print "Gaps found: $ug |$usersSQL|\n";} + + if ($ug > 0) + { + $ug=0; + while ($sthArows > $ug) + { + $temp_ug = ($ug + 1); + $user_fullname = ''; + $stmtA = "SELECT full_name,user_group FROM vicidial_users where user='$DEuser[$ug]' $day_end_groupsSQL limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $user_fullname = " - $aryA[0]"; + $email_message .= "\nGap Detected: $temp_ug \nUser:$DEuser[$ug]$user_fullname \nWeb IP: $DEuser_ip[$ug] \nGap Start: $DEgap_date[$ug] \nGap Length: $DEgap_length[$ug] \n"; + if ($DBX) {print "LG Gap Debug: $DEuser[$ug]$user_fullname|$DEuser_ip[$ug]|$DEgap_date[$ug]|$DEgap_length[$ug]|\n";} + } + else + { + if ($DBX) {print "LG Gap Debug Excluded: $DEuser[$ug]$user_fullname|$DEuser_ip[$ug]|$DEgap_date[$ug]|$DEgap_length[$ug]|\n";} + } + $sthA->finish(); + + $ug++; + } + $sthA->finish(); + } + + if ( ($ug > 0) && (length($email_message)>5) && (length($email_list) > 3) && (length($email_sender) > 3) && (length($email_subject) > 3) ) + { + if (!$Q) {print "Sending email: $email_list\n";} + + use MIME::QuotedPrint; + use MIME::Base64; + use Mail::Sendmail; + + %mail = ( To => "$email_list", + From => "$email_sender", + Subject => "$email_subject", + ); + $boundary = "====" . time() . "===="; + $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\""; + + $message = encode_qp($email_message ); + + $boundary = '--'.$boundary; + $mail{body} .= "$boundary\n"; + $mail{body} .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n"; + $mail{body} .= "Content-Transfer-Encoding: quoted-printable\n\n"; + $mail{body} .= "$message\n"; + $mail{body} .= "$boundary\n"; + $mail{body} .= "--\n"; + + sendmail(%mail) or die $mail::Sendmail::error; + if (!$Q) {print "ok. log says:\n", $mail::sendmail::log;} ### print mail log for status + } + exit; + } +##### END run the Day End Report ##### + + + +##### BEGIN run check for LIVE AGENTS ##### +# $stmtA = "SELECT user FROM vicidial_live_agents where ra_user='' order by user;"; +if ($check_live > 0) + { + $VDL_secBEGIN_master = $VDL_secBEGIN; + $VDL_hourBEGIN_master = $VDL_hourBEGIN; + $VDL_secEND_master = $VDL_secEND; + $XDL_hourEND_master = $XDL_hourEND; + + $stmtA = "SELECT user FROM vicidial_live_agents where ra_user='' order by user;"; + $active_users=''; + $active_users_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "|$sthArows|$stmtA|\n";} + while ($sthArows > $active_users_count) + { + @aryA = $sthA->fetchrow_array; + $users[$active_users_count] = "$aryA[0]"; + $hourEND[$active_users_count] = $XDL_hourEND; + $secEND[$active_users_count] = $VDL_secEND; + $usersSQL .= "'$aryA[0]',"; + $active_users_count++; + } + $sthA->finish(); + if (length($usersSQL) > 3) {$usersSQL =~ s/,$//gi;} + if ($DB) {print "Active Users: $active_users_count |$usersSQL|\n";} + + $i=0; + while ($active_users_count > $i) + { + $VDL_secBEGIN = $VDL_secBEGIN_master; + $VDL_hourBEGIN = $VDL_hourBEGIN_master; + $VDL_secEND = $secEND[$i]; + $XDL_hourEND = $hourEND[$i]; + if ($DB) {print "\nAnalyzing user activity: $users[$i] ($i) starting at $XDL_hourEND ($VDL_secEND)\n";} + $ping_count=0; + $stmtA = "SELECT count(*) FROM $vicidial_agent_latency_log where user='$users[$i]' and log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "|$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $ping_count = $aryA[0]; + } + $sthA->finish(); + + if ($ping_count < $query_length_check_net) + { + $last_login_date = $XDL_hourEND; + $last_login_date_epoch = $VDL_secEND; + $last_logout_date = $VDL_hourBEGIN; + $last_logout_date_epoch = $VDL_secBEGIN; + # checking this user for last login + + $last_login_date_epoch = 0; + $stmtA = "SELECT event_date,UNIX_TIMESTAMP(event_date) FROM vicidial_user_log where user='$users[$i]' and event='LOGIN' and event_date <= \"$VDL_hourBEGIN\" and event_date > \"$VDL_day\" order by event_date desc limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $last_login_date = $aryA[0]; + $last_login_date_epoch = $aryA[1]; + } + $sthA->finish(); + + # checking this user for last logout, if after last login and before the end of the check time + $stmtA = "SELECT event_date,UNIX_TIMESTAMP(event_date) FROM vicidial_user_log where user='$users[$i]' and event IN('LOGOUT','TIMEOUTLOGOUT') and event_date <= \"$VDL_hourBEGIN\" and event_date > \"$last_login_date\" and event_date > \"$XDL_hourEND\" order by event_date limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $last_logout_date = $aryA[0]; + $last_logout_date_epoch = $aryA[1]; + if ($DB) {print "Last Logout within check range, overriding check begin: |$users[$i]|$last_logout_date| |$VDL_hourBEGIN|$XDL_hourEND|\n";} + + $VDL_secBEGIN = $last_logout_date_epoch; + $VDL_hourBEGIN = $last_logout_date; + } + $sthA->finish(); + + if ($DBX) {print "Last Login check: |$users[$i]|$last_login_date| |($last_login_date_epoch >= $VDL_secEND) && ($last_login_date_epoch <= $VDL_secBEGIN)|\n";} + if ( ($last_login_date_epoch >= $VDL_secEND) && ($last_login_date_epoch <= $VDL_secBEGIN) ) + { + if ($DB) {print "Last Login within check range, overriding check end: |$users[$i]|$last_login_date| |$VDL_hourBEGIN|$XDL_hourEND|\n";} + + $VDL_secEND = $last_login_date_epoch; + $XDL_hourEND = $last_login_date; + } + + # run through all latency logs looking for gap + $last_ping_date='1970-01-01 00:00:00'; + $last_ping_date_epoch=0; + $last_ping_web_ip=''; + $last_ping_record=0; + $temp_ping_gap_test=0; + $stmtA = "SELECT log_date,UNIX_TIMESTAMP(log_date),web_ip FROM $vicidial_agent_latency_log where user='$users[$i]' and log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "|$sthArows|$stmtA|\n";} + $p=0; + while ($sthArows > $p) + { + @aryA = $sthA->fetchrow_array; + if ($last_ping_record != $aryA[1]) + { + if ($last_ping_date_epoch < 1) + { + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + else + { + if ( ($aryA[1] >= $temp_ping_gap_test) && (length($last_ping_web_ip) > 3) ) + { + # minimum gap flagged + $gaps_found++; + if ($DB) {print "Ping gap found! |$aryA[1]|$temp_ping_gap_test|\n";} + $temp_gap_sec = ($aryA[1] - $last_ping_date_epoch); + + ### Set all filled vicidial_demographic_quotas_goals records for this campaign to FPENDING status ahead of updates + $stmtA = "INSERT IGNORE INTO vicidial_latency_gaps SET user='$users[$i]',user_ip='$last_ping_web_ip',gap_date='$last_ping_date',gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW' ON DUPLICATE KEY UPDATE gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "LC DEBUG: $affected_rows|$stmtA|\n";} + + if ($affected_rows eq '1') + { + $user_fullname = ''; + $user_user_group = ''; + $stmtA = "SELECT full_name,user_group FROM vicidial_users where user='$users[$i]' limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $user_fullname = " - $aryA[0]"; + $user_user_group = $aryA[1]; + } + $sthA->finish(); + if (length($group_groups[0]) > 0) + { + $ggc=0; + while ($ggc < $group_group_count) + { + if ($group_groups[$ggc] =~ /,$user_user_group,/) + { + $group_email_message[$ggc] .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + $ggc++; + } + } + else + { + $email_message .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + } + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + else + { + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + } + } + $p++; + } + $sthA->finish(); + + if ( ($VDL_secBEGIN >= $temp_ping_gap_test) && ($p > 0) && (length($last_ping_web_ip) > 3) ) + { + # minimum gap flagged + $gaps_found++; + if ($DB) {print "Ping gap found! |$VDL_secBEGIN|$temp_ping_gap_test|\n";} + $temp_gap_sec = ($VDL_secBEGIN - $last_ping_date_epoch); + + ### Insert log record for latency gap + $stmtA = "INSERT IGNORE INTO vicidial_latency_gaps SET user='$users[$i]',user_ip='$last_ping_web_ip',gap_date='$last_ping_date',gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW' ON DUPLICATE KEY UPDATE gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "LC DEBUG: $affected_rows|$stmtA|\n";} + if ($affected_rows eq '1') + { + $user_fullname = ''; + $user_user_group = ''; + $stmtA = "SELECT full_name,user_group FROM vicidial_users where user='$users[$i]' limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $user_fullname = " - $aryA[0]"; + $user_user_group = $aryA[1]; + } + $sthA->finish(); + + if (length($group_groups[0]) > 0) + { + $ggc=0; + while ($ggc < $group_group_count) + { + if ($group_groups[$ggc] =~ /,$user_user_group,/) + { + $group_email_message[$ggc] .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + $ggc++; + } + } + else + { + $email_message .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + } + } + } + else + { + if ($DBX) {print "LC DEBUG: normal ping count for user: $users[$i] {$ping_count >= $query_length_check_net}\n";} + } + $i++; + } + } +##### END run check for LIVE AGENTS ##### + + + + +##### BEGIN time-based checks within last 24 hours ##### +# $stmtA = "SELECT distinct user FROM $vicidial_agent_latency_log where log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\" order by user;"; +# $stmtA = "SELECT distinct user FROM $vicidial_agent_latency_log where log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\" order by user;"; +if ( ($check_fresh > 0) || ($check_recent > 0) || ($check_oneday > 0) || (length($date) > 9) ) + { + $VDL_secBEGIN_master = $VDL_secBEGIN; + $VDL_hourBEGIN_master = $VDL_hourBEGIN; + $VDL_secEND_master = $VDL_secEND; + $XDL_hourEND_master = $XDL_hourEND; + + if ($check_user_sessions > 0) + { + $stmtA = "SELECT user,event_date,UNIX_TIMESTAMP(event_date) FROM vicidial_user_log where event='LOGIN' and event_date <= \"$VDL_hourBEGIN\" and event_date > \"$XDL_hourEND\" order by user,event_date limit 1000000;"; + $active_users=''; + $active_users_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "|$sthArows|$stmtA|\n";} + while ($sthArows > $active_users_count) + { + @aryA = $sthA->fetchrow_array; + $users[$active_users_count] = "$aryA[0]"; + $hourEND[$active_users_count] = "$aryA[1]"; + $secEND[$active_users_count] = "$aryA[2]"; + $usersSQL .= "'$aryA[0]',"; + $active_users_count++; + } + $sthA->finish(); + if (length($usersSQL) > 3) {$usersSQL =~ s/,$//gi;} + if ($DB) {print "Active User Sessions: $active_users_count |$usersSQL|\n";} + } + else + { + $stmtA = "SELECT distinct user FROM $vicidial_agent_latency_log where log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\" order by user;"; + $active_users=''; + $active_users_count=0; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DB) {print "|$sthArows|$stmtA|\n";} + while ($sthArows > $active_users_count) + { + @aryA = $sthA->fetchrow_array; + $users[$active_users_count] = "$aryA[0]"; + $hourEND[$active_users_count] = $XDL_hourEND; + $secEND[$active_users_count] = $VDL_secEND; + $usersSQL .= "'$aryA[0]',"; + $active_users_count++; + } + $sthA->finish(); + if (length($usersSQL) > 3) {$usersSQL =~ s/,$//gi;} + if ($DB) {print "Active Users: $active_users_count |$usersSQL|\n";} + } + + $i=0; + while ($active_users_count > $i) + { + $VDL_secBEGIN = $VDL_secBEGIN_master; + $VDL_hourBEGIN = $VDL_hourBEGIN_master; + $VDL_secEND = $secEND[$i]; + $XDL_hourEND = $hourEND[$i]; + if ($DB) {print "\nAnalyzing user activity: $users[$i] ($i) starting at $XDL_hourEND ($VDL_secEND)\n";} + $ping_count=0; + $stmtA = "SELECT count(*) FROM $vicidial_agent_latency_log where user='$users[$i]' and log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "|$sthArows|$stmtA|\n";} + if ($sthArows > 0) + { + @aryA = $sthA->fetchrow_array; + $ping_count = $aryA[0]; + } + $sthA->finish(); + + if ($ping_count < $query_length_check_net) + { + $last_login_date = $XDL_hourEND; + $last_login_date_epoch = $VDL_secEND; + $last_logout_date = $VDL_hourBEGIN; + $last_logout_date_epoch = $VDL_secBEGIN; + # checking this user for last login + if ($check_user_sessions < 1) + { + $last_login_date_epoch = 0; + $stmtA = "SELECT event_date,UNIX_TIMESTAMP(event_date) FROM vicidial_user_log where user='$users[$i]' and event='LOGIN' and event_date <= \"$VDL_hourBEGIN\" and event_date > \"$VDL_day\" order by event_date desc limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $last_login_date = $aryA[0]; + $last_login_date_epoch = $aryA[1]; + } + $sthA->finish(); + } + + # checking this user for last logout, if after last login and before the end of the check time + $stmtA = "SELECT event_date,UNIX_TIMESTAMP(event_date) FROM vicidial_user_log where user='$users[$i]' and event IN('LOGOUT','TIMEOUTLOGOUT') and event_date <= \"$VDL_hourBEGIN\" and event_date > \"$last_login_date\" and event_date > \"$XDL_hourEND\" order by event_date limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $last_logout_date = $aryA[0]; + $last_logout_date_epoch = $aryA[1]; + if ($DB) {print "Last Logout within check range, overriding check begin: |$users[$i]|$last_logout_date| |$VDL_hourBEGIN|$XDL_hourEND|\n";} + + $VDL_secBEGIN = $last_logout_date_epoch; + $VDL_hourBEGIN = $last_logout_date; + } + $sthA->finish(); + + if ($DBX) {print "Last Login check: |$users[$i]|$last_login_date| |($last_login_date_epoch >= $VDL_secEND) && ($last_login_date_epoch <= $VDL_secBEGIN)|\n";} + if ( ($last_login_date_epoch >= $VDL_secEND) && ($last_login_date_epoch <= $VDL_secBEGIN) ) + { + if ($DB) {print "Last Login within check range, overriding check end: |$users[$i]|$last_login_date| |$VDL_hourBEGIN|$XDL_hourEND|\n";} + + $VDL_secEND = $last_login_date_epoch; + $XDL_hourEND = $last_login_date; + } + + # run through all latency logs looking for gap + $last_ping_date='1970-01-01 00:00:00'; + $last_ping_date_epoch=0; + $last_ping_web_ip=''; + $last_ping_record=0; + $temp_ping_gap_test=0; + $stmtA = "SELECT log_date,UNIX_TIMESTAMP(log_date),web_ip FROM $vicidial_agent_latency_log where user='$users[$i]' and log_date <= \"$VDL_hourBEGIN\" and log_date > \"$XDL_hourEND\";"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArows=$sthA->rows; + if ($DBX) {print "|$sthArows|$stmtA|\n";} + $p=0; + while ($sthArows > $p) + { + @aryA = $sthA->fetchrow_array; + if ($last_ping_record != $aryA[1]) + { + if ($last_ping_date_epoch < 1) + { + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + else + { + if ( ($aryA[1] >= $temp_ping_gap_test) && (length($last_ping_web_ip) > 3) ) + { + # minimum gap flagged + $gaps_found++; + if ($DB) {print "Ping gap found! |$aryA[1]|$temp_ping_gap_test|\n";} + $temp_gap_sec = ($aryA[1] - $last_ping_date_epoch); + + ### Set all filled vicidial_demographic_quotas_goals records for this campaign to FPENDING status ahead of updates + $stmtA = "INSERT IGNORE INTO vicidial_latency_gaps SET user='$users[$i]',user_ip='$last_ping_web_ip',gap_date='$last_ping_date',gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW' ON DUPLICATE KEY UPDATE gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "LC DEBUG: $affected_rows|$stmtA|\n";} + + if ($affected_rows eq '1') + { + $user_fullname = ''; + $user_user_group = ''; + $stmtA = "SELECT full_name,user_group FROM vicidial_users where user='$users[$i]' limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $user_fullname = " - $aryA[0]"; + $user_user_group = $aryA[1]; + } + $sthA->finish(); + + if (length($group_groups[0]) > 0) + { + $ggc=0; + while ($ggc < $group_group_count) + { + if ($group_groups[$ggc] =~ /,$user_user_group,/) + { + $group_email_message[$ggc] .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + $ggc++; + } + } + else + { + $email_message .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + } + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + else + { + $last_ping_date = $aryA[0]; + $last_ping_date_epoch = $aryA[1]; + $last_ping_web_ip = $aryA[2]; + $temp_ping_gap_test = ($last_ping_date_epoch + $minimum_gap); + $last_ping_record = $aryA[1]; + } + } + } + $p++; + } + $sthA->finish(); + + if ( ($VDL_secBEGIN >= $temp_ping_gap_test) && ($p > 0) && (length($last_ping_web_ip) > 3) ) + { + # minimum gap flagged + $gaps_found++; + if ($DB) {print "Ping gap found! |$VDL_secBEGIN|$temp_ping_gap_test|\n";} + $temp_gap_sec = ($VDL_secBEGIN - $last_ping_date_epoch); + + ### Insert log record for latency gap + $stmtA = "INSERT IGNORE INTO vicidial_latency_gaps SET user='$users[$i]',user_ip='$last_ping_web_ip',gap_date='$last_ping_date',gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW' ON DUPLICATE KEY UPDATE gap_length='$temp_gap_sec',last_login_date='$last_login_date',check_date='$SQLdate_NOW';"; + $affected_rows = $dbhA->do($stmtA); + if ($DBX) {print "LC DEBUG: $affected_rows|$stmtA|\n";} + if ($affected_rows eq '1') + { + $user_fullname = ''; + $user_user_group = ''; + $stmtA = "SELECT full_name,user_group FROM vicidial_users where user='$users[$i]' limit 1;"; + $sthA = $dbhA->prepare($stmtA) or die "preparing: ",$dbhA->errstr; + $sthA->execute or die "executing: $stmtA ", $dbhA->errstr; + $sthArowsU=$sthA->rows; + if ($DBX) {print "|$sthArowsU|$stmtA|\n";} + if ($sthArowsU > 0) + { + @aryA = $sthA->fetchrow_array; + $user_fullname = " - $aryA[0]"; + $user_user_group = $aryA[1]; + } + $sthA->finish(); + + if (length($group_groups[0]) > 0) + { + $ggc=0; + while ($ggc < $group_group_count) + { + if ($group_groups[$ggc] =~ /,$user_user_group,/) + { + $group_email_message[$ggc] .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + $ggc++; + } + } + else + { + $email_message .= "\nGap Detected: $gaps_found \nUser:$users[$i]$user_fullname \nWeb IP: $last_ping_web_ip \nGap Start: $last_ping_date \nGap Length: $temp_gap_sec \n"; + } + } + } + } + else + { + if ($DBX) {print "LC DEBUG: normal ping count for user: $users[$i] {$ping_count >= $query_length_check_net}\n";} + } + $i++; + } + } +##### END time-based checks within last 24 hours ##### + + + + + + +$dbhA->disconnect(); + + + +if ( ($gaps_found > 0) && ($email_gaps_notice > 0) && (length($email_message)>5) && (length($email_list) > 3) && (length($email_sender) > 3) && (length($email_subject) > 3) ) + { + if (!$Q) {print "Sending email: $email_list\n";} + + use MIME::QuotedPrint; + use MIME::Base64; + use Mail::Sendmail; + + %mail = ( To => "$email_list", + From => "$email_sender", + Subject => "$email_subject", + ); + $boundary = "====" . time() . "===="; + $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\""; + + $message = encode_qp($email_message ); + + $boundary = '--'.$boundary; + $mail{body} .= "$boundary\n"; + $mail{body} .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n"; + $mail{body} .= "Content-Transfer-Encoding: quoted-printable\n\n"; + $mail{body} .= "$message\n"; + $mail{body} .= "$boundary\n"; + $mail{body} .= "--\n"; + + sendmail(%mail) or die $mail::Sendmail::error; + if (!$Q) {print "ok. log says:\n", $mail::sendmail::log;} ### print mail log for status + } + + +# emails for group groups +if ( ($gaps_found > 0) && ($group_group_count > 0) ) + { + $ggc=0; + while ($ggc < $group_group_count) + { + if ( (length($group_email_message[$ggc]) > 10) && (length($group_email[$ggc]) > 5) && (length($email_sender) > 5) && (length($email_subject) > 1) ) + { + if (!$Q) {print "Sending group group email: $group_email[$ggc]|$group_groups[$ggc]|\n";} + + use MIME::QuotedPrint; + use MIME::Base64; + use Mail::Sendmail; + + %mail = ( To => "$group_email[$ggc]", + From => "$email_sender", + Subject => "$email_subject", + ); + $boundary = "====" . time() . "===="; + $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\""; + + $message = encode_qp($group_email_message[$ggc] ); + + $boundary = '--'.$boundary; + $mail{body} .= "$boundary\n"; + $mail{body} .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n"; + $mail{body} .= "Content-Transfer-Encoding: quoted-printable\n\n"; + $mail{body} .= "$message\n"; + $mail{body} .= "$boundary\n"; + $mail{body} .= "--\n"; + + sendmail(%mail) or die $mail::Sendmail::error; + if (!$Q) {print "ok. log says:\n", $mail::sendmail::log;} ### print mail log for status + } + $ggc++; + } + } + +$secY = time(); +$secZ = ($secY - $secX); + +if (!$q) {print "\nDONE. Gaps found: $gaps_found Script execution time in seconds: $secZ\n";} + +if (!$Q) {print "Script exiting...\n";} +exit; diff --git a/docs/AGENT_SCREEN_LOGGING.txt b/docs/AGENT_SCREEN_LOGGING.txt index 17abfaad..edf0b47a 100644 --- a/docs/AGENT_SCREEN_LOGGING.txt +++ b/docs/AGENT_SCREEN_LOGGING.txt @@ -1,4 +1,4 @@ -AGENT SCREEN LOGGING Started: 2023-04-20 Updated: 2023-04-21 +AGENT SCREEN LOGGING Started: 2023-04-20 Updated: 2023-05-08 @@ -10,6 +10,7 @@ Agent Screen Usage Logging Items: - Agent IP Addresses Viewable in the User Stats page and the User Logins Report and others - Agent Screen Visibility Viewable in the User Stats page - Agent Screen Latency Viewable in the Real-Time Report, the Agent Latency Report and the Agent Debug Log Report +- Agent Screen Latency Gaps Viewable in the Agent Latency Report and the Latency Gaps Report, email alerts also available - Agent Screen Debug Viewable in the Agent Debug Log Report @@ -50,6 +51,13 @@ On the back-end, the 'vicidial_agent_latency_log' database table stores the per- +AGENT SCREEN LATENCY GAPS: + +This metric is derived from the agent screen latency logging. There is a back-end script "AST_latency_gaps.pl" that is run every minute, on the active voicemail server in a cluster, that will analyze the latency logs for all logged-in agents and log the gaps that happen within those logs in real-time. The above script can also send out email alerts as soon as the gaps are detected and those emails can be segregated by User Group as well. There is also the option to send an End-of-Day email with a list of all of the gaps that have happened for that day. For more informaiton on how to configure the "AST_latency_gaps.pl" script, see the named section below. The latency gaps information can also be viewed in the Latency Gaps Report available in the Admin Utilities page. + + + + AGENT SCREEN DEBUG: This metric is really a collection of all of the available agent screen debug data put together. This metric is not enabled by default, to use it you need to enable the "Agent Screen Debug Logging" option in System Settings. The data that is collected is only stored on your system for 7 days. @@ -62,6 +70,47 @@ The "Agent Debug Log Report" will show all of this data, including the back-end +CONFIGURING THE "AST_latency_gaps.pl" SCRIPT: + +This script is run every minute on the active voicemail server in your cluster to analyze the latency log gaps for logged-in agents. This script required a Settings Container to run(added by default: 'AGENT_LATENCY_LOGGING'). If you would like to use the End-of-Day email feature, you can set up an additional Settings Container with only those settings in it and then use that as a crontab entry on one of the servers in your cluster. + +As for the options available in the AGENT_LATENCY_LOGGING container: +(All settings below are optional except for 'minimum_gap') + +minimum_gap The minimum gap in agent latency log entries before a gap will be logged. We suggest 30 seconds, should be 10 of higher. +email_sender The email address that the alert emails will be sent from +email_list The list of email addresses that the alert emails will be sent to, if more than one separate by commas +email_subject The subject of the alert emails +group01_groups Segregated alert emails by User Group, if more than one separate by commas, can add multiple groups, increment number by 1 +group01_email Email list for the above group of user group alerts, can add multiple groups, increment number by 1 +day_end_email_list For the End-of-Day process, the list of email addresses that the alert emails will be sent to +day_end_email_subject For the End-of-Day process, the subject of the end-of-day emails +day_end_minimum_gap For the End-of-Day process, the minimum gap in agent latency log entries that will be sent in the email, must be equal to or greater than minimum_gap +day_end_hours For the End-of-Day process, the number of hours into the past to gather latency gaps from +day_end_groups For the End-of-Day process, the user groups to gather gaps from, if more than one separate by commas + + +Here is an example Settings Container for the "AST_latency_gaps.pl" script: + +minimum_gap => 10 +email_sender => vicidial@gmail.com +email_list => info@vicidial.com,support@vicidial.com +email_subject => Agent Latency Gap Detected +group01_groups => ADMIN,AGENTS +group01_email => vicidial@gmail.com +group02_groups => SUPPORT +group02_email => support@vicidial.com +group03_groups => SALES +group03_email => info@vicidial.com +day_end_email_list => info@vicidial.com +day_end_email_subject => Day-End Agent Latency Gaps Report +day_end_minimum_gap => 11 +day_end_hours => 16 +day_end_groups => ADMIN,AGENTS + + + + diff --git a/docs/DEMOGRAPHIC_QUOTAS.txt b/docs/DEMOGRAPHIC_QUOTAS.txt new file mode 100644 index 00000000..878290da --- /dev/null +++ b/docs/DEMOGRAPHIC_QUOTAS.txt @@ -0,0 +1,276 @@ +DEMOGRAPHIC QUOTAS DOC Started: 2023-04-25 Updated: 2023-05-15 + + +THIS FEATURE WAS DESIGNED FOR SURVEYS AND POLLING BASED ON DEMOGRAPHICS + +*This feature was added to the VICIdial svn/trunk codebase in revision 3723 + + + +The Demographic Quotas features, which allow for a dialing pattern that is based around a set of demographic types and values(like: gender(M,F,U), age-group(18-24,25-34,...), political-party(R,D,I), etc...) with associated quota goals in order of priority. The leads are ranked and dialed in order of priority and as each goal is filled(set to a specific status) the leads are re-ranked until all goals are met and the campaign dialing is deactivated. + +This document is written for call center managers and IT staff that already know how to run a standard campaign on their VICIdial system. + + +In order to use these Demographic Quotas features in a campaign, here are the required steps you should take, in order: + +1. In System Settings, set the 'Demographic Quotas' option to "1" and submit the form +2. Create a new List, load your leads into the list with demographic data in it, see the 'LEADS' section below +3. Create a new Settings Container, see the 'SETTINGS CONTAINER' section below +4. Create a new Campaign, see the 'CAMPAIGN' section below +5. Set the campaign to Active to 'Y', the Demographic Quotas to 'ENABLED' and the Demographic Quotas to 'NOW' +6. Log agents into the campaign and start dialing +7. Look at the "Demographic Quotas Report" to follow the progress of your campaign, see the 'REPORTS' section below +8. When all quota goals are met, the Demographic Quotas setting will change to 'COMPLETE' automatically and all dialing will stop on the campaign within one minute + + + + +-------------------------------------------------------------------------------- +LEADS - demographic data: + +The demographic data used for these features need to be stored in the 'vicidial_list' database table directly, in order to be able to efficiently filter and update leads as active/inactive for dialing. + +The demographic field values need to be strictly defined, that means for example age ranges specifically defined(like '18-24') instead of a specific age('23'). The demographic quotas used will be looking for exact values in these fields, so any extra characters or spaces in a record's values will not find a match. + +As for the field mapping, you can use any of the following default vicidial_list fields for your demographic data: + +SIZE FIELD NOTES +20 vendor_lead_code +50 source_id +4 title +30 first_name +1 middle_initial +30 last_name +100 address1 +100 address2 +100 address3 +50 city +2 state +50 province +10 postal_code +3 country_code +1 gender *only: 'M','F','U' +10 date_of_birth *format: 'YYYY-MM-DD' +12 alt_phone +70 email +100 security_phrase +20 owner + +Data Field Notes: Some of the above fields are smaller than others, some have data restrictions(like 'gender' and 'date_of_birth'), and some of the fields like 'security_phrase' may be altered by inbound call handling depending on how your system is configured. The 'rank' field is not included in the above list specifically because it is used for ranking the leads by the demographic priorities set for the campaign(details on that further down). + + + + +-------------------------------------------------------------------------------- +SETTINGS CONTAINER - demographic fields and value parameters: + +This new "Demographic Quotas" campaign feature uses a "Settings Container" to define the fields to be used for each demographic, the quota count for each field value, and the priority order in which each value should be dialed. + +A sample of a Settings Container using an example set of demographic quotas(container type = DEMOGRAPHIC_QUOTAS), would look something like this: + + +; define finished lead statuses for this campaign that will meet quota: +finished_statuses => SVDONE,COMPLT + +; demo 01 - age range +demo01_field => address3 +; field values(in dial priority order), quota goal of finished leads +demo01_value01 => 18-24,47 +demo01_value02 => 25-34,70 +demo01_value03 => 35-44,72 +demo01_value04 => 45-54,85 +demo01_value05 => 55-64,90 +demo01_value06 => 65-74,79 +demo01_value07 => 75,57 + +; demo 02 - region +demo02_field => province +demo02_value01 => Central,100 +demo02_value02 => Cumberland Plateau,174 +demo02_value03 => Eastern Panhandle,92 +demo02_value04 => Northern Panhandle,34 +demo02_value05 => South West,100 + +; demo 03 - political party +demo03_field => address3 +demo03_value01 => Registered GOP,475 +demo03_value02 => Non-GOP,25 + +; demo 04 - gender +demo04_field => gender +demo04_value01 => M,253 +demo04_value02 => F,247 + + +Notes: +- This system allows up to 10 demographics in the above configuration, as well as up to 10 field values for each demographic, which makes this system extremely flexible different types of polling/survey campaigns. + +- Since each lead covers multiple demographics. For example, one lead may be a 26-year-old, GOP, Female from the Central region. If that person completes a survey, that satisfies 4 separate demographic quotas. There is no need to call that person again for another quota goal because they already completed the survey. So, you are never really calling only one demographic at a time. + +- There is another example of a Demographic Quota Settings Container further down in this document. That example can be used to test these features on any VICIdial system with the included "performance_test_leads.txt" leads file. + + + + +-------------------------------------------------------------------------------- +CAMPAIGN - Demographic Quota settings: + +When you create your new campaign, make sure you first set the campaign's 'List Order' to "UP RANK". + +The 'Demographic Quotas' setting will enable or disable the Demographic Quotas feature for this campaign. For these features to work, you will first need to select a Settings Container for it in that setting below. Once your leads are loaded and all other campaign settings are defined properly, you need to set this field to "ENABLED" and the Re-Rank setting to "NOW" or "NOW_HOUR" for the lead ranking process to start. Once that is complete, your agents can log in and begin dialing on this campaign. If this field is changed by the system to be "INVALID" then something in your configuration is wrong and needs to be corrected before you try setting this field to ENABLED again. To see debug output to help you identify configuration problems, you can click on the "DQ Debug" link directly to the right of this setting field. After your quota goals have all been filled, this field will change to COMPLETE and all dialing will be halted within one minute. NOTE: This feature is not related to Call Quota Lead Ranking and the two features should not be active on any single campaign at the same time. + +The optional 'Demographic Quotas Force Re-Rank' setting is off by default. Demographic Quotas will only re-rank the leads in the campaign lists either when a quota has been reached or the campaign has run out of leads to dial. But this setting can force the system to re-rank the leads once using NOW, every hour using HOUR or every minute using the MINUTE setting. Keep in mind that depending on your system capacity and the number of leads in the campaign lists, this re-ranking process may lead to temporary system disruption, especially if it is run very frequently. When NOW is used, after the re-ranking process, the value of this setting will go back to NO. Default is NO. + +The optional 'Demographic Quotas List Resets' setting can automatically reset the active lists in this campaign if there are leads within the call time available and there are no more dialable leads in the campaign lists or the hopper. We do not recommend activating this setting in most cases because it can result in customers being called an excessive number of times in a single day. Default is MANUAL. If enabled, it will not auto-reset any lists if any list in the campaign has been reset in the last 5 mintues, and any single list within the last 3 hours. Also, no single list can be auto-reset more than 4 times in a single day, even if the list reset limit setting is higher. + +There must be a 'Dispo Call URL' entry set up for the "agc/DQ_dispo.php" script set and active for this campaign, with the 'dispo=--A--dispo--B--' and 'campaign_id=XXXX' values included the URL(the campaign's ID must be in place of the 'XXXX' in the above example). for an example, here is the Dispo Call URL as defined for a campaign ID of "DQTEST": +http://192.168.1.3/agc/DQ_dispo.php?lead_id=--A--lead_id--B--&dispo=--A--dispo--B--&campaign_id=DQTEST&user=--A--user--B--&pass=--A--pass--B-- + +Other important notes: +- If you use a non-default AST_VDhopper.pl flags in your crontab, they need to be added to the HOPPER_CLI_FLAGS Settings Container +- You should disable the "Automatic Hopper Level" campaign setting + + + + +-------------------------------------------------------------------------------- +REPORT - Demographic Quota reporting options: + +A new 'Demographic Quota Goals Report' is also available that will allow you to check on the status of your campaign's quota goals at any time to see what goals have been met and which goals are still being filled. A link to this report is on the Campaign Detail page, next to the "Demographic Quota" setting, it is marked as "DQ Report". This report will show the details of a single campaign's Demographic Quota settings, goals and other basic campaign calling information all on one screen. As quota goals are filled, the goal table rows will change from a green to a purple background color. The numbers in this report are updated once per minute, but the 'count' column can also be updated as agents disposition calls. It is possible for the 'count' column to be higher than it really is if a call is dispositioned at the same time as the back-end process runs, but this will not impact the functions of this feature and the numbers will be corrected within one minute. There are also links near the top of the report to go to the campaign modify page and the debug page to see more information on the last time the Demographic Quotas process ran. + +The 'Campaign Debug' report will also have debug output data from the back-end process that runs the Demographic Quotas features. This output can be useful for many reasons, for example if your configuration is invalid, the reason why will be shown in the Campaign Debug report. + + + + +-------------------------------------------------------------------------------- +BACK-END PROCESSES - Demographic Quota process flow: + +The new back-end process and 'Dispo Call URL' script that will read the above quota specifications for the campaign will start with the "demo01" demographic and dial until either the quotas were filled, or all leads that match those quota values for that demo had been called once. Then, the campaign would move on to "demo02" and then to "demo03" and "demo04". After one run through all lists in the campaign, if any quotas had not been met, the lists can be automatically reset(optional campaign setting for this) and a second pass would start with the dialable leads that were left. This system allows up to 10 demographics in the above configuration, as well as up to 10 field values for each demographic, which makes this system extremely flexible different types of polling/survey campaigns. + +For campaigns that have Demographic Quotas enabled on them, the standard back-end hopper filling process will add a filter to exclude leads with a rank of '-9999'. This is both for improved system performance and also so that leads that are for already filled quota values can be excluded from dialing in the campaign. + +As for any perceptible system lag, that depends on the size of your lists and the capacity of your DB server. The resets should not be very frequent, and you should only have the lists active that you are actively dialing on at any time, which will help with the speed of the quota list management. The back-end process will actually log the amount of time it takes to run the ranking queries and the longest query run time will be shown as part of the Campaign Debug "DEMO_QUOTAS" output. To help reduce database load, if the Re-Rank option is set to HOUR or MINUTE, the number of ranked leads will be limited to the number of leads that can be put into the hopper in a few hours/minutes instead of re-ranking all leads every time the re-ranking process is run. + +On the technical side, the 'AST_VDdemographic_quotas.pl' script is responsible for this set of features, and it is triggered automatically on the server in your cluster defined in System Settings as the "Active Voicemail Server". This is also the server that will run the 'AST_VDhopper.pl' script as it is triggered by the Demographic Quotas processes. + + + + + + +-------------- TESTING EXAMPLE USING BUILT-IN PERFORMANCE TEST LIST AND LOOPBACK CALLING ----------- + +Another Settings Container example for Demographic Quotas: + + +; define finished lead statuses for this campaign that will meet quota: +finished_statuses => SVYCLM,AFTHRS + +; demo 01 - age range +demo01_field => address3 +; field values(in dial priority order), quota goal of finished leads +demo01_value01 => 18-24,2 +demo01_value02 => 25-34,7 +demo01_value03 => 35-44,8 +demo01_value04 => 45-54,8 +demo01_value05 => 55-64,9 +demo01_value06 => 65-74,10 +demo01_value07 => 75,5 + +; demo 02 - region +demo02_field => province +demo02_value01 => North,15 +demo02_value02 => Central,20 +demo02_value03 => South,15 + +; demo 03 - political party +demo03_field => title +demo03_value01 => REP,20 +demo03_value02 => DEM,20 +demo03_value03 => OTH,10 + +; demo 04 - gender +demo04_field => gender +demo04_value01 => M,22 +demo04_value02 => F,28 + + + +To test the above, load the "performance_test_list.txt" sample leads file into list 999884, then perform the following MySQL queries: + +DELETE FROM vicidial_list where list_id=999884 order by RAND() limit 10000; + +UPDATE vicidial_list set gender='U' where list_id=999884; +UPDATE vicidial_list set gender='M' where list_id=999884 order by RAND() limit 22000; +UPDATE vicidial_list set gender='F' where list_id=999884 and gender!='M' order by RAND() limit 28000; + +UPDATE vicidial_list set title='X' where list_id=999884; +UPDATE vicidial_list set title='REP' where list_id=999884 order by RAND() limit 20000; +UPDATE vicidial_list set title='DEM' where list_id=999884 and title NOT IN('REP') order by RAND() limit 20000; +UPDATE vicidial_list set title='OTH' where list_id=999884 and title NOT IN('REP','DEM') order by RAND() limit 10000; + +UPDATE vicidial_list set province='Y' where list_id=999884; +UPDATE vicidial_list set province='North' where list_id=999884 order by RAND() limit 15000; +UPDATE vicidial_list set province='Central' where list_id=999884 and province NOT IN('North') order by RAND() limit 20000; +UPDATE vicidial_list set province='South' where list_id=999884 and province NOT IN('North','Central') order by RAND() limit 15000; + +UPDATE vicidial_list set address3='0' where list_id=999884; +UPDATE vicidial_list set address3='18-24' where list_id=999884 order by RAND() limit 2000; +UPDATE vicidial_list set address3='25-34' where list_id=999884 and address3='0' order by RAND() limit 7000; +UPDATE vicidial_list set address3='35-44' where list_id=999884 and address3='0' order by RAND() limit 8000; +UPDATE vicidial_list set address3='45-54' where list_id=999884 and address3='0' order by RAND() limit 8000; +UPDATE vicidial_list set address3='55-64' where list_id=999884 and address3='0' order by RAND() limit 9000; +UPDATE vicidial_list set address3='65-74' where list_id=999884 and address3='0' order by RAND() limit 10000; +UPDATE vicidial_list set address3='75' where list_id=999884 and address3='0' order by RAND() limit 5000; + +UPDATE vicidial_list set status='SVYCLM' where list_id=999884 order by RAND() limit 50; + + + + + + + + + + +-------------------------------------------------------------------------------- +FOR REFERENCE ONLY, DO NOT RUN THESE QUERIES!!!!!!!!!!!!!!!!!!!! + +Demographic Quotas SQL changes: + +ALTER TABLE system_settings ADD demographic_quotas ENUM('0','1','2','3','4','5','6','7') default '0'; + +ALTER TABLE vicidial_campaigns ADD demographic_quotas ENUM('DISABLED','ENABLED','INVALID','COMPLETE') default 'DISABLED'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_container VARCHAR(40) default 'DISABLED'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_rerank ENUM('NO','NOW','HOUR','MINUTE','NOW_HOUR') default 'NO'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_last_rerank DATETIME default '2000-01-01 00:00:00'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_list_resets ENUM('AUTO','MANUAL') default 'MANUAL'; + +CREATE TABLE vicidial_demographic_quotas_goals ( +vdqg_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, +campaign_id VARCHAR(8) default '', +demographic_quotas_container VARCHAR(40) default '', +quota_field VARCHAR(20) default '', +quota_field_order TINYINT(3) default '0', +quota_value VARCHAR(100) default '', +quota_value_order TINYINT(3) default '0', +quota_goal MEDIUMINT(7) default '0', +quota_count MEDIUMINT(7) default '0', +quota_leads_total MEDIUMINT(7) default '0', +quota_leads_active MEDIUMINT(7) default '0', +quota_status VARCHAR(10) default 'ACTIVE', +quota_modify_date DATETIME, +last_lead_id INT(9) UNSIGNED default '0', +last_list_id BIGINT(14) UNSIGNED default '0', +last_call_date DATETIME, +last_status VARCHAR(6) default '', +index(campaign_id), +index(quota_field), +index(quota_value), +unique index vdqgi (campaign_id,quota_field,quota_field_order,quota_value,quota_value_order) +) ENGINE=MyISAM; + +INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('HOPPER_CLI_FLAGS', 'Comand-line flags for hopper process', 'PERL_CLI', '---ALL---', ''); diff --git a/docs/conf_examples/extensions.conf.sample-18 b/docs/conf_examples/extensions.conf.sample-18 new file mode 100644 index 00000000..a367f4bc --- /dev/null +++ b/docs/conf_examples/extensions.conf.sample-18 @@ -0,0 +1,666 @@ +[general] +static=yes +writeprotect=no + +[globals] +CONSOLE=Console/dsp ; Console interface for demo +TRUNK=DAHDI/r1 ; Trunk interface +TRUNKX=DAHDI/r2 ; 2nd trunk interface +TRUNKIAX=IAX2/ASTtest1:test@10.10.10.16:4569 ; IAX trunk interface +TRUNKIAX1=IAX2/ASTtest1:test@10.10.10.16:4569 ; IAX trunk interface +TRUNKBINFONE=IAX2/1112223333:PASSWORD@iax.binfone.com ; IAX trunk interface +SIPtrunk=SIP/1234:PASSWORD@sip.provider.net ; SIP trunk + +#include extensions-vicidial.conf + +[trunkinbound] +; DID call routing process +; exten => _XXXXXXXXXX,1,AGI(agi-DID_route.agi) ; use this one instead of the one below if you are having delay issues, and match to number of received digits +exten => _X.,1,AGI(agi-DID_route.agi) +exten => _X.,n,Hangup() +; If you have DIDs that arrive with a plus sign at the beginning then uncomment +;exten => _+X.,1,AGI(agi-DID_route.agi) +;exten => _+X.,n,Hangup() +; If you have DIDs that arrive with a plus and 1 at the beginning that you want to filter out, then uncomment +;exten => _+1X.,1,Goto(trunkinbound,${EXTEN:2},1) + +; FastAGI for VICIDIAL/astGUIclient call logging +exten => h,1,AGI(agi://127.0.0.1:4577/call_log--HVcauses--PRI-----NODEBUG-----${HANGUPCAUSE}-----${DIALSTATUS}-----${DIALEDTIME}-----${ANSWEREDTIME}-----${HANGUPCAUSE(${HANGUPCAUSE_KEYS()},tech)})) + +[loopback-no-log] +; This context is to accept calls that have already been logged in another context in Vicidial +; and has been sent through one of the loopbacks. This is why this context is missing the h extension. +; Do not put any extensions in this context unless you specifically understand what this means. + +;exten => _91NXXNXXXXXX,1,Dial(${TRUNKX}/${EXTEN:1},,To) +;exten => _91NXXNXXXXXX,n,Hangup() + +; special Canadian PRI callerIDname settings FOR USE IN LOOPBACK CONTEXT ONLY +;exten => _91NXXNXXXXXX,1,Set(CALLERID(name)="ACME Widgets") +;exten => _91NXXNXXXXXX,n,AGI(agi-CANADA_PRI_CIDname.agi) +;exten => _91NXXNXXXXXX,n,Dial(${TRUNKX}/${EXTEN:1},,To) +;exten => _91NXXNXXXXXX,n,Hangup() + +exten => _999XX11112,1,Wait(2) +exten => _999XX11112,n,Answer() +exten => _999XX11112,n,Playback(ss-noservice) +exten => _999XX11112,n,Playback(vm-goodbye) +exten => _999XX11112,n,Hangup() + +[default] +include => vicidial-auto + +; Local agent alert extensions +exten => _8600XXX*.,1,AGI(agi-VDADfixCXFER.agi) +exten => _8600XXX*.,n,Hangup() +exten => _78600XXX*.,1,AGI(agi-VDADfixCXFER.agi) +exten => _78600XXX*.,n,Hangup() + +; Local blind monitoring +exten => _08600XXX,1,Dial(${TRUNKblind}/6${EXTEN:1},55,To) +exten => _08600XXX,n,Hangup() + + +; playback of recorded prompts +exten => _851XXXXX,1,Answer() +exten => _851XXXXX,n,Playback(${EXTEN}) +exten => _851XXXXX,n,Hangup() + +; this is used for playing a message to an answering machine forwarded from AMD in VICIDIAL +exten => _6851XXXXX,1,Answer() +exten => _6851XXXXX,n,WaitForSilence(2000,1,90) +exten => _6851XXXXX,n,Playback(sip-silence) +exten => _6851XXXXX,n,Playback(${EXTEN:1}) +exten => _6851XXXXX,n,Hangup() +exten => _7851XXXXX,1,WaitForSilence(2000,2) ; AMD got machine. leave message after recording +exten => _7851XXXXX,n,Playback(${EXTEN:1}) +exten => _7851XXXXX,n,AGI(VD_amd_post.agi,${EXTEN:1}) +exten => _7851XXXXX,n,Hangup() + + +; FastAGI for VICIDIAL/astGUIclient call logging +exten => h,1,AGI(agi://127.0.0.1:4577/call_log--HVcauses--PRI-----NODEBUG-----${HANGUPCAUSE}-----${DIALSTATUS}-----${DIALEDTIME}-----${ANSWEREDTIME}-----${HANGUPCAUSE(${HANGUPCAUSE_KEYS()},tech)})) + +; Example phone extensions +; 100-350 phone extensions now auto-generated, so no need to uncommend them +; extensions for other SIP and IAX call center phones +; cc100-cc150 SIP Phones +;exten => _1[0-5]X,1,Dial(sip/cc${EXTEN},20,to) +;exten => _1[0-5]X,n,Hangup() +; cc300-cc350 IAX Phones +;exten => _3[0-5]X,1,Dial(IAX2/cc${EXTEN},20,to) +;exten => _3[0-5]X,n,Hangup() +; extensions if using a T1 channelbank +;exten => _19XX,1,Dial(Zap/${EXTEN:2},30,o) +;exten => _19XX,n,Hangup() +; Extension 4001 rings Zap phone (this example for FXS on Zap port 1) +;exten => 4001,1,Dial(Zap/1,30,o) ; ring Zap device 1 +;exten => 4001,n,Voicemail(u4001) ; Send to voicemail... +;exten => 4001,n,Hangup() + + +; # timeout invalid rules +exten => #,1,Playback(invalid) ; "Thanks for trying the demo" +exten => #,2,Hangup() ; Hang them up. +exten => t,1,Goto(#,1) ; If they take too long, give up +exten => t,n,Hangup() +exten => i,1,Playback(invalid) ; "That's not valid, try again" +exten => i,n,Hangup() + + +; Extensions for performance testing +;exten => _91999NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91999NXXXXXX,n,Dial(${TRUNKloop}/${EXTEN:2},,tTo) +;exten => _91999NXXXXXX,n,Hangup() +;exten => 999999999999,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => 999999999999,n,Dial(${TRUNKloop}/${EXTEN:1},,tTo) +;exten => 999999999999,n,Hangup() + +; This is a loopback dialaround to allow for hearing of ringing for 3way calls +exten => _881NXXNXXXXXX,1,Answer() +exten => _881NXXNXXXXXX,n,Dial(${TRUNKloop}/9${EXTEN:2},,To) +exten => _881NXXNXXXXXX,n,Hangup() + +; Vtiger fax and email log extensions +exten => _9118XXXXXXXX,1,Dial(${TRUNKblind}/9998818112,55,to) +exten => _9118XXXXXXXX,n,Hangup() +exten => _9119XXXXXXXX,1,Dial(${TRUNKblind}/9998819112,55,to) +exten => _9119XXXXXXXX,n,Hangup() + + +; CARRIER DIALING EXTENSIONS, USE THE ADMIN INTERFACE TO PROGRAM THESE +; dial an 800 outbound number +;exten => _91800NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91800NXXXXXX,n,Dial(${TRUNK}/${EXTEN:1},,To) +;exten => _91800NXXXXXX,n,Hangup() +;exten => _91888NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91888NXXXXXX,n,Dial(${TRUNK}/${EXTEN:1},,To) +;exten => _91888NXXXXXX,n,Hangup() +;exten => _91877NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91877NXXXXXX,n,Dial(${TRUNK}/${EXTEN:1},,To) +;exten => _91877NXXXXXX,n,Hangup() +;exten => _91866NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91866NXXXXXX,n,Dial(${TRUNK}/${EXTEN:1},,To) +;exten => _91866NXXXXXX,n,Hangup() +;exten => _91855NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91855NXXXXXX,n,Dial(${TRUNK}/${EXTEN:1},,To) +;exten => _91855NXXXXXX,n,Hangup() + +; dial a long distance outbound number +; This 'o' Dial flag is VERY important for VICIDIAL on outbound calls +;exten => _91NXXNXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _91NXXNXXXXXX,n,Dial(${TRUNKX}/${EXTEN:1},,To) +;exten => _91NXXNXXXXXX,n,Hangup() + +; dial a local outbound number (modified because of only LD T1) +;exten => _9NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _9NXXXXXX,n,Dial(${TRUNK}/1727${EXTEN:1},,To) +;exten => _9NXXXXXX,n,Hangup() + +; dial a local 727 outbound number with area code +;exten => _9727NXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _9727NXXXXXX,n,Dial(${TRUNK}/1${EXTEN:1},,To) +;exten => _9727NXXXXXX,n,Hangup() + +; dial a long distance outbound number to the UK +; This 'o' Dial flag is VERY important for VICIDIAL on outbound calls, +;exten => _901144XXXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _901144XXXXXXXXXX,n,Dial(${TRUNKX}/${EXTEN:1},55,To) +;exten => _901144XXXXXXXXXX,n,Hangup() + +; dial a long distance outbound number to Australia +; This 'o' Dial flag is VERY important for VICIDIAL on outbound calls, +;exten => _901161XXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +;exten => _901161XXXXXXXXX,n,Dial(${TRUNKX}/${EXTEN:1},,To) +;exten => _901161XXXXXXXXX,n,Hangup() + +; dial a long distance outbound number through BINFONE +; exten => _91NXXNXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91NXXNXXXXXX,n,Dial(${TRUNKIAX}/${EXTEN:1},55,To) +; exten => _91NXXNXXXXXX,n,Hangup() +; dial a long distance outbound number through a SIP provider +; exten => _91NXXNXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91NXXNXXXXXX,n,Dial(sip/${EXTEN:1}@SIPtrunk,55,o) +; exten => _91NXXNXXXXXX,n,Hangup() +; special extensions for North America to catch invalid phone numbers +; exten => _91XXX[0-1]XXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXX[0-1]XXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXX[0-1]XXXXXX,n,Hangup() +; exten => _91[0-1]XXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91[0-1]XXXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91[0-1]XXXXXXXXX,n,Hangup() +; exten => _91XXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXX,n,Hangup() +; exten => _91XXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXX,n,Hangup() +; exten => _91XXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXXX,n,Hangup() +; exten => _91XXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXXXX,n,Hangup() +; exten => _91XXXXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXXXXXX,n,Hangup() +; exten => _91XXXXXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXXXXXXX,n,Hangup() +; exten => _91XXXXXXXXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91XXXXXXXXXXXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91XXXXXXXXXXXXX,n,Hangup() +; block calls to 555 numbers +; exten => _91NXX555NXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91NXX555NXXX,n,Dial(${TRUNKloop}/8889990011112,,to) +; exten => _91NXX555NXXX,n,Hangup() +; dial a USA long distance outbound number through the loopback-no-log context +; exten => _91NXXNXXXXXX,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => _91NXXNXXXXXX,n,Dial(${TRUNKloop}/888${EXTEN:2},55,o) +; exten => _91NXXNXXXXXX,n,Hangup() +;exten => _888NXXNXXXXXX,1,Goto(loopback-no-log,91${EXTEN:3},1) +;exten => _888NXXNXXXXXX,n,Hangup() + +exten => 8889990011112,1,Goto(loopback-no-log,9990011112,1) +exten => 8889990011112,n,Hangup() + + +; Inbound call from BINFONE +; exten => 1112223333,1,AGI(agi://127.0.0.1:4577/call_log) +; exten => 1112223333,n,Dial(sip/gs102,55,o) +; exten => 1112223333,n,Hangup() + +; Extension 7275551212 - Inbound local number from PRI with 10 digit delivery +;exten => 7275551212,1,Ringing() +;exten => 7275551212,n,Wait(1) +;exten => 7275551212,n,AGI(agi://127.0.0.1:4577/call_log--fullCID--${EXTEN}-----${CALLERID(all)}-----${CALLERID(num)}-----${CALLERID(name)}) +;exten => 7275551212,n,Answer() +;exten => 7275551212,n,Dial(sip/spa2000&sip/spa2001,30,To) +;exten => 7275551212,n,Voicemail(u2000) +;exten => 7275551212,n,Hangup() + +; parameters for call_inbound.agi (7 fields separated by five dashes "-----"): +; 1. the extension of the phone to ring as defined in the asterisk.phones table +; 2. the phone number that was called, for the live_inbound/_log entry +; 3. a text description of the number that was called in +; 4-7. optional fields, they are also passed as fields in the GUI to web browser +; This is not part of VICIDIAL, it is for astGUIclient agent use only + +; Extension 3429 - Inbound 800 number (1-800-555-3429) example of RBS T1 +; with 10 digit ANI and 4 digit DNIS star separated +;exten => _**3429,1,Ringing +;exten => _**3429,n,AGI(agi://127.0.0.1:4577/call_log) +;exten => _**3429,n,AGI(call_inbound.agi,spa2000-----8005553429-----Inbound 800-----x-----y-----z-----w) +;exten => _**3429,n,Answer() +;exten => _**3429,n,Dial(sip/spa2000&sip/spa2001,30,to) +;exten => _**3429,n,Voicemail(u2000) +;exten => _**3429,n,Hangup() +; Extension 3429 - with ANI [callerID] +;exten => _*NXXNXXXXXX*3429,1,Ringing +;exten => _*NXXNXXXXXX*3429,n,AGI(agi://127.0.0.1:4577/call_log) +;exten => _*NXXNXXXXXX*3429,n,AGI(call_inbound.agi,spa2000-----8005553429-----Inbound 800-----x-----y-----z-----w) +;exten => _*NXXNXXXXXX*3429,n,Answer() +;exten => _*NXXNXXXXXX*3429,n,Dial(sip/spa2000&sip/spa2001,30,to) +;exten => _*NXXNXXXXXX*3429,n,Voicemail(u2000) +;exten => _*NXXNXXXXXX*3429,n,Hangup() + + +; parameters for agi-VDAD_ALL_inbound.agi (upto 12 fields separated by five dashes "-----"): +; Below are the parameters needed for the script to be run properly +; 1. the method of call handling for the script: +; - CID - CID received, add record with phone number +; - CIDLOOKUP - Lookup CID to find record in whole system +; - CIDLOOKUPRL - Restrict lookup to one list +; - CIDLOOKUPRC - Restrict lookup to one campaign's lists +; - CLOSER - Closer calls from VICIDIAL fronters +; - ANI - ANI received, add record with phone number (based on RBS T1s) +; - ANILOOKUP - Lookup ANI to find record in whole system +; - ANILOOKUPRL - Restrict lookup to one list +; - ANILOOKUPRC - Restrict lookup to one campaign's lists +; - VID - Add record with Vendor Lead Code received as argument 12 +; - VIDLOOKUP - Lookup Vendor Lead Code received as argument 12 to find record in whole system +; - VIDLOOKUPRL - Restrict lookup to one list (argument 12) +; - VIDLOOKUPRC - Restrict lookup to one campaign's lists (argument 12) +; - VIDPROMPT - Prompt Vendor Lead Code to User with IVR to add record with Vendor Lead Code +; - VIDPROMPTLOOKUP - Prompt Vendor Lead Code to User with IVR to find record in whole system +; - VIDPROMPTLOOKUPRL - Restrict lookup to one list +; - VIDPROMPTLOOKUPRC - Restrict lookup to one campaign's lists +; - 3DIGITID - Enter 3 digit code to go to agent +; - 4DIGITID - Enter 4 digit code to go to agent +; - XDIGITID - Enter X digit code to go to agent(variable, i.e. 9DIGITID, 12DIGITID, etc...) +; 2. the method of searching for an available agent: +; - LO - Load Balance Overflow only (priority to home server) +; - LB - Load Balance total system +; - SO - Home server only +; 3. the full name of the IN GROUP to be used in vicidial for the inbound call +; 4. the phone number that was called, for the log entry +; 5. the callerID or lead_id of the person that called(usually overridden) +; 6. the park extension audio file name if used +; 7. the status of the call initially(usually not used) +; 8. the list_id to insert the new lead under if it is new (and CID/ANI available) +; 9. the phone dialing code to insert with the new lead if new (and CID/ANI available) +; 10. the campaign_id to search within lists if CIDLOOKUPRC +; 11. the user to queue the call to for AGENTDIRECT in-group calls +; 12. vendor_lead_code if external mechanism like custom IVR is used to prompt user for ID +; +; inbound VICIDIAL call with CID delivery through T1 PRI +;exten => 1234,1,Answer() ; Answer the line +;exten => 1234,n,AGI(agi-VDAD_ALL_inbound.agi,CID-----LB-----CL_GALLERIA-----7274515134-----Closer-----park----------999-----1) +;exten => 1234,n,Hangup() + +; inbound VICIDIAL transfer calls [can arrive through PRI T1 crossover, IAX or SIP channel] +exten => _90009.,1,Answer() ; Answer the line +exten => _90009.,n,Dial(${TRUNKloop}/9${EXTEN},,to) +exten => _90009.,n,Hangup() +exten => _990009.,1,Answer() ; Answer the line, Sometimes needs to be removed +exten => _990009.,n,AGI(agi-VDAD_ALL_inbound.agi,CLOSER-----LB-----CL_TESTCAMP-----7275551212-----Closer-----park----------999-----1) +exten => _990009.,n,Hangup() +; DID forwarded calls +exten => _99909*.,1,Answer() +exten => _99909*.,n,AGI(agi-VDAD_ALL_inbound.agi) +exten => _99909*.,n,Hangup() + + +; barge monitoring extension +exten => 8159,1,ZapBarge() +exten => 8159,n,Hangup() + +; ZapBarge direct channel extensions +exten => _86120XX,1,ZapBarge(${EXTEN:5}) +exten => _86120XX,n,Hangup() + +; MeetMe Adjustment Extensions +exten => _X48600XXX,1,MeetMeAdmin(${EXTEN:2},T,${EXTEN:0:1}) +exten => _X48600XXX,2,Hangup() + +exten => _X38600XXX,1,MeetMeAdmin(${EXTEN:2},t,${EXTEN:0:1}) +exten => _X38600XXX,2,Hangup() + +exten => _X28600XXX,1,MeetMeAdmin(${EXTEN:2},m,${EXTEN:0:1}) +exten => _X28600XXX,2,Hangup() + +exten => _X18600XXX,1,MeetMeAdmin(${EXTEN:2},M,${EXTEN:0:1}) +exten => _X18600XXX,2,Hangup() + +exten => _55558600XXX,1,MeetMeAdmin(${EXTEN:4},K) +exten => _55558600XXX,2,Hangup() + +; immediate hangup extension +exten => 8300,1,Hangup() + +; astGUIclient conferences +exten => _86000[0-4]X,1,Meetme(${EXTEN},q) +exten => _86000[0-4]X,n,Hangup() + +; VICIDIAL conferences +exten => _86000[5-9]X,1,Meetme(${EXTEN},F) +exten => _86000[5-9]X,n,Hangup() +exten => _8600[1-2]XX,1,Meetme(${EXTEN},F) +exten => _8600[1-2]XX,n,Hangup() + +; quiet entry and leaving conferences for VICIDIAL (inbound announce, SendDTMF and ring-agent) +exten => _78600XXX,1,Meetme(${EXTEN:1},Fq) +exten => _78600XXX,n,Hangup() + +; quiet monitor-only extensions for meetme rooms (for room managers) +exten => _68600XXX,1,Meetme(${EXTEN:1},Fmq) +exten => _68600XXX,n,Hangup() + +; Asterisk 1.8 workaround +exten => _58600XXX,1,Meetme(${EXTEN:1},Fmq) +exten => _58600XXX,n,Hangup() + +; quiet monitor-only entry and leaving conferences for VICIDIAL (recording) +exten => _558600XXX,1,Meetme(${EXTEN:2},Fmq) +exten => _558600XXX,n,Hangup() + +; voicelab exten +exten => _86009XX,1,Meetme(${EXTEN},Fmq) +; voicelab exten moderator +exten => _986009XX,1,Meetme(${EXTEN:1}) + + + +; park channel for client GUI parking, hangup after 30 minutes +; create a GSM formatted audio file named "park.gsm" that is 30 minutes long +; and put it in /var/lib/asterisk/sounds +exten => 8301,1,Answer() +exten => 8301,n,AGI(park_CID.agi) +exten => 8301,n,Playback(park) +exten => 8301,n,Hangup() +exten => 8303,1,Answer() +exten => 8303,n,AGI(park_CID.agi) +exten => 8303,n,Playback(conf) +exten => 8303,n,Hangup() + +; park channel for client GUI conferencing, hangup after 30 minutes +; create a GSM formatted audio file named "conf.gsm" that is 30 minutes long +; and put it in /var/lib/asterisk/sounds +exten => 8302,1,Answer() +exten => 8302,n,Playback(conf) +exten => 8302,n,Hangup() + +exten => 8304,1,Answer() +exten => 8304,n,Playback(ding) +exten => 8304,n,Hangup() + +; default audio for safe harbor 2-second-after-hello message then hangup +; create a GSM formatted audio file complies with safe harbor rules +; and put it in /var/lib/asterisk/sounds then change filename below +exten => 8307,1,Answer() +exten => 8307,n,Playback(vm-goodbye) +exten => 8307,n,Hangup() + +; this is used for playing a message to an answering machine forwarded from AMD in VICIDIAL +exten => 8320,1,AGI(VD_amd.agi,${EXTEN}-----YES) +exten => 8320,n,Hangup() +exten => _8320*.,1,AGI(VD_amd.agi,${EXTEN}-----YES) +exten => _8320*.,n,Hangup() + +; these are used for the ring_all function in VICIDIAL +exten => _8331*.,1,Playback(sip-silence) +exten => _8331*.,n,AGI(agi-VDAD_RINGALL.agi,${EXTEN}) +exten => _8331*.,n,AGI(agi-VDAD_RINGALL.agi,${EXTEN}) +exten => _8331*.,n,AGI(agi-VDAD_RINGALL.agi,${EXTEN}) +exten => _8331*.,n,Hangup() + + +; use for selective CallerID hangup by area code(hard-coded) +exten => 8352,1,AGI(agi-VDADselective_CID_hangup.agi,${EXTEN}) +exten => 8352,n,Playback(safe_harbor) +exten => 8352,n,Hangup() + +; this is used for sending DTMF signals within conference calls, the client app +; sends the digits to be played in the callerID field +; sound files must be placed in /var/lib/asterisk/sounds +exten => 8500998,1,Answer() +exten => 8500998,n,Playback(silence) +exten => 8500998,n,AGI(agi-dtmf.agi,signalonly) +exten => 8500998,n,Hangup() + +; multi-remote-monitor entry extensions +exten => 8162,1,Dial(${TRUNKblind}/34567890123456789,55,to) +exten => 8162,n,Hangup() + +exten => 34567890123456789,1,Answer() +exten => 34567890123456789,n,Goto(monitor,s,1) +exten => 34567890123456789,n,Hangup() + +;#### VDAD STANDARD TRANSFER ENTRIES #### +; Below are the parameters needed for the agi-VDAD_ALL_outbound.agi script to be run properly +; 1. the method of call handling for the script: +; - NORMAL - Standard outbound routing to agent +; - TEST - For performance testing only +; - BROADCAST - For no-agent broadcast dialing +; - SURVEY - For survery question then on to agent +; - REMINDER - Reminder campaign +; - REMINDX - Reminder with transfer to agent +; 2. the method of searching for an available agent: +; - LB - Load Balance total system +; - LO - Load Balance Overflow only (priority to home server) +; - SO - Home server only +; 3. the sound file to play when doing a SURVEY, REMINDER, REMINDX campaign +; 4. the acceptible dtmf digits for a SURVEY +; 5. the out-opt digit for a SURVEY (must be in the digit map) +; 6. the sound file to play for a SURVEY when transfering to an agent +; 7. the sound file to play for a SURVEY when DNCing the call +; 8. OPTIN or OPTOUT: if OPTIN call is only sent to agent with button press +; if OPTOUT call is sent to agent if no button press at all +; 9. the status that is use for a SURVEY when someone opts out +; if the status is DNC it will also add them to the internal dnc table + +; Local channel resolution fix for Asterisk 13 +exten => _1383XX,1,AGI(agi-VDAD_local_optimize.agi,${CONNECTEDLINE(name)}) +exten => _1383XX,n,Wait(2) +exten => _1383XX,n,Hangup() + +exten => _138331*.,1,AGI(agi-VDAD_local_optimize.agi,${CONNECTEDLINE(name)}) +exten => _138331*.,n,Wait(2) +exten => _138331*.,n,Hangup() + +; VICIDIAL_auto_dialer transfer script for no-agent campaigns: +exten => 8364,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8364,n,AGI(agi-VDAD_ALL_outbound.agi,NORMAL-----LB-----${CONNECTEDLINE(name)}) +exten => 8364,n,Hangup() + +; VICIDIAL_auto_dialer transfer script: +exten => 8365,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8365,n,AGI(agi-VDAD_ALL_outbound.agi,NORMAL-----SO-----${CONNECTEDLINE(name)}) +exten => 8365,n,Hangup() + +; VICIDIAL_auto_dialer transfer script SURVEY at beginning: +exten => 8366,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8366,n,AGI(agi-VDAD_ALL_outbound.agi,SURVEYCAMP-----LB-----${CONNECTEDLINE(name)}) +exten => 8366,n,Hangup() + +; VICIDIAL_auto_dialer transfer script Load Balance Overflow: +exten => 8367,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8367,n,AGI(agi-VDAD_ALL_outbound.agi,NORMAL-----LO-----${CONNECTEDLINE(name)}) +exten => 8367,n,Hangup() + +; VICIDIAL_auto_dialer transfer script Load Balanced: +exten => 8368,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8368,n,AGI(agi-VDAD_ALL_outbound.agi,NORMAL-----LB-----${CONNECTEDLINE(name)}) +exten => 8368,n,Hangup() + +; VICIDIAL_auto_dialer transfer script AMD with Load Balanced: +exten => 8369,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8369,n,Playback(sip-silence) +exten => 8369,n,AMD(2000,2000,1000,5000,120,50,4,256) +exten => 8369,n,AGI(VD_amd.agi,${EXTEN}) +exten => 8369,n,AGI(agi-VDAD_ALL_outbound.agi,NORMAL-----LB-----${CONNECTEDLINE(name)}) +exten => 8369,n,Hangup() + +; VICIDIAL auto-dial reminder script +exten => 8372,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8372,n,AGI(agi-VDADautoREMINDER.agi,${EXTEN}) +exten => 8372,n,Hangup() + +; VICIDIAL SURVEY transfer script AMD with Load Balanced: +exten => 8373,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8373,n,Playback(sip-silence) +exten => 8373,n,AMD(2000,2000,1000,5000,120,50,4,256) +exten => 8373,n,AGI(VD_amd.agi,${EXTEN}) +exten => 8373,n,AGI(agi-VDAD_ALL_outbound.agi,SURVEYCAMP-----LB-----${CONNECTEDLINE(name)}) +exten => 8373,n,Hangup() + +; VICIDIAL SURVEY transfer script with Cepstral names: +exten => 8374,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8374,n,AGI(agi-VDAD_ALL_outbound.agi,SURVEYCAMPCEP-----LB-----${CONNECTEDLINE(name)}) +exten => 8374,n,Hangup() + +; VICIDIAL SURVEY transfer script AMD with Cepstral variables: +exten => 8375,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8375,n,Playback(sip-silence) +exten => 8375,n,AMD(2000,2000,1000,5000,120,50,4,256) +exten => 8375,n,AGI(VD_amd.agi,${EXTEN}) +exten => 8375,n,AGI(agi-VDAD_ALL_outbound.agi,SURVEYCAMPCEP-----LB-----${CONNECTEDLINE(name)}) +exten => 8375,n,Hangup() + +; BETA VICIDIAL_auto_dialer transfer script Load Balanced: +exten => 8377,1,AGI(agi://127.0.0.1:4577/call_log) +exten => 8377,n,Set(LRct=1) +exten => 8377,n,While($[${LRct} < 100]) +exten => 8377,n,AGI(agi-VDAD_ALL_outboundBETA.agi,NORMAL-----LB-----${CONNECTEDLINE(name)}) +exten => 8377,n,Set(LRct=$[${LRct} + 1]) +exten => 8377,n,EndWhile() +exten => 8377,n,AGI(agi-VDAD_ALL_outboundBETA.agi,NORMAL-----LB-----${CONNECTEDLINE(name)}) +exten => 8377,n,Hangup() + + +; PERFORMANCE TESTING +exten => _999XXXXXX1,1,Answer() +exten => _999XXXXXX1,n,Wait(2) +exten => _999XXXXXX1,n,Playback(vicidial-welcome) +exten => _999XXXXXX1,n,Hangup() + +exten => _999XX11112,1,Wait(2) +exten => _999XX11112,n,Answer() +exten => _999XX11112,n,Playback(ss-noservice) +exten => _999XX11112,n,Playback(vm-goodbye) +exten => _999XX11112,n,Hangup() + +exten => _999XX18112,1,Wait(2) +exten => _999XX18112,n,Answer() +exten => _999XX18112,n,Playback(vtiger-fax) +exten => _999XX18112,n,Playback(vtiger-fax) +exten => _999XX18112,n,Hangup() + +exten => _999XX19112,1,Wait(2) +exten => _999XX19112,n,Answer() +exten => _999XX19112,n,Playback(vtiger-email) +exten => _999XX19112,n,Playback(vtiger-email) +exten => _999XX19112,n,Hangup() + +exten => _999XXXX112,1,Wait(5) +exten => _999XXXX112,n,Answer() +exten => _999XXXX112,n,Playback(demo-instruct) +exten => _999XXXX112,n,Playback(demo-instruct) +exten => _999XXXX112,n,Hangup() + +exten => _999XXXXXX2,1,Wait(8) +exten => _999XXXXXX2,n,Answer() +exten => _999XXXXXX2,n,Playback(demo-instruct) +exten => _999XXXXXX2,n,Hangup() + +exten => _999XXXXXX3,1,Set(PRI_CAUSE=1) +exten => _999XXXXXX3,n,Hangup() + +exten => _999XXXXXX4,1,Set(PRI_CAUSE=27) +exten => _999XXXXXX4,n,Hangup() + +exten => _999XXXXXX5,1,Ringing +exten => _999XXXXXX5,n,Wait(120) +exten => _999XXXXXX5,n,Hangup() + +exten => _999XXXXXX6,1,Wait(10) +exten => _999XXXXXX6,n,Answer() +exten => _999XXXXXX6,n,Playback(demo-instruct) +exten => _999XXXXXX6,n,Hangup() + +exten => _999XXXXXX7,1,Wait(12) +exten => _999XXXXXX7,n,Answer() +exten => _999XXXXXX7,n,Playback(demo-enterkeywords) +exten => _999XXXXXX7,n,Hangup() + +exten => _999XXXXXX8,1,Set(PRI_CAUSE=17) +exten => _999XXXXXX8,n,Hangup() + +exten => _999XXXXXX9,1,Wait(6) +exten => _999XXXXXX9,n,Answer() +exten => _999XXXXXX9,n,Playback(demo-abouttotry) +exten => _999XXXXXX9,n,Hangup() + +exten => _999XXXXXX0,1,Wait(5) +exten => _999XXXXXX0,n,Answer() +exten => _999XXXXXX0,n,Playback(vm-goodbye) +exten => _999XXXXXX0,n,Hangup() + +;exten => 99999999999,1,Answer() +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Playback(conf) +;exten => 99999999999,n,Hangup() + + +[monitor] +exten => h,1,AGI(agi://127.0.0.1:4577/call_log--HVcauses--PRI-----NODEBUG-----${HANGUPCAUSE}-----${DIALSTATUS}-----${DIALEDTIME}-----${ANSWEREDTIME}-----${HANGUPCAUSE(${HANGUPCAUSE_KEYS()},tech)})) +exten => s,1,Set(TIMEOUT(digit)=10) +exten => s,n,Set(TIMEOUT(response)=10) +exten => s,n,Set(MEETME_EXIT_CONTEXT=monitor_exit) +exten => s,n,Background(vm-extension) ; need audio prompt. +exten => s,n,WaitExten(10) +exten => s,n,Hangup() + +exten => i,1,Goto(monitor_exit,s,1) +exten => i,n,Hangup() +exten => #,1,Goto(monitor_exit,s,1) +exten => #,n,Hangup() +exten => t,1,Goto(monitor_exit,s,1) +exten => t,n,Hangup() + +exten => _8[0-2]XX,1,Meetme(8600${EXTEN:1},mqX) ; Listen +exten => _8[0-2]XX,n,Hangup() +exten => _99[0-2]XX,1,Meetme(8600${EXTEN:2},X) ; Barge +exten => _99[0-2]XX,n,Hangup() + +[monitor_exit] +exten => h,1,AGI(agi://127.0.0.1:4577/call_log--HVcauses--PRI-----NODEBUG-----${HANGUPCAUSE}-----${DIALSTATUS}-----${DIALEDTIME}-----${ANSWEREDTIME}-----${HANGUPCAUSE(${HANGUPCAUSE_KEYS()},tech)})) +exten => _X,1,Goto(monitor,s,1) +exten => _X,n,Hangup() + +exten => i,1,Goto(monitor,s,1) +exten => i,n,Hangup() +exten => #,1,Goto(monitor,s,1) +exten => #,n,Hangup() +exten => t,1,Goto(monitor,s,1) +exten => t,n,Hangup() diff --git a/extras/MySQL_AST_CREATE_tables.sql b/extras/MySQL_AST_CREATE_tables.sql index dd4baf96..15375ce5 100644 --- a/extras/MySQL_AST_CREATE_tables.sql +++ b/extras/MySQL_AST_CREATE_tables.sql @@ -1104,7 +1104,12 @@ user_group_script ENUM('DISABLED','ENABLED') default 'DISABLED', agent_hangup_route ENUM('HANGUP','MESSAGE','EXTENSION','IN_GROUP','CALLMENU') default 'HANGUP', agent_hangup_value TEXT, agent_hangup_ig_override ENUM('Y','N') default 'N', -show_confetti ENUM('DISABLED','SALES','CALLBACKS','SALES_AND_CALLBACKS') default 'DISABLED' +show_confetti ENUM('DISABLED','SALES','CALLBACKS','SALES_AND_CALLBACKS') default 'DISABLED', +demographic_quotas ENUM('DISABLED','ENABLED','INVALID','COMPLETE') default 'DISABLED', +demographic_quotas_container VARCHAR(40) default 'DISABLED', +demographic_quotas_rerank ENUM('NO','NOW','HOUR','MINUTE','NOW_HOUR') default 'NO', +demographic_quotas_last_rerank DATETIME default '2000-01-01 00:00:00', +demographic_quotas_list_resets ENUM('AUTO','MANUAL') default 'MANUAL' ) ENGINE=MyISAM; CREATE TABLE vicidial_lists ( @@ -1981,7 +1986,9 @@ max_logged_in_agents ENUM('0','1','2','3','4','5','6','7') default '0', user_codes_admin ENUM('0','1','2','3','4','5','6','7') default '0', login_kickall ENUM('0','1','2','3','4','5','6','7') default '0', abandon_check_queue ENUM('0','1','2','3','4','5','6','7') default '0', -agent_notifications ENUM('0','1','2','3','4','5','6','7') default '0' +agent_notifications ENUM('0','1','2','3','4','5','6','7') default '0', +demographic_quotas ENUM('0','1','2','3','4','5','6','7') default '0', +log_latency_gaps ENUM('0','1','2','3','4','5','6','7') default '1' ) ENGINE=MyISAM; CREATE TABLE vicidial_campaigns_list_mix ( @@ -4969,6 +4976,43 @@ index (user), index (log_date) ) ENGINE=MyISAM; +CREATE TABLE vicidial_demographic_quotas_goals ( +vdqg_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, +campaign_id VARCHAR(8) default '', +demographic_quotas_container VARCHAR(40) default '', +quota_field VARCHAR(20) default '', +quota_field_order TINYINT(3) default '0', +quota_value VARCHAR(100) default '', +quota_value_order TINYINT(3) default '0', +quota_goal MEDIUMINT(7) default '0', +quota_count MEDIUMINT(7) default '0', +quota_leads_total MEDIUMINT(7) default '0', +quota_leads_active MEDIUMINT(7) default '0', +quota_status VARCHAR(10) default 'ACTIVE', +quota_modify_date DATETIME, +last_lead_id INT(9) UNSIGNED default '0', +last_list_id BIGINT(14) UNSIGNED default '0', +last_call_date DATETIME, +last_status VARCHAR(6) default '', +index(campaign_id), +index(quota_field), +index(quota_value), +unique index vdqgi (campaign_id,quota_field,quota_field_order,quota_value,quota_value_order) +) ENGINE=MyISAM; + +CREATE TABLE vicidial_latency_gaps ( +user VARCHAR(20) default '', +user_ip VARCHAR(45) default '', +gap_date DATETIME, +gap_length MEDIUMINT(5) UNSIGNED default '0', +last_login_date DATETIME, +check_date DATETIME, +index(user), +index(gap_date), +index(check_date), +unique index vlgi (user,gap_date) +) ENGINE=MyISAM; + ALTER TABLE vicidial_email_list MODIFY message text character set utf8; @@ -5248,6 +5292,9 @@ CREATE UNIQUE INDEX vdalla on vicidial_agent_latency_log_archive (user,log_date) CREATE TABLE vicidial_agent_latency_summary_log_archive LIKE vicidial_agent_latency_summary_log; CREATE UNIQUE INDEX vdalsla on vicidial_agent_latency_summary_log_archive (user,log_date,web_ip); +CREATE TABLE vicidial_latency_gaps_archive LIKE vicidial_latency_gaps; +CREATE UNIQUE INDEX vdlga on vicidial_latency_gaps_archive (user,gap_date); + GRANT RELOAD ON *.* TO cron@'%'; GRANT RELOAD ON *.* TO cron@localhost; @@ -5334,6 +5381,8 @@ INSERT INTO vicidial_settings_containers(container_id,container_notes,container_ INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('USER_CODES_SYSTEM','User Codes List','OTHER','---ALL---',''); INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('VICIPHONE_SETTINGS','VICIphone WebRTC Extra Settings','WEBPHONE_SETTINGS','---ALL---','# determines if automatic gain control is enabled\nautoGain : 0\n\n# determines if echo cancellation is enabled\nechoCan : 0\n\n# determines if noise suppression is enabled\nnoiseSup :0\n\n# determines if the reg_exten is called upon successful registration\ndialRegExten : 1\n\n# determines the regional sound to use for progress audio\nprogReg : na\n\n# English translation phrases\nlangAttempting:"Attempting"\nlangConnected:"WS Connected"\nlangDisconnected:"WS Disconnected"\nlangExten:"Extension"\nlangIncall:"Incall"\nlangInit:"Initializing..."\nlangRedirect:"Redirect"\nlangRegFailed:"Reg. Failed"\nlangRegistering:"Registering"\nlangRegistered:"Registered"\nlangReject:"Rejected"\nlangRinging:"Ringing"\nlangSend:"Send"\nlangTrying:"Trying"\nlangUnregFailed:"Unreg. Failed"\nlangUnregistered:"Unregistered"\nlangUnregistering:"Unregistering"\nlangWebrtcError:"Something went wrong with WebRTC. Either your browser does not support the necessary WebRTC functions, you did not allow your browser to access the microphone, or there is a configuration issue. Please check your browsers error console for more details. For a list of compatible browsers please vist http://webrtc.org/"'); INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('CONFETTI_SETTINGS', 'Confetti settings for screen display', 'OTHER', '---ALL---', '; Confetti settings, to add visual interest to certain events\r\n; duration is how long the confetti animation runs, maxParticleCount is the\r\n; max number of confetti \"pieces\", and particleSpeed is how fast they float\r\nduration => 2\r\nmaxParticleCount => 2350\r\nparticleSpeed => 2\r\n'); +INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('HOPPER_CLI_FLAGS', 'Comand-line flags for hopper process', 'PERL_CLI', '---ALL---', ''); +INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('AGENT_LATENCY_LOGGING','Default agent latency logging settings','PERL_CLI','---ALL---','minimum_gap => 30\r\nemail_sender => \r\nemail_list => \r\nemail_subject => Agent Network Alert'); INSERT INTO `vicidial_settings_containers` VALUES ('VERM_STATUS_NAMES_OVERRIDE','Override dialer status names in enhanced reporting','OTHER','---ALL---','; For each status name you want overridden, type the status followed by\r\n; a pipe, then the new status name\r\n; Ex:\r\n; NZ|Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupoka\r\n201214|Request To Cancel\r\n210200|No Answer-Incomplete Call\r\n210201|Contact Established\r\n210202|Provider Review - HB\r\n210203|Promise to Pay\r\n210204|Setup Payment Plan\r\n210205|Research-Inquiry\r\n210206|Voice Mail Left - HB\r\n210207|Do Not Call\r\n210208|Appeal Verification\r\n210209|Bad Phone\r\n210210|Bad Address\r\n210211|Direct Pay Verification\r\n210213|Provider Approved\r\n210215|Update Notes Only\r\n210216|Voicemail-No Status Change\r\n210217|Sent Letter Request - HB\r\n210218|Auto VoiceMail Left - HB\r\n210219|Auto VoiceMail-No Status Change\r\n210302|Provider Review - LB\r\n210306|Voice Mail Left - LB\r\n210317|Sent Letter Request - LB\r\n210318|Auto VoiceMail Left - LB\r\n211503|Provider - COVID-19\r\n211603|Transferred Call to MLA\r\n'), ('VERM_REPORT_OPTIONS','Container for customizing VERM report output','OTHER','---ALL---','; This is the report queue used if none is chosen by the user\r\n; It\'s preloaded in some forms as well\r\nVERM_default_report_queue => ALL\r\n\r\n; If there are statuses to exclude from reports, list them here\r\n; Separate with commas. Default is AFTHRS\r\nexc_addtl_statuses => AFTHRS\r\n\r\n; Set the below value to 1 (or anything non-blank/non-zero) in order to \r\n; show the agents ID in addition to their full name in the report results\r\nshow_full_agent_info => 1\r\n\r\n; Some reports count \"lost\" calls - which are defined by the below variable\r\n; listing what you define as \"lost\" dispos. Separate with commas.\r\nlost_statuses => LOST,210208,DISPO\r\n\r\n; You can create a detailed IVR survey report for ingroups by defining\r\n; \"ivr_survey_ingroups_detail\" and \"ivr_survey_ingroups_voicemails.\"\r\n; For \"details\", supply an ingroup used as a tracking group on call menus.\r\n; Then, add a pipe and after that list all call menus that use the ingroup\r\n; as the tracking group, separating each with a comma\r\n; To track whether the calls went to voicemail, list every call menu/option\r\n; combination that goes to voicemail, separating the call menu from the \r\n; option with a pipe. One callmenu/option combo per line.\r\nivr_survey_ingroups_detail => 521205|561401,561402,561403,561404,561505\r\nivr_survey_ingroups_voicemails => 561505|t\r\n\r\n; #####################################################\r\n; # ALL of the below are used in the wallboard report #\r\n; #####################################################\r\nVERM_default_outb_widget_queue => ALL_OUT\r\nVERM_default_inb_widget_queue1 => 514915v_USA_Shared\r\nVERM_default_inb_widget_queue2 => 515915v_MLA_Shared\r\n\r\n; Used specifically for the SLA widget\r\n; Uses ingroups - separate multiple ingroups by commas\r\n; Comment out or leave blank to count all ingroups\r\nSLA_LEVEL_PCT_ingroups => 514915v,515915v\r\n\r\n; This removes remote agents from the wallboard reports\r\n; Comment out to include remote agents (or set to zero)\r\nomit_remote_agents => 1\r\n\r\n\r\n; #### AUTO DOWNLOAD ####\r\n; If the "total calls" value on any report requested exceeds the below \r\n; limit, automatically download the three "DETAILS" reports instead\r\n; of attempting to display that many records on-screen\r\nauto_download_limit => 50000\r\n\r\n; #### OUTCOMES report overrides ####\r\n; Use "outcome_lagged_status_overrides" for conditions where the call \r\n; record in the vicidial_log or vicidial_closer_log table has no uniqueid\r\n; value despite having a status/outcome, which can indicate a call \r\n; affected by network lag for certain statuses. This will change the call \r\n; status to "LAGGED". Separate statuses with commas. Default is the \r\n; automatic "PU" status.\r\noutcome_lagged_status_overrides => PU\r\n\r\n; Use "unknown_network_statuses" to change call statuses to read "Network/\r\n; LAGGED" on the OUTCOMES report. Separate statuses with commas.\r\n; IMPORTANT: if you are using the outcome_lagged_status_overrides option \r\n; above, make sure "LAGGED" is one of the unknown_network_statuses here\r\n; unknown_network_statuses => LAGGED\r\n\r\n; Use "outcome_status_overrides" to change one status to another on the \r\n; OUTCOMES report. Overrides are comma-separated pairs of dispositions \r\n; where the first disposition is the disposition to change, and the second\r\n; is the disposition to change to. Separate pairs with a pipe character as\r\n; in the below example. Off by default.\r\n; outcome_status_overrides => CBHOLD,DISPO|XFER,AL'); INSERT INTO `wallboard_widgets` VALUES ('queues_widget_1','AGENTS_AND_QUEUES','queues','','TEXT',5,'N',1,'Queue Information','','',NULL,'','',NULL,2),('queues_widget_0','AGENTS_AND_QUEUES','queues','','LOGO',2,'N',1,NULL,'','',NULL,'','',NULL,1),('queues_widget_2','AGENTS_AND_QUEUES','queues','SLA Level %','SLA_LEVEL_PCT',1,'N',1,NULL,'','>60',NULL,'','',NULL,3),('queues_widget_3','AGENTS_AND_QUEUES','queues','Outbound calls','LIVE_QUEUE_INFO',1,'N',1,'','201201','','','','','yellow_alarm,|red_alarm,',4),('queues_widget_4','AGENTS_AND_QUEUES','queues','USA Ded Inbound','LIVE_QUEUE_INFO',1,'N',1,'','ALL_IN','','','','','yellow_alarm,|red_alarm,',5),('queues_widget_5','AGENTS_AND_QUEUES','queues','MLA Ded Inbound','LIVE_QUEUE_INFO',1,'N',1,'','514911','','','','','yellow_alarm,|red_alarm,',6),('queues_widget_6','AGENTS_AND_QUEUES','queues','N Waiting Calls','N_WAITING_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,7),('queues_widget_7','AGENTS_AND_QUEUES','queues','Offered Calls','OFFERED_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,8),('queues_widget_8','AGENTS_AND_QUEUES','queues','Answered Calls','ANSWERED_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,9),('queues_widget_9','AGENTS_AND_QUEUES','queues','Lost Calls','LOST_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,10),('queues_widget_10','AGENTS_AND_QUEUES','queues','Longest Wait','LONGEST_WAIT',1,'N',1,NULL,'','',NULL,'','',NULL,11),('queues_widget_11','AGENTS_AND_QUEUES','queues','Live Queues','LIVE_QUEUES',1,'Y',1,NULL,'','',NULL,'','',NULL,12),('queues_widget_12','AGENTS_AND_QUEUES','queues','Live Calls','LIVE_CALLS',1,'Y',2,NULL,'','',NULL,'','',NULL,13),('agent_widget_0','AGENTS_AND_QUEUES','agents','','LOGO',2,'N',1,NULL,'','',NULL,'','',NULL,1),('agent_widget_1','AGENTS_AND_QUEUES','agents','N Waiting Calls','N_WAITING_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,2),('agent_widget_2','AGENTS_AND_QUEUES','agents','Agents Ready','AGENTS_READY',1,'N',1,NULL,'','',NULL,'','',NULL,3),('agent_widget_3','AGENTS_AND_QUEUES','agents','Agents On Call','N_AGENTS_ON_CALL',1,'N',1,NULL,'','',NULL,'','',NULL,4),('agent_widget_4','AGENTS_AND_QUEUES','agents','N Answered Calls','N_ANSWERED_CALLS',1,'N',1,NULL,'','',NULL,'','',NULL,5),('agent_widget_5','AGENTS_AND_QUEUES','agents','Clock','CLOCK',1,'N',1,NULL,'','',NULL,'','',NULL,6),('agent_widget_6','AGENTS_AND_QUEUES','agents','Live Agents','LIVE_AGENTS',1,'Y',3,NULL,'','',NULL,'','',NULL,7); @@ -5342,4 +5391,4 @@ INSERT INTO `wallboard_reports` VALUES ('AGENTS_AND_QUEUES','Agents and Queues', UPDATE system_settings set vdc_agent_api_active='1'; -UPDATE system_settings SET db_schema_version='1682',db_schema_update_date=NOW(),reload_timestamp=NOW(); +UPDATE system_settings SET db_schema_version='1683',db_schema_update_date=NOW(),reload_timestamp=NOW(); diff --git a/extras/upgrade_2.14.sql b/extras/upgrade_2.14.sql index 77281766..d989c9c9 100644 --- a/extras/upgrade_2.14.sql +++ b/extras/upgrade_2.14.sql @@ -2269,3 +2269,58 @@ CREATE TABLE vicidial_agent_latency_summary_log_archive LIKE vicidial_agent_late CREATE UNIQUE INDEX vdalsla on vicidial_agent_latency_summary_log_archive (user,log_date,web_ip); UPDATE system_settings SET db_schema_version='1682',db_schema_update_date=NOW() where db_schema_version < 1682; + +ALTER TABLE system_settings ADD demographic_quotas ENUM('0','1','2','3','4','5','6','7') default '0'; +ALTER TABLE system_settings ADD log_latency_gaps ENUM('0','1','2','3','4','5','6','7') default '1'; + +ALTER TABLE vicidial_campaigns ADD demographic_quotas ENUM('DISABLED','ENABLED','INVALID','COMPLETE') default 'DISABLED'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_container VARCHAR(40) default 'DISABLED'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_rerank ENUM('NO','NOW','HOUR','MINUTE','NOW_HOUR') default 'NO'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_last_rerank DATETIME default '2000-01-01 00:00:00'; +ALTER TABLE vicidial_campaigns ADD demographic_quotas_list_resets ENUM('AUTO','MANUAL') default 'MANUAL'; + +CREATE TABLE vicidial_demographic_quotas_goals ( +vdqg_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, +campaign_id VARCHAR(8) default '', +demographic_quotas_container VARCHAR(40) default '', +quota_field VARCHAR(20) default '', +quota_field_order TINYINT(3) default '0', +quota_value VARCHAR(100) default '', +quota_value_order TINYINT(3) default '0', +quota_goal MEDIUMINT(7) default '0', +quota_count MEDIUMINT(7) default '0', +quota_leads_total MEDIUMINT(7) default '0', +quota_leads_active MEDIUMINT(7) default '0', +quota_status VARCHAR(10) default 'ACTIVE', +quota_modify_date DATETIME, +last_lead_id INT(9) UNSIGNED default '0', +last_list_id BIGINT(14) UNSIGNED default '0', +last_call_date DATETIME, +last_status VARCHAR(6) default '', +index(campaign_id), +index(quota_field), +index(quota_value), +unique index vdqgi (campaign_id,quota_field,quota_field_order,quota_value,quota_value_order) +) ENGINE=MyISAM; + +CREATE TABLE vicidial_latency_gaps ( +user VARCHAR(20) default '', +user_ip VARCHAR(45) default '', +gap_date DATETIME, +gap_length MEDIUMINT(5) UNSIGNED default '0', +last_login_date DATETIME, +check_date DATETIME, +index(user), +index(gap_date), +index(check_date), +unique index vlgi (user,gap_date) +) ENGINE=MyISAM; + +CREATE TABLE vicidial_latency_gaps_archive LIKE vicidial_latency_gaps; +CREATE UNIQUE INDEX vdlga on vicidial_latency_gaps_archive (user,gap_date); + +INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('HOPPER_CLI_FLAGS', 'Comand-line flags for hopper process', 'PERL_CLI', '---ALL---', ''); + +INSERT INTO vicidial_settings_containers(container_id,container_notes,container_type,user_group,container_entry) VALUES ('AGENT_LATENCY_LOGGING','Default agent latency logging settings','PERL_CLI','---ALL---','minimum_gap => 30\r\nemail_sender => \r\nemail_list => \r\nemail_subject => Agent Network Alert'); + +UPDATE system_settings SET db_schema_version='1683',db_schema_update_date=NOW() where db_schema_version < 1683; diff --git a/install.pl b/install.pl index fb2aa1ed..39da7f5f 100644 --- a/install.pl +++ b/install.pl @@ -50,6 +50,7 @@ # 220829-1434 - Added 'C' keepalive option # 221228-2049 - Added KhompEnabled option # 230117-2220 - Added --khomp-enable CLI flag +# 230508-0809 - Added Asterisk 18 compatibility # ############################################ @@ -2741,11 +2742,24 @@ if ( ($PROMPTcopy_conf_files =~ /y/i) || ($CLIcopy_conf_files =~ /y/i) ) } else { - `cp -f ./docs/conf_examples/extensions.conf.sample-1.4 /etc/asterisk/extensions.conf`; - `cp -f ./docs/conf_examples/iax.conf.sample-1.4 /etc/asterisk/iax.conf`; - `cp -f ./docs/conf_examples/sip.conf.sample-1.4 /etc/asterisk/sip.conf`; - `cp -f ./docs/conf_examples/manager.conf.sample /etc/asterisk/manager.conf`; - `cp -f ./docs/conf_examples/voicemail.conf.sample /etc/asterisk/voicemail.conf`; + if ($VARasterisk_version =~ /^18|^20/) + { + `cp -f ./docs/conf_examples/extensions.conf.sample-18 /etc/asterisk/extensions.conf`; + `cp -f ./docs/conf_examples/iax.conf.sample-1.4 /etc/asterisk/iax.conf`; + `cp -f ./docs/conf_examples/sip.conf.sample-13 /etc/asterisk/sip.conf`; + `cp -f ./docs/conf_examples/manager.conf.sample-13 /etc/asterisk/manager.conf`; + `cp -f ./docs/conf_examples/voicemail.conf.sample-1.8 /etc/asterisk/voicemail.conf`; + `cp -f ./docs/conf_examples/pjsip.conf.sample-16 /etc/asterisk/pjsip.conf`; + `cp -f ./docs/conf_examples/pjsip_wizard.conf.sample-16 /etc/asterisk/pjsip_wizard.conf`; + } + else + { + `cp -f ./docs/conf_examples/extensions.conf.sample-1.4 /etc/asterisk/extensions.conf`; + `cp -f ./docs/conf_examples/iax.conf.sample-1.4 /etc/asterisk/iax.conf`; + `cp -f ./docs/conf_examples/sip.conf.sample-1.4 /etc/asterisk/sip.conf`; + `cp -f ./docs/conf_examples/manager.conf.sample /etc/asterisk/manager.conf`; + `cp -f ./docs/conf_examples/voicemail.conf.sample /etc/asterisk/voicemail.conf`; + } } } } diff --git a/www/agc/DQ_dispo.php b/www/agc/DQ_dispo.php new file mode 100644 index 00000000..8a1d9a9b --- /dev/null +++ b/www/agc/DQ_dispo.php @@ -0,0 +1,371 @@ + LICENSE: AGPLv2 +# +# This script is designed to be used in the "Dispo Call URL" field of a campaign +# It should take in the 'lead_id' and 'dispo' to check for the campaign's +# Demographic Quotas settings, and if there is a match, increment the count +# +# This script is part of the API group and any modifications of data are +# logged to the vicidial_api_log table. +# +# This script is a required part of the Demographic Quotas feature, for more +# information on how it works, read the DEMOGRAPHIC_QUOTAS.txt document. +# +# Example of what to put in the Dispo URL field: +# VARhttp://192.168.1.1/agc/DQ_dispo.php?lead_id=--A--lead_id--B--&dispo=--A--dispo--B--&campaign_id=TESTCAMP&user=--A--user--B--&pass=--A--pass--B--&log_to_file=1 +# +# Example of what to put in the No Agent Call URL field: +# (IMPORTANT: user needs to be NOAGENTURL and pass needs to be set to the call_id) +# VARhttp://192.168.1.1/agc/DQ_dispo.php?lead_id=--A--lead_id--B--&dispo=--A--dispo--B--&campaign_id=TESTCAMP&user=NOAGENTURL&pass=--A--call_id--B--&log_to_file=1 +# +# Definable Fields: (other fields should be left as they are) +# - log_to_file - (0,1) if set to 1, will create a log file in the agc directory +# - campaign_id - (MUST BE SET TO THE CAMPAIGN ID) +# + +# +# CHANGES +# 230511-1100 - First Build +# + +$api_script = 'DQdispo'; +$php_script = 'DQ_dispo.php'; + +require_once("dbconnect_mysqli.php"); +require_once("functions.php"); + +$filedate = date("Ymd"); +$filetime = date("H:i:s"); +$IP = getenv ("REMOTE_ADDR"); +$BR = getenv ("HTTP_USER_AGENT"); + +$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER']; +$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW']; +if (isset($_GET["lead_id"])) {$lead_id=$_GET["lead_id"];} + elseif (isset($_POST["lead_id"])) {$lead_id=$_POST["lead_id"];} +if (isset($_GET["campaign_id"])) {$campaign_id=$_GET["campaign_id"];} + elseif (isset($_POST["campaign_id"])) {$campaign_id=$_POST["campaign_id"];} +if (isset($_GET["dispo"])) {$dispo=$_GET["dispo"];} + elseif (isset($_POST["dispo"])) {$dispo=$_POST["dispo"];} +if (isset($_GET["user"])) {$user=$_GET["user"];} + elseif (isset($_POST["user"])) {$user=$_POST["user"];} +if (isset($_GET["pass"])) {$pass=$_GET["pass"];} + elseif (isset($_POST["pass"])) {$pass=$_POST["pass"];} +if (isset($_GET["DB"])) {$DB=$_GET["DB"];} + elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];} +if (isset($_GET["log_to_file"])) {$log_to_file=$_GET["log_to_file"];} + elseif (isset($_POST["log_to_file"])) {$log_to_file=$_POST["log_to_file"];} + +$DB=preg_replace("/[^0-9a-zA-Z]/","",$DB); + +#$DB = '1'; # DEBUG override +$US = '_'; +$TD = '---'; +$STARTtime = date("U"); +$NOW_TIME = date("Y-m-d H:i:s"); +$k=0; +$DQupdates=0; +$DQupdate_notes=''; +$DQgoals_reached=0; + +# filter variables +$user=preg_replace("/\'|\"|\\\\|;| /","",$user); +$pass=preg_replace("/\'|\"|\\\\|;| /","",$pass); + +# if options file exists, use the override values for the above variables +# see the options-example.php file for more information +if (file_exists('options.php')) + { + require_once('options.php'); + } + +header ("Content-type: text/html; charset=utf-8"); + +############################################# +##### START SYSTEM_SETTINGS AND USER LANGUAGE LOOKUP ##### +$stmt = "SELECT use_non_latin,enable_languages,language_method,allow_web_debug,demographic_quotas FROM system_settings;"; +$rslt=mysql_to_mysqli($stmt, $link); +#if ($DB) {echo "$stmt\n";} +$qm_conf_ct = mysqli_num_rows($rslt); +if ($qm_conf_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $non_latin = $row[0]; + $SSenable_languages = $row[1]; + $SSlanguage_method = $row[2]; + $SSallow_web_debug = $row[3]; + $SSdemographic_quotas = $row[4]; + } +if ($SSallow_web_debug < 1) {$DB=0;} + +if ($SSdemographic_quotas < 1) + { + echo "demographic_quotas is disabled on this system: $SSdemographic_quotas \n"; + exit; + } + +$VUselected_language = ''; +$stmt="SELECT selected_language from vicidial_users where user='$user';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$sl_ct = mysqli_num_rows($rslt); +if ($sl_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $VUselected_language = $row[0]; + } +##### END SETTINGS LOOKUP ##### +########################################### + +$lead_id = preg_replace('/[^_0-9]/', '', $lead_id); +$log_to_file = preg_replace('/[^-_0-9a-zA-Z]/', '', $log_to_file); + +if ($non_latin < 1) + { + $user=preg_replace("/[^-_0-9a-zA-Z]/","",$user); + $pass=preg_replace("/[^-\.\+\/\=_0-9a-zA-Z]/","",$pass); + $dispo = preg_replace('/[^-_0-9a-zA-Z]/', '', $dispo); + $campaign_id = preg_replace('/[^-_0-9a-zA-Z]/', '', $campaign_id); + } +else + { + $user = preg_replace('/[^-_0-9\p{L}]/u','',$user); + $pass = preg_replace('/[^-\.\+\/\=_0-9\p{L}]/u','',$pass); + $dispo = preg_replace('/[^-_0-9\p{L}]/u', '', $dispo); + $campaign_id = preg_replace('/[^-_0-9\p{L}]/u', '', $campaign_id); + } + +if ($DB>0) {echo "$lead_id|$dispo|$campaign_id|$user|$pass|$DB|$log_to_file|\n";} + +if (strlen($dispo) < 1) + { + echo "no dispo value given, exiting: $dispo \n"; + exit; + } +if (strlen($campaign_id) < 1) + { + echo "no campaign_id value given, exiting: $campaign_id \n"; + exit; + } +if (strlen($lead_id) < 1) + { + echo "no lead_id value given, exiting: $lead_id \n"; + exit; + } + + +# gather campaign details from campaign_id, and what the Demographic Quotas settings are +$DQcontainer=''; +$stmt="SELECT demographic_quotas_container,demographic_quotas_rerank from vicidial_campaigns where campaign_id='$campaign_id' and active='Y' and demographic_quotas IN('ENABLED','COMPLETE');"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$DQcamprows = mysqli_num_rows($rslt); +if ($DQcamprows > 0) + { + $row=mysqli_fetch_row($rslt); + $DQcontainer = $row[0]; + $demographic_quotas_rerank = $row[1]; + } +if (strlen($DQcontainer) < 1) + { + echo _QXZ("demographic_quotas not enabled on campaign:")." |$campaign_id| \n"; + exit; + } + +$DQcontainer_entry=''; +$stmt="SELECT container_entry from vicidial_settings_containers where container_id='$DQcontainer';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$DQcontrows = mysqli_num_rows($rslt); +if ($DQcontrows > 0) + { + $row=mysqli_fetch_row($rslt); + $DQcontainer_entry = $row[0]; + } +if (strlen($DQcontainer_entry) < 10) + { + echo _QXZ("demographic_quotas container is invalid:")." |$DQcontainer| \n"; + exit; + } + + +if ($non_latin < 1) + { + $user=preg_replace("/[^-_0-9a-zA-Z]/","",$user); +# $pass=preg_replace("/[^-_0-9a-zA-Z]/","",$pass); + } + +if (preg_match("/NOAGENTURL/",$user)) + { + $PADlead_id = sprintf("%010s", $lead_id); + if ( (strlen($pass) > 15) and (preg_match("/$PADlead_id$/",$pass)) ) + { + $four_hours_ago = date("Y-m-d H:i:s", mktime(date("H")-4,date("i"),date("s"),date("m"),date("d"),date("Y"))); + + $stmt="SELECT count(*) from vicidial_log_extended where caller_code='$pass' and call_date > \"$four_hours_ago\";"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $authlive=$row[0]; + $auth=$row[0]; + if ($authlive < 1) + { + echo _QXZ("Call Not Found:")." 2|$user|$pass|$authlive|\n"; + exit; + } + } + else + { + echo _QXZ("Invalid Call ID:")." 1|$user|$pass|$PADlead_id|\n"; + exit; + } + } +else + { + $auth=0; + $auth_message = user_authorization($user,$pass,'',0,0,0,0,'dispo_move_list'); + if ($auth_message == 'GOOD') + {$auth=1;} + + $stmt="SELECT count(*) from vicidial_live_agents where user='$user';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $authlive=$row[0]; + } + +if ( (strlen($user)<2) or (strlen($pass)<2) or ($auth==0) or ($authlive==0)) + { + echo _QXZ("Invalid Username/Password:")." |$user|$pass|$auth|$authlive|$auth_message|\n"; + exit; + } + +if (strlen($lead_id) > 0) + { + # go through DQ container, gather finished_statuses + $DQcontainer_entry = preg_replace("/\r|\t|\'|\"/",'',$DQcontainer_entry); + $DQ_settings = explode("\n",$DQcontainer_entry); + $DQ_settings_ct = count($DQ_settings); + $finished_statuses=''; + $finished_statusesSQL=''; + $sea=0; + while ($DQ_settings_ct >= $sea) + { + if (preg_match("/^finished_statuses=>|^finished_statuses => /",$DQ_settings[$sea])) + { + $finished_statuses = $DQ_settings[$sea]; + $finished_statuses = preg_replace("/^finished_statuses=>|^finished_statuses => /i",'',$finished_statuses); + $finished_statusesSQL = preg_replace("/,/","','",$finished_statuses); + $finished_statusesSQL = "'$finished_statusesSQL'"; + if ($DB) {print "DEBUG finished_statuses defined: |$finished_statuses|$finished_statusesSQL| \n";} + } + $sea++; + } + if (strlen($finished_statuses) < 1) + { + echo _QXZ("No finished_statuses defined in container:")." |$DQcontainer|\n"; + exit; + } + + if (preg_match("/'$dispo'/",$finished_statusesSQL)) + { + if ($DB) {print "DEBUG finished_statuses match with dispo: |$dispo|$finished_statusesSQL| \n";} + + # confirm lead_id exists in the system, and gather lead field values for demographics + $stmt="SELECT rank,vendor_lead_code,source_id,title,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,gender,date_of_birth,alt_phone,email,security_phrase,owner,list_id from vicidial_list where lead_id='$lead_id' limit 1;"; + $rslt=mysql_to_mysqli($stmt, $link); + $VLrows = mysqli_num_rows($rslt); + if ($DB) {echo "$VLrows|$stmt|\n";} + if ($VLrows > 0) + { + $row=mysqli_fetch_row($rslt); + $DQfields = array('rank','vendor_lead_code','source_id','title','first_name','middle_initial','last_name','address1','address2','address3','city','state','province','postal_code','country_code','gender','date_of_birth','alt_phone','email','security_phrase','owner'); + $DQfield_values = array("$row[0]","$row[1]","$row[2]","$row[3]","$row[4]","$row[5]","$row[6]","$row[7]","$row[8]","$row[9]","$row[10]","$row[11]","$row[12]","$row[13]","$row[14]","$row[15]","$row[16]","$row[17]","$row[18]","$row[19]","$row[20]"); + $last_list_id = $row[21]; + + $DQc=0; + while ($DQc <= 20) + { + $stmt="SELECT quota_goal,quota_count,quota_status from vicidial_demographic_quotas_goals where campaign_id='$campaign_id' and demographic_quotas_container='$DQcontainer' and quota_field='$DQfields[$DQc]' and quota_value='$DQfield_values[$DQc]' and quota_status!='ARCHIVE' limit 1;"; + $rslt=mysql_to_mysqli($stmt, $link); + $VDQGrows = mysqli_num_rows($rslt); + if ($DB) {echo "$VDQGrows|$stmt|\n";} + if ($VDQGrows > 0) + { + $row=mysqli_fetch_row($rslt); + $quota_goal = $row[0]; + $quota_count = $row[1]; + $quota_status = $row[2]; + $new_quota_count = ($quota_count + 1); + if ($DB) {print "DEBUG DQ field value match: |$DQfields[$DQc]|$DQfield_values[$DQc]| |$quota_goal|$quota_count|$quota_status| \n";} + + if ($new_quota_count == $quota_goal) + { + $DQgoals_reached++; + if ($DB) {print "DEBUG DQ goal reached: |$new_quota_count == $quota_goal| \n";} + } + + $stmt="UPDATE vicidial_demographic_quotas_goals SET quota_count=(quota_count+1),last_lead_id='$lead_id',last_list_id='$last_list_id',last_call_date=NOW(),last_status='$dispo' where campaign_id='$campaign_id' and demographic_quotas_container='$DQcontainer' and quota_field='$DQfields[$DQc]' and quota_value='$DQfield_values[$DQc]' and quota_status!='ARCHIVE' limit 1;"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $affected_rows = mysqli_affected_rows($link); + $DQupdates = ($DQupdates + $affected_rows); + $DQupdate_notes .= "$DQfields[$DQc] = $DQfield_values[$DQc] update $affected_rows|"; + if ($DB) {print "DEBUG DQ quota goals updated: |$affected_rows|$last_list_id| \n";} + } + $DQc++; + } + } + else + { + echo _QXZ("Lead ID not found in system:")." |$lead_id|$VLrows|\n"; + exit; + } + } + + if ($DQupdates > 0) + { + if ($DQgoals_reached > 0) + { + if ($demographic_quotas_rerank == 'HOUR') + {$demographic_quotas_rerank == 'NOW_HOUR';} + if ($demographic_quotas_rerank == 'NO') + {$demographic_quotas_rerank == 'NOW';} + # update campaign to force refresh of DQ leads if one of the goals reached + $stmt="UPDATE vicidial_campaigns SET demographic_quotas_rerank='$demographic_quotas_rerank' where campaign_id='$campaign_id' limit 1;"; + $rslt=mysql_to_mysqli($stmt, $link); + $affected_rows = mysqli_affected_rows($link); + if ($DB) {echo "$affected_rows|$stmt|\n";} + } + + $SQL_log = "$DQupdate_notes"; + $SQL_log = preg_replace('/;/','',$SQL_log); + $SQL_log = addslashes($SQL_log); + $stmt="INSERT INTO vicidial_api_log set user='$user',agent_user='$user',function='DQdispo',value='$lead_id',result='$DQupdates',result_reason='$lead_id',source='vdc',data='$SQL_log',api_date='$NOW_TIME',api_script='$api_script';"; + $rslt=mysql_to_mysqli($stmt, $link); + + $MESSAGE = _QXZ("DONE: %1s DQ updates made, for lead_id %2s goals reached %3s",0,'',$DQupdates,$lead_id,$DQgoals_reached); + echo "$MESSAGE\n"; + } + else + { + $MESSAGE = _QXZ("DONE: no match found for lead %1s",0,'',$lead_id); + echo "$MESSAGE\n"; + } + } +else + { + $MESSAGE = _QXZ("DONE: lead_id %1s is not populated",0,'',$lead_id); + echo "$MESSAGE\n"; + } + + +if ($log_to_file > 0) + { + $fp = fopen ("./DQ_dispo.txt", "w"); +# fwrite ($fp, "$NOW_TIME|$k|$lead_id|$dispo|$user|$campaign_id|$DB|$log_to_file|$campaign_id|$MESSAGE|\n"); + fwrite ($fp, "$NOW_TIME|\n"); + fclose($fp); + } diff --git a/www/vicidial/AST_latency_gaps_report.php b/www/vicidial/AST_latency_gaps_report.php new file mode 100644 index 00000000..22668c6b --- /dev/null +++ b/www/vicidial/AST_latency_gaps_report.php @@ -0,0 +1,486 @@ + LICENSE: AGPLv2 +# +# CHANGES +# 230430-1952 - First build +# + +$startMS = microtime(); + +require("dbconnect_mysqli.php"); +require("functions.php"); + +$report_name='Latency Gaps Report'; + +$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER']; +$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW']; +$PHP_SELF=$_SERVER['PHP_SELF']; +$PHP_SELF = preg_replace('/\.php.*/i','.php',$PHP_SELF); +if (isset($_GET["query_date"])) {$query_date=$_GET["query_date"];} + elseif (isset($_POST["query_date"])) {$query_date=$_POST["query_date"];} +if (isset($_GET["query_date_D"])) {$query_date_D=$_GET["query_date_D"];} + elseif (isset($_POST["query_date_D"])) {$query_date_D=$_POST["query_date_D"];} +if (isset($_GET["query_date_T"])) {$query_date_T=$_GET["query_date_T"];} + elseif (isset($_POST["query_date_T"])) {$query_date_T=$_POST["query_date_T"];} +if (isset($_GET["file_download"])) {$file_download=$_GET["file_download"];} + elseif (isset($_POST["file_download"])) {$file_download=$_POST["file_download"];} +if (isset($_GET["lower_limit"])) {$lower_limit=$_GET["lower_limit"];} + elseif (isset($_POST["lower_limit"])) {$lower_limit=$_POST["lower_limit"];} +if (isset($_GET["upper_limit"])) {$upper_limit=$_GET["upper_limit"];} + elseif (isset($_POST["upper_limit"])) {$upper_limit=$_POST["upper_limit"];} +if (isset($_GET["DB"])) {$DB=$_GET["DB"];} + elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];} +if (isset($_GET["submit"])) {$submit=$_GET["submit"];} + elseif (isset($_POST["submit"])) {$submit=$_POST["submit"];} +if (isset($_GET["SUBMIT"])) {$SUBMIT=$_GET["SUBMIT"];} + elseif (isset($_POST["SUBMIT"])) {$SUBMIT=$_POST["SUBMIT"];} +if (isset($_GET["report_display_type"])) {$report_display_type=$_GET["report_display_type"];} + elseif (isset($_POST["report_display_type"])) {$report_display_type=$_POST["report_display_type"];} + +$DB=preg_replace("/[^0-9a-zA-Z]/","",$DB); + +$NOW_DATE = date("Y-m-d"); +if (!isset($query_date)) {$query_date = $NOW_DATE;} +if (strlen($query_date_D) < 6) {$query_date_D = "00:00:00";} +if (strlen($query_date_T) < 6) {$query_date_T = "23:59:59";} + +############################################# +##### START SYSTEM_SETTINGS LOOKUP ##### +$stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db,enable_languages,language_method,allow_web_debug FROM system_settings;"; +$rslt=mysql_to_mysqli($stmt, $link); +#if ($DB) {$MAIN.="$stmt\n";} +$qm_conf_ct = mysqli_num_rows($rslt); +if ($qm_conf_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $non_latin = $row[0]; + $outbound_autodial_active = $row[1]; + $slave_db_server = $row[2]; + $reports_use_slave_db = $row[3]; + $SSenable_languages = $row[4]; + $SSlanguage_method = $row[5]; + $SSallow_web_debug = $row[6]; + } +if ($SSallow_web_debug < 1) {$DB=0;} +##### END SETTINGS LOOKUP ##### +########################################### + +$query_date = preg_replace('/[^- \:\_0-9a-zA-Z]/', '', $query_date); +$query_date_D = preg_replace('/[^- \:\_0-9a-zA-Z]/', '', $query_date_D); +$query_date_T = preg_replace('/[^- \:\_0-9a-zA-Z]/', '', $query_date_T); +$lower_limit = preg_replace('/[^-_0-9a-zA-Z]/', '', $lower_limit); +$upper_limit = preg_replace('/[^-_0-9a-zA-Z]/', '', $upper_limit); +$submit = preg_replace('/[^-_0-9a-zA-Z]/', '', $submit); +$SUBMIT = preg_replace('/[^-_0-9a-zA-Z]/', '', $SUBMIT); +$report_display_type = preg_replace('/[^-_0-9a-zA-Z]/', '', $report_display_type); +$file_download = preg_replace('/[^-_0-9a-zA-Z]/', '', $file_download); + +if ($non_latin < 1) + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW); + } +else + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_PW); + } + +$stmt="SELECT selected_language,user_group from vicidial_users where user='$PHP_AUTH_USER';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$sl_ct = mysqli_num_rows($rslt); +if ($sl_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $VUselected_language = $row[0]; + $LOGuser_group = $row[1]; + } + +$auth=0; +$reports_auth=0; +$admin_auth=0; +$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1,0); +if ($auth_message == 'GOOD') + {$auth=1;} + +if ($auth > 0) + { + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $admin_auth=$row[0]; + + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $reports_auth=$row[0]; + + if ($reports_auth < 1) + { + $VDdisplayMESSAGE = _QXZ("You are not allowed to view reports"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ( ($reports_auth > 0) and ($admin_auth < 1) ) + { + $ADD=999999; + $reports_only_user=1; + } + } +else + { + $VDdisplayMESSAGE = _QXZ("Login incorrect, please try again"); + if ($auth_message == 'LOCK') + { + $VDdisplayMESSAGE = _QXZ("Too many login attempts, try again in 15 minutes"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ($auth_message == 'IPBLOCK') + { + $VDdisplayMESSAGE = _QXZ("Your IP Address is not allowed") . ": $ip"; + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); + Header("HTTP/1.0 401 Unauthorized"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n"; + exit; + } + +$stmt="SELECT allowed_campaigns,allowed_reports,admin_viewable_groups,admin_viewable_call_times from vicidial_user_groups where user_group='$LOGuser_group';"; +if ($DB) {$HTML_text.="|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$row=mysqli_fetch_row($rslt); +$LOGallowed_campaigns = $row[0]; +$LOGallowed_reports = $row[1]; +$LOGadmin_viewable_groups = $row[2]; +$LOGadmin_viewable_call_times = $row[3]; + +$LOGallowed_campaignsSQL=''; +$whereLOGallowed_campaignsSQL=''; +if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) ) + { + $rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns); + $rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL); + $LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')"; + $whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')"; + } +$regexLOGallowed_campaigns = " $LOGallowed_campaigns "; + +if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) ) + { + Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); + Header("HTTP/1.0 401 Unauthorized"); + echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n"; + exit; + } + +##### BEGIN log visit to the vicidial_report_log table ##### +$LOGip = getenv("REMOTE_ADDR"); +$LOGbrowser = getenv("HTTP_USER_AGENT"); +$LOGscript_name = getenv("SCRIPT_NAME"); +$LOGserver_name = getenv("SERVER_NAME"); +$LOGserver_port = getenv("SERVER_PORT"); +$LOGrequest_uri = getenv("REQUEST_URI"); +$LOGhttp_referer = getenv("HTTP_REFERER"); +$LOGbrowser=preg_replace("/\'|\"|\\\\/","",$LOGbrowser); +$LOGrequest_uri=preg_replace("/\'|\"|\\\\/","",$LOGrequest_uri); +$LOGhttp_referer=preg_replace("/\'|\"|\\\\/","",$LOGhttp_referer); +if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';} + else {$HTTPprotocol = 'http://';} +if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';} +else {$LOGserver_port = ":$LOGserver_port";} +$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri"; + +$LOGhostname = php_uname('n'); +if (strlen($LOGhostname)<1) {$LOGhostname='X';} +if (strlen($LOGserver_name)<1) {$LOGserver_name='X';} + +$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;"; +$rslt=mysql_to_mysqli($stmt, $link); +if ($DB) {echo "$stmt\n";} +$webserver_id_ct = mysqli_num_rows($rslt); +if ($webserver_id_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $webserver_id = $row[0]; + } +else + { + ##### insert webserver entry + $stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $affected_rows = mysqli_affected_rows($link); + $webserver_id = mysqli_insert_id($link); + } + +$stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$query_date, $end_date, $lower_limit, $upper_limit, $file_download|', url='$LOGfull_url', webserver='$webserver_id';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$report_log_id = mysqli_insert_id($link); +##### END log visit to the vicidial_report_log table ##### + + +if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) ) + { + mysqli_close($link); + $use_slave_server=1; + $db_source = 'S'; + require("dbconnect_mysqli.php"); + $MAIN.="\n"; + } + +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; +$HEADER.="\n"; + +$HEADER.="\n"; +$HEADER.=""._QXZ("$report_name")."\n"; + +$short_header=1; + +$MAIN.="\n"; + echo "\n"; - echo "\n"; + echo "\n"; } + + if ($SSdemographic_quotas > 0) + { + ##### get container listings for demographic quotas pulldown menu + $stmt="SELECT container_id,container_notes from vicidial_settings_containers where container_type='DEMOGRAPHIC_QUOTAS' $LOGadmin_viewable_groupsSQL order by container_id;"; + $rslt=mysql_to_mysqli($stmt, $link); + $cqlr_to_print = mysqli_num_rows($rslt); + $demo_quota_container_menu=''; + $cqlr_selected=0; + $o=0; + while ($cqlr_to_print > $o) + { + $rowx=mysqli_fetch_row($rslt); + if (mb_strlen($rowx[1],'utf-8')>40) + {$rowx[1] = mb_substr($rowx[1],0,40,'utf-8') . '...';} + $demo_quota_container_menu .= "\n"; + $o++; + } + + $DQdebug = "   "._QXZ("DQ Debug")." | "._QXZ("DQ Report").""; + if ($demographic_quotas == 'INVALID') + {$DQdebug = "   "._QXZ("DQ configuration invalid")."$DQdebug";} + if ($demographic_quotas == 'COMPLETE') + {$DQdebug = "   "._QXZ("DQ goals have been met")."$DQdebug";} + + echo "\n"; + + if ($demographic_quotas == 'COMPLETE') + { + echo "\n"; + } + + echo "\n"; + + echo "\n"; + + echo "\n"; + } + else + { + echo "\n"; + } + + + + + echo "\n"; echo "\n"; @@ -30362,13 +30457,11 @@ if ($ADD==34) echo " - "._QXZ("SHOW")."

"; } - - - $stmt="SELECT count(*) FROM vicidial_hopper where campaign_id='$campaign_id' and status IN('READY') $LOGallowed_campaignsSQL;"; - if ($DB) {echo "$stmt\n";} - $rslt=mysql_to_mysqli($stmt, $link); - $rowx=mysqli_fetch_row($rslt); - $hopper_leads = "$rowx[0]"; + $stmt="SELECT count(*) FROM vicidial_hopper where campaign_id='$campaign_id' and status IN('READY') $LOGallowed_campaignsSQL;"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $rowx=mysqli_fetch_row($rslt); + $hopper_leads = "$rowx[0]"; echo _QXZ("This campaign has")." $hopper_leads "._QXZ("leads in the dial hopper")."

\n"; echo ""._QXZ("Click here to see what leads are in the hopper right now")."

\n"; @@ -41612,6 +41705,7 @@ if ($ADD==392111111111) + @@ -41652,12 +41746,12 @@ if ($ADD==392111111111) echo "
"; +$MAIN.="
\n"; +$MAIN.="\n"; + +$MAIN.=""; +$MAIN.="
\n"; +$MAIN.="\n"; +$MAIN.=_QXZ("Date").":\n"; +$MAIN.=""; +$MAIN.=""; + +$MAIN.=" "._QXZ("to")." "; + +$MAIN.="\n"; +$MAIN.=_QXZ("Display as").":"; +$MAIN.="\n"; +$MAIN.="
\n"; +if ($SUBMIT && $query_date) + { + $distinct_users='|'; + $distinct_users_ct=0; + $users_ary[0]=''; + $users_ct_ary[0]=0; + $rpt_stmt="SELECT * from vicidial_latency_gaps where gap_date>='$query_date $query_date_D' and gap_date<='$query_date $query_date_T' order by user, gap_date asc"; + $rpt_rslt=mysql_to_mysqli($rpt_stmt, $link); + $ASCII_text="
\n";
+	$HTML_text="";
+	if ($DB) {$ASCII_text.=$rpt_stmt."\n";}
+	if (mysqli_num_rows($rpt_rslt)>0) 
+		{
+		if (!$lower_limit) {$lower_limit=1;}
+		if ($lower_limit+999>=mysqli_num_rows($rpt_rslt)) {$upper_limit=($lower_limit+mysqli_num_rows($rpt_rslt)%1000)-1;} else {$upper_limit=$lower_limit+999;}
+
+		$ASCII_text.="--- "._QXZ("LATENCY GAP RECORDS FOR")." $query_date, $query_date_D "._QXZ("TO")." $query_date_T $server_rpt_string, "._QXZ("RECORDS")." #$lower_limit-$upper_limit               ["._QXZ("DOWNLOAD")."]\n";
+		$lagged_rpt.="+----------------------+-----------------+---------------------+-----------+----------------------+----------------------+\n";
+		$lagged_rpt.="| "._QXZ("USER",20)." | "._QXZ("USER WEB IP",15)." | "._QXZ("GAP BEGIN",19)." | "._QXZ("GAP SEC",9)." | "._QXZ("LAST LOGIN",20)." | "._QXZ("GAP DETECTION TIME",20)." |\n";
+		$lagged_rpt.="+----------------------+-----------------+---------------------+-----------+----------------------+----------------------+\n";
+
+		$HTML_text.="

"; + $HTML_rpt.=""; + $HTML_rpt.=""; + + $CSV_text="\""._QXZ("USER")."\",\""._QXZ("USER WEB IP")."\",\""._QXZ("GAP BEGIN")."\",\""._QXZ("GAP SEC")."\",\""._QXZ("LAST LOGIN")."\",\""._QXZ("GAP DETECTION TIME")."\"\n"; + + for ($i=1; $i<=mysqli_num_rows($rpt_rslt); $i++) + { + $row=mysqli_fetch_array($rpt_rslt); + $temp_user=$row[user]; + if ($i == '1') + { + $users_ary[$distinct_users_ct] = $temp_user; + $users_ct_ary[$distinct_users_ct]++; + $distinct_users .= "$temp_user|"; + $distinct_users_ct++; + } + else + { + if (!preg_match("/\|$temp_user\|/",$distinct_users)) + { + $users_ary[$distinct_users_ct] = $temp_user; + $users_ct_ary[$distinct_users_ct]++; + $distinct_users .= "$temp_user|"; + $distinct_users_ct++; + } + else + { + $users_ct_ary[$distinct_users_ct]++; + } + } + + $CSV_text.="\"$row[user]\",\"$row[user_ip]\",\"$row[gap_date]\",\"$row[gap_length]\",\"$row[last_login_date]\",\"$row[check_date]\"\n"; + if ($i>=$lower_limit && $i<=$upper_limit) + { + if ($i%2==0) {$color_class="grey_graph_cell";} else {$color_class='white_graph_cell';} + + $HTML_rpt.=""; + + $lagged_rpt.="| ".sprintf("%-21s", $row["user"]).""; + $lagged_rpt.="| ".sprintf("%-16s", $row["user_ip"]); + $lagged_rpt.="| ".sprintf("%-20s", $row["gap_date"]); + $lagged_rpt.="| ".sprintf("%-10s", $row["gap_length"]); + $lagged_rpt.="| ".sprintf("%-21s", $row["last_login_date"]); + $lagged_rpt.="| ".sprintf("%-21s", $row["check_date"]); + $lagged_rpt.="|\n"; + } + } + $lagged_rpt.="+----------------------+-----------------+---------------------+-----------+----------------------+----------------------+\n"; + + $lagged_rpt_hf=""; + $HTML_rpt_hf=""; + $ll=$lower_limit-1000; + if ($ll<1 || ($lower_limit+1000)>=mysqli_num_rows($rpt_rslt)) {$HTML_colspan=6;} else {$HTML_colspan=3;} + + if ($ll>=1) + { + $lagged_rpt_hf.="[<<< "._QXZ("PREV 1000 records")."]"; + $HTML_rpt_hf.=""; + $lagged_rpt_hf.="\n"; + $temp_user_count_output = "Users: $distinct_users_ct\n"; + $ASCII_text.=$temp_user_count_output; + $ASCII_text.=$lagged_rpt_hf.$lagged_rpt.$lagged_rpt_hf; + $HTML_text.=$HTML_rpt_hf.$HTML_rpt.$HTML_rpt_hf."
"._QXZ("LATENCY GAP RECORDS FOR")." $query_date, $query_date_D "._QXZ("TO")." $query_date_T $server_rpt_string, "._QXZ("RECORDS")." #$lower_limit-$upper_limit["._QXZ("DOWNLOAD")."]
"._QXZ("USER").""._QXZ("USER WEB IP").""._QXZ("GAP BEGIN").""._QXZ("GAP SEC").""._QXZ("LAST LOGIN").""._QXZ("GAP DETECTION TIME")."
$row[user]$row[user_ip]$row[gap_date]$row[last_login_date]$row[check_date]
[<<< "._QXZ("PREV 1000 records")."]"; + } + else + { + $lagged_rpt_hf.=sprintf("%-23s", " "); + } + $lagged_rpt_hf.=sprintf("%-145s", " "); + if (($lower_limit+1000)=mysqli_num_rows($rpt_rslt)) {$max_limit=mysqli_num_rows($rpt_rslt)-$upper_limit;} else {$max_limit=1000;} + $lagged_rpt_hf.="["._QXZ("NEXT")." $max_limit "._QXZ("records")." >>>]"; + $HTML_rpt_hf.="["._QXZ("NEXT")." $max_limit "._QXZ("records")." >>>]"; + } + else + { + $lagged_rpt_hf.=sprintf("%23s", " "); + } + $HTML_rpt_hf.="
"; + } + else + { + $MAIN.="*** "._QXZ("NO RECORDS FOUND")." ***\n"; + } + $ASCII_text.="
\n"; + + if ($report_display_type=="HTML") + { + $MAIN.=$HTML_text; + } + else + { + $MAIN.=$ASCII_text; + } + + $MAIN.="
\n"; + + $MAIN.="\n"; + $MAIN.="\n"; + $MAIN.="\n"; + $MAIN.="
\n"; + $MAIN.="\n"; + $MAIN.="
\n"; + $MAIN.="
LOADING, PLEASE WAIT...
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + $MAIN.="
\n"; + + $MAIN.="\n"; + } + +if ($file_download>0) + { + $FILE_TIME = date("Ymd-His"); + $CSVfilename = "AST_url_log_report_$US$FILE_TIME.csv"; + $CSV_text=preg_replace('/ +\"/', '"', $CSV_text); + $CSV_text=preg_replace('/\" +/', '"', $CSV_text); + // We'll be outputting a TXT file + header('Content-type: application/octet-stream'); + + // It will be called LIST_101_20090209-121212.txt + header("Content-Disposition: attachment; filename=\"$CSVfilename\""); + header('Expires: 0'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Pragma: public'); + ob_clean(); + flush(); + + echo "$CSV_text"; + + exit; + } +else + { + echo $HEADER; + require("admin_header.php"); + echo $MAIN; + } + +if ($db_source == 'S') + { + mysqli_close($link); + $use_slave_server=0; + $db_source = 'M'; + require("dbconnect_mysqli.php"); + } + +$endMS = microtime(); +$startMSary = explode(" ",$startMS); +$endMSary = explode(" ",$endMS); +$runS = ($endMSary[0] - $startMSary[0]); +$runM = ($endMSary[1] - $startMSary[1]); +$TOTALrun = ($runS + $runM); + +$stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); + +exit; + +?> diff --git a/www/vicidial/admin.php b/www/vicidial/admin.php index 2e32644e..a46ab71f 100644 --- a/www/vicidial/admin.php +++ b/www/vicidial/admin.php @@ -125,9 +125,9 @@ $PHP_SELF = preg_replace('/\.php.*/i','.php',$PHP_SELF); $QUERY_STRING = getenv("QUERY_STRING"); $groups=array(); -$Vreports = 'NONE, Real-Time Main Report, Real-Time Campaign Summary, Real-Time Whiteboard Report, VERM Reports, Inbound Report, Inbound Report by DID, Inbound Service Level Report, Inbound Summary Hourly Report, Inbound Daily Report, Inbound DID Report, Inbound DID Summary Report, Agent DID Report, Inbound DID Detail Report, Inbound IVR Report, Inbound Forecasting Report, Advanced Forecasting Report, Outbound Calling Report, Outbound Summary Interval Report, Outbound IVR Report, Callmenu Survey Report, Outbound Lead Source Report, Fronter - Closer Report, Fronter - Closer Detail Report, Lists Campaign Statuses Report, Lists Statuses Report, Campaign Status List Report, Export Calls Report, Export Leads Report, Agent Time Detail, Agent Status Detail, Agent Inbound Status Summary, Agent Performance Detail, Team Performance Detail, Performance Comparison Report, Single Agent Daily, Single Agent Daily Time, User Group Login Report, User Group Hourly Report, User Group Detail Hourly Report, User Timeclock Report, User Group Timeclock Status Report, User Timeclock Detail Report, Server Performance Report, Administration Change Log, List Update Stats, User Stats, User Time Sheet, Download List, Dialer Inventory Report, Maximum System Stats, Maximum Stats Detail, Search Leads Logs, Email Log Report, Carrier Log Report, Campaign Debug, Shared Debug, Asterisk Debug, Hangup Cause Report, Lists Pass Report, Called Counts List IDs Report, Agent Debug Log Report, Agent Parked Call Report, Agent-Manager Chat Log, Recording Access Log Report, API Log Report, Real-Time Monitoring Log Report, AMD Log Report, SIP Event Report, Caller ID Log Report, Quality Control Report, Settings Compare, Phone Stats, Hopper List Report, In-Group User List, Webserver-URL Report, VDAD Debug Log Report, URL Log Report, Medialog Inventory Report, Asterisk Debug, SPH Report, Shared Debug, Process Report, Group Alias Report, Hangup Cause Report, IVR Filter Report, LAGGED Agent Log Report, Agent Latency Report, Agent Disposition Report, Agent Performance Report, Carrier Log Report, Dial Log Report, Inbound Extension Stats, Agents Time On Calls, Callbacks Export, User Logins Report'; +$Vreports = 'NONE, Real-Time Main Report, Real-Time Campaign Summary, Real-Time Whiteboard Report, VERM Reports, Inbound Report, Inbound Report by DID, Inbound Service Level Report, Inbound Summary Hourly Report, Inbound Daily Report, Inbound DID Report, Inbound DID Summary Report, Agent DID Report, Inbound DID Detail Report, Inbound IVR Report, Inbound Forecasting Report, Advanced Forecasting Report, Outbound Calling Report, Outbound Summary Interval Report, Outbound IVR Report, Callmenu Survey Report, Outbound Lead Source Report, Fronter - Closer Report, Fronter - Closer Detail Report, Lists Campaign Statuses Report, Lists Statuses Report, Campaign Status List Report, Export Calls Report, Export Leads Report, Agent Time Detail, Agent Status Detail, Agent Inbound Status Summary, Agent Performance Detail, Team Performance Detail, Performance Comparison Report, Single Agent Daily, Single Agent Daily Time, User Group Login Report, User Group Hourly Report, User Group Detail Hourly Report, User Timeclock Report, User Group Timeclock Status Report, User Timeclock Detail Report, Server Performance Report, Administration Change Log, List Update Stats, User Stats, User Time Sheet, Download List, Dialer Inventory Report, Maximum System Stats, Maximum Stats Detail, Search Leads Logs, Email Log Report, Carrier Log Report, Campaign Debug, Shared Debug, Asterisk Debug, Hangup Cause Report, Lists Pass Report, Called Counts List IDs Report, Agent Debug Log Report, Agent Parked Call Report, Agent-Manager Chat Log, Recording Access Log Report, API Log Report, Real-Time Monitoring Log Report, AMD Log Report, SIP Event Report, Caller ID Log Report, Quality Control Report, Settings Compare, Phone Stats, Hopper List Report, In-Group User List, Webserver-URL Report, VDAD Debug Log Report, URL Log Report, Medialog Inventory Report, Asterisk Debug, SPH Report, Shared Debug, Process Report, Group Alias Report, Hangup Cause Report, IVR Filter Report, LAGGED Agent Log Report, Agent Latency Report, Latency Gaps Report, Agent Disposition Report, Agent Performance Report, Carrier Log Report, Dial Log Report, Inbound Extension Stats, Agents Time On Calls, Callbacks Export, User Logins Report, Demographic Quotas Report'; -$UGreports = 'ALL REPORTS, NONE, Real-Time Main Report, Real-Time Campaign Summary, Real-Time Whiteboard Report, VERM Reports, Inbound Report, Inbound Report by DID, Inbound Service Level Report, Inbound Summary Hourly Report, Inbound Daily Report, Inbound DID Report, Inbound DID Summary Report, Agent DID Report, Inbound DID Detail Report, Inbound Email Report, Inbound Chat Report, Inbound IVR Report, Inbound Forecasting Report, Advanced Forecasting Report, Outbound Calling Report, Outbound Summary Interval Report, Outbound IVR Report, Callmenu Survey Report, Outbound Lead Source Report, Fronter - Closer Report, Fronter - Closer Detail Report, Lists Campaign Statuses Report, Lists Statuses Report, Campaign Status List Report, Export Calls Report, Export Leads Report, Agent Time Detail, Agent Status Detail, Agent Inbound Status Summary, Agent Performance Detail, Team Performance Detail, Performance Comparison Report, Single Agent Daily, Single Agent Daily Time, User Group Login Report, User Group Hourly Report, User Group Detail Hourly Report, User Timeclock Report, User Group Timeclock Status Report, User Timeclock Detail Report, Server Performance Report, Administration Change Log, List Update Stats, User Stats, User Time Sheet, Download List, Dialer Inventory Report, Custom Reports Links, CallCard Search, Maximum System Stats, Maximum Stats Detail, Search Leads Logs, Email Log Report, Lists Pass Report, Called Counts List IDs Report, Front Page System Summary, Report Page Servers Summary, Admin Utilities Page, Agent Debug Log Report, Agent Parked Call Report, Agent-Manager Chat Log, Recording Access Log Report, API Log Report, Real-Time Monitoring Log Report, AMD Log Report, SIP Event Report, Caller ID Log Report, Quality Control Report, Settings Compare, Phone Stats, Hopper List Report, In-Group User List, Webserver-URL Report, VDAD Debug Log Report, URL Log Report, Medialog Inventory Report, Asterisk Debug, SPH Report, Shared Debug, Process Report, Group Alias Report, Hangup Cause Report, IVR Filter Report, LAGGED Agent Log Report, Agent Latency Report, Agent Disposition Report, Agent Performance Report, Carrier Log Report, Dial Log Report, Inbound Extension Stats, Agents Time On Calls, Callbacks Export, User Logins Report, VERM QA Links'; +$UGreports = 'ALL REPORTS, NONE, Real-Time Main Report, Real-Time Campaign Summary, Real-Time Whiteboard Report, VERM Reports, Inbound Report, Inbound Report by DID, Inbound Service Level Report, Inbound Summary Hourly Report, Inbound Daily Report, Inbound DID Report, Inbound DID Summary Report, Agent DID Report, Inbound DID Detail Report, Inbound Email Report, Inbound Chat Report, Inbound IVR Report, Inbound Forecasting Report, Advanced Forecasting Report, Outbound Calling Report, Outbound Summary Interval Report, Outbound IVR Report, Callmenu Survey Report, Outbound Lead Source Report, Fronter - Closer Report, Fronter - Closer Detail Report, Lists Campaign Statuses Report, Lists Statuses Report, Campaign Status List Report, Export Calls Report, Export Leads Report, Agent Time Detail, Agent Status Detail, Agent Inbound Status Summary, Agent Performance Detail, Team Performance Detail, Performance Comparison Report, Single Agent Daily, Single Agent Daily Time, User Group Login Report, User Group Hourly Report, User Group Detail Hourly Report, User Timeclock Report, User Group Timeclock Status Report, User Timeclock Detail Report, Server Performance Report, Administration Change Log, List Update Stats, User Stats, User Time Sheet, Download List, Dialer Inventory Report, Custom Reports Links, CallCard Search, Maximum System Stats, Maximum Stats Detail, Search Leads Logs, Email Log Report, Lists Pass Report, Called Counts List IDs Report, Front Page System Summary, Report Page Servers Summary, Admin Utilities Page, Agent Debug Log Report, Agent Parked Call Report, Agent-Manager Chat Log, Recording Access Log Report, API Log Report, Real-Time Monitoring Log Report, AMD Log Report, SIP Event Report, Caller ID Log Report, Quality Control Report, Settings Compare, Phone Stats, Hopper List Report, In-Group User List, Webserver-URL Report, VDAD Debug Log Report, URL Log Report, Medialog Inventory Report, Asterisk Debug, SPH Report, Shared Debug, Process Report, Group Alias Report, Hangup Cause Report, IVR Filter Report, LAGGED Agent Log Report, Agent Latency Report, Latency Gaps Report, Agent Disposition Report, Agent Performance Report, Carrier Log Report, Dial Log Report, Inbound Extension Stats, Agents Time On Calls, Callbacks Export, User Logins Report, Demographic Quotas Report, VERM QA Links'; $Vtables = 'NONE,log_noanswer,did_agent_log,contact_information'; @@ -2750,6 +2750,16 @@ if (isset($_GET["webphone_settings"])) {$webphone_settings=$_GET["webphone_set elseif (isset($_POST["webphone_settings"])) {$webphone_settings=$_POST["webphone_settings"];} if (isset($_GET["agent_notifications"])) {$agent_notifications=$_GET["agent_notifications"];} elseif (isset($_POST["agent_notifications"])) {$agent_notifications=$_POST["agent_notifications"];} +if (isset($_GET["demographic_quotas"])) {$demographic_quotas=$_GET["demographic_quotas"];} + elseif (isset($_POST["demographic_quotas"])) {$demographic_quotas=$_POST["demographic_quotas"];} +if (isset($_GET["demographic_quotas_container"])) {$demographic_quotas_container=$_GET["demographic_quotas_container"];} + elseif (isset($_POST["demographic_quotas_container"])) {$demographic_quotas_container=$_POST["demographic_quotas_container"];} +if (isset($_GET["demographic_quotas_rerank"])) {$demographic_quotas_rerank=$_GET["demographic_quotas_rerank"];} + elseif (isset($_POST["demographic_quotas_rerank"])) {$demographic_quotas_rerank=$_POST["demographic_quotas_rerank"];} +if (isset($_GET["demographic_quotas_list_resets"])) {$demographic_quotas_list_resets=$_GET["demographic_quotas_list_resets"];} + elseif (isset($_POST["demographic_quotas_list_resets"])) {$demographic_quotas_list_resets=$_POST["demographic_quotas_list_resets"];} +if (isset($_GET["log_latency_gaps"])) {$log_latency_gaps=$_GET["log_latency_gaps"];} + elseif (isset($_POST["log_latency_gaps"])) {$log_latency_gaps=$_POST["log_latency_gaps"];} $DB=preg_replace("/[^0-9a-zA-Z]/","",$DB); @@ -2765,7 +2775,7 @@ if (strlen($dial_status) > 0) ############################################# ##### START SYSTEM_SETTINGS LOOKUP ##### -$stmt = "SELECT use_non_latin,enable_queuemetrics_logging,enable_vtiger_integration,qc_features_active,outbound_autodial_active,sounds_central_control_active,enable_second_webform,user_territories_active,custom_fields_enabled,admin_web_directory,webphone_url,first_login_trigger,hosted_settings,default_phone_registration_password,default_phone_login_password,default_server_password,test_campaign_calls,active_voicemail_server,voicemail_timezones,default_voicemail_timezone,default_local_gmt,campaign_cid_areacodes_enabled,pllb_grouping_limit,did_ra_extensions_enabled,expanded_list_stats,contacts_enabled,alt_log_server_ip,alt_log_dbname,alt_log_login,alt_log_pass,tables_use_alt_log_db,call_menu_qualify_enabled,admin_list_counts,allow_voicemail_greeting,svn_revision,allow_emails,level_8_disable_add,pass_key,pass_hash_enabled,disable_auto_dial,country_code_list_stats,frozen_server_call_clear,active_modules,allow_chats,enable_languages,language_method,meetme_enter_login_filename,meetme_enter_leave3way_filename,enable_did_entry_list_id,enable_third_webform,default_language,user_hide_realtime_enabled,log_recording_access,alt_ivr_logging,admin_row_click,admin_screen_colors,ofcom_uk_drop_calc,agent_screen_colors,script_remove_js,manual_auto_next,user_new_lead_limit,agent_xfer_park_3way,agent_soundboards,web_loader_phone_length,agent_script,enable_auto_reports,enable_pause_code_limits,enable_drop_lists,allow_ip_lists,system_ip_blacklist,hide_inactive_lists,allow_manage_active_lists,expired_lists_inactive,did_system_filter,enable_gdpr_download_deletion,mute_recordings,user_admin_redirect,list_status_modification_confirmation,sip_event_logging,call_quota_lead_ranking,enable_second_script,enable_first_webform,recording_buttons,opensips_cid_name,require_password_length,user_account_emails,outbound_cid_any,entries_per_page,browser_call_alerts,inbound_answer_config,enable_international_dncs,daily_call_count_limit,allow_shared_dial,agent_search_method,admin_home_url,qc_claim_limit,qc_expire_days,two_factor_auth_hours,two_factor_container,call_limit_24hour,allowed_sip_stacks,agent_hide_hangup,allow_web_debug,max_logged_in_agents,user_codes_admin,abandon_check_queue,agent_notifications FROM system_settings;"; +$stmt = "SELECT use_non_latin,enable_queuemetrics_logging,enable_vtiger_integration,qc_features_active,outbound_autodial_active,sounds_central_control_active,enable_second_webform,user_territories_active,custom_fields_enabled,admin_web_directory,webphone_url,first_login_trigger,hosted_settings,default_phone_registration_password,default_phone_login_password,default_server_password,test_campaign_calls,active_voicemail_server,voicemail_timezones,default_voicemail_timezone,default_local_gmt,campaign_cid_areacodes_enabled,pllb_grouping_limit,did_ra_extensions_enabled,expanded_list_stats,contacts_enabled,alt_log_server_ip,alt_log_dbname,alt_log_login,alt_log_pass,tables_use_alt_log_db,call_menu_qualify_enabled,admin_list_counts,allow_voicemail_greeting,svn_revision,allow_emails,level_8_disable_add,pass_key,pass_hash_enabled,disable_auto_dial,country_code_list_stats,frozen_server_call_clear,active_modules,allow_chats,enable_languages,language_method,meetme_enter_login_filename,meetme_enter_leave3way_filename,enable_did_entry_list_id,enable_third_webform,default_language,user_hide_realtime_enabled,log_recording_access,alt_ivr_logging,admin_row_click,admin_screen_colors,ofcom_uk_drop_calc,agent_screen_colors,script_remove_js,manual_auto_next,user_new_lead_limit,agent_xfer_park_3way,agent_soundboards,web_loader_phone_length,agent_script,enable_auto_reports,enable_pause_code_limits,enable_drop_lists,allow_ip_lists,system_ip_blacklist,hide_inactive_lists,allow_manage_active_lists,expired_lists_inactive,did_system_filter,enable_gdpr_download_deletion,mute_recordings,user_admin_redirect,list_status_modification_confirmation,sip_event_logging,call_quota_lead_ranking,enable_second_script,enable_first_webform,recording_buttons,opensips_cid_name,require_password_length,user_account_emails,outbound_cid_any,entries_per_page,browser_call_alerts,inbound_answer_config,enable_international_dncs,daily_call_count_limit,allow_shared_dial,agent_search_method,admin_home_url,qc_claim_limit,qc_expire_days,two_factor_auth_hours,two_factor_container,call_limit_24hour,allowed_sip_stacks,agent_hide_hangup,allow_web_debug,max_logged_in_agents,user_codes_admin,abandon_check_queue,agent_notifications,demographic_quotas FROM system_settings;"; $rslt=mysql_to_mysqli($stmt, $link); #if ($DB) {echo "$stmt\n";} $qm_conf_ct = mysqli_num_rows($rslt); @@ -2879,6 +2889,7 @@ if ($qm_conf_ct > 0) $SSuser_codes_admin = $row[104]; $SSabandon_check_queue = $row[105]; $SSagent_notifications = $row[106]; + $SSdemographic_quotas = $row[107]; } if ($SSallow_web_debug < 1) {$DB=0;} ##### END SETTINGS LOOKUP ##### @@ -3473,6 +3484,9 @@ $user_codes_admin = preg_replace('/[^-_0-9a-zA-Z]/','',$user_codes_admin); $conf_engine = preg_replace('/[^-_0-9a-zA-Z]/','',$conf_engine); $user_group_script = preg_replace('/[^-_0-9a-zA-Z]/','',$user_group_script); $abandon_check_queue = preg_replace('/[^-_0-9a-zA-Z]/','',$abandon_check_queue); +$demographic_quotas_rerank = preg_replace('/[^-_0-9a-zA-Z]/','',$demographic_quotas_rerank); +$demographic_quotas_list_resets = preg_replace('/[^-_0-9a-zA-Z]/','',$demographic_quotas_list_resets); +$log_latency_gaps = preg_replace('/[^-_0-9a-zA-Z]/','',$log_latency_gaps); if ($non_latin < 1) { @@ -3902,6 +3916,8 @@ if ($non_latin < 1) $agent_hangup_route = preg_replace('/[^-_0-9a-zA-Z]/','',$agent_hangup_route); $show_confetti = preg_replace('/[^-_0-9a-zA-Z]/','',$show_confetti); $webphone_settings = preg_replace('/[^-_0-9a-zA-Z]/','',$webphone_settings); + $demographic_quotas = preg_replace('/[^-_0-9a-zA-Z]/','',$demographic_quotas); + $demographic_quotas_container = preg_replace('/[^-_0-9a-zA-Z]/','',$demographic_quotas_container); ### ALPHA-NUMERIC and underscore $qc_statuses_id = preg_replace('/[^_0-9a-zA-Z]/','',$qc_statuses_id); @@ -4628,6 +4644,8 @@ else $agent_hangup_route = preg_replace('/[^-_0-9\p{L}]/u','',$agent_hangup_route); $show_confetti = preg_replace('/[^-_0-9\p{L}]/u','',$show_confetti); $webphone_settings = preg_replace('/[^-_0-9\p{L}]/u','',$webphone_settings); + $demographic_quotas = preg_replace('/[^-_0-9\p{L}]/u','',$demographic_quotas); + $demographic_quotas_container = preg_replace('/[^-_0-9\p{L}]/u','',$demographic_quotas_container); ### ALPHA-NUMERIC and underscore and dash and slash and dot $menu_timeout_prompt = preg_replace('/[^-\/\|\._0-9\p{L}]/u','',$menu_timeout_prompt); @@ -5997,12 +6015,13 @@ if ($SSscript_remove_js > 0) # 230412-0946 - Added send_notification Agent-API function, agent_notifications system_setting # 230421-0847 - Added Agent Latency Report # 230421-1739 - Fix for QC issue #1352 +# 230515-1621 - Added demographic_quotas system setting and cammpaign options and DEMOGRAPHIC_QUOTAS container, Latency Gaps Report # # make sure you have added a user to the vicidial_users MySQL table with at least user_level 9 to access this page the first time -$admin_version = '2.14-882a'; -$build = '230421-1739'; +$admin_version = '2.14-883a'; +$build = '230515-1621'; $STARTtime = date("U"); $SQLdate = date("Y-m-d H:i:s"); @@ -11270,6 +11289,7 @@ if ($ADD==192111111111) + @@ -12416,7 +12436,7 @@ if ($ADD==20) $rslt=mysql_to_mysqli($stmtX, $link); } - $stmt="INSERT INTO vicidial_campaigns (campaign_name,campaign_id,active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,qc_get_record_launch,qc_show_recording,qc_shift_id,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_fourth_digit,survey_third_audio_file,survey_fourth_audio_file,survey_third_status,survey_fourth_status,survey_third_exten,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,allow_chats,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,in_group_dial,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti) SELECT \"$campaign_name\",\"$campaign_id\",\"N\",dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,\"DISABLED\",campaign_allow_inbound,manual_dial_list_id,default_xfer_group,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,qc_get_record_launch,qc_show_recording,qc_shift_id,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_fourth_digit,survey_third_audio_file,survey_fourth_audio_file,survey_third_status,survey_fourth_status,survey_third_exten,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,allow_chats,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,in_group_dial,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti from vicidial_campaigns where campaign_id='$source_campaign_id';"; + $stmt="INSERT INTO vicidial_campaigns (campaign_name,campaign_id,active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,qc_get_record_launch,qc_show_recording,qc_shift_id,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_fourth_digit,survey_third_audio_file,survey_fourth_audio_file,survey_third_status,survey_fourth_status,survey_third_exten,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,allow_chats,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,in_group_dial,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti,demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets) SELECT \"$campaign_name\",\"$campaign_id\",\"N\",dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,\"DISABLED\",campaign_allow_inbound,manual_dial_list_id,default_xfer_group,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,qc_get_record_launch,qc_show_recording,qc_shift_id,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_fourth_digit,survey_third_audio_file,survey_fourth_audio_file,survey_third_status,survey_fourth_status,survey_third_exten,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,allow_chats,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,in_group_dial,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti,demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets from vicidial_campaigns where campaign_id='$source_campaign_id';"; $rslt=mysql_to_mysqli($stmt, $link); $affected_rows = mysqli_affected_rows($link); @@ -16908,7 +16928,7 @@ if ($ADD==41) } ### gather server information - $stmt="SELECT asterisk_version,routing_prefix FROM servers where server_ip='$old_server_ip';"; + $stmt="SELECT asterisk_version,routing_prefix,server_id FROM servers where server_ip='$old_server_ip';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {echo "$stmt\n";} $srv_ct = mysqli_num_rows($rslt); @@ -16919,6 +16939,7 @@ if ($ADD==41) $row=mysqli_fetch_row($rslt); $asterisk_version = $row[0]; $routing_prefix = $row[1]; + $server_id = $row[2]; } $CCID_on=0; $CCID=''; @@ -16969,15 +16990,25 @@ if ($ADD==41) $rslt=mysql_to_mysqli($stmt, $link); if ($mel > 0) {mysql_error_logging($NOW_TIME,$link,$mel,$stmt,'00XXX',$user,$server_ip,$session_name,$one_mysql_log);} + ### log outbound call in the user dial log + $stmt = "INSERT INTO vicidial_user_dial_log SET caller_code='$VqueryCID',user='$PHP_AUTH_USER',call_date='$SQLdate',call_type='M',notes='Admin test call CAMPAIGN_TEST';"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + + ### log outbound call in the user call log + $stmt = "INSERT INTO user_call_log (user,call_date,call_type,server_ip,phone_number,number_dialed,lead_id,callerid,group_alias_id,preset_name) values('$PHP_AUTH_USER','$SQLdate','ADMIN','$old_server_ip','$phone_number','$Ndialstring','$lead_id','$CCID','','')"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + ### LOG INSERTION Admin Log Table, for campaign ### $SQL_log = "$stmtA|$stmtB|$stmtC|"; $SQL_log = preg_replace('/;/', '', $SQL_log); $SQL_log = addslashes($SQL_log); - $stmt="INSERT INTO vicidial_admin_log set event_date='$SQLdate', user='$PHP_AUTH_USER', ip_address='$ip', event_section='CAMPAIGNS', event_type='OTHER', record_id='$campaign_id', event_code='ADMIN CAMPAIGN TEST CALL', event_sql=\"$SQL_log\", event_notes='';"; + $stmt="INSERT INTO vicidial_admin_log set event_date='$SQLdate', user='$PHP_AUTH_USER', ip_address='$ip', event_section='CAMPAIGNS', event_type='OTHER', record_id='$campaign_id', event_code='ADMIN CAMPAIGN TEST CALL', event_sql=\"$SQL_log\", event_notes='Placed call to $phone_code $phone_number from $old_server_ip - $server_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB > 0) {echo "|$stmtA|\n|$stmtB|\n|$stmtC|\n";} - echo " "._QXZ("PLACED TO")." $phone_code $phone_number\n
"; + echo " "._QXZ("PLACED TO")." $phone_code $phone_number "._QXZ("FROM")." $old_server_ip - $server_id \n
"; } } @@ -17158,8 +17189,9 @@ if ($ADD==41) $hdrtSQL = ",hopper_drop_run_trigger='A'"; $hdrtMESSAGE='Hopper All-Drops-Run Triggered'; } + if ($demographic_quotas == 'ENABLED') {$use_auto_hopper='N';} - $stmtA="UPDATE vicidial_campaigns set campaign_name='$campaign_name',active='$active',dial_status_a='$dial_status_a',dial_status_b='$dial_status_b',dial_status_c='$dial_status_c',dial_status_d='$dial_status_d',dial_status_e='$dial_status_e',lead_order='$lead_order',allow_closers='$allow_closers',hopper_level='$hopper_level', auto_trim_hopper='$auto_trim_hopper', use_auto_hopper='$use_auto_hopper', auto_hopper_multi='$auto_hopper_multi', $adlSQL next_agent_call='$next_agent_call', local_call_time='$local_call_time', voicemail_ext='$voicemail_ext', dial_timeout='$dial_timeout', dial_prefix='$dial_prefix', campaign_cid='$campaign_cid', campaign_vdad_exten='$campaign_vdad_exten', web_form_address='" . mysqli_real_escape_string($link, $web_form_address) . "', park_ext='$park_ext', park_file_name='$park_file_name', campaign_rec_exten='$campaign_rec_exten', campaign_recording='$campaign_recording', campaign_rec_filename='$campaign_rec_filename', campaign_script='$script_id', get_call_launch='$get_call_launch', am_message_exten='$am_message_exten', amd_send_to_vmx='$amd_send_to_vmx', xferconf_a_dtmf='$xferconf_a_dtmf',xferconf_a_number='$xferconf_a_number',xferconf_b_dtmf='$xferconf_b_dtmf',xferconf_b_number='$xferconf_b_number',lead_filter_id='$lead_filter_id',alt_number_dialing='$alt_number_dialing',scheduled_callbacks='$scheduled_callbacks',drop_action='$drop_action',drop_call_seconds='$drop_call_seconds',safe_harbor_exten='$safe_harbor_exten',wrapup_seconds='$wrapup_seconds',wrapup_message='$wrapup_message',closer_campaigns=$closer_campaignsSQL,use_internal_dnc='$use_internal_dnc',allcalls_delay='$allcalls_delay',omit_phone_code='$omit_phone_code',dial_method='$dial_method',available_only_ratio_tally='$available_only_ratio_tally',adaptive_dropped_percentage='$adaptive_dropped_percentage',adaptive_maximum_level='$adaptive_maximum_level',adaptive_latest_server_time='$adaptive_latest_server_time',adaptive_intensity='$adaptive_intensity',adaptive_dl_diff_target='$adaptive_dl_diff_target',concurrent_transfers='$concurrent_transfers',auto_alt_dial='$auto_alt_dial',agent_pause_codes_active='$agent_pause_codes_active',campaign_description='$campaign_description',campaign_changedate='$SQLdate',campaign_stats_refresh='$campaign_stats_refresh',disable_alter_custdata='$disable_alter_custdata',no_hopper_leads_logins='$no_hopper_leads_logins',list_order_mix='$list_order_mix',campaign_allow_inbound='$campaign_allow_inbound',manual_dial_list_id='$manual_dial_list_id',default_xfer_group='$default_xfer_group',xfer_groups='$XFERgroups_value',queue_priority='$queue_priority',drop_inbound_group='$drop_inbound_group',disable_alter_custphone='$disable_alter_custphone',display_queue_count='$display_queue_count',manual_dial_filter='$manual_dial_filter',agent_clipboard_copy='$agent_clipboard_copy',agent_extended_alt_dial='$agent_extended_alt_dial',use_campaign_dnc='$use_campaign_dnc',three_way_call_cid='$three_way_call_cid',three_way_dial_prefix='$three_way_dial_prefix',web_form_target='$web_form_target',vtiger_search_category='$vtiger_search_category',vtiger_create_call_record='$vtiger_create_call_record',vtiger_create_lead_record='$vtiger_create_lead_record',vtiger_screen_login='$vtiger_screen_login',cpd_amd_action='$cpd_amd_action',agent_allow_group_alias='$agent_allow_group_alias',default_group_alias='$default_group_alias',vtiger_search_dead='$vtiger_search_dead',vtiger_status_call='$vtiger_status_call',drop_lockout_time='$drop_lockout_time',quick_transfer_button='$quick_transfer_button',prepopulate_transfer_preset='$prepopulate_transfer_preset',drop_rate_group='$drop_rate_group',view_calls_in_queue='$view_calls_in_queue',view_calls_in_queue_launch='$view_calls_in_queue_launch',grab_calls_in_queue='$grab_calls_in_queue',call_requeue_button='$call_requeue_button',pause_after_each_call='$pause_after_each_call',no_hopper_dialing='$no_hopper_dialing',agent_dial_owner_only='$agent_dial_owner_only',agent_display_dialable_leads='$agent_display_dialable_leads',web_form_address_two='" . mysqli_real_escape_string($link, $web_form_address_two) . "',waitforsilence_options='$waitforsilence_options',agent_select_territories='$agent_select_territories',crm_popup_login='$crm_popup_login',crm_login_address='" . mysqli_real_escape_string($link, $crm_login_address) . "',timer_action='$timer_action',timer_action_message='$timer_action_message',timer_action_seconds='$timer_action_seconds',start_call_url='" . mysqli_real_escape_string($link, $start_call_url) . "',dispo_call_url='" . mysqli_real_escape_string($link, $dispo_call_url) . "',xferconf_c_number='$xferconf_c_number',xferconf_d_number='$xferconf_d_number',xferconf_e_number='$xferconf_e_number',use_custom_cid='$use_custom_cid',scheduled_callbacks_alert='$scheduled_callbacks_alert',queuemetrics_callstatus_override='$queuemetrics_callstatus',extension_appended_cidname='$extension_appended_cidname',scheduled_callbacks_count='$scheduled_callbacks_count',manual_dial_override='$manual_dial_override',blind_monitor_warning='$blind_monitor_warning',blind_monitor_message='" . mysqli_real_escape_string($link, $blind_monitor_message) . "',blind_monitor_filename='$blind_monitor_filename',inbound_queue_no_dial='$inbound_queue_no_dial',timer_action_destination='$timer_action_destination',enable_xfer_presets='$enable_xfer_presets',hide_xfer_number_to_dial='$hide_xfer_number_to_dial',manual_dial_prefix='$manual_dial_prefix',customer_3way_hangup_logging='$customer_3way_hangup_logging',customer_3way_hangup_seconds='$customer_3way_hangup_seconds',customer_3way_hangup_action='$customer_3way_hangup_action',ivr_park_call='$ivr_park_call',ivr_park_call_agi='$ivr_park_call_agi',manual_preview_dial='$manual_preview_dial',realtime_agent_time_stats='$realtime_agent_time_stats',api_manual_dial='$api_manual_dial',manual_dial_call_time_check='$manual_dial_call_time_check',lead_order_randomize='$lead_order_randomize',lead_order_secondary='$lead_order_secondary',per_call_notes='$per_call_notes',my_callback_option='$my_callback_option',agent_lead_search='$agent_lead_search',agent_lead_search_method='$agent_lead_search_method',queuemetrics_phone_environment='$queuemetrics_phone_environment',auto_pause_precall='$auto_pause_precall',auto_resume_precall='$auto_resume_precall',auto_pause_precall_code='$auto_pause_precall_code',manual_dial_cid='$manual_dial_cid',post_phone_time_diff_alert='$post_phone_time_diff_alert',custom_3way_button_transfer='$custom_3way_button_transfer',available_only_tally_threshold='$available_only_tally_threshold',available_only_tally_threshold_agents='$available_only_tally_threshold_agents',dial_level_threshold='$dial_level_threshold',dial_level_threshold_agents='$dial_level_threshold_agents',safe_harbor_audio='$safe_harbor_audio',safe_harbor_menu_id='$safe_harbor_menu_id',callback_days_limit='$callback_days_limit',dl_diff_target_method='$dl_diff_target_method',disable_dispo_screen='$disable_dispo_screen',disable_dispo_status='$disable_dispo_status',screen_labels='$screen_labels',status_display_fields='$status_display_fields',na_call_url='" . mysqli_real_escape_string($link, $na_call_url) . "',pllb_grouping='$pllb_grouping',pllb_grouping_limit='$pllb_grouping_limit',call_count_limit='$call_count_limit',call_count_target='$call_count_target',callback_hours_block='$callback_hours_block',callback_list_calltime='$callback_list_calltime',user_group='$user_group',hopper_vlc_dup_check='$hopper_vlc_dup_check',in_group_dial='$in_group_dial',in_group_dial_select='$in_group_dial_select',safe_harbor_audio_field='$safe_harbor_audio_field',pause_after_next_call='$pause_after_next_call',owner_populate='$owner_populate',use_other_campaign_dnc='$use_other_campaign_dnc',allow_emails='$allow_emails',allow_chats='$allow_chats',amd_inbound_group='$amd_inbound_group',amd_callmenu='$amd_callmenu',manual_dial_lead_id='$manual_dial_lead_id',dead_max='$dead_max',dispo_max='$dispo_max',pause_max='$pause_max',dead_max_dispo='$dead_max_dispo',dispo_max_dispo='$dispo_max_dispo',max_inbound_calls='$max_inbound_calls',manual_dial_search_checkbox='$manual_dial_search_checkbox',hide_call_log_info='$hide_call_log_info',timer_alt_seconds='$timer_alt_seconds',wrapup_bypass='$wrapup_bypass',wrapup_after_hotkey='$wrapup_after_hotkey',callback_active_limit='$callback_active_limit',callback_active_limit_override='$callback_active_limit_override',comments_all_tabs='$comments_all_tabs',comments_dispo_screen='$comments_dispo_screen',comments_callback_screen='$comments_callback_screen',qc_comment_history='$qc_comment_history',show_previous_callback='$show_previous_callback',clear_script='$clear_script',cpd_unknown_action='$cpd_unknown_action',manual_dial_search_filter='$manual_dial_search_filter',web_form_address_three='" . mysqli_real_escape_string($link, $web_form_address_three) . "',manual_dial_override_field='$manual_dial_override_field',status_display_ingroup='$status_display_ingroup',customer_gone_seconds='$customer_gone_seconds',agent_display_fields='$agent_display_fields',am_message_wildcards='$am_message_wildcards',manual_dial_timeout='$manual_dial_timeout',routing_initiated_recordings='$routing_initiated_recordings',manual_dial_hopper_check='$manual_dial_hopper_check',callback_useronly_move_minutes='$callback_useronly_move_minutes',ofcom_uk_drop_calc='$ofcom_uk_drop_calc',manual_auto_next='$manual_auto_next',manual_auto_show='$manual_auto_show',allow_required_fields='$allow_required_fields',dead_to_dispo='$dead_to_dispo',agent_xfer_validation='$agent_xfer_validation',ready_max_logout='$ready_max_logout',callback_display_days='$callback_display_days',three_way_record_stop='$three_way_record_stop',hangup_xfer_record_start='$hangup_xfer_record_start',scheduled_callbacks_email_alert='$scheduled_callbacks_email_alert',max_inbound_calls_outcome='$max_inbound_calls_outcome',manual_auto_next_options='$manual_auto_next_options',agent_screen_time_display='$agent_screen_time_display',next_dial_my_callbacks='$next_dial_my_callbacks',inbound_no_agents_no_dial_container='$inbound_no_agents_no_dial_container',inbound_no_agents_no_dial_threshold='$inbound_no_agents_no_dial_threshold',cid_group_id='$cid_group_id',pause_max_dispo='$pause_max_dispo',script_top_dispo='$script_top_dispo',dead_trigger_seconds='$dead_trigger_seconds',dead_trigger_action='$dead_trigger_action',dead_trigger_repeat='$dead_trigger_repeat',dead_trigger_filename='$dead_trigger_filename',dead_trigger_url='" . mysqli_real_escape_string($link, $dead_trigger_url) . "',scheduled_callbacks_force_dial='$scheduled_callbacks_force_dial',scheduled_callbacks_auto_reschedule='$scheduled_callbacks_auto_reschedule',scheduled_callbacks_timezones_container='$scheduled_callbacks_timezones_container',three_way_volume_buttons='$three_way_volume_buttons',callback_dnc='$callback_dnc',manual_dial_validation='$manual_dial_validation',mute_recordings='$mute_recordings',auto_active_list_new='$auto_active_list_new',call_quota_lead_ranking='$call_quota_lead_ranking',sip_event_logging='$sip_event_logging',campaign_script_two='$campaign_script_two',leave_vm_no_dispo='$leave_vm_no_dispo',leave_vm_message_group_id='$leave_vm_message_group_id',dial_timeout_lead_container='$dial_timeout_lead_container',amd_type='$amd_type',vmm_daily_limit='$vmm_daily_limit',opensips_cid_name='$opensips_cid_name',amd_agent_route_options='$amd_agent_route_options',browser_alert_sound='$browser_alert_sound',browser_alert_volume='$browser_alert_volume',three_way_record_stop_exception='$three_way_record_stop_exception',pause_max_exceptions='$pause_max_exceptions',daily_call_count_limit='$daily_call_count_limit',daily_limit_manual='$daily_limit_manual',transfer_button_launch='$transfer_button_launch',shared_dial_rank='$shared_dial_rank',agent_search_method='$agent_search_method',clear_form='$clear_form',leave_3way_start_recording='$leave_3way_start_recording',leave_3way_start_recording_exception='$leave_3way_start_recording_exception',calls_waiting_vl_one='$calls_waiting_vl_one',calls_waiting_vl_two='$calls_waiting_vl_two',calls_inqueue_count_one='$calls_inqueue_count_one',calls_inqueue_count_two='$calls_inqueue_count_two',in_man_dial_next_ready_seconds='$in_man_dial_next_ready_seconds',in_man_dial_next_ready_seconds_override='$in_man_dial_next_ready_seconds_override',transfer_no_dispo='$transfer_no_dispo',call_limit_24hour_method='$call_limit_24hour_method',call_limit_24hour_scope='$call_limit_24hour_scope',call_limit_24hour='$call_limit_24hour',call_limit_24hour_override='$call_limit_24hour_override',cid_group_id_two='$cid_group_id_two',incall_tally_threshold_seconds='$incall_tally_threshold_seconds',auto_alt_threshold='$auto_alt_threshold',pause_max_url='$pause_max_url',agent_hide_hangup='$agent_hide_hangup',ig_xfer_list_sort='$ig_xfer_list_sort',script_tab_frame_size='$script_tab_frame_size',max_logged_in_agents='$max_logged_in_agents',user_group_script='$user_group_script',agent_hangup_route='$agent_hangup_route',agent_hangup_value='$agent_hangup_value',agent_hangup_ig_override='$agent_hangup_ig_override',show_confetti='$show_confetti'$hdrtSQL where campaign_id='$campaign_id';"; + $stmtA="UPDATE vicidial_campaigns set campaign_name='$campaign_name',active='$active',dial_status_a='$dial_status_a',dial_status_b='$dial_status_b',dial_status_c='$dial_status_c',dial_status_d='$dial_status_d',dial_status_e='$dial_status_e',lead_order='$lead_order',allow_closers='$allow_closers',hopper_level='$hopper_level', auto_trim_hopper='$auto_trim_hopper', use_auto_hopper='$use_auto_hopper', auto_hopper_multi='$auto_hopper_multi', $adlSQL next_agent_call='$next_agent_call', local_call_time='$local_call_time', voicemail_ext='$voicemail_ext', dial_timeout='$dial_timeout', dial_prefix='$dial_prefix', campaign_cid='$campaign_cid', campaign_vdad_exten='$campaign_vdad_exten', web_form_address='" . mysqli_real_escape_string($link, $web_form_address) . "', park_ext='$park_ext', park_file_name='$park_file_name', campaign_rec_exten='$campaign_rec_exten', campaign_recording='$campaign_recording', campaign_rec_filename='$campaign_rec_filename', campaign_script='$script_id', get_call_launch='$get_call_launch', am_message_exten='$am_message_exten', amd_send_to_vmx='$amd_send_to_vmx', xferconf_a_dtmf='$xferconf_a_dtmf',xferconf_a_number='$xferconf_a_number',xferconf_b_dtmf='$xferconf_b_dtmf',xferconf_b_number='$xferconf_b_number',lead_filter_id='$lead_filter_id',alt_number_dialing='$alt_number_dialing',scheduled_callbacks='$scheduled_callbacks',drop_action='$drop_action',drop_call_seconds='$drop_call_seconds',safe_harbor_exten='$safe_harbor_exten',wrapup_seconds='$wrapup_seconds',wrapup_message='$wrapup_message',closer_campaigns=$closer_campaignsSQL,use_internal_dnc='$use_internal_dnc',allcalls_delay='$allcalls_delay',omit_phone_code='$omit_phone_code',dial_method='$dial_method',available_only_ratio_tally='$available_only_ratio_tally',adaptive_dropped_percentage='$adaptive_dropped_percentage',adaptive_maximum_level='$adaptive_maximum_level',adaptive_latest_server_time='$adaptive_latest_server_time',adaptive_intensity='$adaptive_intensity',adaptive_dl_diff_target='$adaptive_dl_diff_target',concurrent_transfers='$concurrent_transfers',auto_alt_dial='$auto_alt_dial',agent_pause_codes_active='$agent_pause_codes_active',campaign_description='$campaign_description',campaign_changedate='$SQLdate',campaign_stats_refresh='$campaign_stats_refresh',disable_alter_custdata='$disable_alter_custdata',no_hopper_leads_logins='$no_hopper_leads_logins',list_order_mix='$list_order_mix',campaign_allow_inbound='$campaign_allow_inbound',manual_dial_list_id='$manual_dial_list_id',default_xfer_group='$default_xfer_group',xfer_groups='$XFERgroups_value',queue_priority='$queue_priority',drop_inbound_group='$drop_inbound_group',disable_alter_custphone='$disable_alter_custphone',display_queue_count='$display_queue_count',manual_dial_filter='$manual_dial_filter',agent_clipboard_copy='$agent_clipboard_copy',agent_extended_alt_dial='$agent_extended_alt_dial',use_campaign_dnc='$use_campaign_dnc',three_way_call_cid='$three_way_call_cid',three_way_dial_prefix='$three_way_dial_prefix',web_form_target='$web_form_target',vtiger_search_category='$vtiger_search_category',vtiger_create_call_record='$vtiger_create_call_record',vtiger_create_lead_record='$vtiger_create_lead_record',vtiger_screen_login='$vtiger_screen_login',cpd_amd_action='$cpd_amd_action',agent_allow_group_alias='$agent_allow_group_alias',default_group_alias='$default_group_alias',vtiger_search_dead='$vtiger_search_dead',vtiger_status_call='$vtiger_status_call',drop_lockout_time='$drop_lockout_time',quick_transfer_button='$quick_transfer_button',prepopulate_transfer_preset='$prepopulate_transfer_preset',drop_rate_group='$drop_rate_group',view_calls_in_queue='$view_calls_in_queue',view_calls_in_queue_launch='$view_calls_in_queue_launch',grab_calls_in_queue='$grab_calls_in_queue',call_requeue_button='$call_requeue_button',pause_after_each_call='$pause_after_each_call',no_hopper_dialing='$no_hopper_dialing',agent_dial_owner_only='$agent_dial_owner_only',agent_display_dialable_leads='$agent_display_dialable_leads',web_form_address_two='" . mysqli_real_escape_string($link, $web_form_address_two) . "',waitforsilence_options='$waitforsilence_options',agent_select_territories='$agent_select_territories',crm_popup_login='$crm_popup_login',crm_login_address='" . mysqli_real_escape_string($link, $crm_login_address) . "',timer_action='$timer_action',timer_action_message='$timer_action_message',timer_action_seconds='$timer_action_seconds',start_call_url='" . mysqli_real_escape_string($link, $start_call_url) . "',dispo_call_url='" . mysqli_real_escape_string($link, $dispo_call_url) . "',xferconf_c_number='$xferconf_c_number',xferconf_d_number='$xferconf_d_number',xferconf_e_number='$xferconf_e_number',use_custom_cid='$use_custom_cid',scheduled_callbacks_alert='$scheduled_callbacks_alert',queuemetrics_callstatus_override='$queuemetrics_callstatus',extension_appended_cidname='$extension_appended_cidname',scheduled_callbacks_count='$scheduled_callbacks_count',manual_dial_override='$manual_dial_override',blind_monitor_warning='$blind_monitor_warning',blind_monitor_message='" . mysqli_real_escape_string($link, $blind_monitor_message) . "',blind_monitor_filename='$blind_monitor_filename',inbound_queue_no_dial='$inbound_queue_no_dial',timer_action_destination='$timer_action_destination',enable_xfer_presets='$enable_xfer_presets',hide_xfer_number_to_dial='$hide_xfer_number_to_dial',manual_dial_prefix='$manual_dial_prefix',customer_3way_hangup_logging='$customer_3way_hangup_logging',customer_3way_hangup_seconds='$customer_3way_hangup_seconds',customer_3way_hangup_action='$customer_3way_hangup_action',ivr_park_call='$ivr_park_call',ivr_park_call_agi='$ivr_park_call_agi',manual_preview_dial='$manual_preview_dial',realtime_agent_time_stats='$realtime_agent_time_stats',api_manual_dial='$api_manual_dial',manual_dial_call_time_check='$manual_dial_call_time_check',lead_order_randomize='$lead_order_randomize',lead_order_secondary='$lead_order_secondary',per_call_notes='$per_call_notes',my_callback_option='$my_callback_option',agent_lead_search='$agent_lead_search',agent_lead_search_method='$agent_lead_search_method',queuemetrics_phone_environment='$queuemetrics_phone_environment',auto_pause_precall='$auto_pause_precall',auto_resume_precall='$auto_resume_precall',auto_pause_precall_code='$auto_pause_precall_code',manual_dial_cid='$manual_dial_cid',post_phone_time_diff_alert='$post_phone_time_diff_alert',custom_3way_button_transfer='$custom_3way_button_transfer',available_only_tally_threshold='$available_only_tally_threshold',available_only_tally_threshold_agents='$available_only_tally_threshold_agents',dial_level_threshold='$dial_level_threshold',dial_level_threshold_agents='$dial_level_threshold_agents',safe_harbor_audio='$safe_harbor_audio',safe_harbor_menu_id='$safe_harbor_menu_id',callback_days_limit='$callback_days_limit',dl_diff_target_method='$dl_diff_target_method',disable_dispo_screen='$disable_dispo_screen',disable_dispo_status='$disable_dispo_status',screen_labels='$screen_labels',status_display_fields='$status_display_fields',na_call_url='" . mysqli_real_escape_string($link, $na_call_url) . "',pllb_grouping='$pllb_grouping',pllb_grouping_limit='$pllb_grouping_limit',call_count_limit='$call_count_limit',call_count_target='$call_count_target',callback_hours_block='$callback_hours_block',callback_list_calltime='$callback_list_calltime',user_group='$user_group',hopper_vlc_dup_check='$hopper_vlc_dup_check',in_group_dial='$in_group_dial',in_group_dial_select='$in_group_dial_select',safe_harbor_audio_field='$safe_harbor_audio_field',pause_after_next_call='$pause_after_next_call',owner_populate='$owner_populate',use_other_campaign_dnc='$use_other_campaign_dnc',allow_emails='$allow_emails',allow_chats='$allow_chats',amd_inbound_group='$amd_inbound_group',amd_callmenu='$amd_callmenu',manual_dial_lead_id='$manual_dial_lead_id',dead_max='$dead_max',dispo_max='$dispo_max',pause_max='$pause_max',dead_max_dispo='$dead_max_dispo',dispo_max_dispo='$dispo_max_dispo',max_inbound_calls='$max_inbound_calls',manual_dial_search_checkbox='$manual_dial_search_checkbox',hide_call_log_info='$hide_call_log_info',timer_alt_seconds='$timer_alt_seconds',wrapup_bypass='$wrapup_bypass',wrapup_after_hotkey='$wrapup_after_hotkey',callback_active_limit='$callback_active_limit',callback_active_limit_override='$callback_active_limit_override',comments_all_tabs='$comments_all_tabs',comments_dispo_screen='$comments_dispo_screen',comments_callback_screen='$comments_callback_screen',qc_comment_history='$qc_comment_history',show_previous_callback='$show_previous_callback',clear_script='$clear_script',cpd_unknown_action='$cpd_unknown_action',manual_dial_search_filter='$manual_dial_search_filter',web_form_address_three='" . mysqli_real_escape_string($link, $web_form_address_three) . "',manual_dial_override_field='$manual_dial_override_field',status_display_ingroup='$status_display_ingroup',customer_gone_seconds='$customer_gone_seconds',agent_display_fields='$agent_display_fields',am_message_wildcards='$am_message_wildcards',manual_dial_timeout='$manual_dial_timeout',routing_initiated_recordings='$routing_initiated_recordings',manual_dial_hopper_check='$manual_dial_hopper_check',callback_useronly_move_minutes='$callback_useronly_move_minutes',ofcom_uk_drop_calc='$ofcom_uk_drop_calc',manual_auto_next='$manual_auto_next',manual_auto_show='$manual_auto_show',allow_required_fields='$allow_required_fields',dead_to_dispo='$dead_to_dispo',agent_xfer_validation='$agent_xfer_validation',ready_max_logout='$ready_max_logout',callback_display_days='$callback_display_days',three_way_record_stop='$three_way_record_stop',hangup_xfer_record_start='$hangup_xfer_record_start',scheduled_callbacks_email_alert='$scheduled_callbacks_email_alert',max_inbound_calls_outcome='$max_inbound_calls_outcome',manual_auto_next_options='$manual_auto_next_options',agent_screen_time_display='$agent_screen_time_display',next_dial_my_callbacks='$next_dial_my_callbacks',inbound_no_agents_no_dial_container='$inbound_no_agents_no_dial_container',inbound_no_agents_no_dial_threshold='$inbound_no_agents_no_dial_threshold',cid_group_id='$cid_group_id',pause_max_dispo='$pause_max_dispo',script_top_dispo='$script_top_dispo',dead_trigger_seconds='$dead_trigger_seconds',dead_trigger_action='$dead_trigger_action',dead_trigger_repeat='$dead_trigger_repeat',dead_trigger_filename='$dead_trigger_filename',dead_trigger_url='" . mysqli_real_escape_string($link, $dead_trigger_url) . "',scheduled_callbacks_force_dial='$scheduled_callbacks_force_dial',scheduled_callbacks_auto_reschedule='$scheduled_callbacks_auto_reschedule',scheduled_callbacks_timezones_container='$scheduled_callbacks_timezones_container',three_way_volume_buttons='$three_way_volume_buttons',callback_dnc='$callback_dnc',manual_dial_validation='$manual_dial_validation',mute_recordings='$mute_recordings',auto_active_list_new='$auto_active_list_new',call_quota_lead_ranking='$call_quota_lead_ranking',sip_event_logging='$sip_event_logging',campaign_script_two='$campaign_script_two',leave_vm_no_dispo='$leave_vm_no_dispo',leave_vm_message_group_id='$leave_vm_message_group_id',dial_timeout_lead_container='$dial_timeout_lead_container',amd_type='$amd_type',vmm_daily_limit='$vmm_daily_limit',opensips_cid_name='$opensips_cid_name',amd_agent_route_options='$amd_agent_route_options',browser_alert_sound='$browser_alert_sound',browser_alert_volume='$browser_alert_volume',three_way_record_stop_exception='$three_way_record_stop_exception',pause_max_exceptions='$pause_max_exceptions',daily_call_count_limit='$daily_call_count_limit',daily_limit_manual='$daily_limit_manual',transfer_button_launch='$transfer_button_launch',shared_dial_rank='$shared_dial_rank',agent_search_method='$agent_search_method',clear_form='$clear_form',leave_3way_start_recording='$leave_3way_start_recording',leave_3way_start_recording_exception='$leave_3way_start_recording_exception',calls_waiting_vl_one='$calls_waiting_vl_one',calls_waiting_vl_two='$calls_waiting_vl_two',calls_inqueue_count_one='$calls_inqueue_count_one',calls_inqueue_count_two='$calls_inqueue_count_two',in_man_dial_next_ready_seconds='$in_man_dial_next_ready_seconds',in_man_dial_next_ready_seconds_override='$in_man_dial_next_ready_seconds_override',transfer_no_dispo='$transfer_no_dispo',call_limit_24hour_method='$call_limit_24hour_method',call_limit_24hour_scope='$call_limit_24hour_scope',call_limit_24hour='$call_limit_24hour',call_limit_24hour_override='$call_limit_24hour_override',cid_group_id_two='$cid_group_id_two',incall_tally_threshold_seconds='$incall_tally_threshold_seconds',auto_alt_threshold='$auto_alt_threshold',pause_max_url='$pause_max_url',agent_hide_hangup='$agent_hide_hangup',ig_xfer_list_sort='$ig_xfer_list_sort',script_tab_frame_size='$script_tab_frame_size',max_logged_in_agents='$max_logged_in_agents',user_group_script='$user_group_script',agent_hangup_route='$agent_hangup_route',agent_hangup_value='$agent_hangup_value',agent_hangup_ig_override='$agent_hangup_ig_override',show_confetti='$show_confetti',demographic_quotas='$demographic_quotas',demographic_quotas_container='$demographic_quotas_container',demographic_quotas_rerank='$demographic_quotas_rerank',demographic_quotas_list_resets='$demographic_quotas_list_resets'$hdrtSQL where campaign_id='$campaign_id';"; if ($DB) {echo "|$stmt|\n";} $rslt=mysql_to_mysqli($stmtA, $link); @@ -20887,7 +20919,7 @@ if ($ADD==411111111111111) } } - $stmt="UPDATE system_settings set use_non_latin='$use_non_latin',webroot_writable='$webroot_writable',enable_queuemetrics_logging='$enable_queuemetrics_logging',queuemetrics_server_ip='$queuemetrics_server_ip',queuemetrics_dbname='$queuemetrics_dbname',queuemetrics_login='$queuemetrics_login',queuemetrics_pass='$queuemetrics_pass',queuemetrics_url='" . mysqli_real_escape_string($link, $queuemetrics_url) . "',queuemetrics_log_id='$queuemetrics_log_id',queuemetrics_eq_prepend='$queuemetrics_eq_prepend',vicidial_agent_disable='$vicidial_agent_disable',allow_sipsak_messages='$allow_sipsak_messages',admin_home_url='" . mysqli_real_escape_string($link, $admin_home_url) . "',enable_agc_xfer_log='$enable_agc_xfer_log',timeclock_end_of_day='$timeclock_end_of_day',vdc_header_date_format='$vdc_header_date_format',vdc_customer_date_format='$vdc_customer_date_format',vdc_header_phone_format='$vdc_header_phone_format',vdc_agent_api_active='$vdc_agent_api_active',enable_vtiger_integration='$enable_vtiger_integration',vtiger_server_ip='$vtiger_server_ip',vtiger_dbname='$vtiger_dbname',vtiger_login='$vtiger_login',vtiger_pass='$vtiger_pass',vtiger_url='" . mysqli_real_escape_string($link, $vtiger_url) . "',qc_features_active='$qc_features_active',outbound_autodial_active='$outbound_autodial_active',outbound_calls_per_second='$outbound_calls_per_second',enable_tts_integration='$enable_tts_integration',agentonly_callback_campaign_lock='$agentonly_callback_campaign_lock',sounds_central_control_active='$sounds_central_control_active',sounds_web_server='$sounds_web_server',sounds_web_directory='$sounds_web_directory',active_voicemail_server='$active_voicemail_server',auto_dial_limit='$auto_dial_limit',user_territories_active='$user_territories_active',allow_custom_dialplan='$allow_custom_dialplan',enable_second_webform='$enable_second_webform',default_webphone='$default_webphone',default_external_server_ip='$default_external_server_ip',webphone_url='" . mysqli_real_escape_string($link, $webphone_url) . "',enable_agc_dispo_log='$enable_agc_dispo_log',queuemetrics_loginout='$queuemetrics_loginout',callcard_enabled='$callcard_enabled',queuemetrics_callstatus='$queuemetrics_callstatus',default_codecs='$default_codecs',admin_web_directory='$admin_web_directory',label_title='$label_title',label_first_name='$label_first_name',label_middle_initial='$label_middle_initial',label_last_name='$label_last_name',label_address1='$label_address1',label_address2='$label_address2',label_address3='$label_address3',label_city='$label_city',label_state='$label_state',label_province='$label_province',label_postal_code='$label_postal_code',label_vendor_lead_code='$label_vendor_lead_code',label_gender='$label_gender',label_phone_number='$label_phone_number',label_phone_code='$label_phone_code',label_alt_phone='$label_alt_phone',label_security_phrase='$label_security_phrase',label_email='$label_email',label_comments='$label_comments',label_lead_id='$label_lead_id',label_list_id='$label_list_id',label_entry_date='$label_entry_date',label_gmt_offset_now='$label_gmt_offset_now',label_source_id='$label_source_id',label_called_since_last_reset='$label_called_since_last_reset',label_status='$label_status',label_user='$label_user',label_date_of_birth='$label_date_of_birth',label_country_code='$label_country_code',label_last_local_call_time='$label_last_local_call_time',label_called_count='$label_called_count',label_rank='$label_rank',label_owner='$label_owner',label_entry_list_id='$label_entry_list_id',custom_fields_enabled='$custom_fields_enabled',slave_db_server='$slave_db_server',reports_use_slave_db='$reports_use_slave_db'$custom_reports_slave_SQL,webphone_systemkey='$webphone_systemkey',first_login_trigger='$first_login_trigger',default_phone_registration_password='$default_phone_registration_password',default_phone_login_password='$default_phone_login_password',default_server_password='$default_server_password',admin_modify_refresh='$admin_modify_refresh',nocache_admin='$nocache_admin',generate_cross_server_exten='$generate_cross_server_exten',queuemetrics_addmember_enabled='$queuemetrics_addmember_enabled',queuemetrics_dispo_pause='$queuemetrics_dispo_pause',label_hide_field_logs='$label_hide_field_logs',queuemetrics_pe_phone_append='$queuemetrics_pe_phone_append',test_campaign_calls='$test_campaign_calls',agents_calls_reset='$agents_calls_reset',default_voicemail_timezone='$default_voicemail_timezone',default_local_gmt='$default_local_gmt',noanswer_log='$noanswer_log',alt_log_server_ip='$alt_log_server_ip',alt_log_dbname='$alt_log_dbname',alt_log_login='$alt_log_login',alt_log_pass='$alt_log_pass',tables_use_alt_log_db='$tables_use_alt_log_db',did_agent_log='$did_agent_log',campaign_cid_areacodes_enabled='$campaign_cid_areacodes_enabled',pllb_grouping_limit='$pllb_grouping_limit',did_ra_extensions_enabled='$did_ra_extensions_enabled',expanded_list_stats='$expanded_list_stats',contacts_enabled='$contacts_enabled',call_menu_qualify_enabled='$call_menu_qualify_enabled',admin_list_counts='$admin_list_counts',allow_voicemail_greeting='$allow_voicemail_greeting',queuemetrics_socket='$queuemetrics_socket',queuemetrics_socket_url='$queuemetrics_socket_url',enhanced_disconnect_logging='$enhanced_disconnect_logging',allow_emails='$allow_emails',level_8_disable_add='$level_8_disable_add',queuemetrics_record_hold='$queuemetrics_record_hold',country_code_list_stats='$country_code_list_stats',queuemetrics_pause_type='$queuemetrics_pause_type',frozen_server_call_clear='$frozen_server_call_clear',callback_time_24hour='$callback_time_24hour',enable_languages='$enable_languages',language_method='$language_method',meetme_enter_login_filename='$meetme_enter_login_filename',meetme_enter_leave3way_filename='$meetme_enter_leave3way_filename',enable_did_entry_list_id='$enable_did_entry_list_id',enable_third_webform='$enable_third_webform',allow_chats='$allow_chats',chat_url='" . mysqli_real_escape_string($link, $chat_url) . "',chat_timeout='$chat_timeout',agent_debug_logging='$agent_debug_logging',default_language='$default_language',agent_whisper_enabled='$agent_whisper_enabled',user_hide_realtime_enabled='$user_hide_realtime_enabled',usacan_phone_dialcode_fix='$usacan_phone_dialcode_fix',cache_carrier_stats_realtime='$cache_carrier_stats_realtime',log_recording_access='$log_recording_access',report_default_format='$report_default_format',alt_ivr_logging='$alt_ivr_logging',default_phone_code='$default_phone_code',admin_row_click='$admin_row_click',admin_screen_colors='$admin_screen_colors',ofcom_uk_drop_calc='$ofcom_uk_drop_calc',agent_screen_colors='$agent_screen_colors',script_remove_js='$script_remove_js',manual_auto_next='$manual_auto_next',user_new_lead_limit='$user_new_lead_limit',agent_xfer_park_3way='$agent_xfer_park_3way',agent_soundboards='$agent_soundboards',web_loader_phone_length='$web_loader_phone_length',agent_script='$agent_script',agent_chat_screen_colors='$agent_chat_screen_colors',enable_auto_reports='$enable_auto_reports',enable_pause_code_limits='$enable_pause_code_limits',enable_drop_lists='$enable_drop_lists',allow_ip_lists='$allow_ip_lists',system_ip_blacklist='$system_ip_blacklist',agent_push_events='$agent_push_events',agent_push_url='$agent_push_url',hide_inactive_lists='$hide_inactive_lists',allow_manage_active_lists='$allow_manage_active_lists',expired_lists_inactive='$expired_lists_inactive',did_system_filter='$did_system_filter',anyone_callback_inactive_lists='$anyone_callback_inactive_lists',enable_gdpr_download_deletion='$enable_gdpr_download_deletion',source_id_display='$source_id_display',agent_logout_link='$agent_logout_link',manual_dial_validation='$manual_dial_validation',mute_recordings='$mute_recordings',user_admin_redirect='$user_admin_redirect',list_status_modification_confirmation='$list_status_modification_confirmation',sip_event_logging='$sip_event_logging',call_quota_lead_ranking='$call_quota_lead_ranking',enable_second_script='$enable_second_script',enable_first_webform='$enable_first_webform',recording_buttons='$recording_buttons',opensips_cid_name='$opensips_cid_name',require_password_length='$require_password_length',user_account_emails='$user_account_emails',outbound_cid_any='$outbound_cid_any',entries_per_page='$entries_per_page',browser_call_alerts='$browser_call_alerts',queuemetrics_pausereason='$queuemetrics_pausereason',inbound_answer_config='$inbound_answer_config',enable_international_dncs='$enable_international_dncs',web_loader_phone_strip='$web_loader_phone_strip',manual_dial_phone_strip='$manual_dial_phone_strip',daily_call_count_limit='$daily_call_count_limit',allow_shared_dial='$allow_shared_dial',agent_search_method='$agent_search_method',phone_defaults_container='$phone_defaults_container',qc_claim_limit='$qc_claim_limit',qc_expire_days='$qc_expire_days',two_factor_auth_hours='$two_factor_auth_hours',two_factor_container='$two_factor_container',agent_hidden_sound='$agent_hidden_sound',agent_hidden_sound_volume='$agent_hidden_sound_volume',agent_hidden_sound_seconds='$agent_hidden_sound_seconds',agent_screen_timer='$agent_screen_timer',call_limit_24hour='$call_limit_24hour',allowed_sip_stacks='$allowed_sip_stacks',agent_hide_hangup='$agent_hide_hangup',allow_web_debug='$allow_web_debug',max_logged_in_agents='$max_logged_in_agents',user_codes_admin='$user_codes_admin',login_kickall='$login_kickall',abandon_check_queue='$abandon_check_queue',agent_notifications='$agent_notifications'$custom_dialplanSQL;"; + $stmt="UPDATE system_settings set use_non_latin='$use_non_latin',webroot_writable='$webroot_writable',enable_queuemetrics_logging='$enable_queuemetrics_logging',queuemetrics_server_ip='$queuemetrics_server_ip',queuemetrics_dbname='$queuemetrics_dbname',queuemetrics_login='$queuemetrics_login',queuemetrics_pass='$queuemetrics_pass',queuemetrics_url='" . mysqli_real_escape_string($link, $queuemetrics_url) . "',queuemetrics_log_id='$queuemetrics_log_id',queuemetrics_eq_prepend='$queuemetrics_eq_prepend',vicidial_agent_disable='$vicidial_agent_disable',allow_sipsak_messages='$allow_sipsak_messages',admin_home_url='" . mysqli_real_escape_string($link, $admin_home_url) . "',enable_agc_xfer_log='$enable_agc_xfer_log',timeclock_end_of_day='$timeclock_end_of_day',vdc_header_date_format='$vdc_header_date_format',vdc_customer_date_format='$vdc_customer_date_format',vdc_header_phone_format='$vdc_header_phone_format',vdc_agent_api_active='$vdc_agent_api_active',enable_vtiger_integration='$enable_vtiger_integration',vtiger_server_ip='$vtiger_server_ip',vtiger_dbname='$vtiger_dbname',vtiger_login='$vtiger_login',vtiger_pass='$vtiger_pass',vtiger_url='" . mysqli_real_escape_string($link, $vtiger_url) . "',qc_features_active='$qc_features_active',outbound_autodial_active='$outbound_autodial_active',outbound_calls_per_second='$outbound_calls_per_second',enable_tts_integration='$enable_tts_integration',agentonly_callback_campaign_lock='$agentonly_callback_campaign_lock',sounds_central_control_active='$sounds_central_control_active',sounds_web_server='$sounds_web_server',sounds_web_directory='$sounds_web_directory',active_voicemail_server='$active_voicemail_server',auto_dial_limit='$auto_dial_limit',user_territories_active='$user_territories_active',allow_custom_dialplan='$allow_custom_dialplan',enable_second_webform='$enable_second_webform',default_webphone='$default_webphone',default_external_server_ip='$default_external_server_ip',webphone_url='" . mysqli_real_escape_string($link, $webphone_url) . "',enable_agc_dispo_log='$enable_agc_dispo_log',queuemetrics_loginout='$queuemetrics_loginout',callcard_enabled='$callcard_enabled',queuemetrics_callstatus='$queuemetrics_callstatus',default_codecs='$default_codecs',admin_web_directory='$admin_web_directory',label_title='$label_title',label_first_name='$label_first_name',label_middle_initial='$label_middle_initial',label_last_name='$label_last_name',label_address1='$label_address1',label_address2='$label_address2',label_address3='$label_address3',label_city='$label_city',label_state='$label_state',label_province='$label_province',label_postal_code='$label_postal_code',label_vendor_lead_code='$label_vendor_lead_code',label_gender='$label_gender',label_phone_number='$label_phone_number',label_phone_code='$label_phone_code',label_alt_phone='$label_alt_phone',label_security_phrase='$label_security_phrase',label_email='$label_email',label_comments='$label_comments',label_lead_id='$label_lead_id',label_list_id='$label_list_id',label_entry_date='$label_entry_date',label_gmt_offset_now='$label_gmt_offset_now',label_source_id='$label_source_id',label_called_since_last_reset='$label_called_since_last_reset',label_status='$label_status',label_user='$label_user',label_date_of_birth='$label_date_of_birth',label_country_code='$label_country_code',label_last_local_call_time='$label_last_local_call_time',label_called_count='$label_called_count',label_rank='$label_rank',label_owner='$label_owner',label_entry_list_id='$label_entry_list_id',custom_fields_enabled='$custom_fields_enabled',slave_db_server='$slave_db_server',reports_use_slave_db='$reports_use_slave_db'$custom_reports_slave_SQL,webphone_systemkey='$webphone_systemkey',first_login_trigger='$first_login_trigger',default_phone_registration_password='$default_phone_registration_password',default_phone_login_password='$default_phone_login_password',default_server_password='$default_server_password',admin_modify_refresh='$admin_modify_refresh',nocache_admin='$nocache_admin',generate_cross_server_exten='$generate_cross_server_exten',queuemetrics_addmember_enabled='$queuemetrics_addmember_enabled',queuemetrics_dispo_pause='$queuemetrics_dispo_pause',label_hide_field_logs='$label_hide_field_logs',queuemetrics_pe_phone_append='$queuemetrics_pe_phone_append',test_campaign_calls='$test_campaign_calls',agents_calls_reset='$agents_calls_reset',default_voicemail_timezone='$default_voicemail_timezone',default_local_gmt='$default_local_gmt',noanswer_log='$noanswer_log',alt_log_server_ip='$alt_log_server_ip',alt_log_dbname='$alt_log_dbname',alt_log_login='$alt_log_login',alt_log_pass='$alt_log_pass',tables_use_alt_log_db='$tables_use_alt_log_db',did_agent_log='$did_agent_log',campaign_cid_areacodes_enabled='$campaign_cid_areacodes_enabled',pllb_grouping_limit='$pllb_grouping_limit',did_ra_extensions_enabled='$did_ra_extensions_enabled',expanded_list_stats='$expanded_list_stats',contacts_enabled='$contacts_enabled',call_menu_qualify_enabled='$call_menu_qualify_enabled',admin_list_counts='$admin_list_counts',allow_voicemail_greeting='$allow_voicemail_greeting',queuemetrics_socket='$queuemetrics_socket',queuemetrics_socket_url='$queuemetrics_socket_url',enhanced_disconnect_logging='$enhanced_disconnect_logging',allow_emails='$allow_emails',level_8_disable_add='$level_8_disable_add',queuemetrics_record_hold='$queuemetrics_record_hold',country_code_list_stats='$country_code_list_stats',queuemetrics_pause_type='$queuemetrics_pause_type',frozen_server_call_clear='$frozen_server_call_clear',callback_time_24hour='$callback_time_24hour',enable_languages='$enable_languages',language_method='$language_method',meetme_enter_login_filename='$meetme_enter_login_filename',meetme_enter_leave3way_filename='$meetme_enter_leave3way_filename',enable_did_entry_list_id='$enable_did_entry_list_id',enable_third_webform='$enable_third_webform',allow_chats='$allow_chats',chat_url='" . mysqli_real_escape_string($link, $chat_url) . "',chat_timeout='$chat_timeout',agent_debug_logging='$agent_debug_logging',default_language='$default_language',agent_whisper_enabled='$agent_whisper_enabled',user_hide_realtime_enabled='$user_hide_realtime_enabled',usacan_phone_dialcode_fix='$usacan_phone_dialcode_fix',cache_carrier_stats_realtime='$cache_carrier_stats_realtime',log_recording_access='$log_recording_access',report_default_format='$report_default_format',alt_ivr_logging='$alt_ivr_logging',default_phone_code='$default_phone_code',admin_row_click='$admin_row_click',admin_screen_colors='$admin_screen_colors',ofcom_uk_drop_calc='$ofcom_uk_drop_calc',agent_screen_colors='$agent_screen_colors',script_remove_js='$script_remove_js',manual_auto_next='$manual_auto_next',user_new_lead_limit='$user_new_lead_limit',agent_xfer_park_3way='$agent_xfer_park_3way',agent_soundboards='$agent_soundboards',web_loader_phone_length='$web_loader_phone_length',agent_script='$agent_script',agent_chat_screen_colors='$agent_chat_screen_colors',enable_auto_reports='$enable_auto_reports',enable_pause_code_limits='$enable_pause_code_limits',enable_drop_lists='$enable_drop_lists',allow_ip_lists='$allow_ip_lists',system_ip_blacklist='$system_ip_blacklist',agent_push_events='$agent_push_events',agent_push_url='$agent_push_url',hide_inactive_lists='$hide_inactive_lists',allow_manage_active_lists='$allow_manage_active_lists',expired_lists_inactive='$expired_lists_inactive',did_system_filter='$did_system_filter',anyone_callback_inactive_lists='$anyone_callback_inactive_lists',enable_gdpr_download_deletion='$enable_gdpr_download_deletion',source_id_display='$source_id_display',agent_logout_link='$agent_logout_link',manual_dial_validation='$manual_dial_validation',mute_recordings='$mute_recordings',user_admin_redirect='$user_admin_redirect',list_status_modification_confirmation='$list_status_modification_confirmation',sip_event_logging='$sip_event_logging',call_quota_lead_ranking='$call_quota_lead_ranking',enable_second_script='$enable_second_script',enable_first_webform='$enable_first_webform',recording_buttons='$recording_buttons',opensips_cid_name='$opensips_cid_name',require_password_length='$require_password_length',user_account_emails='$user_account_emails',outbound_cid_any='$outbound_cid_any',entries_per_page='$entries_per_page',browser_call_alerts='$browser_call_alerts',queuemetrics_pausereason='$queuemetrics_pausereason',inbound_answer_config='$inbound_answer_config',enable_international_dncs='$enable_international_dncs',web_loader_phone_strip='$web_loader_phone_strip',manual_dial_phone_strip='$manual_dial_phone_strip',daily_call_count_limit='$daily_call_count_limit',allow_shared_dial='$allow_shared_dial',agent_search_method='$agent_search_method',phone_defaults_container='$phone_defaults_container',qc_claim_limit='$qc_claim_limit',qc_expire_days='$qc_expire_days',two_factor_auth_hours='$two_factor_auth_hours',two_factor_container='$two_factor_container',agent_hidden_sound='$agent_hidden_sound',agent_hidden_sound_volume='$agent_hidden_sound_volume',agent_hidden_sound_seconds='$agent_hidden_sound_seconds',agent_screen_timer='$agent_screen_timer',call_limit_24hour='$call_limit_24hour',allowed_sip_stacks='$allowed_sip_stacks',agent_hide_hangup='$agent_hide_hangup',allow_web_debug='$allow_web_debug',max_logged_in_agents='$max_logged_in_agents',user_codes_admin='$user_codes_admin',login_kickall='$login_kickall',abandon_check_queue='$abandon_check_queue',agent_notifications='$agent_notifications',demographic_quotas='$demographic_quotas',log_latency_gaps='$log_latency_gaps'$custom_dialplanSQL;"; $rslt=mysql_to_mysqli($stmt, $link); $update_main_rows=mysqli_affected_rows($link); if ($DB) {echo "$update_main_rows|$stmt|\n";} @@ -25836,7 +25868,7 @@ if ($ADD==31) $enable_vtiger_integration_LU = $row[0]; $vtiger_url_LU = $row[1]; - $stmt="SELECT campaign_id,campaign_name,active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,xfer_groups,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_shift_id,qc_get_record_launch,qc_show_recording,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_third_audio_file,survey_third_status,survey_third_exten,survey_fourth_digit,survey_fourth_audio_file,survey_fourth_status,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,campaign_calldate,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,in_group_dial,in_group_dial_select,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,allow_chats,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,call_quota_process_running,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti from vicidial_campaigns where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;"; + $stmt="SELECT campaign_id,campaign_name,active,dial_status_a,dial_status_b,dial_status_c,dial_status_d,dial_status_e,lead_order,park_ext,park_file_name,web_form_address,allow_closers,hopper_level,auto_dial_level,next_agent_call,local_call_time,voicemail_ext,dial_timeout,dial_prefix,campaign_cid,campaign_vdad_exten,campaign_rec_exten,campaign_recording,campaign_rec_filename,campaign_script,get_call_launch,am_message_exten,amd_send_to_vmx,xferconf_a_dtmf,xferconf_a_number,xferconf_b_dtmf,xferconf_b_number,alt_number_dialing,scheduled_callbacks,lead_filter_id,drop_call_seconds,drop_action,safe_harbor_exten,display_dialable_count,wrapup_seconds,wrapup_message,closer_campaigns,use_internal_dnc,allcalls_delay,omit_phone_code,dial_method,available_only_ratio_tally,adaptive_dropped_percentage,adaptive_maximum_level,adaptive_latest_server_time,adaptive_intensity,adaptive_dl_diff_target,concurrent_transfers,auto_alt_dial,auto_alt_dial_statuses,agent_pause_codes_active,campaign_description,campaign_changedate,campaign_stats_refresh,campaign_logindate,dial_statuses,disable_alter_custdata,no_hopper_leads_logins,list_order_mix,campaign_allow_inbound,manual_dial_list_id,default_xfer_group,xfer_groups,queue_priority,drop_inbound_group,qc_enabled,qc_statuses,qc_lists,qc_shift_id,qc_get_record_launch,qc_show_recording,qc_web_form_address,qc_script,survey_first_audio_file,survey_dtmf_digits,survey_ni_digit,survey_opt_in_audio_file,survey_ni_audio_file,survey_method,survey_no_response_action,survey_ni_status,survey_response_digit_map,survey_xfer_exten,survey_camp_record_dir,disable_alter_custphone,display_queue_count,manual_dial_filter,agent_clipboard_copy,agent_extended_alt_dial,use_campaign_dnc,three_way_call_cid,three_way_dial_prefix,web_form_target,vtiger_search_category,vtiger_create_call_record,vtiger_create_lead_record,vtiger_screen_login,cpd_amd_action,agent_allow_group_alias,default_group_alias,vtiger_search_dead,vtiger_status_call,survey_third_digit,survey_third_audio_file,survey_third_status,survey_third_exten,survey_fourth_digit,survey_fourth_audio_file,survey_fourth_status,survey_fourth_exten,drop_lockout_time,quick_transfer_button,prepopulate_transfer_preset,drop_rate_group,view_calls_in_queue,view_calls_in_queue_launch,grab_calls_in_queue,call_requeue_button,pause_after_each_call,no_hopper_dialing,agent_dial_owner_only,agent_display_dialable_leads,web_form_address_two,waitforsilence_options,agent_select_territories,campaign_calldate,crm_popup_login,crm_login_address,timer_action,timer_action_message,timer_action_seconds,start_call_url,dispo_call_url,xferconf_c_number,xferconf_d_number,xferconf_e_number,use_custom_cid,scheduled_callbacks_alert,queuemetrics_callstatus_override,extension_appended_cidname,scheduled_callbacks_count,manual_dial_override,blind_monitor_warning,blind_monitor_message,blind_monitor_filename,inbound_queue_no_dial,timer_action_destination,enable_xfer_presets,hide_xfer_number_to_dial,manual_dial_prefix,customer_3way_hangup_logging,customer_3way_hangup_seconds,customer_3way_hangup_action,ivr_park_call,ivr_park_call_agi,manual_preview_dial,realtime_agent_time_stats,use_auto_hopper,auto_hopper_multi,auto_trim_hopper,api_manual_dial,manual_dial_call_time_check,display_leads_count,lead_order_randomize,lead_order_secondary,per_call_notes,my_callback_option,agent_lead_search,agent_lead_search_method,queuemetrics_phone_environment,auto_pause_precall,auto_resume_precall,auto_pause_precall_code,manual_dial_cid,post_phone_time_diff_alert,custom_3way_button_transfer,available_only_tally_threshold,available_only_tally_threshold_agents,dial_level_threshold,dial_level_threshold_agents,safe_harbor_audio,safe_harbor_menu_id,survey_menu_id,callback_days_limit,dl_diff_target_method,disable_dispo_screen,disable_dispo_status,screen_labels,status_display_fields,na_call_url,survey_recording,pllb_grouping,pllb_grouping_limit,call_count_limit,call_count_target,callback_hours_block,callback_list_calltime,user_group,hopper_vlc_dup_check,in_group_dial,in_group_dial_select,safe_harbor_audio_field,pause_after_next_call,owner_populate,use_other_campaign_dnc,allow_emails,amd_inbound_group,amd_callmenu,survey_wait_sec,manual_dial_lead_id,dead_max,dispo_max,pause_max,dead_max_dispo,dispo_max_dispo,max_inbound_calls,manual_dial_search_checkbox,hide_call_log_info,timer_alt_seconds,wrapup_bypass,wrapup_after_hotkey,callback_active_limit,callback_active_limit_override,allow_chats,comments_all_tabs,comments_dispo_screen,comments_callback_screen,qc_comment_history,show_previous_callback,clear_script,cpd_unknown_action,manual_dial_search_filter,web_form_address_three,manual_dial_override_field,status_display_ingroup,customer_gone_seconds,agent_display_fields,am_message_wildcards,manual_dial_timeout,routing_initiated_recordings,manual_dial_hopper_check,callback_useronly_move_minutes,ofcom_uk_drop_calc,manual_auto_next,manual_auto_show,allow_required_fields,dead_to_dispo,agent_xfer_validation,ready_max_logout,callback_display_days,three_way_record_stop,hangup_xfer_record_start,scheduled_callbacks_email_alert,max_inbound_calls_outcome,manual_auto_next_options,agent_screen_time_display,next_dial_my_callbacks,inbound_no_agents_no_dial_container,inbound_no_agents_no_dial_threshold,cid_group_id,pause_max_dispo,script_top_dispo,dead_trigger_seconds,dead_trigger_action,dead_trigger_repeat,dead_trigger_filename,dead_trigger_url,scheduled_callbacks_force_dial,scheduled_callbacks_auto_reschedule,scheduled_callbacks_timezones_container,three_way_volume_buttons,callback_dnc,manual_dial_validation,mute_recordings,auto_active_list_new,call_quota_lead_ranking,call_quota_process_running,sip_event_logging,campaign_script_two,leave_vm_no_dispo,leave_vm_message_group_id,dial_timeout_lead_container,amd_type,vmm_daily_limit,opensips_cid_name,amd_agent_route_options,browser_alert_sound,browser_alert_volume,three_way_record_stop_exception,pause_max_exceptions,hopper_drop_run_trigger,daily_call_count_limit,daily_limit_manual,transfer_button_launch,shared_dial_rank,agent_search_method,qc_scorecard_id,qc_statuses_id,clear_form,leave_3way_start_recording,leave_3way_start_recording_exception,calls_waiting_vl_one,calls_waiting_vl_two,calls_inqueue_count_one,calls_inqueue_count_two,in_man_dial_next_ready_seconds,in_man_dial_next_ready_seconds_override,transfer_no_dispo,call_limit_24hour_method,call_limit_24hour_scope,call_limit_24hour,call_limit_24hour_override,cid_group_id_two,incall_tally_threshold_seconds,auto_alt_threshold,pause_max_url,agent_hide_hangup,ig_xfer_list_sort,script_tab_frame_size,max_logged_in_agents,user_group_script,agent_hangup_route,agent_hangup_value,agent_hangup_ig_override,show_confetti,demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets,demographic_quotas_last_rerank from vicidial_campaigns where campaign_id='$campaign_id' $LOGallowed_campaignsSQL;"; $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $campaign_name = $row[1]; @@ -26169,6 +26201,11 @@ if ($ADD==31) $agent_hangup_value=$row[328]; $agent_hangup_ig_override=$row[329]; $show_confetti=$row[330]; + $demographic_quotas=$row[331]; + $demographic_quotas_container=$row[332]; + $demographic_quotas_rerank=$row[333]; + $demographic_quotas_list_resets=$row[334]; + $demographic_quotas_last_rerank=$row[335]; if (preg_match('/DISABLED/', $list_order_mix)) {$DEFlistDISABLE = ''; $DEFstatusDISABLED=0;} @@ -26815,9 +26852,9 @@ if ($ADD==31) $o++; } - echo "
"._QXZ("Auto Active List New").": $NWB#campaigns-auto_active_list_new$NWE
"._QXZ("Auto Active List New").": $NWB#campaigns-auto_active_list_new$NWE
"; + echo "
"; if ($cqlr_selected > 0) {echo ""._QXZ("Call Quota Lead Ranking")."";} else @@ -26826,8 +26863,66 @@ if ($ADD==31) } else { - echo "
"._QXZ("Demographic Quotas").": $NWB#campaigns-demographic_quotas$NWE $DQdebug
"._QXZ("All Demographic Quota goals have been filled for this campaign")."
"._QXZ("Demographic Quotas Force Re-Rank").": $NWB#campaigns-demographic_quotas_rerank$NWE   "._QXZ("last re-rank").": $demographic_quotas_last_rerank
"._QXZ("Demographic Quotas List Resets").": $NWB#campaigns-demographic_quotas_list_resets$NWE
"; + if ($cqlr_selected > 0) + {echo ""._QXZ("Demographic Quotas Container")."";} + else + {echo _QXZ("Demographic Quotas Container");} + echo ": $NWB#campaigns-demographic_quotas_container$NWE
"._QXZ("Hopper Drop-Run Trigger").":   "._QXZ("All Drops").": $NWB#campaigns-hopper_drop_run_trigger$NWE
"._QXZ("Drop Lockout Time").": $NWB#campaigns-drop_lockout_time$NWE


\n"; - if (preg_match("/WEEKDAY_TIMERANGE_SECONDS|CALL_QUOTA|CALL_LIMITS_OVERRIDE|SIP_EVENT_ACTIONS|CALLS_IN_QUEUE_COUNT|TIMEZONE_LIST|PHONE_NUMBERS|DIAL_TIMEOUTS|INGROUP_LIST|PAUSE_CODES_LIST/",$container_type)) + if (preg_match("/WEEKDAY_TIMERANGE_SECONDS|CALL_QUOTA|CALL_LIMITS_OVERRIDE|SIP_EVENT_ACTIONS|CALLS_IN_QUEUE_COUNT|TIMEZONE_LIST|PHONE_NUMBERS|DIAL_TIMEOUTS|INGROUP_LIST|PAUSE_CODES_LIST|DEMOGRAPHIC_QUOTAS/",$container_type)) { echo ""._QXZ("CAMPAIGNS USING THIS SETTINGS CONTAINER").":
\n"; echo "\n"; - $stmt="SELECT campaign_id,campaign_name from vicidial_campaigns where ( (in_man_dial_next_ready_seconds_override='$container_id') or (pause_max_exceptions='$container_id') or (call_quota_lead_ranking='$container_id') or (call_limit_24hour_override='$container_id') or (inbound_no_agents_no_dial_container='$container_id') or (dial_timeout_lead_container='$container_id') or (three_way_record_stop_exception='$container_id') or (leave_3way_start_recording_exception='$container_id') or (scheduled_callbacks_timezones_container='$container_id') or (in_man_dial_next_ready_seconds_override='$container_id') or (sip_event_logging='$container_id') or (calls_inqueue_count_one='$container_id') or (calls_inqueue_count_two='$container_id') ) $LOGallowed_campaignsSQL;"; + $stmt="SELECT campaign_id,campaign_name from vicidial_campaigns where ( (in_man_dial_next_ready_seconds_override='$container_id') or (pause_max_exceptions='$container_id') or (call_quota_lead_ranking='$container_id') or (call_limit_24hour_override='$container_id') or (inbound_no_agents_no_dial_container='$container_id') or (dial_timeout_lead_container='$container_id') or (three_way_record_stop_exception='$container_id') or (leave_3way_start_recording_exception='$container_id') or (scheduled_callbacks_timezones_container='$container_id') or (in_man_dial_next_ready_seconds_override='$container_id') or (sip_event_logging='$container_id') or (calls_inqueue_count_one='$container_id') or (calls_inqueue_count_two='$container_id') or (demographic_quotas_container='$container_id') ) $LOGallowed_campaignsSQL;"; $rslt=mysql_to_mysqli($stmt, $link); $ig_to_print = mysqli_num_rows($rslt); if ($DB > 0) {echo "$ig_to_print|$stmt
\n";} @@ -42786,7 +42880,7 @@ if ($ADD==311111111111111) $ALLagent_count = $rowx[2]; } - $stmt="SELECT version,install_date,use_non_latin,webroot_writable,enable_queuemetrics_logging,queuemetrics_server_ip,queuemetrics_dbname,queuemetrics_login,queuemetrics_pass,queuemetrics_url,queuemetrics_log_id,queuemetrics_eq_prepend,vicidial_agent_disable,allow_sipsak_messages,admin_home_url,enable_agc_xfer_log,db_schema_version,auto_user_add_value,timeclock_end_of_day,timeclock_last_reset_date,vdc_header_date_format,vdc_customer_date_format,vdc_header_phone_format,vdc_agent_api_active,qc_last_pull_time,enable_vtiger_integration,vtiger_server_ip,vtiger_dbname,vtiger_login,vtiger_pass,vtiger_url,qc_features_active,outbound_autodial_active,outbound_calls_per_second,enable_tts_integration,agentonly_callback_campaign_lock,sounds_central_control_active,sounds_web_server,sounds_web_directory,active_voicemail_server,auto_dial_limit,user_territories_active,allow_custom_dialplan,db_schema_update_date,enable_second_webform,default_webphone,default_external_server_ip,webphone_url,enable_agc_dispo_log,custom_dialplan_entry,queuemetrics_loginout,callcard_enabled,queuemetrics_callstatus,default_codecs,admin_web_directory,label_title,label_first_name,label_middle_initial,label_last_name,label_address1,label_address2,label_address3,label_city,label_state,label_province,label_postal_code,label_vendor_lead_code,label_gender,label_phone_number,label_phone_code,label_alt_phone,label_security_phrase,label_email,label_comments,custom_fields_enabled,slave_db_server,reports_use_slave_db,webphone_systemkey,first_login_trigger,default_phone_registration_password,default_phone_login_password,default_server_password,admin_modify_refresh,nocache_admin,generate_cross_server_exten,queuemetrics_addmember_enabled,queuemetrics_dispo_pause,label_hide_field_logs,queuemetrics_pe_phone_append,test_campaign_calls,agents_calls_reset,default_voicemail_timezone,default_local_gmt,noanswer_log,alt_log_server_ip,alt_log_dbname,alt_log_login,alt_log_pass,tables_use_alt_log_db,did_agent_log,campaign_cid_areacodes_enabled,pllb_grouping_limit,did_ra_extensions_enabled,expanded_list_stats,contacts_enabled,call_menu_qualify_enabled,admin_list_counts,allow_voicemail_greeting,svn_revision,queuemetrics_socket,queuemetrics_socket_url,enhanced_disconnect_logging,allow_emails,level_8_disable_add,pass_hash_enabled,pass_key,pass_cost,disable_auto_dial,queuemetrics_record_hold,country_code_list_stats,reload_timestamp,queuemetrics_pause_type,frozen_server_call_clear,callback_time_24hour,allow_chats,chat_url,chat_timeout,enable_languages,language_method,meetme_enter_login_filename,meetme_enter_leave3way_filename,enable_did_entry_list_id,enable_third_webform,agent_debug_logging,default_language,agent_whisper_enabled,user_hide_realtime_enabled,usacan_phone_dialcode_fix,cache_carrier_stats_realtime,oldest_logs_date,log_recording_access,report_default_format,alt_ivr_logging,default_phone_code,admin_row_click,admin_screen_colors,ofcom_uk_drop_calc,agent_screen_colors,script_remove_js,manual_auto_next,user_new_lead_limit,agent_xfer_park_3way,rec_prompt_count,agent_soundboards,web_loader_phone_length,agent_script,agent_chat_screen_colors,enable_auto_reports,enable_pause_code_limits,enable_drop_lists,allow_ip_lists,system_ip_blacklist,agent_push_events,agent_push_url,hide_inactive_lists,allow_manage_active_lists,expired_lists_inactive,did_system_filter,anyone_callback_inactive_lists,enable_gdpr_download_deletion,source_id_display,agent_logout_link,manual_dial_validation,mute_recordings,user_admin_redirect,list_status_modification_confirmation,sip_event_logging,call_quota_lead_ranking,enable_second_script,enable_first_webform,recording_buttons,opensips_cid_name,require_password_length,user_account_emails,outbound_cid_any,entries_per_page,browser_call_alerts,queuemetrics_pausereason,inbound_answer_config,enable_international_dncs,web_loader_phone_strip,manual_dial_phone_strip,daily_call_count_limit,allow_shared_dial,agent_search_method,phone_defaults_container,qc_claim_limit,qc_expire_days,two_factor_auth_hours,two_factor_container,agent_hidden_sound,agent_hidden_sound_volume,agent_hidden_sound_seconds,agent_screen_timer,label_lead_id,label_list_id,label_entry_date,label_gmt_offset_now,label_source_id,label_called_since_last_reset,label_status,label_user,label_date_of_birth,label_country_code,label_last_local_call_time,label_called_count,label_rank,label_owner,label_entry_list_id,call_limit_24hour,allowed_sip_stacks,agent_hide_hangup,allow_web_debug,max_logged_in_agents,user_codes_admin,login_kickall,abandon_check_queue,agent_notifications from system_settings;"; + $stmt="SELECT version,install_date,use_non_latin,webroot_writable,enable_queuemetrics_logging,queuemetrics_server_ip,queuemetrics_dbname,queuemetrics_login,queuemetrics_pass,queuemetrics_url,queuemetrics_log_id,queuemetrics_eq_prepend,vicidial_agent_disable,allow_sipsak_messages,admin_home_url,enable_agc_xfer_log,db_schema_version,auto_user_add_value,timeclock_end_of_day,timeclock_last_reset_date,vdc_header_date_format,vdc_customer_date_format,vdc_header_phone_format,vdc_agent_api_active,qc_last_pull_time,enable_vtiger_integration,vtiger_server_ip,vtiger_dbname,vtiger_login,vtiger_pass,vtiger_url,qc_features_active,outbound_autodial_active,outbound_calls_per_second,enable_tts_integration,agentonly_callback_campaign_lock,sounds_central_control_active,sounds_web_server,sounds_web_directory,active_voicemail_server,auto_dial_limit,user_territories_active,allow_custom_dialplan,db_schema_update_date,enable_second_webform,default_webphone,default_external_server_ip,webphone_url,enable_agc_dispo_log,custom_dialplan_entry,queuemetrics_loginout,callcard_enabled,queuemetrics_callstatus,default_codecs,admin_web_directory,label_title,label_first_name,label_middle_initial,label_last_name,label_address1,label_address2,label_address3,label_city,label_state,label_province,label_postal_code,label_vendor_lead_code,label_gender,label_phone_number,label_phone_code,label_alt_phone,label_security_phrase,label_email,label_comments,custom_fields_enabled,slave_db_server,reports_use_slave_db,webphone_systemkey,first_login_trigger,default_phone_registration_password,default_phone_login_password,default_server_password,admin_modify_refresh,nocache_admin,generate_cross_server_exten,queuemetrics_addmember_enabled,queuemetrics_dispo_pause,label_hide_field_logs,queuemetrics_pe_phone_append,test_campaign_calls,agents_calls_reset,default_voicemail_timezone,default_local_gmt,noanswer_log,alt_log_server_ip,alt_log_dbname,alt_log_login,alt_log_pass,tables_use_alt_log_db,did_agent_log,campaign_cid_areacodes_enabled,pllb_grouping_limit,did_ra_extensions_enabled,expanded_list_stats,contacts_enabled,call_menu_qualify_enabled,admin_list_counts,allow_voicemail_greeting,svn_revision,queuemetrics_socket,queuemetrics_socket_url,enhanced_disconnect_logging,allow_emails,level_8_disable_add,pass_hash_enabled,pass_key,pass_cost,disable_auto_dial,queuemetrics_record_hold,country_code_list_stats,reload_timestamp,queuemetrics_pause_type,frozen_server_call_clear,callback_time_24hour,allow_chats,chat_url,chat_timeout,enable_languages,language_method,meetme_enter_login_filename,meetme_enter_leave3way_filename,enable_did_entry_list_id,enable_third_webform,agent_debug_logging,default_language,agent_whisper_enabled,user_hide_realtime_enabled,usacan_phone_dialcode_fix,cache_carrier_stats_realtime,oldest_logs_date,log_recording_access,report_default_format,alt_ivr_logging,default_phone_code,admin_row_click,admin_screen_colors,ofcom_uk_drop_calc,agent_screen_colors,script_remove_js,manual_auto_next,user_new_lead_limit,agent_xfer_park_3way,rec_prompt_count,agent_soundboards,web_loader_phone_length,agent_script,agent_chat_screen_colors,enable_auto_reports,enable_pause_code_limits,enable_drop_lists,allow_ip_lists,system_ip_blacklist,agent_push_events,agent_push_url,hide_inactive_lists,allow_manage_active_lists,expired_lists_inactive,did_system_filter,anyone_callback_inactive_lists,enable_gdpr_download_deletion,source_id_display,agent_logout_link,manual_dial_validation,mute_recordings,user_admin_redirect,list_status_modification_confirmation,sip_event_logging,call_quota_lead_ranking,enable_second_script,enable_first_webform,recording_buttons,opensips_cid_name,require_password_length,user_account_emails,outbound_cid_any,entries_per_page,browser_call_alerts,queuemetrics_pausereason,inbound_answer_config,enable_international_dncs,web_loader_phone_strip,manual_dial_phone_strip,daily_call_count_limit,allow_shared_dial,agent_search_method,phone_defaults_container,qc_claim_limit,qc_expire_days,two_factor_auth_hours,two_factor_container,agent_hidden_sound,agent_hidden_sound_volume,agent_hidden_sound_seconds,agent_screen_timer,label_lead_id,label_list_id,label_entry_date,label_gmt_offset_now,label_source_id,label_called_since_last_reset,label_status,label_user,label_date_of_birth,label_country_code,label_last_local_call_time,label_called_count,label_rank,label_owner,label_entry_list_id,call_limit_24hour,allowed_sip_stacks,agent_hide_hangup,allow_web_debug,max_logged_in_agents,user_codes_admin,login_kickall,abandon_check_queue,agent_notifications,demographic_quotas,log_latency_gaps from system_settings;"; $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $version = $row[0]; @@ -43017,6 +43111,8 @@ if ($ADD==311111111111111) $login_kickall = $row[225]; $abandon_check_queue = $row[226]; $agent_notifications = $row[227]; + $demographic_quotas = $row[228]; + $log_latency_gaps = $row[229]; if ($pass_hash_enabled > 0) {$pass_hash_enabled = 'ENABLED';} else {$pass_hash_enabled = 'DISABLED';} @@ -43431,7 +43527,9 @@ if ($ADD==311111111111111) echo "\n"; - echo "\n"; + echo "\n"; + + echo "\n"; echo "\n"; @@ -43457,6 +43555,8 @@ if ($ADD==311111111111111) echo "\n"; + echo "\n"; + echo "\n"; echo "\n"; @@ -49688,6 +49788,13 @@ if ($ADD==999995) echo ""; + echo ""; + echo "\n"; + echo "\n"; + echo "\n"; + + echo ""; + echo ""; echo "\n"; echo "\n"; @@ -49730,7 +49837,7 @@ if ($ADD==999994) echo "

\n"; echo "
  • "._QXZ("Settings Compare Utility")."\n"; echo "
  • "._QXZ("Campaign Debug Page")."\n"; - echo "
  • "._QXZ("Shared Debug Page")."\n"; + echo "
  • "._QXZ("Shared Debug Page")." | "._QXZ("Demographic Quotas Report")."\n"; echo "
  • "._QXZ("Dial Log Report")."\n"; echo "
  • "._QXZ("Carrier Log Report")."\n"; echo "
  • "._QXZ("Caller ID Log Report")."\n"; @@ -49744,7 +49851,7 @@ if ($ADD==999994) echo "
  • "._QXZ("Export Calls Report Carrier")."\n"; echo "
  • "._QXZ("URL Log Report")."\n"; echo "
  • "._QXZ("Webserver-URL Report")."\n"; - echo "
  • "._QXZ("Agent LAGGED Report")." | "._QXZ("Agent Latency Report")."\n"; + echo "
  • "._QXZ("Agent LAGGED Report")." | "._QXZ("Agent Latency Report")." | "._QXZ("Latency Gaps")."\n"; echo "
  • "._QXZ("User Group Login Report")."\n"; echo "
  • "._QXZ("User Logins Report")."\n"; echo "
  • "._QXZ("Agent Debug Log Report")."\n"; diff --git a/www/vicidial/demographic_quotas_report.php b/www/vicidial/demographic_quotas_report.php new file mode 100644 index 00000000..703d8797 --- /dev/null +++ b/www/vicidial/demographic_quotas_report.php @@ -0,0 +1,464 @@ + LICENSE: AGPLv2 +# +# CHANGES +# 230515-0922 - First build +# + +$startMS = microtime(); + +$report_name='Demographic Quotas Report'; + +require("dbconnect_mysqli.php"); +require("functions.php"); + +$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER']; +$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW']; +$PHP_SELF=$_SERVER['PHP_SELF']; +$PHP_SELF = preg_replace('/\.php.*/i','.php',$PHP_SELF); +if (isset($_GET["DB"])) {$DB=$_GET["DB"];} + elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];} +if (isset($_GET["group"])) {$group=$_GET["group"];} + elseif (isset($_POST["group"])) {$group=$_POST["group"];} +if (isset($_GET["submit"])) {$submit=$_GET["submit"];} + elseif (isset($_POST["submit"])) {$submit=$_POST["submit"];} +if (isset($_GET["SUBMIT"])) {$SUBMIT=$_GET["SUBMIT"];} + elseif (isset($_POST["SUBMIT"])) {$SUBMIT=$_POST["SUBMIT"];} + +$DB=preg_replace("/[^0-9a-zA-Z]/","",$DB); + +$NOW_DATE = date("Y-m-d"); +$NOW_TIME = date("Y-m-d H:i:s"); +$STARTtime = date("U"); + +############################################# +##### START SYSTEM_SETTINGS LOOKUP ##### +$stmt = "SELECT use_non_latin,webroot_writable,outbound_autodial_active,user_territories_active,enable_languages,language_method,allow_shared_dial,allow_web_debug FROM system_settings;"; +$rslt=mysql_to_mysqli($stmt, $link); +#if ($DB) {echo "$stmt\n";} +$qm_conf_ct = mysqli_num_rows($rslt); +if ($qm_conf_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $non_latin = $row[0]; + $webroot_writable = $row[1]; + $SSoutbound_autodial_active = $row[2]; + $user_territories_active = $row[3]; + $SSenable_languages = $row[4]; + $SSlanguage_method = $row[5]; + $SSallow_shared_dial = $row[6]; + $SSallow_web_debug = $row[7]; + } +if ($SSallow_web_debug < 1) {$DB=0;} +##### END SETTINGS LOOKUP ##### +########################################### + +$submit = preg_replace('/[^-_0-9a-zA-Z]/', '', $submit); +$SUBMIT = preg_replace('/[^-_0-9a-zA-Z]/', '', $SUBMIT); + +if ($non_latin < 1) + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW); + $group = preg_replace('/[^-_0-9a-zA-Z]/', '', $group); + } +else + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_PW); + $group = preg_replace('/[^-_0-9\p{L}]/u', '', $group); + } + +$stmt="SELECT selected_language,user_group from vicidial_users where user='$PHP_AUTH_USER';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$sl_ct = mysqli_num_rows($rslt); +if ($sl_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $VUselected_language = $row[0]; + $LOGuser_group = $row[1]; + } + +$auth=0; +$reports_auth=0; +$admin_auth=0; +$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'',1,0); +if ($auth_message == 'GOOD') + {$auth=1;} + +if ($auth > 0) + { + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $admin_auth=$row[0]; + + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $reports_auth=$row[0]; + + if ($reports_auth < 1) + { + $VDdisplayMESSAGE = _QXZ("You are not allowed to view reports"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ( ($reports_auth > 0) and ($admin_auth < 1) ) + { + $ADD=999999; + $reports_only_user=1; + } + } +else + { + $VDdisplayMESSAGE = _QXZ("Login incorrect, please try again"); + if ($auth_message == 'LOCK') + { + $VDdisplayMESSAGE = _QXZ("Too many login attempts, try again in 15 minutes"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ($auth_message == 'IPBLOCK') + { + $VDdisplayMESSAGE = _QXZ("Your IP Address is not allowed") . ": $ip"; + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); + Header("HTTP/1.0 401 Unauthorized"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n"; + exit; + } + +$stmt="SELECT modify_campaigns,user_group from vicidial_users where user='$PHP_AUTH_USER';"; +$rslt=mysql_to_mysqli($stmt, $link); +$row=mysqli_fetch_row($rslt); +$LOGmodify_campaigns = $row[0]; +$LOGuser_group = $row[1]; + +if ($LOGmodify_campaigns < 1) + { + Header ("Content-type: text/html; charset=utf-8"); + echo _QXZ("You do not have permissions for campaign debugging").": |$PHP_AUTH_USER|\n"; + exit; + } + +$stmt="SELECT allowed_campaigns,allowed_reports,admin_viewable_groups,admin_viewable_call_times from vicidial_user_groups where user_group='$LOGuser_group';"; +if ($DB) {$HTML_text.="|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$row=mysqli_fetch_row($rslt); +$LOGallowed_campaigns = $row[0]; +$LOGallowed_reports = $row[1]; +$LOGadmin_viewable_groups = $row[2]; +$LOGadmin_viewable_call_times = $row[3]; + +$LOGallowed_campaignsSQL=''; +$whereLOGallowed_campaignsSQL=''; +if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) ) + { + $rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns); + $rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL); + $LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')"; + $whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')"; + } +$regexLOGallowed_campaigns = " $LOGallowed_campaigns "; + +if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) ) + { + Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); + Header("HTTP/1.0 401 Unauthorized"); + echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n"; + exit; + } + + +##### BEGIN log visit to the vicidial_report_log table ##### +$LOGip = getenv("REMOTE_ADDR"); +$LOGbrowser = getenv("HTTP_USER_AGENT"); +$LOGscript_name = getenv("SCRIPT_NAME"); +$LOGserver_name = getenv("SERVER_NAME"); +$LOGserver_port = getenv("SERVER_PORT"); +$LOGrequest_uri = getenv("REQUEST_URI"); +$LOGhttp_referer = getenv("HTTP_REFERER"); +$LOGbrowser=preg_replace("/\'|\"|\\\\/","",$LOGbrowser); +$LOGrequest_uri=preg_replace("/\'|\"|\\\\/","",$LOGrequest_uri); +$LOGhttp_referer=preg_replace("/\'|\"|\\\\/","",$LOGhttp_referer); +if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';} + else {$HTTPprotocol = 'http://';} +if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';} +else {$LOGserver_port = ":$LOGserver_port";} +$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri"; + +$LOGhostname = php_uname('n'); +if (strlen($LOGhostname)<1) {$LOGhostname='X';} +if (strlen($LOGserver_name)<1) {$LOGserver_name='X';} + +$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;"; +$rslt=mysql_to_mysqli($stmt, $link); +if ($DB) {echo "$stmt\n";} +$webserver_id_ct = mysqli_num_rows($rslt); +if ($webserver_id_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $webserver_id = $row[0]; + } +else + { + ##### insert webserver entry + $stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');"; + if ($DB) {echo "$stmt\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $affected_rows = mysqli_affected_rows($link); + $webserver_id = mysqli_insert_id($link); + } + +$stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name', url='$LOGfull_url', webserver='$webserver_id';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$report_log_id = mysqli_insert_id($link); +##### END log visit to the vicidial_report_log table ##### + +if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) ) + { + mysqli_close($link); + $use_slave_server=1; + $db_source = 'S'; + require("dbconnect_mysqli.php"); + $MAIN.="\n"; + } + +$stmt="select campaign_id,campaign_name from vicidial_campaigns order by campaign_id;"; +$rslt=mysql_to_mysqli($stmt, $link); +if ($DB) {echo "$stmt\n";} +$campaigns_to_print = mysqli_num_rows($rslt); +$i=0; +while ($i < $campaigns_to_print) + { + $row=mysqli_fetch_row($rslt); + $campaign_id[$i] =$row[0]; + $campaign_name[$i] =$row[1]; + $i++; + } + +$NWB = "\"HELP\""; +?> + + + + + +\n"; +echo "\n"; +echo "\n"; +echo ""._QXZ("$report_name")."\n"; +echo ""; + + $short_header=1; + + require("admin_header.php"); + +echo ""._QXZ("$report_name")." $NWB#DQreport$NWE\n"; + +echo "
  • "._QXZ("Enable 24-Hour Called Count Limits").": $NWB#settings-call_limit_24hour$NWE
    "._QXZ("Call Quota Lead Ranking").": $NWB#settings-call_quota_lead_ranking$NWE
    "._QXZ("Call Quota Lead Ranking").": $NWB#settings-call_quota_lead_ranking$NWE
    "._QXZ("Demographic Quotas").": $NWB#settings-demographic_quotas$NWE
    "._QXZ("Enable Custom List Fields").": $NWB#settings-custom_fields_enabled$NWE
    "._QXZ("Agent Screen Debug Logging").": $NWB#settings-agent_debug_logging$NWE
    "._QXZ("Agent Latency Gaps Logging").": $NWB#settings-log_latency_gaps$NWE
    "._QXZ("Agent Screen Timer").": $NWB#settings-agent_screen_timer$NWE
    "._QXZ("Enhanced Disconnect Logging").": $NWB#settings-enhanced_disconnect_logging$NWE
     
    "._QXZ("Dygraphs").": "._QXZ("Copyright").":   "._QXZ("The Dygraphs javascript library was written by Dygraphs Contributors").", © 2023
    "._QXZ("License").":   "._QXZ("Dygraphs is licensed under the")." MIT "._QXZ("open source license")."
    "._QXZ("Source Code").":   "._QXZ("Dygraphs original source code is available at")." "._QXZ("this link").".
     
    "._QXZ("Jquery").": "._QXZ("Copyright").":   "._QXZ("The Jquery javascript library was written by OpenJS Foundation contributors").", © 2023
    "._QXZ("License").":   "._QXZ("Jquery is licensed under the")." MIT "._QXZ("open source license")."
    "; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + $DQgoals_content .= "\n"; + + } + + if (strlen($DQgoals_content) > 10) + { + $DQgoals_header = "
    "._QXZ("Demographic Quota Goals")." -           "._QXZ("Active").": $active_goals_count   "._QXZ("Filled").": $filled_goals_count."; + $DQgoals_header .= "
    "; +echo "
    \n"; +echo "\n"; +echo "\n"; +echo "           "._QXZ("MODIFY")." | "._QXZ("DQ Debug")."\n"; +echo "
    \n\n"; + +echo "
    \n\n";
    +
    +
    +if (!$group)
    +	{
    +	echo "\n\n";
    +	echo _QXZ("PLEASE SELECT A CAMPAIGN ABOVE AND CLICK SUBMIT")."\n";
    +	}
    +
    +else
    +	{
    +	$stmt="select count(*) from vicidial_hopper where campaign_id='" . mysqli_real_escape_string($link, $group) . "';";
    +	$rslt=mysql_to_mysqli($stmt, $link);
    +	if ($DB) {echo "$stmt\n";}
    +	$row=mysqli_fetch_row($rslt);
    +	$TOTALcalls =	sprintf("%10s", $row[0]);
    +
    +
    +	echo _QXZ("Report run time").":                       $NOW_TIME\n
    "; + + + $campaign_activeSTATUS = ""._QXZ("INACTIVE").""; + $stmt="select demographic_quotas,demographic_quotas_container,demographic_quotas_rerank,demographic_quotas_list_resets,campaign_logindate,campaign_calldate,campaign_name,active,dial_statuses,hopper_level,demographic_quotas_last_rerank from vicidial_campaigns where campaign_id='" . mysqli_real_escape_string($link, $group) . "';"; + $rslt=mysql_to_mysqli($stmt, $link); + $camp_ct = mysqli_num_rows($rslt); + if ($DB) {echo "$camp_ct|$stmt|\n";} + if ($camp_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $demographic_quotas = $row[0]; + $demographic_quotas_container = $row[1]; + $demographic_quotas_rerank = $row[2]; + $demographic_quotas_list_resets = $row[3]; + $campaign_logindate = $row[4]; + $campaign_calldate = $row[5]; + $campaign_name = $row[6]; + $campaign_active = $row[7]; + $dial_statuses = $row[8]; + $hopper_level = $row[9]; + $demographic_quotas_last_rerank = $row[10]; + if ($campaign_active == 'Y') + {$campaign_activeSTATUS = ""._QXZ("ACTIVE")."";} + } + + $dialable_leads=0; + $calls_today=0; + $calls_hour=0; + $calls_fivemin=0; + $stmt="select dialable_leads,calls_today,calls_hour,calls_fivemin from vicidial_campaign_stats where campaign_id='" . mysqli_real_escape_string($link, $group) . "';"; + $rslt=mysql_to_mysqli($stmt, $link); + $camp_ct = mysqli_num_rows($rslt); + if ($DB) {echo "$camp_ct|$stmt|\n";} + if ($camp_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $dialable_leads = $row[0]; + $calls_today = $row[1]; + $calls_hour = $row[2]; + $calls_fivemin = $row[3]; + } + + if ($demographic_quotas == 'INVALID') + {$DQdebug = "   "._QXZ("DQ configuration invalid")."";} + if ($demographic_quotas == 'COMPLETE') + {$DQdebug = "   "._QXZ("DQ goals have been met")."$DQdebug";} + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
    "._QXZ("Campaign").": $group - $campaign_name   $campaign_activeSTATUS
    "._QXZ("Total leads in hopper right now").": $TOTALcalls   "._QXZ("level").": $hopper_level   "._QXZ("dialable").": $dialable_leads
    "._QXZ("Dial statuses").": $dial_statuses
    "._QXZ("Campaign last call date").": $campaign_calldate   "._QXZ("calls today").": $calls_today   ("._QXZ("calls, last hour / five-min").": $calls_hour / $calls_fivemin)
    "._QXZ("Campaign last agent login date").": $campaign_logindate
    "._QXZ("Demographic Quotas").": $demographic_quotas   $DQdebug
    "._QXZ("Demographic Quotas Container").": $demographic_quotas_container
    "._QXZ("Demographic Quotas Re-Rank").": $demographic_quotas_rerank   "._QXZ("last re-rank").": $demographic_quotas_last_rerank
    "._QXZ("Demographic Quotas List Resets").": $demographic_quotas_list_resets
    \n"; + + $DQgoals_content=''; + $active_goals_count=0; + $filled_goals_count=0; + $stmt="SELECT quota_field,quota_field_order,quota_value,quota_value_order,quota_goal,quota_count,quota_leads_total,quota_leads_active,quota_status,quota_modify_date from vicidial_demographic_quotas_goals where campaign_id='" . mysqli_real_escape_string($link, $group) . "' and demographic_quotas_container='$demographic_quotas_container' and quota_status!='ARCHIVE' order by quota_field_order,quota_value_order limit 200;"; + $rslt=mysql_to_mysqli($stmt, $link); + if ($DB) {echo "$stmt\n";} + $debugs_to_print = mysqli_num_rows($rslt); + $i=0; + while ($debugs_to_print > $i) + { + $row=mysqli_fetch_row($rslt); + $quota_field = $row[0]; + $quota_field_order = $row[1]; + $quota_value = $row[2]; + $quota_value_order = $row[3]; + $quota_goal = $row[4]; + $quota_count = $row[5]; + $quota_leads_total = $row[6]; + $quota_leads_active = $row[7]; + $quota_status = $row[8]; + $quota_modify_date = $row[9]; + + $i++; + + $row_color='#CCCCCC'; + if (preg_match("/ACTIVE/",$quota_status)) {$row_color='#33FF33'; $active_goals_count++;} + if (preg_match("/FILLED/",$quota_status)) {$row_color='#CC99CC'; $filled_goals_count++;} + $DQgoals_content .= "
    $i$quota_field$quota_field_order$quota_value$quota_value_order$quota_goal$quota_count$quota_leads_total$quota_leads_active$quota_status$quota_modify_date
    "; + $DQgoals_header .= ""; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + $DQgoals_header .= "\n"; + echo "$DQgoals_header$DQgoals_content
    # "._QXZ("Quota Field")." "._QXZ("Field Order")." "._QXZ("Value")." "._QXZ("Value Order")." "._QXZ("Goal")." "._QXZ("Count")." "._QXZ("Leads Total")." "._QXZ("Leads Active")." "._QXZ("Quota Status")." "._QXZ("Last Update")."
    \n"; + } + else + { + echo "

    "._QXZ("No Goals found for this campaign")."."; + } + } + +if ($db_source == 'S') + { + mysqli_close($link); + $use_slave_server=0; + $db_source = 'M'; + require("dbconnect_mysqli.php"); + } + +$endMS = microtime(); +$startMSary = explode(" ",$startMS); +$endMSary = explode(" ",$endMS); +$runS = ($endMSary[0] - $startMSary[0]); +$runM = ($endMSary[1] - $startMSary[1]); +$TOTALrun = ($runS + $runM); + +$stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); + +echo "

    "._QXZ("report run time").": $TOTALrun."; + +?> + + diff --git a/www/vicidial/dygraph.css b/www/vicidial/dygraph.css new file mode 100644 index 00000000..3757069d --- /dev/null +++ b/www/vicidial/dygraph.css @@ -0,0 +1,121 @@ +/** + * Default styles for the dygraphs charting library. + */ + +.dygraph-legend { + position: absolute; + font-size: 14px; + z-index: 10; + width: 250px; /* labelsDivWidth */ + /* + dygraphs determines these based on the presence of chart labels. + It might make more sense to create a wrapper div around the chart proper. + top: 0px; + right: 2px; + */ + background: white; + line-height: normal; + text-align: left; + overflow: hidden; +} + +.dygraph-legend[dir="rtl"] { + text-align: right; +} + +/* styles for a solid line in the legend */ +.dygraph-legend-line { + display: inline-block; + position: relative; + bottom: .5ex; + padding-left: 1em; + height: 1px; + border-bottom-width: 2px; + border-bottom-style: solid; + /* border-bottom-color is set based on the series color */ +} + +/* styles for a dashed line in the legend, e.g. when strokePattern is set */ +.dygraph-legend-dash { + display: inline-block; + position: relative; + bottom: .5ex; + height: 1px; + border-bottom-width: 2px; + border-bottom-style: solid; + /* border-bottom-color is set based on the series color */ + /* margin-right is set based on the stroke pattern */ + /* padding-left is set based on the stroke pattern */ +} + +.dygraph-roller { + position: absolute; + z-index: 10; +} + +/* This class is shared by all annotations, including those with icons */ +.dygraph-annotation { + position: absolute; + z-index: 10; + overflow: hidden; +} + +/* This class only applies to annotations without icons */ +/* Old class name: .dygraphDefaultAnnotation */ +.dygraph-default-annotation { + border: 1px solid black; + background-color: white; + text-align: center; +} + +.dygraph-axis-label { + /* position: absolute; */ + /* font-size: 14px; */ + z-index: 10; + line-height: normal; + overflow: hidden; + color: black; /* replaces old axisLabelColor option */ +} + +.dygraph-axis-label-x { +} + +.dygraph-axis-label-y { +} + +.dygraph-axis-label-y2 { +} + +.dygraph-title { + font-weight: bold; + z-index: 10; + text-align: center; + /* font-size: based on titleHeight option */ +} + +.dygraph-xlabel { + text-align: center; + /* font-size: based on xLabelHeight option */ +} + +/* For y-axis label */ +.dygraph-label-rotate-left { + text-align: center; + /* See http://caniuse.com/#feat=transforms2d */ + transform: rotate(90deg); + -webkit-transform: rotate(90deg); + -moz-transform: rotate(90deg); + -o-transform: rotate(90deg); + -ms-transform: rotate(90deg); +} + +/* For y2-axis label */ +.dygraph-label-rotate-right { + text-align: center; + /* See http://caniuse.com/#feat=transforms2d */ + transform: rotate(-90deg); + -webkit-transform: rotate(-90deg); + -moz-transform: rotate(-90deg); + -o-transform: rotate(-90deg); + -ms-transform: rotate(-90deg); +} diff --git a/www/vicidial/dygraph.js b/www/vicidial/dygraph.js new file mode 100644 index 00000000..edd2f8b2 --- /dev/null +++ b/www/vicidial/dygraph.js @@ -0,0 +1,11502 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Dygraph = f()}})(function(){var define,module,exports;var r=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * Copyright (c) 2011 Paul Felix + * Copyright (c) 2011, 2013 Robert Konigsberg + * Copyright (c) 2013 David Eberlein + * Copyright (c) 2013 Google, Inc. + * Copyright (c) 2014 mirabilos + * Copyright (c) 2015 Petr Shevtsov + * Copyright (c) 2022, 2023 mirabilos + * Deutsche Telekom LLCTO + * and numerous contributors (see git log) + * + * Some tests additionally are: + * + * Copyright (c) 2011, 2012 Google, Inc. + * or contributed by: + * - Benoit Boivin + * - Paul Felix + * - Marek Janda + * - Robert Konigsberg + * - George Madrid + * - Anthony Robledo + * - Fr. Sauter AG + * - Fr. Sauter AG + * - Ümit Seren + * - Sergey Slepian + * - Dan Vanderkam + * + * Parts of the documentation are or make use of code that is: + * + * Copyright (c) 2012 Google, Inc. + * - Robert Konigsberg + * + * The automatically added browser-pack shim is: + * + * Copyright (c) 2013, 2014 James Halliday + * Copyright (c) 2013 Roman Shtylman + * Copyright (c) 2013 Esa-Matti Suuronen + * Copyright (c) 2018 Philipp Simon Schmidt + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The documentation and gallery uses Bootstrap and jQuery; see the + * relevant licence files of those external libraries for details. + * + * The icons under common/ are CC0-licenced and adapted by mirabilos. + * In Debian, /usr/share/common-licenses/CC0-1.0 has the full text. + */ +"use strict"; + +},{}],"dygraphs/src/datahandler/bars-custom.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler implementation for the custom bars option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _bars = _interopRequireDefault(require("./bars")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @constructor + * @extends Dygraph.DataHandlers.BarsHandler + */ +var CustomBarsHandler = function CustomBarsHandler() {}; +CustomBarsHandler.prototype = new _bars["default"](); + +/** @inheritDoc */ +CustomBarsHandler.prototype.extractSeries = function (rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point; + var seriesLabel = options.get("labels")[i]; + var logScale = options.getForSeries("logscale", seriesLabel); + for (var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0 || point[2] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + y = point[1]; + if (y !== null && !isNaN(y)) { + series.push([x, y, [point[0], point[2]]]); + } else { + series.push([x, y, [y, y]]); + } + } else { + series.push([x, null, [null, null]]); + } + } + return series; +}; + +/** @inheritDoc */ +CustomBarsHandler.prototype.rollingAverage = function (originalData, rollPeriod, options, i) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var y, low, high, mid, count, i, extremes; + low = 0; + mid = 0; + high = 0; + count = 0; + for (i = 0; i < originalData.length; i++) { + y = originalData[i][1]; + extremes = originalData[i][2]; + rollingData[i] = originalData[i]; + if (y !== null && !isNaN(y)) { + low += extremes[0]; + mid += y; + high += extremes[1]; + count += 1; + } + if (i - rollPeriod >= 0) { + var prev = originalData[i - rollPeriod]; + if (prev[1] !== null && !isNaN(prev[1])) { + low -= prev[2][0]; + mid -= prev[1]; + high -= prev[2][1]; + count -= 1; + } + } + if (count) { + rollingData[i] = [originalData[i][0], 1.0 * mid / count, [1.0 * low / count, 1.0 * high / count]]; + } else { + rollingData[i] = [originalData[i][0], null, [null, null]]; + } + } + return rollingData; +}; +var _default = CustomBarsHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"./bars":"dygraphs/src/datahandler/bars.js"}],"dygraphs/src/datahandler/bars-error.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler implementation for the errorBars option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _bars = _interopRequireDefault(require("./bars")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @constructor + * @extends BarsHandler + */ +var ErrorBarsHandler = function ErrorBarsHandler() {}; +ErrorBarsHandler.prototype = new _bars["default"](); + +/** @inheritDoc */ +ErrorBarsHandler.prototype.extractSeries = function (rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, variance, point; + var seriesLabel = options.get("labels")[i]; + var logScale = options.getForSeries("logscale", seriesLabel); + var sigma = options.getForSeries("sigma", seriesLabel); + for (var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[0] - sigma * point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + y = point[0]; + if (y !== null && !isNaN(y)) { + variance = sigma * point[1]; + // preserve original error value in extras for further + // filtering + series.push([x, y, [y - variance, y + variance, point[1]]]); + } else { + series.push([x, y, [y, y, y]]); + } + } else { + series.push([x, null, [null, null, null]]); + } + } + return series; +}; + +/** @inheritDoc */ +ErrorBarsHandler.prototype.rollingAverage = function (originalData, rollPeriod, options, i) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var seriesLabel = options.get("labels")[i]; + var sigma = options.getForSeries("sigma", seriesLabel); + var i, j, y, v, sum, num_ok, stddev, variance, value; + + // Calculate the rolling average for the first rollPeriod - 1 points + // where there is not enough data to roll over the full number of points + for (i = 0; i < originalData.length; i++) { + sum = 0; + variance = 0; + num_ok = 0; + for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { + y = originalData[j][1]; + if (y === null || isNaN(y)) continue; + num_ok++; + sum += y; + variance += Math.pow(originalData[j][2][2], 2); + } + if (num_ok) { + stddev = Math.sqrt(variance) / num_ok; + value = sum / num_ok; + rollingData[i] = [originalData[i][0], value, [value - sigma * stddev, value + sigma * stddev]]; + } else { + // This explicitly preserves NaNs to aid with "independent + // series". + // See testRollingAveragePreservesNaNs. + v = rollPeriod == 1 ? originalData[i][1] : null; + rollingData[i] = [originalData[i][0], v, [v, v]]; + } + } + return rollingData; +}; +var _default = ErrorBarsHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"./bars":"dygraphs/src/datahandler/bars.js"}],"dygraphs/src/datahandler/bars-fractions.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler implementation for the combination + * of error bars and fractions options. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _bars = _interopRequireDefault(require("./bars")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @constructor + * @extends Dygraph.DataHandlers.BarsHandler + */ +var FractionsBarsHandler = function FractionsBarsHandler() {}; +FractionsBarsHandler.prototype = new _bars["default"](); + +/** @inheritDoc */ +FractionsBarsHandler.prototype.extractSeries = function (rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point, num, den, value, stddev, variance; + var mult = 100.0; + var seriesLabel = options.get("labels")[i]; + var logScale = options.getForSeries("logscale", seriesLabel); + var sigma = options.getForSeries("sigma", seriesLabel); + for (var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + num = point[0]; + den = point[1]; + if (num !== null && !isNaN(num)) { + value = den ? num / den : 0.0; + stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; + variance = mult * stddev; + y = mult * value; + // preserve original values in extras for further filtering + series.push([x, y, [y - variance, y + variance, num, den]]); + } else { + series.push([x, num, [num, num, num, den]]); + } + } else { + series.push([x, null, [null, null, null, null]]); + } + } + return series; +}; + +/** @inheritDoc */ +FractionsBarsHandler.prototype.rollingAverage = function (originalData, rollPeriod, options, i) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var seriesLabel = options.get("labels")[i]; + var sigma = options.getForSeries("sigma", seriesLabel); + var wilsonInterval = options.getForSeries("wilsonInterval", seriesLabel); + var low, high, i, stddev; + var num = 0; + var den = 0; // numerator/denominator + var mult = 100.0; + for (i = 0; i < originalData.length; i++) { + num += originalData[i][2][2]; + den += originalData[i][2][3]; + if (i - rollPeriod >= 0) { + num -= originalData[i - rollPeriod][2][2]; + den -= originalData[i - rollPeriod][2][3]; + } + var date = originalData[i][0]; + var value = den ? num / den : 0.0; + if (wilsonInterval) { + // For more details on this confidence interval, see: + // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval + if (den) { + var p = value < 0 ? 0 : value, + n = den; + var pm = sigma * Math.sqrt(p * (1 - p) / n + sigma * sigma / (4 * n * n)); + var denom = 1 + sigma * sigma / den; + low = (p + sigma * sigma / (2 * den) - pm) / denom; + high = (p + sigma * sigma / (2 * den) + pm) / denom; + rollingData[i] = [date, p * mult, [low * mult, high * mult]]; + } else { + rollingData[i] = [date, 0, [0, 0]]; + } + } else { + stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; + rollingData[i] = [date, mult * value, [mult * (value - stddev), mult * (value + stddev)]]; + } + } + return rollingData; +}; +var _default = FractionsBarsHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"./bars":"dygraphs/src/datahandler/bars.js"}],"dygraphs/src/datahandler/bars.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler base implementation for the "bar" + * data formats. This implementation must be extended and the + * extractSeries and rollingAverage must be implemented. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +/*global DygraphLayout:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _datahandler = _interopRequireDefault(require("./datahandler")); +var _dygraphLayout = _interopRequireDefault(require("../dygraph-layout")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @constructor + * @extends {Dygraph.DataHandler} + */ +var BarsHandler = function BarsHandler() { + _datahandler["default"].call(this); +}; +BarsHandler.prototype = new _datahandler["default"](); + +// TODO(danvk): figure out why the jsdoc has to be copy/pasted from superclass. +// (I get closure compiler errors if this isn't here.) +/** + * @override + * @param {!Array.} rawData The raw data passed into dygraphs where + * rawData[i] = [x,ySeries1,...,ySeriesN]. + * @param {!number} seriesIndex Index of the series to extract. All other + * series should be ignored. + * @param {!DygraphOptions} options Dygraph options. + * @return {Array.<[!number,?number,?]>} The series in the unified data format + * where series[i] = [x,y,{extras}]. + */ +BarsHandler.prototype.extractSeries = function (rawData, seriesIndex, options) { + // Not implemented here must be extended +}; + +/** + * @override + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!number} rollPeriod The number of points over which to average the data + * @param {!DygraphOptions} options The dygraph options. + * @param {!number} seriesIndex Index of the series this was extracted from. + * TODO(danvk): be more specific than "Array" here. + * @return {!Array.<[!number,?number,?]>} the rolled series. + */ +BarsHandler.prototype.rollingAverage = function (series, rollPeriod, options, seriesIndex) { + // Not implemented here, must be extended. +}; + +/** @inheritDoc */ +BarsHandler.prototype.onPointsCreated_ = function (series, points) { + for (var i = 0; i < series.length; ++i) { + var item = series[i]; + var point = points[i]; + point.y_top = NaN; + point.y_bottom = NaN; + point.yval_minus = _datahandler["default"].parseFloat(item[2][0]); + point.yval_plus = _datahandler["default"].parseFloat(item[2][1]); + } +}; + +/** @inheritDoc */ +BarsHandler.prototype.getExtremeYValues = function (series, dateWindow, stepPlot) { + var minY = null, + maxY = null, + y; + var firstIdx = 0; + var lastIdx = series.length - 1; + for (var j = firstIdx; j <= lastIdx; j++) { + y = series[j][1]; + if (y === null || isNaN(y)) continue; + var low = series[j][2][0]; + var high = series[j][2][1]; + if (low > y) low = y; // this can happen with custom bars, + if (high < y) high = y; // e.g. in tests/custom-bars.html + + if (maxY === null || high > maxY) maxY = high; + if (minY === null || low < minY) minY = low; + } + return [minY, maxY]; +}; + +/** @inheritDoc */ +BarsHandler.prototype.onLineEvaluated = function (points, axis, logscale) { + var point; + for (var j = 0; j < points.length; j++) { + // Copy over the error terms + point = points[j]; + point.y_top = _dygraphLayout["default"].calcYNormal_(axis, point.yval_minus, logscale); + point.y_bottom = _dygraphLayout["default"].calcYNormal_(axis, point.yval_plus, logscale); + } +}; +var _default = BarsHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"../dygraph-layout":"dygraphs/src/dygraph-layout.js","./datahandler":"dygraphs/src/datahandler/datahandler.js"}],"dygraphs/src/datahandler/datahandler.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview This file contains the managment of data handlers + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + * + * The idea is to define a common, generic data format that works for all data + * structures supported by dygraphs. To make this possible, the DataHandler + * interface is introduced. This makes it possible, that dygraph itself can work + * with the same logic for every data type independent of the actual format and + * the DataHandler takes care of the data format specific jobs. + * DataHandlers are implemented for all data types supported by Dygraphs and + * return Dygraphs compliant formats. + * By default the correct DataHandler is chosen based on the options set. + * Optionally the user may use his own DataHandler (similar to the plugin + * system). + * + * + * The unified data format returend by each handler is defined as so: + * series[n][point] = [x,y,(extras)] + * + * This format contains the common basis that is needed to draw a simple line + * series extended by optional extras for more complex graphing types. It + * contains a primitive x value as first array entry, a primitive y value as + * second array entry and an optional extras object for additional data needed. + * + * x must always be a number. + * y must always be a number, NaN of type number or null. + * extras is optional and must be interpreted by the DataHandler. It may be of + * any type. + * + * In practice this might look something like this: + * default: [x, yVal] + * errorBar / customBar: [x, yVal, [yTopVariance, yBottomVariance] ] + * + */ +/*global Dygraph:false */ +/*global DygraphLayout:false */ + +"use strict"; + +/** + * + * The data handler is responsible for all data specific operations. All of the + * series data it receives and returns is always in the unified data format. + * Initially the unified data is created by the extractSeries method + * @constructor + */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var DygraphDataHandler = function DygraphDataHandler() {}; +var handler = DygraphDataHandler; + +/** + * X-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.X = 0; + +/** + * Y-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.Y = 1; + +/** + * Extras-value array index constant for unified data samples. + * @const + * @type {number} + */ +handler.EXTRAS = 2; + +/** + * Extracts one series from the raw data (a 2D array) into an array of the + * unified data format. + * This is where undesirable points (i.e. negative values on log scales and + * missing values through which we wish to connect lines) are dropped. + * TODO(danvk): the "missing values" bit above doesn't seem right. + * + * @param {!Array.} rawData The raw data passed into dygraphs where + * rawData[i] = [x,ySeries1,...,ySeriesN]. + * @param {!number} seriesIndex Index of the series to extract. All other + * series should be ignored. + * @param {!DygraphOptions} options Dygraph options. + * @return {Array.<[!number,?number,?]>} The series in the unified data format + * where series[i] = [x,y,{extras}]. + */ +handler.prototype.extractSeries = function (rawData, seriesIndex, options) {}; + +/** + * Converts a series to a Point array. The resulting point array must be + * returned in increasing order of idx property. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!string} setName Name of the series. + * @param {!number} boundaryIdStart Index offset of the first point, equal to the + * number of skipped points left of the date window minimum (if any). + * @return {!Array.} List of points for this series. + */ +handler.prototype.seriesToPoints = function (series, setName, boundaryIdStart) { + // TODO(bhs): these loops are a hot-spot for high-point-count charts. In + // fact, + // on chrome+linux, they are 6 times more expensive than iterating through + // the + // points and drawing the lines. The brunt of the cost comes from allocating + // the |point| structures. + var points = []; + for (var i = 0; i < series.length; ++i) { + var item = series[i]; + var yraw = item[1]; + var yval = yraw === null ? null : handler.parseFloat(yraw); + var point = { + x: NaN, + y: NaN, + xval: handler.parseFloat(item[0]), + yval: yval, + name: setName, + // TODO(danvk): is this really necessary? + idx: i + boundaryIdStart, + canvasx: NaN, + // add these so we do not alter the structure later, which slows Chrome + canvasy: NaN + }; + points.push(point); + } + this.onPointsCreated_(series, points); + return points; +}; + +/** + * Callback called for each series after the series points have been generated + * which will later be used by the plotters to draw the graph. + * Here data may be added to the seriesPoints which is needed by the plotters. + * The indexes of series and points are in sync meaning the original data + * sample for series[i] is points[i]. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!Array.} points The corresponding points passed + * to the plotter. + * @protected + */ +handler.prototype.onPointsCreated_ = function (series, points) {}; + +/** + * Calculates the rolling average of a data set. + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x,y,{extras}]. + * @param {!number} rollPeriod The number of points over which to average the data + * @param {!DygraphOptions} options The dygraph options. + * @param {!number} seriesIndex Index of the series this was extracted from. + * @return {!Array.<[!number,?number,?]>} the rolled series. + */ +handler.prototype.rollingAverage = function (series, rollPeriod, options, seriesIndex) {}; + +/** + * Computes the range of the data series (including confidence intervals). + * + * @param {!Array.<[!number,?number,?]>} series The series in the unified + * data format where series[i] = [x, y, {extras}]. + * @param {!Array.} dateWindow The x-value range to display with + * the format: [min, max]. + * @param {boolean} stepPlot Whether the stepPlot option is set. + * @return {Array.} The low and high extremes of the series in the + * given window with the format: [low, high]. + */ +handler.prototype.getExtremeYValues = function (series, dateWindow, stepPlot) {}; + +/** + * Callback called for each series after the layouting data has been + * calculated before the series is drawn. Here normalized positioning data + * should be calculated for the extras of each point. + * + * @param {!Array.} points The points passed to + * the plotter. + * @param {!Object} axis The axis on which the series will be plotted. + * @param {!boolean} logscale Whether or not to use a logscale. + */ +handler.prototype.onLineEvaluated = function (points, axis, logscale) {}; + +/** + * Optimized replacement for parseFloat, which was way too slow when almost + * all values were type number, with few edge cases, none of which were strings. + * @param {?number} val + * @return {number} + * @protected + */ +handler.parseFloat = function (val) { + // parseFloat(null) is NaN + if (val === null) { + return NaN; + } + + // Assume it's a number or NaN. If it's something else, I'll be shocked. + return val; +}; +var _default = DygraphDataHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{}],"dygraphs/src/datahandler/default-fractions.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler implementation for the fractions option. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _datahandler = _interopRequireDefault(require("./datahandler")); +var _default2 = _interopRequireDefault(require("./default")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @extends DefaultHandler + * @constructor + */ +var DefaultFractionHandler = function DefaultFractionHandler() {}; +DefaultFractionHandler.prototype = new _default2["default"](); +DefaultFractionHandler.prototype.extractSeries = function (rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var x, y, point, num, den, value; + var mult = 100.0; + var seriesLabel = options.get("labels")[i]; + var logScale = options.getForSeries("logscale", seriesLabel); + for (var j = 0; j < rawData.length; j++) { + x = rawData[j][0]; + point = rawData[j][i]; + if (logScale && point !== null) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point[0] <= 0 || point[1] <= 0) { + point = null; + } + } + // Extract to the unified data format. + if (point !== null) { + num = point[0]; + den = point[1]; + if (num !== null && !isNaN(num)) { + value = den ? num / den : 0.0; + y = mult * value; + // preserve original values in extras for further filtering + series.push([x, y, [num, den]]); + } else { + series.push([x, num, [num, den]]); + } + } else { + series.push([x, null, [null, null]]); + } + } + return series; +}; +DefaultFractionHandler.prototype.rollingAverage = function (originalData, rollPeriod, options, i) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var i; + var num = 0; + var den = 0; // numerator/denominator + var mult = 100.0; + for (i = 0; i < originalData.length; i++) { + num += originalData[i][2][0]; + den += originalData[i][2][1]; + if (i - rollPeriod >= 0) { + num -= originalData[i - rollPeriod][2][0]; + den -= originalData[i - rollPeriod][2][1]; + } + var date = originalData[i][0]; + var value = den ? num / den : 0.0; + rollingData[i] = [date, mult * value]; + } + return rollingData; +}; +var _default = DefaultFractionHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"./datahandler":"dygraphs/src/datahandler/datahandler.js","./default":"dygraphs/src/datahandler/default.js"}],"dygraphs/src/datahandler/default.js":[function(require,module,exports){ +/** + * @license + * Copyright 2013 David Eberlein (david.eberlein@ch.sauter-bc.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DataHandler default implementation used for simple line charts. + * @author David Eberlein (david.eberlein@ch.sauter-bc.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _datahandler = _interopRequireDefault(require("./datahandler")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * @constructor + * @extends Dygraph.DataHandler + */ +var DefaultHandler = function DefaultHandler() {}; +DefaultHandler.prototype = new _datahandler["default"](); + +/** @inheritDoc */ +DefaultHandler.prototype.extractSeries = function (rawData, i, options) { + // TODO(danvk): pre-allocate series here. + var series = []; + var seriesLabel = options.get("labels")[i]; + var logScale = options.getForSeries("logscale", seriesLabel); + for (var j = 0; j < rawData.length; j++) { + var x = rawData[j][0]; + var point = rawData[j][i]; + if (logScale) { + // On the log scale, points less than zero do not exist. + // This will create a gap in the chart. + if (point <= 0) { + point = null; + } + } + series.push([x, point]); + } + return series; +}; + +/** @inheritDoc */ +DefaultHandler.prototype.rollingAverage = function (originalData, rollPeriod, options, i) { + rollPeriod = Math.min(rollPeriod, originalData.length); + var rollingData = []; + var i, j, y, sum, num_ok; + // Calculate the rolling average for the first rollPeriod - 1 points + // where + // there is not enough data to roll over the full number of points + if (rollPeriod == 1) { + return originalData; + } + for (i = 0; i < originalData.length; i++) { + sum = 0; + num_ok = 0; + for (j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { + y = originalData[j][1]; + if (y === null || isNaN(y)) continue; + num_ok++; + sum += originalData[j][1]; + } + if (num_ok) { + rollingData[i] = [originalData[i][0], sum / num_ok]; + } else { + rollingData[i] = [originalData[i][0], null]; + } + } + return rollingData; +}; + +/** @inheritDoc */ +DefaultHandler.prototype.getExtremeYValues = function getExtremeYValues(series, dateWindow, stepPlot) { + var minY = null, + maxY = null, + y; + var firstIdx = 0, + lastIdx = series.length - 1; + for (var j = firstIdx; j <= lastIdx; j++) { + y = series[j][1]; + if (y === null || isNaN(y)) continue; + if (maxY === null || y > maxY) { + maxY = y; + } + if (minY === null || y < minY) { + minY = y; + } + } + return [minY, maxY]; +}; +var _default = DefaultHandler; +exports["default"] = _default; +module.exports = exports.default; + +},{"./datahandler":"dygraphs/src/datahandler/datahandler.js"}],"dygraphs/src/dygraph-canvas.js":[function(require,module,exports){ +/** + * @license + * Copyright 2006 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the + * needs of dygraphs. + * + * In particular, support for: + * - grid overlays + * - high/low bands + * - dygraphs attribute system + */ + +/** + * The DygraphCanvasRenderer class does the actual rendering of the chart onto + * a canvas. It's based on PlotKit.CanvasRenderer. + * @param {Object} element The canvas to attach to + * @param {Object} elementContext The 2d context of the canvas (injected so it + * can be mocked for testing.) + * @param {Layout} layout The DygraphLayout object for this graph. + * @constructor + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +var _dygraph = _interopRequireDefault(require("./dygraph")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * @constructor + * + * This gets called when there are "new points" to chart. This is generally the + * case when the underlying data being charted has changed. It is _not_ called + * in the common case that the user has zoomed or is panning the view. + * + * The chart canvas has already been created by the Dygraph object. The + * renderer simply gets a drawing context. + * + * @param {Dygraph} dygraph The chart to which this renderer belongs. + * @param {HTMLCanvasElement} element The <canvas> DOM element on which to draw. + * @param {CanvasRenderingContext2D} elementContext The drawing context. + * @param {DygraphLayout} layout The chart's DygraphLayout object. + * + * TODO(danvk): remove the elementContext property. + */ +var DygraphCanvasRenderer = function DygraphCanvasRenderer(dygraph, element, elementContext, layout) { + this.dygraph_ = dygraph; + this.layout = layout; + this.element = element; + this.elementContext = elementContext; + this.height = dygraph.height_; + this.width = dygraph.width_; + + // --- check whether everything is ok before we return + if (!utils.isCanvasSupported(this.element)) { + throw "Canvas is not supported."; + } + + // internal state + this.area = layout.getPlotArea(); + + // Set up a clipping area for the canvas (and the interaction canvas). + // This ensures that we don't overdraw. + var ctx = this.dygraph_.canvas_ctx_; + ctx.beginPath(); + ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); + ctx.clip(); + ctx = this.dygraph_.hidden_ctx_; + ctx.beginPath(); + ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h); + ctx.clip(); +}; + +/** + * Clears out all chart content and DOM elements. + * This is called immediately before render() on every frame, including + * during zooms and pans. + * @private + */ +DygraphCanvasRenderer.prototype.clear = function () { + this.elementContext.clearRect(0, 0, this.width, this.height); +}; + +/** + * This method is responsible for drawing everything on the chart, including + * lines, high/low bands, fills and axes. + * It is called immediately after clear() on every frame, including during pans + * and zooms. + * @private + */ +DygraphCanvasRenderer.prototype.render = function () { + // attaches point.canvas{x,y} + this._updatePoints(); + + // actually draws the chart. + this._renderLineChart(); +}; + +/** + * Returns a predicate to be used with an iterator, which will + * iterate over points appropriately, depending on whether + * connectSeparatedPoints is true. When it's false, the predicate will + * skip over points with missing yVals. + */ +DygraphCanvasRenderer._getIteratorPredicate = function (connectSeparatedPoints) { + return connectSeparatedPoints ? DygraphCanvasRenderer._predicateThatSkipsEmptyPoints : null; +}; +DygraphCanvasRenderer._predicateThatSkipsEmptyPoints = function (array, idx) { + return array[idx].yval !== null; +}; + +/** + * Draws a line with the styles passed in and calls all the drawPointCallbacks. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawStyledLine = function (e, color, strokeWidth, strokePattern, drawPoints, drawPointCallback, pointSize) { + var g = e.dygraph; + // TODO(konigsberg): Compute attributes outside this method call. + var stepPlot = g.getBooleanOption("stepPlot", e.setName); + if (!utils.isArrayLike(strokePattern)) { + strokePattern = null; + } + var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName); + var points = e.points; + var setName = e.setName; + var iter = utils.createIterator(points, 0, points.length, DygraphCanvasRenderer._getIteratorPredicate(g.getBooleanOption("connectSeparatedPoints", setName))); + var stroking = strokePattern && strokePattern.length >= 2; + var ctx = e.drawingContext; + ctx.save(); + if (stroking) { + if (ctx.setLineDash) ctx.setLineDash(strokePattern); + } + var pointsOnLine = DygraphCanvasRenderer._drawSeries(e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color); + DygraphCanvasRenderer._drawPointsOnLine(e, pointsOnLine, drawPointCallback, color, pointSize); + if (stroking) { + if (ctx.setLineDash) ctx.setLineDash([]); + } + ctx.restore(); +}; + +/** + * This does the actual drawing of lines on the canvas, for just one series. + * Returns a list of [canvasx, canvasy] pairs for points for which a + * drawPointCallback should be fired. These include isolated points, or all + * points if drawPoints=true. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawSeries = function (e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) { + var prevCanvasX = null; + var prevCanvasY = null; + var nextCanvasY = null; + var isIsolated; // true if this point is isolated (no line segments) + var point; // the point being processed in the while loop + var pointsOnLine = []; // Array of [canvasx, canvasy] pairs. + var first = true; // the first cycle through the while loop + + var ctx = e.drawingContext; + ctx.beginPath(); + ctx.strokeStyle = color; + ctx.lineWidth = strokeWidth; + + // NOTE: we break the iterator's encapsulation here for about a 25% speedup. + var arr = iter.array_; + var limit = iter.end_; + var predicate = iter.predicate_; + for (var i = iter.start_; i < limit; i++) { + point = arr[i]; + if (predicate) { + while (i < limit && !predicate(arr, i)) { + i++; + } + if (i == limit) break; + point = arr[i]; + } + + // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test + // doesn't catch Infinity values. Could change this to + // !isFinite(point.canvasy), but I assume it avoids isNaN for performance? + if (point.canvasy === null || point.canvasy != point.canvasy) { + if (stepPlot && prevCanvasX !== null) { + // Draw a horizontal line to the start of the missing data + ctx.moveTo(prevCanvasX, prevCanvasY); + ctx.lineTo(point.canvasx, prevCanvasY); + } + prevCanvasX = prevCanvasY = null; + } else { + isIsolated = false; + if (drawGapPoints || prevCanvasX === null) { + iter.nextIdx_ = i; + iter.next(); + nextCanvasY = iter.hasNext ? iter.peek.canvasy : null; + var isNextCanvasYNullOrNaN = nextCanvasY === null || nextCanvasY != nextCanvasY; + isIsolated = prevCanvasX === null && isNextCanvasYNullOrNaN; + if (drawGapPoints) { + // Also consider a point to be "isolated" if it's adjacent to a + // null point, excluding the graph edges. + if (!first && prevCanvasX === null || iter.hasNext && isNextCanvasYNullOrNaN) { + isIsolated = true; + } + } + } + if (prevCanvasX !== null) { + if (strokeWidth) { + if (stepPlot) { + ctx.moveTo(prevCanvasX, prevCanvasY); + ctx.lineTo(point.canvasx, prevCanvasY); + } + ctx.lineTo(point.canvasx, point.canvasy); + } + } else { + ctx.moveTo(point.canvasx, point.canvasy); + } + if (drawPoints || isIsolated) { + pointsOnLine.push([point.canvasx, point.canvasy, point.idx]); + } + prevCanvasX = point.canvasx; + prevCanvasY = point.canvasy; + } + first = false; + } + ctx.stroke(); + return pointsOnLine; +}; + +/** + * This fires the drawPointCallback functions, which draw dots on the points by + * default. This gets used when the "drawPoints" option is set, or when there + * are isolated points. + * @param {Object} e The dictionary passed to the plotter function. + * @private + */ +DygraphCanvasRenderer._drawPointsOnLine = function (e, pointsOnLine, drawPointCallback, color, pointSize) { + var ctx = e.drawingContext; + for (var idx = 0; idx < pointsOnLine.length; idx++) { + var cb = pointsOnLine[idx]; + ctx.save(); + drawPointCallback.call(e.dygraph, e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]); + ctx.restore(); + } +}; + +/** + * Attaches canvas coordinates to the points array. + * @private + */ +DygraphCanvasRenderer.prototype._updatePoints = function () { + // Update Points + // TODO(danvk): here + // + // TODO(bhs): this loop is a hot-spot for high-point-count charts. These + // transformations can be pushed into the canvas via linear transformation + // matrices. + // NOTE(danvk): this is trickier than it sounds at first. The transformation + // needs to be done before the .moveTo() and .lineTo() calls, but must be + // undone before the .stroke() call to ensure that the stroke width is + // unaffected. An alternative is to reduce the stroke width in the + // transformed coordinate space, but you can't specify different values for + // each dimension (as you can with .scale()). The speedup here is ~12%. + var sets = this.layout.points; + for (var i = sets.length; i--;) { + var points = sets[i]; + for (var j = points.length; j--;) { + var point = points[j]; + point.canvasx = this.area.w * point.x + this.area.x; + point.canvasy = this.area.h * point.y + this.area.y; + } + } +}; + +/** + * Add canvas Actually draw the lines chart, including high/low bands. + * + * This function can only be called if DygraphLayout's points array has been + * updated with canvas{x,y} attributes, i.e. by + * DygraphCanvasRenderer._updatePoints. + * + * @param {string=} opt_seriesName when specified, only that series will + * be drawn. (This is used for expedited redrawing with highlightSeriesOpts) + * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing + * context. However, lines are typically drawn on the object's + * elementContext. + * @private + */ +DygraphCanvasRenderer.prototype._renderLineChart = function (opt_seriesName, opt_ctx) { + var ctx = opt_ctx || this.elementContext; + var i; + var sets = this.layout.points; + var setNames = this.layout.setNames; + var setName; + this.colors = this.dygraph_.colorsMap_; + + // Determine which series have specialized plotters. + var plotter_attr = this.dygraph_.getOption("plotter"); + var plotters = plotter_attr; + if (!utils.isArrayLike(plotters)) { + plotters = [plotters]; + } + var setPlotters = {}; // series name -> plotter fn. + for (i = 0; i < setNames.length; i++) { + setName = setNames[i]; + var setPlotter = this.dygraph_.getOption("plotter", setName); + if (setPlotter == plotter_attr) continue; // not specialized. + + setPlotters[setName] = setPlotter; + } + for (i = 0; i < plotters.length; i++) { + var plotter = plotters[i]; + var is_last = i == plotters.length - 1; + for (var j = 0; j < sets.length; j++) { + setName = setNames[j]; + if (opt_seriesName && setName != opt_seriesName) continue; + var points = sets[j]; + + // Only throw in the specialized plotters on the last iteration. + var p = plotter; + if (setName in setPlotters) { + if (is_last) { + p = setPlotters[setName]; + } else { + // Don't use the standard plotters in this case. + continue; + } + } + var color = this.colors[setName]; + var strokeWidth = this.dygraph_.getOption("strokeWidth", setName); + ctx.save(); + ctx.strokeStyle = color; + ctx.lineWidth = strokeWidth; + p({ + points: points, + setName: setName, + drawingContext: ctx, + color: color, + strokeWidth: strokeWidth, + dygraph: this.dygraph_, + axis: this.dygraph_.axisPropertiesForSeries(setName), + plotArea: this.area, + seriesIndex: j, + seriesCount: sets.length, + singleSeriesName: opt_seriesName, + allSeriesPoints: sets + }); + ctx.restore(); + } + } +}; + +/** + * Standard plotters. These may be used by clients via Dygraph.Plotters. + * See comments there for more details. + */ +DygraphCanvasRenderer._Plotters = { + linePlotter: function linePlotter(e) { + DygraphCanvasRenderer._linePlotter(e); + }, + fillPlotter: function fillPlotter(e) { + DygraphCanvasRenderer._fillPlotter(e); + }, + errorPlotter: function errorPlotter(e) { + DygraphCanvasRenderer._errorPlotter(e); + } +}; + +/** + * Plotter which draws the central lines for a series. + * @private + */ +DygraphCanvasRenderer._linePlotter = function (e) { + var g = e.dygraph; + var setName = e.setName; + var strokeWidth = e.strokeWidth; + + // TODO(danvk): Check if there's any performance impact of just calling + // getOption() inside of _drawStyledLine. Passing in so many parameters makes + // this code a bit nasty. + var borderWidth = g.getNumericOption("strokeBorderWidth", setName); + var drawPointCallback = g.getOption("drawPointCallback", setName) || utils.Circles.DEFAULT; + var strokePattern = g.getOption("strokePattern", setName); + var drawPoints = g.getBooleanOption("drawPoints", setName); + var pointSize = g.getNumericOption("pointSize", setName); + if (borderWidth && strokeWidth) { + DygraphCanvasRenderer._drawStyledLine(e, g.getOption("strokeBorderColor", setName), strokeWidth + 2 * borderWidth, strokePattern, drawPoints, drawPointCallback, pointSize); + } + DygraphCanvasRenderer._drawStyledLine(e, e.color, strokeWidth, strokePattern, drawPoints, drawPointCallback, pointSize); +}; + +/** + * Draws the shaded high/low bands (confidence intervals) for each series. + * This happens before the center lines are drawn, since the center lines + * need to be drawn on top of the high/low bands for all series. + * @private + */ +DygraphCanvasRenderer._errorPlotter = function (e) { + var g = e.dygraph; + var setName = e.setName; + var errorBars = g.getBooleanOption("errorBars") || g.getBooleanOption("customBars"); + if (!errorBars) return; + var fillGraph = g.getBooleanOption("fillGraph", setName); + if (fillGraph) { + console.warn("Can't use fillGraph option with customBars or errorBars option"); + } + var ctx = e.drawingContext; + var color = e.color; + var fillAlpha = g.getNumericOption('fillAlpha', setName); + var stepPlot = g.getBooleanOption("stepPlot", setName); + var points = e.points; + var iter = utils.createIterator(points, 0, points.length, DygraphCanvasRenderer._getIteratorPredicate(g.getBooleanOption("connectSeparatedPoints", setName))); + var newYs; + + // setup graphics context + var prevX = NaN; + var prevY = NaN; + var prevYs = [-1, -1]; + // should be same color as the lines but only 15% opaque. + var rgb = utils.toRGB_(color); + var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; + ctx.fillStyle = err_color; + ctx.beginPath(); + var isNullUndefinedOrNaN = function isNullUndefinedOrNaN(x) { + return x === null || x === undefined || isNaN(x); + }; + while (iter.hasNext) { + var point = iter.next(); + if (!stepPlot && isNullUndefinedOrNaN(point.y) || stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY)) { + prevX = NaN; + continue; + } + newYs = [point.y_bottom, point.y_top]; + if (stepPlot) { + prevY = point.y; + } + + // The documentation specifically disallows nulls inside the point arrays, + // but in case it happens we should do something sensible. + if (isNaN(newYs[0])) newYs[0] = point.y; + if (isNaN(newYs[1])) newYs[1] = point.y; + newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y; + newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y; + if (!isNaN(prevX)) { + if (stepPlot) { + ctx.moveTo(prevX, prevYs[0]); + ctx.lineTo(point.canvasx, prevYs[0]); + ctx.lineTo(point.canvasx, prevYs[1]); + } else { + ctx.moveTo(prevX, prevYs[0]); + ctx.lineTo(point.canvasx, newYs[0]); + ctx.lineTo(point.canvasx, newYs[1]); + } + ctx.lineTo(prevX, prevYs[1]); + ctx.closePath(); + } + prevYs = newYs; + prevX = point.canvasx; + } + ctx.fill(); +}; + +/** + * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are + * superfluous. It accumulates all movements which haven't changed the x-value + * and only applies the two with the most extreme y-values. + * + * Calls to lineTo/moveTo must have non-decreasing x-values. + */ +DygraphCanvasRenderer._fastCanvasProxy = function (context) { + var pendingActions = []; // array of [type, x, y] tuples + var lastRoundedX = null; + var lastFlushedX = null; + var LINE_TO = 1, + MOVE_TO = 2; + var actionCount = 0; // number of moveTos and lineTos passed to context. + + // Drop superfluous motions + // Assumes all pendingActions have the same (rounded) x-value. + var compressActions = function compressActions(opt_losslessOnly) { + if (pendingActions.length <= 1) return; + + // Lossless compression: drop inconsequential moveTos. + for (var i = pendingActions.length - 1; i > 0; i--) { + var action = pendingActions[i]; + if (action[0] == MOVE_TO) { + var prevAction = pendingActions[i - 1]; + if (prevAction[1] == action[1] && prevAction[2] == action[2]) { + pendingActions.splice(i, 1); + } + } + } + + // Lossless compression: ... drop consecutive moveTos ... + for /* incremented internally */ + (var i = 0; i < pendingActions.length - 1;) { + var action = pendingActions[i]; + if (action[0] == MOVE_TO && pendingActions[i + 1][0] == MOVE_TO) { + pendingActions.splice(i, 1); + } else { + i++; + } + } + + // Lossy compression: ... drop all but the extreme y-values ... + if (pendingActions.length > 2 && !opt_losslessOnly) { + // keep an initial moveTo, but drop all others. + var startIdx = 0; + if (pendingActions[0][0] == MOVE_TO) startIdx++; + var minIdx = null, + maxIdx = null; + for (var i = startIdx; i < pendingActions.length; i++) { + var action = pendingActions[i]; + if (action[0] != LINE_TO) continue; + if (minIdx === null && maxIdx === null) { + minIdx = i; + maxIdx = i; + } else { + var y = action[2]; + if (y < pendingActions[minIdx][2]) { + minIdx = i; + } else if (y > pendingActions[maxIdx][2]) { + maxIdx = i; + } + } + } + var minAction = pendingActions[minIdx], + maxAction = pendingActions[maxIdx]; + pendingActions.splice(startIdx, pendingActions.length - startIdx); + if (minIdx < maxIdx) { + pendingActions.push(minAction); + pendingActions.push(maxAction); + } else if (minIdx > maxIdx) { + pendingActions.push(maxAction); + pendingActions.push(minAction); + } else { + pendingActions.push(minAction); + } + } + }; + var flushActions = function flushActions(opt_noLossyCompression) { + compressActions(opt_noLossyCompression); + for (var i = 0, len = pendingActions.length; i < len; i++) { + var action = pendingActions[i]; + if (action[0] == LINE_TO) { + context.lineTo(action[1], action[2]); + } else if (action[0] == MOVE_TO) { + context.moveTo(action[1], action[2]); + } + } + if (pendingActions.length) { + lastFlushedX = pendingActions[pendingActions.length - 1][1]; + } + actionCount += pendingActions.length; + pendingActions = []; + }; + var addAction = function addAction(action, x, y) { + var rx = Math.round(x); + if (lastRoundedX === null || rx != lastRoundedX) { + // if there are large gaps on the x-axis, it's essential to keep the + // first and last point as well. + var hasGapOnLeft = lastRoundedX - lastFlushedX > 1, + hasGapOnRight = rx - lastRoundedX > 1, + hasGap = hasGapOnLeft || hasGapOnRight; + flushActions(hasGap); + lastRoundedX = rx; + } + pendingActions.push([action, x, y]); + }; + return { + moveTo: function moveTo(x, y) { + addAction(MOVE_TO, x, y); + }, + lineTo: function lineTo(x, y) { + addAction(LINE_TO, x, y); + }, + // for major operations like stroke/fill, we skip compression to ensure + // that there are no artifacts at the right edge. + stroke: function stroke() { + flushActions(true); + context.stroke(); + }, + fill: function fill() { + flushActions(true); + context.fill(); + }, + beginPath: function beginPath() { + flushActions(true); + context.beginPath(); + }, + closePath: function closePath() { + flushActions(true); + context.closePath(); + }, + _count: function _count() { + return actionCount; + } + }; +}; + +/** + * Draws the shaded regions when "fillGraph" is set. + * Not to be confused with high/low bands (historically misnamed errorBars). + * + * For stacked charts, it's more convenient to handle all the series + * simultaneously. So this plotter plots all the points on the first series + * it's asked to draw, then ignores all the other series. + * + * @private + */ +DygraphCanvasRenderer._fillPlotter = function (e) { + // Skip if we're drawing a single series for interactive highlight overlay. + if (e.singleSeriesName) return; + + // We'll handle all the series at once, not one-by-one. + if (e.seriesIndex !== 0) return; + var g = e.dygraph; + var setNames = g.getLabels().slice(1); // remove x-axis + + // getLabels() includes names for invisible series, which are not included in + // allSeriesPoints. We remove those to make the two match. + // TODO(danvk): provide a simpler way to get this information. + for (var i = setNames.length; i >= 0; i--) { + if (!g.visibility()[i]) setNames.splice(i, 1); + } + var anySeriesFilled = function () { + for (var i = 0; i < setNames.length; i++) { + if (g.getBooleanOption("fillGraph", setNames[i])) return true; + } + return false; + }(); + if (!anySeriesFilled) return; + var area = e.plotArea; + var sets = e.allSeriesPoints; + var setCount = sets.length; + var stackedGraph = g.getBooleanOption("stackedGraph"); + var colors = g.getColors(); + + // For stacked graphs, track the baseline for filling. + // + // The filled areas below graph lines are trapezoids with two + // vertical edges. The top edge is the line segment being drawn, and + // the baseline is the bottom edge. Each baseline corresponds to the + // top line segment from the previous stacked line. In the case of + // step plots, the trapezoids are rectangles. + var baseline = {}; + var currBaseline; + var prevStepPlot; // for different line drawing modes (line/step) per series + + // Helper function to trace a line back along the baseline. + var traceBackPath = function traceBackPath(ctx, baselineX, baselineY, pathBack) { + ctx.lineTo(baselineX, baselineY); + if (stackedGraph) { + for (var i = pathBack.length - 1; i >= 0; i--) { + var pt = pathBack[i]; + ctx.lineTo(pt[0], pt[1]); + } + } + }; + + // process sets in reverse order (needed for stacked graphs) + for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) { + var ctx = e.drawingContext; + var setName = setNames[setIdx]; + if (!g.getBooleanOption('fillGraph', setName)) continue; + var fillAlpha = g.getNumericOption('fillAlpha', setName); + var stepPlot = g.getBooleanOption('stepPlot', setName); + var color = colors[setIdx]; + var axis = g.axisPropertiesForSeries(setName); + var axisY = 1.0 + axis.minyval * axis.yscale; + if (axisY < 0.0) axisY = 0.0;else if (axisY > 1.0) axisY = 1.0; + axisY = area.h * axisY + area.y; + var points = sets[setIdx]; + var iter = utils.createIterator(points, 0, points.length, DygraphCanvasRenderer._getIteratorPredicate(g.getBooleanOption("connectSeparatedPoints", setName))); + + // setup graphics context + var prevX = NaN; + var prevYs = [-1, -1]; + var newYs; + // should be same color as the lines but only 15% opaque. + var rgb = utils.toRGB_(color); + var err_color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')'; + ctx.fillStyle = err_color; + ctx.beginPath(); + var last_x, + is_first = true; + + // If the point density is high enough, dropping segments on their way to + // the canvas justifies the overhead of doing so. + if (points.length > 2 * g.width_ || _dygraph["default"].FORCE_FAST_PROXY) { + ctx = DygraphCanvasRenderer._fastCanvasProxy(ctx); + } + + // For filled charts, we draw points from left to right, then back along + // the x-axis to complete a shape for filling. + // For stacked plots, this "back path" is a more complex shape. This array + // stores the [x, y] values needed to trace that shape. + var pathBack = []; + + // TODO(danvk): there are a lot of options at play in this loop. + // The logic would be much clearer if some (e.g. stackGraph and + // stepPlot) were split off into separate sub-plotters. + var point; + while (iter.hasNext) { + point = iter.next(); + if (!utils.isOK(point.y) && !stepPlot) { + traceBackPath(ctx, prevX, prevYs[1], pathBack); + pathBack = []; + prevX = NaN; + if (point.y_stacked !== null && !isNaN(point.y_stacked)) { + baseline[point.canvasx] = area.h * point.y_stacked + area.y; + } + continue; + } + if (stackedGraph) { + if (!is_first && last_x == point.xval) { + continue; + } else { + is_first = false; + last_x = point.xval; + } + currBaseline = baseline[point.canvasx]; + var lastY; + if (currBaseline === undefined) { + lastY = axisY; + } else { + if (prevStepPlot) { + lastY = currBaseline[0]; + } else { + lastY = currBaseline; + } + } + newYs = [point.canvasy, lastY]; + if (stepPlot) { + // Step plots must keep track of the top and bottom of + // the baseline at each point. + if (prevYs[0] === -1) { + baseline[point.canvasx] = [point.canvasy, axisY]; + } else { + baseline[point.canvasx] = [point.canvasy, prevYs[0]]; + } + } else { + baseline[point.canvasx] = point.canvasy; + } + } else { + if (isNaN(point.canvasy) && stepPlot) { + newYs = [area.y + area.h, axisY]; + } else { + newYs = [point.canvasy, axisY]; + } + } + if (!isNaN(prevX)) { + // Move to top fill point + if (stepPlot) { + ctx.lineTo(point.canvasx, prevYs[0]); + ctx.lineTo(point.canvasx, newYs[0]); + } else { + ctx.lineTo(point.canvasx, newYs[0]); + } + + // Record the baseline for the reverse path. + if (stackedGraph) { + pathBack.push([prevX, prevYs[1]]); + if (prevStepPlot && currBaseline) { + // Draw to the bottom of the baseline + pathBack.push([point.canvasx, currBaseline[1]]); + } else { + pathBack.push([point.canvasx, newYs[1]]); + } + } + } else { + ctx.moveTo(point.canvasx, newYs[1]); + ctx.lineTo(point.canvasx, newYs[0]); + } + prevYs = newYs; + prevX = point.canvasx; + } + prevStepPlot = stepPlot; + if (newYs && point) { + traceBackPath(ctx, point.canvasx, newYs[1], pathBack); + pathBack = []; + } + ctx.fill(); + } +}; +var _default = DygraphCanvasRenderer; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph":"dygraphs/src/dygraph.js","./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-default-attrs.js":[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var DygraphTickers = _interopRequireWildcard(require("./dygraph-tickers")); +var _dygraphInteractionModel = _interopRequireDefault(require("./dygraph-interaction-model")); +var _dygraphCanvas = _interopRequireDefault(require("./dygraph-canvas")); +var utils = _interopRequireWildcard(require("./dygraph-utils")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +// Default attribute values. +var DEFAULT_ATTRS = { + highlightCircleSize: 3, + highlightSeriesOpts: null, + highlightSeriesBackgroundAlpha: 0.5, + highlightSeriesBackgroundColor: 'rgb(255, 255, 255)', + labelsSeparateLines: false, + labelsShowZeroValues: true, + labelsKMB: false, + labelsKMG2: false, + showLabelsOnHighlight: true, + digitsAfterDecimal: 2, + maxNumberWidth: 6, + sigFigs: null, + strokeWidth: 1.0, + strokeBorderWidth: 0, + strokeBorderColor: "white", + axisTickSize: 3, + axisLabelFontSize: 14, + rightGap: 5, + showRoller: false, + xValueParser: undefined, + delimiter: ',', + sigma: 2.0, + errorBars: false, + fractions: false, + wilsonInterval: true, + // only relevant if fractions is true + customBars: false, + fillGraph: false, + fillAlpha: 0.15, + connectSeparatedPoints: false, + stackedGraph: false, + stackedGraphNaNFill: 'all', + hideOverlayOnMouseOut: true, + resizable: 'no', + legend: 'onmouseover', + legendFollowOffsetX: 50, + legendFollowOffsetY: -50, + stepPlot: false, + xRangePad: 0, + yRangePad: null, + drawAxesAtZero: false, + // Sizes of the various chart labels. + titleHeight: 28, + xLabelHeight: 18, + yLabelWidth: 18, + axisLineColor: "black", + axisLineWidth: 0.3, + gridLineWidth: 0.3, + axisLabelWidth: 50, + gridLineColor: "rgb(128,128,128)", + interactionModel: _dygraphInteractionModel["default"].defaultModel, + animatedZooms: false, + // (for now) + animateBackgroundFade: true, + // Range selector options + showRangeSelector: false, + rangeSelectorHeight: 40, + rangeSelectorPlotStrokeColor: "#808FAB", + rangeSelectorPlotFillGradientColor: "white", + rangeSelectorPlotFillColor: "#A7B1C4", + rangeSelectorBackgroundStrokeColor: "gray", + rangeSelectorBackgroundLineWidth: 1, + rangeSelectorPlotLineWidth: 1.5, + rangeSelectorForegroundStrokeColor: "black", + rangeSelectorForegroundLineWidth: 1, + rangeSelectorAlpha: 0.6, + showInRangeSelector: null, + // The ordering here ensures that central lines always appear above any + // fill bars/error bars. + plotter: [_dygraphCanvas["default"]._fillPlotter, _dygraphCanvas["default"]._errorPlotter, _dygraphCanvas["default"]._linePlotter], + plugins: [], + // per-axis options + axes: { + x: { + pixelsPerLabel: 70, + axisLabelWidth: 60, + axisLabelFormatter: utils.dateAxisLabelFormatter, + valueFormatter: utils.dateValueFormatter, + drawGrid: true, + drawAxis: true, + independentTicks: true, + ticker: DygraphTickers.dateTicker + }, + y: { + axisLabelWidth: 50, + pixelsPerLabel: 30, + valueFormatter: utils.numberValueFormatter, + axisLabelFormatter: utils.numberAxisLabelFormatter, + drawGrid: true, + drawAxis: true, + independentTicks: true, + ticker: DygraphTickers.numericTicks + }, + y2: { + axisLabelWidth: 50, + pixelsPerLabel: 30, + valueFormatter: utils.numberValueFormatter, + axisLabelFormatter: utils.numberAxisLabelFormatter, + drawAxis: true, + // only applies when there are two axes of data. + drawGrid: false, + independentTicks: false, + ticker: DygraphTickers.numericTicks + } + } +}; +var _default = DEFAULT_ATTRS; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph-canvas":"dygraphs/src/dygraph-canvas.js","./dygraph-interaction-model":"dygraphs/src/dygraph-interaction-model.js","./dygraph-tickers":"dygraphs/src/dygraph-tickers.js","./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-gviz.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview A wrapper around the Dygraph class which implements the + * interface for a GViz (aka Google Visualization API) visualization. + * It is designed to be a drop-in replacement for Google's AnnotatedTimeline, + * so the documentation at + * http://code.google.com/apis/chart/interactive/docs/gallery/annotatedtimeline.html + * translates over directly. + * + * For a full demo, see: + * - http://dygraphs.com/tests/gviz.html + * - http://dygraphs.com/tests/annotation-gviz.html + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _dygraph = _interopRequireDefault(require("./dygraph")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +/** + * A wrapper around Dygraph that implements the gviz API. + * @param {!HTMLDivElement} container The DOM object the visualization should + * live in. + * @constructor + */ +var GVizChart = function GVizChart(container) { + this.container = container; +}; + +/** + * @param {GVizDataTable} data + * @param {Object.<*>} options + */ +GVizChart.prototype.draw = function (data, options) { + // Clear out any existing dygraph. + // TODO(danvk): would it make more sense to simply redraw using the current + // date_graph object? + this.container.innerHTML = ''; + if (typeof this.date_graph != 'undefined') { + this.date_graph.destroy(); + } + this.date_graph = new _dygraph["default"](this.container, data, options); +}; + +/** + * Google charts compatible setSelection + * Only row selection is supported, all points in the row will be highlighted + * @param {Array.<{row:number}>} selection_array array of the selected cells + * @public + */ +GVizChart.prototype.setSelection = function (selection_array) { + var row = false; + if (selection_array.length) { + row = selection_array[0].row; + } + this.date_graph.setSelection(row); +}; + +/** + * Google charts compatible getSelection implementation + * @return {Array.<{row:number,column:number}>} array of the selected cells + * @public + */ +GVizChart.prototype.getSelection = function () { + var selection = []; + var row = this.date_graph.getSelection(); + if (row < 0) return selection; + var points = this.date_graph.layout_.points; + for (var setIdx = 0; setIdx < points.length; ++setIdx) { + selection.push({ + row: row, + column: setIdx + 1 + }); + } + return selection; +}; +var _default = GVizChart; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph":"dygraphs/src/dygraph.js"}],"dygraphs/src/dygraph-interaction-model.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Robert Konigsberg (konigsberg@google.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview The default interaction model for Dygraphs. This is kept out + * of dygraph.js for better navigability. + * @author Robert Konigsberg (konigsberg@google.com) + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * You can drag this many pixels past the edge of the chart and still have it + * be considered a zoom. This makes it easier to zoom to the exact edge of the + * chart, a fairly common operation. + */ +var DRAG_EDGE_MARGIN = 100; + +/** + * A collection of functions to facilitate build custom interaction models. + * @class + */ +var DygraphInteraction = {}; + +/** + * Checks whether the beginning & ending of an event were close enough that it + * should be considered a click. If it should, dispatch appropriate events. + * Returns true if the event was treated as a click. + * + * @param {Event} event + * @param {Dygraph} g + * @param {Object} context + */ +DygraphInteraction.maybeTreatMouseOpAsClick = function (event, g, context) { + context.dragEndX = utils.dragGetX_(event, context); + context.dragEndY = utils.dragGetY_(event, context); + var regionWidth = Math.abs(context.dragEndX - context.dragStartX); + var regionHeight = Math.abs(context.dragEndY - context.dragStartY); + if (regionWidth < 2 && regionHeight < 2 && g.lastx_ !== undefined && g.lastx_ !== null) { + DygraphInteraction.treatMouseOpAsClick(g, event, context); + } + context.regionWidth = regionWidth; + context.regionHeight = regionHeight; +}; + +/** + * Called in response to an interaction model operation that + * should start the default panning behavior. + * + * It's used in the default callback for "mousedown" operations. + * Custom interaction model builders can use it to provide the default + * panning behavior. + * + * @param {Event} event the event object which led to the startPan call. + * @param {Dygraph} g The dygraph on which to act. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.startPan = function (event, g, context) { + var i, axis; + context.isPanning = true; + var xRange = g.xAxisRange(); + if (g.getOptionForAxis("logscale", "x")) { + context.initialLeftmostDate = utils.log10(xRange[0]); + context.dateRange = utils.log10(xRange[1]) - utils.log10(xRange[0]); + } else { + context.initialLeftmostDate = xRange[0]; + context.dateRange = xRange[1] - xRange[0]; + } + context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1); + if (g.getNumericOption("panEdgeFraction")) { + var maxXPixelsToDraw = g.width_ * g.getNumericOption("panEdgeFraction"); + var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes! + + var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw; + var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw; + var boundedLeftDate = g.toDataXCoord(boundedLeftX); + var boundedRightDate = g.toDataXCoord(boundedRightX); + context.boundedDates = [boundedLeftDate, boundedRightDate]; + var boundedValues = []; + var maxYPixelsToDraw = g.height_ * g.getNumericOption("panEdgeFraction"); + for (i = 0; i < g.axes_.length; i++) { + axis = g.axes_[i]; + var yExtremes = axis.extremeRange; + var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw; + var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw; + var boundedTopValue = g.toDataYCoord(boundedTopY, i); + var boundedBottomValue = g.toDataYCoord(boundedBottomY, i); + boundedValues[i] = [boundedTopValue, boundedBottomValue]; + } + context.boundedValues = boundedValues; + } else { + // undo effect if it was once set + context.boundedDates = null; + context.boundedValues = null; + } + + // Record the range of each y-axis at the start of the drag. + // If any axis has a valueRange, then we want a 2D pan. + // We can't store data directly in g.axes_, because it does not belong to us + // and could change out from under us during a pan (say if there's a data + // update). + context.is2DPan = false; + context.axes = []; + for (i = 0; i < g.axes_.length; i++) { + axis = g.axes_[i]; + var axis_data = {}; + var yRange = g.yAxisRange(i); + // TODO(konigsberg): These values should be in |context|. + // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale. + var logscale = g.attributes_.getForAxis("logscale", i); + if (logscale) { + axis_data.initialTopValue = utils.log10(yRange[1]); + axis_data.dragValueRange = utils.log10(yRange[1]) - utils.log10(yRange[0]); + } else { + axis_data.initialTopValue = yRange[1]; + axis_data.dragValueRange = yRange[1] - yRange[0]; + } + axis_data.unitsPerPixel = axis_data.dragValueRange / (g.plotter_.area.h - 1); + context.axes.push(axis_data); + + // While calculating axes, set 2dpan. + if (axis.valueRange) context.is2DPan = true; + } +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that pans the view. + * + * It's used in the default callback for "mousemove" operations. + * Custom interaction model builders can use it to provide the default + * panning behavior. + * + * @param {Event} event the event object which led to the movePan call. + * @param {Dygraph} g The dygraph on which to act. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.movePan = function (event, g, context) { + context.dragEndX = utils.dragGetX_(event, context); + context.dragEndY = utils.dragGetY_(event, context); + var minDate = context.initialLeftmostDate - (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel; + if (context.boundedDates) { + minDate = Math.max(minDate, context.boundedDates[0]); + } + var maxDate = minDate + context.dateRange; + if (context.boundedDates) { + if (maxDate > context.boundedDates[1]) { + // Adjust minDate, and recompute maxDate. + minDate = minDate - (maxDate - context.boundedDates[1]); + maxDate = minDate + context.dateRange; + } + } + if (g.getOptionForAxis("logscale", "x")) { + g.dateWindow_ = [Math.pow(utils.LOG_SCALE, minDate), Math.pow(utils.LOG_SCALE, maxDate)]; + } else { + g.dateWindow_ = [minDate, maxDate]; + } + + // y-axis scaling is automatic unless this is a full 2D pan. + if (context.is2DPan) { + var pixelsDragged = context.dragEndY - context.dragStartY; + + // Adjust each axis appropriately. + for (var i = 0; i < g.axes_.length; i++) { + var axis = g.axes_[i]; + var axis_data = context.axes[i]; + var unitsDragged = pixelsDragged * axis_data.unitsPerPixel; + var boundedValue = context.boundedValues ? context.boundedValues[i] : null; + + // In log scale, maxValue and minValue are the logs of those values. + var maxValue = axis_data.initialTopValue + unitsDragged; + if (boundedValue) { + maxValue = Math.min(maxValue, boundedValue[1]); + } + var minValue = maxValue - axis_data.dragValueRange; + if (boundedValue) { + if (minValue < boundedValue[0]) { + // Adjust maxValue, and recompute minValue. + maxValue = maxValue - (minValue - boundedValue[0]); + minValue = maxValue - axis_data.dragValueRange; + } + } + if (g.attributes_.getForAxis("logscale", i)) { + axis.valueRange = [Math.pow(utils.LOG_SCALE, minValue), Math.pow(utils.LOG_SCALE, maxValue)]; + } else { + axis.valueRange = [minValue, maxValue]; + } + } + } + g.drawGraph_(false); +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that ends panning. + * + * It's used in the default callback for "mouseup" operations. + * Custom interaction model builders can use it to provide the default + * panning behavior. + * + * @param {Event} event the event object which led to the endPan call. + * @param {Dygraph} g The dygraph on which to act. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.endPan = DygraphInteraction.maybeTreatMouseOpAsClick; + +/** + * Called in response to an interaction model operation that + * responds to an event that starts zooming. + * + * It's used in the default callback for "mousedown" operations. + * Custom interaction model builders can use it to provide the default + * zooming behavior. + * + * @param {Event} event the event object which led to the startZoom call. + * @param {Dygraph} g The dygraph on which to act. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.startZoom = function (event, g, context) { + context.isZooming = true; + context.zoomMoved = false; +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that defines zoom boundaries. + * + * It's used in the default callback for "mousemove" operations. + * Custom interaction model builders can use it to provide the default + * zooming behavior. + * + * @param {Event} event the event object which led to the moveZoom call. + * @param {Dygraph} g The dygraph on which to act. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.moveZoom = function (event, g, context) { + context.zoomMoved = true; + context.dragEndX = utils.dragGetX_(event, context); + context.dragEndY = utils.dragGetY_(event, context); + var xDelta = Math.abs(context.dragStartX - context.dragEndX); + var yDelta = Math.abs(context.dragStartY - context.dragEndY); + + // drag direction threshold for y axis is twice as large as x axis + context.dragDirection = xDelta < yDelta / 2 ? utils.VERTICAL : utils.HORIZONTAL; + g.drawZoomRect_(context.dragDirection, context.dragStartX, context.dragEndX, context.dragStartY, context.dragEndY, context.prevDragDirection, context.prevEndX, context.prevEndY); + context.prevEndX = context.dragEndX; + context.prevEndY = context.dragEndY; + context.prevDragDirection = context.dragDirection; +}; + +/** + * TODO(danvk): move this logic into dygraph.js + * @param {Dygraph} g + * @param {Event} event + * @param {Object} context + */ +DygraphInteraction.treatMouseOpAsClick = function (g, event, context) { + var clickCallback = g.getFunctionOption('clickCallback'); + var pointClickCallback = g.getFunctionOption('pointClickCallback'); + var selectedPoint = null; + + // Find out if the click occurs on a point. + var closestIdx = -1; + var closestDistance = Number.MAX_VALUE; + + // check if the click was on a particular point. + for (var i = 0; i < g.selPoints_.length; i++) { + var p = g.selPoints_[i]; + var distance = Math.pow(p.canvasx - context.dragEndX, 2) + Math.pow(p.canvasy - context.dragEndY, 2); + if (!isNaN(distance) && (closestIdx == -1 || distance < closestDistance)) { + closestDistance = distance; + closestIdx = i; + } + } + + // Allow any click within two pixels of the dot. + var radius = g.getNumericOption('highlightCircleSize') + 2; + if (closestDistance <= radius * radius) { + selectedPoint = g.selPoints_[closestIdx]; + } + if (selectedPoint) { + var e = { + cancelable: true, + point: selectedPoint, + canvasx: context.dragEndX, + canvasy: context.dragEndY + }; + var defaultPrevented = g.cascadeEvents_('pointClick', e); + if (defaultPrevented) { + // Note: this also prevents click / clickCallback from firing. + return; + } + if (pointClickCallback) { + pointClickCallback.call(g, event, selectedPoint); + } + } + var e = { + cancelable: true, + xval: g.lastx_, + // closest point by x value + pts: g.selPoints_, + canvasx: context.dragEndX, + canvasy: context.dragEndY + }; + if (!g.cascadeEvents_('click', e)) { + if (clickCallback) { + // TODO(danvk): pass along more info about the points, e.g. 'x' + clickCallback.call(g, event, g.lastx_, g.selPoints_); + } + } +}; + +/** + * Called in response to an interaction model operation that + * responds to an event that performs a zoom based on previously defined + * bounds.. + * + * It's used in the default callback for "mouseup" operations. + * Custom interaction model builders can use it to provide the default + * zooming behavior. + * + * @param {Event} event the event object which led to the endZoom call. + * @param {Dygraph} g The dygraph on which to end the zoom. + * @param {Object} context The dragging context object (with + * dragStartX/dragStartY/etc. properties). This function modifies the + * context. + */ +DygraphInteraction.endZoom = function (event, g, context) { + g.clearZoomRect_(); + context.isZooming = false; + DygraphInteraction.maybeTreatMouseOpAsClick(event, g, context); + + // The zoom rectangle is visibly clipped to the plot area, so its behavior + // should be as well. + // See http://code.google.com/p/dygraphs/issues/detail?id=280 + var plotArea = g.getArea(); + if (context.regionWidth >= 10 && context.dragDirection == utils.HORIZONTAL) { + var left = Math.min(context.dragStartX, context.dragEndX), + right = Math.max(context.dragStartX, context.dragEndX); + left = Math.max(left, plotArea.x); + right = Math.min(right, plotArea.x + plotArea.w); + if (left < right) { + g.doZoomX_(left, right); + } + context.cancelNextDblclick = true; + } else if (context.regionHeight >= 10 && context.dragDirection == utils.VERTICAL) { + var top = Math.min(context.dragStartY, context.dragEndY), + bottom = Math.max(context.dragStartY, context.dragEndY); + top = Math.max(top, plotArea.y); + bottom = Math.min(bottom, plotArea.y + plotArea.h); + if (top < bottom) { + g.doZoomY_(top, bottom); + } + context.cancelNextDblclick = true; + } + context.dragStartX = null; + context.dragStartY = null; +}; + +/** + * @private + */ +DygraphInteraction.startTouch = function (event, g, context) { + event.preventDefault(); // touch browsers are all nice. + if (event.touches.length > 1) { + // If the user ever puts two fingers down, it's not a double tap. + context.startTimeForDoubleTapMs = null; + } + var touches = []; + for (var i = 0; i < event.touches.length; i++) { + var t = event.touches[i]; + var rect = t.target.getBoundingClientRect(); + // we dispense with 'dragGetX_' because all touchBrowsers support pageX + touches.push({ + pageX: t.pageX, + pageY: t.pageY, + dataX: g.toDataXCoord(t.clientX - rect.left), + dataY: g.toDataYCoord(t.clientY - rect.top) + // identifier: t.identifier + }); + } + + context.initialTouches = touches; + if (touches.length == 1) { + // This is just a swipe. + context.initialPinchCenter = touches[0]; + context.touchDirections = { + x: true, + y: true + }; + } else if (touches.length >= 2) { + // It's become a pinch! + // In case there are 3+ touches, we ignore all but the "first" two. + + // only screen coordinates can be averaged (data coords could be log scale). + context.initialPinchCenter = { + pageX: 0.5 * (touches[0].pageX + touches[1].pageX), + pageY: 0.5 * (touches[0].pageY + touches[1].pageY), + // TODO(danvk): remove + dataX: 0.5 * (touches[0].dataX + touches[1].dataX), + dataY: 0.5 * (touches[0].dataY + touches[1].dataY) + }; + + // Make pinches in a 45-degree swath around either axis 1-dimensional zooms. + var initialAngle = 180 / Math.PI * Math.atan2(context.initialPinchCenter.pageY - touches[0].pageY, touches[0].pageX - context.initialPinchCenter.pageX); + + // use symmetry to get it into the first quadrant. + initialAngle = Math.abs(initialAngle); + if (initialAngle > 90) initialAngle = 90 - initialAngle; + context.touchDirections = { + x: initialAngle < 90 - 45 / 2, + y: initialAngle > 45 / 2 + }; + } + + // save the full x & y ranges. + context.initialRange = { + x: g.xAxisRange(), + y: g.yAxisRange() + }; +}; + +/** + * @private + */ +DygraphInteraction.moveTouch = function (event, g, context) { + // If the tap moves, then it's definitely not part of a double-tap. + context.startTimeForDoubleTapMs = null; + var i, + touches = []; + for (i = 0; i < event.touches.length; i++) { + var t = event.touches[i]; + touches.push({ + pageX: t.pageX, + pageY: t.pageY + }); + } + var initialTouches = context.initialTouches; + var c_now; + + // old and new centers. + var c_init = context.initialPinchCenter; + if (touches.length == 1) { + c_now = touches[0]; + } else { + c_now = { + pageX: 0.5 * (touches[0].pageX + touches[1].pageX), + pageY: 0.5 * (touches[0].pageY + touches[1].pageY) + }; + } + + // this is the "swipe" component + // we toss it out for now, but could use it in the future. + var swipe = { + pageX: c_now.pageX - c_init.pageX, + pageY: c_now.pageY - c_init.pageY + }; + var dataWidth = context.initialRange.x[1] - context.initialRange.x[0]; + var dataHeight = context.initialRange.y[0] - context.initialRange.y[1]; + swipe.dataX = swipe.pageX / g.plotter_.area.w * dataWidth; + swipe.dataY = swipe.pageY / g.plotter_.area.h * dataHeight; + var xScale, yScale; + + // The residual bits are usually split into scale & rotate bits, but we split + // them into x-scale and y-scale bits. + if (touches.length == 1) { + xScale = 1.0; + yScale = 1.0; + } else if (touches.length >= 2) { + var initHalfWidth = initialTouches[1].pageX - c_init.pageX; + xScale = (touches[1].pageX - c_now.pageX) / initHalfWidth; + var initHalfHeight = initialTouches[1].pageY - c_init.pageY; + yScale = (touches[1].pageY - c_now.pageY) / initHalfHeight; + } + + // Clip scaling to [1/8, 8] to prevent too much blowup. + xScale = Math.min(8, Math.max(0.125, xScale)); + yScale = Math.min(8, Math.max(0.125, yScale)); + var didZoom = false; + if (context.touchDirections.x) { + var cFactor = c_init.dataX - swipe.dataX / xScale; + g.dateWindow_ = [cFactor + (context.initialRange.x[0] - c_init.dataX) / xScale, cFactor + (context.initialRange.x[1] - c_init.dataX) / xScale]; + didZoom = true; + } + if (context.touchDirections.y) { + for (i = 0; i < 1 /*g.axes_.length*/; i++) { + var axis = g.axes_[i]; + var logscale = g.attributes_.getForAxis("logscale", i); + if (logscale) { + // TODO(danvk): implement + } else { + var cFactor = c_init.dataY - swipe.dataY / yScale; + axis.valueRange = [cFactor + (context.initialRange.y[0] - c_init.dataY) / yScale, cFactor + (context.initialRange.y[1] - c_init.dataY) / yScale]; + didZoom = true; + } + } + } + g.drawGraph_(false); + + // We only call zoomCallback on zooms, not pans, to mirror desktop behavior. + if (didZoom && touches.length > 1 && g.getFunctionOption('zoomCallback')) { + var viewWindow = g.xAxisRange(); + g.getFunctionOption("zoomCallback").call(g, viewWindow[0], viewWindow[1], g.yAxisRanges()); + } +}; + +/** + * @private + */ +DygraphInteraction.endTouch = function (event, g, context) { + if (event.touches.length !== 0) { + // this is effectively a "reset" + DygraphInteraction.startTouch(event, g, context); + } else if (event.changedTouches.length == 1) { + // Could be part of a "double tap" + // The heuristic here is that it's a double-tap if the two touchend events + // occur within 500ms and within a 50x50 pixel box. + var now = new Date().getTime(); + var t = event.changedTouches[0]; + if (context.startTimeForDoubleTapMs && now - context.startTimeForDoubleTapMs < 500 && context.doubleTapX && Math.abs(context.doubleTapX - t.screenX) < 50 && context.doubleTapY && Math.abs(context.doubleTapY - t.screenY) < 50) { + g.resetZoom(); + } else { + context.startTimeForDoubleTapMs = now; + context.doubleTapX = t.screenX; + context.doubleTapY = t.screenY; + } + } +}; + +// Determine the distance from x to [left, right]. +var distanceFromInterval = function distanceFromInterval(x, left, right) { + if (x < left) { + return left - x; + } else if (x > right) { + return x - right; + } else { + return 0; + } +}; + +/** + * Returns the number of pixels by which the event happens from the nearest + * edge of the chart. For events in the interior of the chart, this returns zero. + */ +var distanceFromChart = function distanceFromChart(event, g) { + var chartPos = utils.findPos(g.canvas_); + var box = { + left: chartPos.x, + right: chartPos.x + g.canvas_.offsetWidth, + top: chartPos.y, + bottom: chartPos.y + g.canvas_.offsetHeight + }; + var pt = { + x: utils.pageX(event), + y: utils.pageY(event) + }; + var dx = distanceFromInterval(pt.x, box.left, box.right), + dy = distanceFromInterval(pt.y, box.top, box.bottom); + return Math.max(dx, dy); +}; + +/** + * Default interation model for dygraphs. You can refer to specific elements of + * this when constructing your own interaction model, e.g.: + * g.updateOptions( { + * interactionModel: { + * mousedown: DygraphInteraction.defaultInteractionModel.mousedown + * } + * } ); + */ +DygraphInteraction.defaultModel = { + // Track the beginning of drag events + mousedown: function mousedown(event, g, context) { + // Right-click should not initiate a zoom. + if (event.button && event.button == 2) return; + context.initializeMouseDown(event, g, context); + if (event.altKey || event.shiftKey) { + DygraphInteraction.startPan(event, g, context); + } else { + DygraphInteraction.startZoom(event, g, context); + } + + // Note: we register mousemove/mouseup on document to allow some leeway for + // events to move outside of the chart. Interaction model events get + // registered on the canvas, which is too small to allow this. + var mousemove = function mousemove(event) { + if (context.isZooming) { + // When the mouse moves >200px from the chart edge, cancel the zoom. + var d = distanceFromChart(event, g); + if (d < DRAG_EDGE_MARGIN) { + DygraphInteraction.moveZoom(event, g, context); + } else { + if (context.dragEndX !== null) { + context.dragEndX = null; + context.dragEndY = null; + g.clearZoomRect_(); + } + } + } else if (context.isPanning) { + DygraphInteraction.movePan(event, g, context); + } + }; + var mouseup = function mouseup(event) { + if (context.isZooming) { + if (context.dragEndX !== null) { + DygraphInteraction.endZoom(event, g, context); + } else { + DygraphInteraction.maybeTreatMouseOpAsClick(event, g, context); + } + } else if (context.isPanning) { + DygraphInteraction.endPan(event, g, context); + } + utils.removeEvent(document, 'mousemove', mousemove); + utils.removeEvent(document, 'mouseup', mouseup); + context.destroy(); + }; + g.addAndTrackEvent(document, 'mousemove', mousemove); + g.addAndTrackEvent(document, 'mouseup', mouseup); + }, + willDestroyContextMyself: true, + touchstart: function touchstart(event, g, context) { + DygraphInteraction.startTouch(event, g, context); + }, + touchmove: function touchmove(event, g, context) { + DygraphInteraction.moveTouch(event, g, context); + }, + touchend: function touchend(event, g, context) { + DygraphInteraction.endTouch(event, g, context); + }, + // Disable zooming out if panning. + dblclick: function dblclick(event, g, context) { + if (context.cancelNextDblclick) { + context.cancelNextDblclick = false; + return; + } + + // Give plugins a chance to grab this event. + var e = { + canvasx: context.dragEndX, + canvasy: context.dragEndY, + cancelable: true + }; + if (g.cascadeEvents_('dblclick', e)) { + return; + } + if (event.altKey || event.shiftKey) { + return; + } + g.resetZoom(); + } +}; + +/* +Dygraph.DEFAULT_ATTRS.interactionModel = DygraphInteraction.defaultModel; + +// old ways of accessing these methods/properties +Dygraph.defaultInteractionModel = DygraphInteraction.defaultModel; +Dygraph.endZoom = DygraphInteraction.endZoom; +Dygraph.moveZoom = DygraphInteraction.moveZoom; +Dygraph.startZoom = DygraphInteraction.startZoom; +Dygraph.endPan = DygraphInteraction.endPan; +Dygraph.movePan = DygraphInteraction.movePan; +Dygraph.startPan = DygraphInteraction.startPan; +*/ + +DygraphInteraction.nonInteractiveModel_ = { + mousedown: function mousedown(event, g, context) { + context.initializeMouseDown(event, g, context); + }, + mouseup: DygraphInteraction.maybeTreatMouseOpAsClick +}; + +// Default interaction model when using the range selector. +DygraphInteraction.dragIsPanInteractionModel = { + mousedown: function mousedown(event, g, context) { + context.initializeMouseDown(event, g, context); + DygraphInteraction.startPan(event, g, context); + }, + mousemove: function mousemove(event, g, context) { + if (context.isPanning) { + DygraphInteraction.movePan(event, g, context); + } + }, + mouseup: function mouseup(event, g, context) { + if (context.isPanning) { + DygraphInteraction.endPan(event, g, context); + } + } +}; +var _default = DygraphInteraction; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-layout.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview Based on PlotKitLayout, but modified to meet the needs of + * dygraphs. + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * Creates a new DygraphLayout object. + * + * This class contains all the data to be charted. + * It uses data coordinates, but also records the chart range (in data + * coordinates) and hence is able to calculate percentage positions ('In this + * view, Point A lies 25% down the x-axis.') + * + * Two things that it does not do are: + * 1. Record pixel coordinates for anything. + * 2. (oddly) determine anything about the layout of chart elements. + * + * The naming is a vestige of Dygraph's original PlotKit roots. + * + * @constructor + */ +var DygraphLayout = function DygraphLayout(dygraph) { + this.dygraph_ = dygraph; + /** + * Array of points for each series. + * + * [series index][row index in series] = |Point| structure, + * where series index refers to visible series only, and the + * point index is for the reduced set of points for the current + * zoom region (including one point just outside the window). + * All points in the same row index share the same X value. + * + * @type {Array.>} + */ + this.points = []; + this.setNames = []; + this.annotations = []; + this.yAxes_ = null; + + // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, + // but xticks and yticks are outputs. Clean this up. + this.xTicks_ = null; + this.yTicks_ = null; +}; + +/** + * Add points for a single series. + * + * @param {string} setname Name of the series. + * @param {Array.} set_xy Points for the series. + */ +DygraphLayout.prototype.addDataset = function (setname, set_xy) { + this.points.push(set_xy); + this.setNames.push(setname); +}; + +/** + * Returns the box which the chart should be drawn in. This is the canvas's + * box, less space needed for the axis and chart labels. + * + * @return {{x: number, y: number, w: number, h: number}} + */ +DygraphLayout.prototype.getPlotArea = function () { + return this.area_; +}; + +// Compute the box which the chart should be drawn in. This is the canvas's +// box, less space needed for axis, chart labels, and other plug-ins. +// NOTE: This should only be called by Dygraph.predraw_(). +DygraphLayout.prototype.computePlotArea = function () { + var area = { + // TODO(danvk): per-axis setting. + x: 0, + y: 0 + }; + area.w = this.dygraph_.width_ - area.x - this.dygraph_.getOption('rightGap'); + area.h = this.dygraph_.height_; + + // Let plugins reserve space. + var e = { + chart_div: this.dygraph_.graphDiv, + reserveSpaceLeft: function reserveSpaceLeft(px) { + var r = { + x: area.x, + y: area.y, + w: px, + h: area.h + }; + area.x += px; + area.w -= px; + return r; + }, + reserveSpaceRight: function reserveSpaceRight(px) { + var r = { + x: area.x + area.w - px, + y: area.y, + w: px, + h: area.h + }; + area.w -= px; + return r; + }, + reserveSpaceTop: function reserveSpaceTop(px) { + var r = { + x: area.x, + y: area.y, + w: area.w, + h: px + }; + area.y += px; + area.h -= px; + return r; + }, + reserveSpaceBottom: function reserveSpaceBottom(px) { + var r = { + x: area.x, + y: area.y + area.h - px, + w: area.w, + h: px + }; + area.h -= px; + return r; + }, + chartRect: function chartRect() { + return { + x: area.x, + y: area.y, + w: area.w, + h: area.h + }; + } + }; + this.dygraph_.cascadeEvents_('layout', e); + this.area_ = area; +}; +DygraphLayout.prototype.setAnnotations = function (ann) { + // The Dygraph object's annotations aren't parsed. We parse them here and + // save a copy. If there is no parser, then the user must be using raw format. + this.annotations = []; + var parse = this.dygraph_.getOption('xValueParser') || function (x) { + return x; + }; + for (var i = 0; i < ann.length; i++) { + var a = {}; + if (!ann[i].xval && ann[i].x === undefined) { + console.error("Annotations must have an 'x' property"); + return; + } + if (ann[i].icon && !(ann[i].hasOwnProperty('width') && ann[i].hasOwnProperty('height'))) { + console.error("Must set width and height when setting " + "annotation.icon property"); + return; + } + utils.update(a, ann[i]); + if (!a.xval) a.xval = parse(a.x); + this.annotations.push(a); + } +}; +DygraphLayout.prototype.setXTicks = function (xTicks) { + this.xTicks_ = xTicks; +}; + +// TODO(danvk): add this to the Dygraph object's API or move it into Layout. +DygraphLayout.prototype.setYAxes = function (yAxes) { + this.yAxes_ = yAxes; +}; +DygraphLayout.prototype.evaluate = function () { + this._xAxis = {}; + this._evaluateLimits(); + this._evaluateLineCharts(); + this._evaluateLineTicks(); + this._evaluateAnnotations(); +}; +DygraphLayout.prototype._evaluateLimits = function () { + var xlimits = this.dygraph_.xAxisRange(); + this._xAxis.minval = xlimits[0]; + this._xAxis.maxval = xlimits[1]; + var xrange = xlimits[1] - xlimits[0]; + this._xAxis.scale = xrange !== 0 ? 1 / xrange : 1.0; + if (this.dygraph_.getOptionForAxis("logscale", 'x')) { + this._xAxis.xlogrange = utils.log10(this._xAxis.maxval) - utils.log10(this._xAxis.minval); + this._xAxis.xlogscale = this._xAxis.xlogrange !== 0 ? 1.0 / this._xAxis.xlogrange : 1.0; + } + for (var i = 0; i < this.yAxes_.length; i++) { + var axis = this.yAxes_[i]; + axis.minyval = axis.computedValueRange[0]; + axis.maxyval = axis.computedValueRange[1]; + axis.yrange = axis.maxyval - axis.minyval; + axis.yscale = axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0; + if (this.dygraph_.getOption("logscale") || axis.logscale) { + axis.ylogrange = utils.log10(axis.maxyval) - utils.log10(axis.minyval); + axis.ylogscale = axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0; + if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) { + console.error('axis ' + i + ' of graph at ' + axis.g + ' can\'t be displayed in log scale for range [' + axis.minyval + ' - ' + axis.maxyval + ']'); + } + } + } +}; +DygraphLayout.calcXNormal_ = function (value, xAxis, logscale) { + if (logscale) { + return (utils.log10(value) - utils.log10(xAxis.minval)) * xAxis.xlogscale; + } else { + return (value - xAxis.minval) * xAxis.scale; + } +}; + +/** + * @param {DygraphAxisType} axis + * @param {number} value + * @param {boolean} logscale + * @return {number} + */ +DygraphLayout.calcYNormal_ = function (axis, value, logscale) { + if (logscale) { + var x = 1.0 - (utils.log10(value) - utils.log10(axis.minyval)) * axis.ylogscale; + return isFinite(x) ? x : NaN; // shim for v8 issue; see pull request 276 + } else { + return 1.0 - (value - axis.minyval) * axis.yscale; + } +}; +DygraphLayout.prototype._evaluateLineCharts = function () { + var isStacked = this.dygraph_.getOption("stackedGraph"); + var isLogscaleForX = this.dygraph_.getOptionForAxis("logscale", 'x'); + for (var setIdx = 0; setIdx < this.points.length; setIdx++) { + var points = this.points[setIdx]; + var setName = this.setNames[setIdx]; + var connectSeparated = this.dygraph_.getOption('connectSeparatedPoints', setName); + var axis = this.dygraph_.axisPropertiesForSeries(setName); + // TODO (konigsberg): use optionsForAxis instead. + var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName); + for (var j = 0; j < points.length; j++) { + var point = points[j]; + + // Range from 0-1 where 0 represents left and 1 represents right. + point.x = DygraphLayout.calcXNormal_(point.xval, this._xAxis, isLogscaleForX); + // Range from 0-1 where 0 represents top and 1 represents bottom + var yval = point.yval; + if (isStacked) { + point.y_stacked = DygraphLayout.calcYNormal_(axis, point.yval_stacked, logscale); + if (yval !== null && !isNaN(yval)) { + yval = point.yval_stacked; + } + } + if (yval === null) { + yval = NaN; + if (!connectSeparated) { + point.yval = NaN; + } + } + point.y = DygraphLayout.calcYNormal_(axis, yval, logscale); + } + this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale); + } +}; +DygraphLayout.prototype._evaluateLineTicks = function () { + var i, tick, label, pos, v, has_tick; + this.xticks = []; + for (i = 0; i < this.xTicks_.length; i++) { + tick = this.xTicks_[i]; + label = tick.label; + has_tick = !('label_v' in tick); + v = has_tick ? tick.v : tick.label_v; + pos = this.dygraph_.toPercentXCoord(v); + if (pos >= 0.0 && pos < 1.0) { + this.xticks.push({ + pos: pos, + label: label, + has_tick: has_tick + }); + } + } + this.yticks = []; + for (i = 0; i < this.yAxes_.length; i++) { + var axis = this.yAxes_[i]; + for (var j = 0; j < axis.ticks.length; j++) { + tick = axis.ticks[j]; + label = tick.label; + has_tick = !('label_v' in tick); + v = has_tick ? tick.v : tick.label_v; + pos = this.dygraph_.toPercentYCoord(v, i); + if (pos > 0.0 && pos <= 1.0) { + this.yticks.push({ + axis: i, + pos: pos, + label: label, + has_tick: has_tick + }); + } + } + } +}; +DygraphLayout.prototype._evaluateAnnotations = function () { + // Add the annotations to the point to which they belong. + // Make a map from (setName, xval) to annotation for quick lookups. + var i; + var annotations = {}; + for (i = 0; i < this.annotations.length; i++) { + var a = this.annotations[i]; + annotations[a.xval + "," + a.series] = a; + } + this.annotated_points = []; + + // Exit the function early if there are no annotations. + if (!this.annotations || !this.annotations.length) { + return; + } + + // TODO(antrob): loop through annotations not points. + for (var setIdx = 0; setIdx < this.points.length; setIdx++) { + var points = this.points[setIdx]; + for (i = 0; i < points.length; i++) { + var p = points[i]; + var k = p.xval + "," + p.name; + if (k in annotations) { + p.annotation = annotations[k]; + this.annotated_points.push(p); + //if there are multiple same x-valued points, the annotation would be rendered multiple times + //remove already rendered annotation + delete annotations[k]; + } + } + } +}; + +/** + * Convenience function to remove all the data sets from a graph + */ +DygraphLayout.prototype.removeAllDatasets = function () { + delete this.points; + delete this.setNames; + delete this.setPointsLengths; + delete this.setPointsOffsets; + this.points = []; + this.setNames = []; + this.setPointsLengths = []; + this.setPointsOffsets = []; +}; +var _default = DygraphLayout; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-options-reference.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var OPTIONS_REFERENCE = null; +if (true) { + // For "production" code, this gets removed by uglifyjs. + + // NOTE: in addition to parsing as JS, this snippet is expected to be valid + // JSON. This assumption cannot be checked in JS, but it will be checked when + // documentation is generated by the generate-documentation.py script. For the + // most part, this just means that you should always use double quotes. + OPTIONS_REFERENCE = + // + { + "animateBackgroundFade": { + "default": "true", + "labels": ["Overall display"], + "type": "boolean", + "description": "Activate an animation effect for a gradual fade." + }, + "xValueParser": { + "default": "parseFloat() or Date.parse()*", + "labels": ["CSV parsing"], + "type": "function(str) -> number", + "description": "A function which parses x-values (i.e. the dependent series). Must return a number, even when the values are dates. In this case, millis since epoch are used. This is used primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which it will parse. See code for details." + }, + "stackedGraph": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "If set, stack series on top of one another rather than drawing them independently. The first series specified in the input data will wind up on top of the chart and the last will be on bottom. NaN values are drawn as white areas without a line on top, see stackedGraphNaNFill for details." + }, + "stackedGraphNaNFill": { + "default": "all", + "labels": ["Data Line display"], + "type": "string", + "description": "Controls handling of NaN values inside a stacked graph. NaN values are interpolated/extended for stacking purposes, but the actual point value remains NaN in the legend display. Valid option values are \"all\" (interpolate internally, repeat leftmost and rightmost value as needed), \"inside\" (interpolate internally only, use zero outside leftmost and rightmost value), and \"none\" (treat NaN as zero everywhere)." + }, + "pointSize": { + "default": "1", + "labels": ["Data Line display"], + "type": "integer", + "description": "The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is \"isolated\", i.e. there is a missing point on either side of it. This also controls the size of those dots." + }, + "drawPoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Draw a small dot at each point, in addition to a line going through the point. This makes the individual data points easier to see, but can increase visual clutter in the chart. The small dot can be replaced with a custom rendering by supplying a drawPointCallback." + }, + "drawGapEdgePoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities." + }, + "drawPointCallback": { + "default": "null", + "labels": ["Data Line display"], + "type": "function(g, seriesName, canvasContext, cx, cy, color, pointSize, idx)", + "parameters": [["g", "the reference graph"], ["seriesName", "the name of the series"], ["canvasContext", "the canvas to draw on"], ["cx", "center x coordinate"], ["cy", "center y coordinate"], ["color", "series color"], ["pointSize", "the radius of the image."], ["idx", "the row-index of the point in the data."]], + "description": "Draw a custom item when drawPoints is enabled. Default is a small dot matching the series color. This method should constrain drawing to within pointSize pixels from (cx, cy). Also see drawHighlightPointCallback" + }, + "height": { + "default": "320", + "labels": ["Overall display"], + "type": "integer", + "description": "Height, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored." + }, + "resizable": { + "default": "no", + "labels": ["Overall display"], + "type": "string", + "description": "Whether to add a ResizeObserver to the container div (\"passive\") and additionally make it resizable (\"horizontal\", \"vertical\", \"both\"). In any case, if the container div has CSS \"overflow:visible;\" it will be changed to \"overflow:hidden;\" to make CSS resizing possible. Note that this is distinct from resizing the graph when the window size changes, which is always active; this feature adds user-resizable “handles” to the container div." + }, + "zoomCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(minDate, maxDate, yRanges)", + "parameters": [["minDate", "milliseconds since epoch"], ["maxDate", "milliseconds since epoch."], ["yRanges", "is an array of [bottom, top] pairs, one for each y-axis."]], + "description": "A function to call when the zoom window is changed (either by zooming in or out). When animatedZooms is set, zoomCallback is called once at the end of the transition (it will not be called for intermediate frames)." + }, + "pointClickCallback": { + "snippet": "function(e, point){
      alert(point);
    }", + "default": "null", + "labels": ["Callbacks", "Interactive Elements"], + "type": "function(e, point)", + "parameters": [["e", "the event object for the click"], ["point", "the point that was clicked See Point properties for details"]], + "description": "A function to call when a data point is clicked. and the point that was clicked." + }, + "color": { + "default": "(see description)", + "labels": ["Data Series Colors"], + "type": "string", + "example": "red", + "description": "A per-series color definition. Used in conjunction with, and overrides, the colors option." + }, + "colors": { + "default": "(see description)", + "labels": ["Data Series Colors"], + "type": "Array of strings", + "example": "['red', '#00FF00']", + "description": "List of colors for the data series. These can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\", etc. If not specified, equally-spaced points around a color wheel are used. Overridden by the “color” option." + }, + "connectSeparatedPoints": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Usually, when Dygraphs encounters a missing value in a data series, it interprets this as a gap and draws it as such. If, instead, the missing values represents an x-value for which only a different series has data, then you’ll want to connect the dots by setting this to true. To explicitly include a gap with this option set, use a value of NaN." + }, + "highlightCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(event, x, points, row, seriesName)", + "description": "When set, this callback gets called every time a new point is highlighted.", + "parameters": [["event", "the JavaScript mousemove event"], ["x", "the x-coordinate of the highlighted points"], ["points", "an array of highlighted points: [ {name: 'series', yval: y-value}, … ]"], ["row", "integer index of the highlighted row in the data table, starting from 0"], ["seriesName", "name of the highlighted series, only present if highlightSeriesOpts is set."]] + }, + "drawHighlightPointCallback": { + "default": "null", + "labels": ["Data Line display"], + "type": "function(g, seriesName, canvasContext, cx, cy, color, pointSize, idx)", + "parameters": [["g", "the reference graph"], ["seriesName", "the name of the series"], ["canvasContext", "the canvas to draw on"], ["cx", "center x coordinate"], ["cy", "center y coordinate"], ["color", "series color"], ["pointSize", "the radius of the image."], ["idx", "the row-index of the point in the data."]], + "description": "Draw a custom item when a point is highlighted. Default is a small dot matching the series color. This method should constrain drawing to within pointSize pixels from (cx, cy) Also see drawPointCallback" + }, + "highlightSeriesOpts": { + "default": "null", + "labels": ["Interactive Elements"], + "type": "Object", + "description": "When set, the options from this object are applied to the timeseries closest to the mouse pointer for interactive highlighting. See also “highlightCallback”. Example: highlightSeriesOpts: { strokeWidth: 3 }." + }, + "highlightSeriesBackgroundAlpha": { + "default": "0.5", + "labels": ["Interactive Elements"], + "type": "float", + "description": "Fade the background while highlighting series. 1=fully visible background (disable fading), 0=hiddden background (show highlighted series only)." + }, + "highlightSeriesBackgroundColor": { + "default": "rgb(255, 255, 255)", + "labels": ["Interactive Elements"], + "type": "string", + "description": "Sets the background color used to fade out the series in conjunction with “highlightSeriesBackgroundAlpha”." + }, + "includeZero": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "Usually, dygraphs will use the range of the data plus some padding to set the range of the y-axis. If this option is set, the y-axis will always include zero, typically as the lowest value. This can be used to avoid exaggerating the variance in the data" + }, + "rollPeriod": { + "default": "1", + "labels": ["Error Bars", "Rolling Averages"], + "type": "integer >= 1", + "description": "Number of days over which to average data. Discussed extensively above." + }, + "unhighlightCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(event)", + "parameters": [["event", "the mouse event"]], + "description": "When set, this callback gets called every time the user stops highlighting any point by mousing out of the graph." + }, + "axisTickSize": { + "default": "3.0", + "labels": ["Axis display"], + "type": "number", + "description": "The size of the line to display next to each tick mark on x- or y-axes." + }, + "labelsSeparateLines": { + "default": "false", + "labels": ["Legend"], + "type": "boolean", + "description": "Put <br/> between lines in the label string. Often used in conjunction with labelsDiv." + }, + "valueFormatter": { + "default": "Depends on the type of your data.", + "labels": ["Legend", "Value display/formatting"], + "type": "function(num_or_millis, opts, seriesName, dygraph, row, col)", + "description": "Function to provide a custom display format for the values displayed on mouseover. This does not affect the values that appear on tick marks next to the axes. To format those, see axisLabelFormatter. This is usually set on a per-axis basis. .", + "parameters": [["num_or_millis", "The value to be formatted. This is always a number. For date axes, it’s millis since epoch. You can call new Date(millis) to get a Date object."], ["opts", "This is a function you can call to access various options (e.g. opts('labelsKMB')). It returns per-axis values for the option when available."], ["seriesName", "The name of the series from which the point came, e.g. 'X', 'Y', 'A', etc."], ["dygraph", "The dygraph object for which the formatting is being done"], ["row", "The row of the data from which this point comes. g.getValue(row, 0) will return the x-value for this point."], ["col", "The column of the data from which this point comes. g.getValue(row, col) will return the original y-value for this point. This can be used to get the full confidence interval for the point, or access un-rolled values for the point."]] + }, + "annotationMouseOverHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "description": "If provided, this function is called whenever the user mouses over an annotation." + }, + "annotationMouseOutHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [["annotation", "the annotation left"], ["point", "the point associated with the annotation"], ["dygraph", "the reference graph"], ["event", "the mouse event"]], + "description": "If provided, this function is called whenever the user mouses out of an annotation." + }, + "annotationClickHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [["annotation", "the annotation left"], ["point", "the point associated with the annotation"], ["dygraph", "the reference graph"], ["event", "the mouse event"]], + "description": "If provided, this function is called whenever the user clicks on an annotation." + }, + "annotationDblClickHandler": { + "default": "null", + "labels": ["Annotations"], + "type": "function(annotation, point, dygraph, event)", + "parameters": [["annotation", "the annotation left"], ["point", "the point associated with the annotation"], ["dygraph", "the reference graph"], ["event", "the mouse event"]], + "description": "If provided, this function is called whenever the user double-clicks on an annotation." + }, + "drawCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(dygraph, is_initial)", + "parameters": [["dygraph", "The graph being drawn"], ["is_initial", "True if this is the initial draw, false for subsequent draws."]], + "description": "When set, this callback gets called every time the dygraph is drawn. This includes the initial draw, after zooming and repeatedly while panning." + }, + "labelsKMG2": { + "default": "false", + "labels": ["Value display/formatting"], + "type": "boolean", + "description": "Show Ki/Mi/Gi for powers of 1024 on y-axis. If used together with labelsKMB (deprecated), K/M/G are used instead." + }, + "delimiter": { + "default": ",", + "labels": ["CSV parsing"], + "type": "string", + "description": "The delimiter to look for when separating fields of a CSV file. Setting this to a tab is not usually necessary, since tab-delimited data is auto-detected." + }, + "axisLabelFontSize": { + "default": "14", + "labels": ["Axis display"], + "type": "integer", + "description": "Size of the font (in pixels) to use in the axis labels, both x- and y-axis." + }, + "underlayCallback": { + "default": "null", + "labels": ["Callbacks"], + "type": "function(context, area, dygraph)", + "parameters": [["context", "the canvas drawing context on which to draw"], ["area", "An object with {x,y,w,h} properties describing the drawing area."], ["dygraph", "the reference graph"]], + "description": "When set, this callback gets called before the chart is drawn. It details on how to use this." + }, + "width": { + "default": "480", + "labels": ["Overall display"], + "type": "integer", + "description": "Width, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored." + }, + "pixelRatio": { + "default": "(devicePixelRatio / context.backingStoreRatio)", + "labels": ["Overall display"], + "type": "float", + "description": "Overrides the pixel ratio scaling factor for the canvas’ 2d context. Ordinarily, this is set to the devicePixelRatio / (context.backingStoreRatio || 1), so on mobile devices, where the devicePixelRatio can be somewhere around 3, performance can be improved by overriding this value to something less precise, like 1, at the expense of resolution." + }, + "interactionModel": { + "default": "...", + "labels": ["Interactive Elements"], + "type": "Object", + "description": "TODO(konigsberg): document this" + }, + "ticker": { + "default": "Dygraph.dateTicker or Dygraph.numericTicks", + "labels": ["Axis display"], + "type": "function(min, max, pixels, opts, dygraph, vals) → [{v: …, label: …}, …]", + "parameters": [["min", ""], ["max", ""], ["pixels", ""], ["opts", ""], ["dygraph", "the reference graph"], ["vals", ""]], + "description": "This lets you specify an arbitrary function to generate tick marks on an axis. The tick marks are an array of (value, label) pairs. The built-in functions go to great lengths to choose good tick marks so, if you set this option, you’ll most likely want to call one of them and modify the result. See dygraph-tickers.js for an extensive discussion. This is set on a per-axis basis." + }, + "xAxisHeight": { + "default": "(null)", + "labels": ["Axis display"], + "type": "integer", + "description": "Height, in pixels, of the x-axis. If not set explicitly, this is computed based on axisLabelFontSize and axisTickSize." + }, + "showLabelsOnHighlight": { + "default": "true", + "labels": ["Interactive Elements", "Legend"], + "type": "boolean", + "description": "Whether to show the legend upon mouseover." + }, + "axis": { + "default": "(none)", + "labels": ["Axis display"], + "type": "string", + "description": "Set to either 'y1' or 'y2' to assign a series to a y-axis (primary or secondary). Must be set per-series." + }, + "pixelsPerLabel": { + "default": "70 (x-axis) or 30 (y-axes)", + "labels": ["Axis display", "Grid"], + "type": "integer", + "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks. This is set on a per-axis basis." + }, + "labelsDiv": { + "default": "null", + "labels": ["Legend"], + "type": "DOM element or string", + "example": "document.getElementById('foo') or 'foo'", + "description": "Show data labels in an external div, rather than on the graph. This value can either be a div element or a div id." + }, + "fractions": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "When set, attempt to parse each cell in the CSV file as \"a/b\", where a and b are integers. The ratio will be plotted. This allows computation of Wilson confidence intervals (see below)." + }, + "logscale": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "When set for the y-axis or x-axis, the graph shows that axis in log scale. Any values less than or equal to zero are not displayed. Showing log scale with ranges that go below zero will result in an unviewable graph.\n\n Not compatible with showZero. connectSeparatedPoints is ignored. This is ignored for date-based x-axes." + }, + "strokeWidth": { + "default": "1.0", + "labels": ["Data Line display"], + "type": "float", + "example": "0.5, 2.0", + "description": "The width of the lines connecting data points. This can be used to increase the contrast or some graphs." + }, + "strokePattern": { + "default": "null", + "labels": ["Data Line display"], + "type": "Array of integers", + "example": "[10, 2, 5, 2]", + "description": "A custom pattern array where the even index is a draw and odd is a space in pixels. If null then it draws a solid line. The array should have a even length as any odd lengthed array could be expressed as a smaller even length array. This is used to create dashed lines." + }, + "strokeBorderWidth": { + "default": "null", + "labels": ["Data Line display"], + "type": "float", + "example": "1.0", + "description": "Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines." + }, + "strokeBorderColor": { + "default": "white", + "labels": ["Data Line display"], + "type": "string", + "example": "red, #ccffdd", + "description": "Color for the line border used if strokeBorderWidth is set." + }, + "wilsonInterval": { + "default": "true", + "labels": ["Error Bars"], + "type": "boolean", + "description": "Use in conjunction with the \"fractions\" option. Instead of plotting +/- N standard deviations, dygraphs will compute a Wilson confidence interval and plot that. This has more reasonable behavior for ratios close to 0 or 1." + }, + "fillGraph": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "Should the area underneath the graph be filled? This option is not compatible with customBars nor errorBars. This may be set on a per-series basis." + }, + "highlightCircleSize": { + "default": "3", + "labels": ["Interactive Elements"], + "type": "integer", + "description": "The size in pixels of the dot drawn over highlighted points." + }, + "gridLineColor": { + "default": "rgb(128,128,128)", + "labels": ["Grid"], + "type": "red, blue", + "description": "The color of the gridlines. This may be set on a per-axis basis to define each axis’ grid separately." + }, + "gridLinePattern": { + "default": "null", + "labels": ["Grid"], + "type": "Array of integers", + "example": "[10, 2, 5, 2]", + "description": "A custom pattern array where the even index is a draw and odd is a space in pixels. If null then it draws a solid line. The array should have a even length as any odd lengthed array could be expressed as a smaller even length array. This is used to create dashed gridlines." + }, + "visibility": { + "default": "[true, true, ...]", + "labels": ["Data Line display"], + "type": "Array of booleans", + "description": "Which series should initially be visible? Once the Dygraph has been constructed, you can access and modify the visibility of each series using the visibility and setVisibility methods." + }, + "valueRange": { + "default": "Full range of the input is shown", + "labels": ["Axis display"], + "type": "Array of two numbers", + "example": "[10, 110]", + "description": "Explicitly set the vertical range of the graph to [low, high]. This may be set on a per-axis basis to define each y-axis separately. If either limit is unspecified, it will be calculated automatically (e.g. [null, 30] to automatically calculate just the lower bound)" + }, + "colorSaturation": { + "default": "1.0", + "labels": ["Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description": "If colors is not specified, saturation of the automatically-generated data series colors." + }, + "hideOverlayOnMouseOut": { + "default": "true", + "labels": ["Interactive Elements", "Legend"], + "type": "boolean", + "description": "Whether to hide the legend when the mouse leaves the chart area." + }, + "legend": { + "default": "onmouseover", + "labels": ["Legend"], + "type": "string", + "description": "When to display the legend. By default, it only appears when a user mouses over the chart. Set it to \"always\" to always display a legend of some sort, \"never\" to hide it. When set to \"follow\", legend follows highlighted points." + }, + "legendFollowOffsetX": { + "default": "50", + "labels": ["Legend"], + "type": "integer", + "description": "Number of pixels to use as horizontal offset from the point for a “floating” legend (\"follow\" mode). This should be positive (to the right) because the legend flips over to the left side if it’s too wide." + }, + "legendFollowOffsetY": { + "default": "-50", + "labels": ["Legend"], + "type": "integer", + "description": "Number of pixels to use as vertical offset from the point for a “floating” legend (\"follow\" mode)." + }, + "legendFormatter": { + "default": "null", + "labels": ["Legend"], + "type": "function(data): string or DocumentFragment node", + "params": [["data", "An object containing information about the selection (or lack of a selection). This includes formatted values and series information. See docs/legend-formatter.md (online) for sample values."]], + "description": "Set this to supply a custom formatter for the legend. See docs/legend-formatter.md (online) and the legendFormatter demo for usage." + }, + "labelsShowZeroValues": { + "default": "true", + "labels": ["Legend"], + "type": "boolean", + "description": "Show zero value labels in the labelsDiv." + }, + "stepPlot": { + "default": "false", + "labels": ["Data Line display"], + "type": "boolean", + "description": "When set, display the graph as a step plot instead of a line plot. This option may either be set for the whole graph or for single series." + }, + "labelsUTC": { + "default": "false", + "labels": ["Value display/formatting", "Axis display"], + "type": "boolean", + "description": "Show date/time labels according to UTC (instead of local time)." + }, + "labelsKMB": { + "default": "false", + "labels": ["Value display/formatting"], + "type": "boolean", + "description": "Show k/M/B for thousands/millions/billions on y-axis." + }, + "rightGap": { + "default": "5", + "labels": ["Overall display"], + "type": "integer", + "description": "Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to highlight the right-most data point." + }, + "drawAxesAtZero": { + "default": "false", + "labels": ["Axis display"], + "type": "boolean", + "description": "When set, draw the X axis at the Y=0 position and the Y axis at the X=0 position if those positions are inside the graph’s visible area. Otherwise, draw the axes at the bottom or left graph edge as usual." + }, + "xRangePad": { + "default": "0", + "labels": ["Axis display"], + "type": "float", + "description": "Add the specified amount of extra space (in pixels) around the X-axis value range to ensure points at the edges remain visible." + }, + "yRangePad": { + "default": "null", + "labels": ["Axis display"], + "type": "float", + "description": "If set, add the specified amount of extra space (in pixels) around the Y-axis value range to ensure points at the edges remain visible. If unset, use the traditional Y padding algorithm." + }, + "axisLabelFormatter": { + "default": "Depends on the data type", + "labels": ["Axis display"], + "type": "function(number_or_Date, granularity, opts, dygraph)", + "parameters": [["number_or_Date", "Either a number (for a numeric axis) or a Date object (for a date axis)"], ["granularity", "specifies how fine-grained the axis is. For date axes, this is a reference to the time granularity enumeration, defined in dygraph-tickers.js, e.g. Dygraph.WEEKLY."], ["opts", "a function which provides access to various options on the dygraph, e.g. opts('labelsKMB')."], ["dygraph", "the referenced graph"]], + "description": "Function to call to format the tick values that appear along an axis. This is usually set on a per-axis basis." + }, + "clickCallback": { + "snippet": "function(e, date_millis){
      alert(new Date(date_millis));
    }", + "default": "null", + "labels": ["Callbacks"], + "type": "function(e, x, points)", + "parameters": [["e", "The event object for the click"], ["x", "The x value that was clicked (for dates, this is milliseconds since epoch)"], ["points", "The closest points along that date. See Point properties for details."]], + "description": "A function to call when the canvas is clicked." + }, + "labels": { + "default": "[\"X\", \"Y1\", \"Y2\", ...]*", + "labels": ["Legend"], + "type": "Array of strings", + "description": "A distinct name for each data series, including the independent (X) series. For CSV files and DataTable objects, this is determined by context. For raw data, this must be specified. If it is not, default values are supplied and a warning is logged. Make sure no two names are the same!" + }, + "dateWindow": { + "default": "Full range of the input is shown", + "labels": ["Axis display"], + "type": "Array of two numbers", + "example": "[
      Date.parse('2006-01-01'),
      (new Date()).valueOf()
    ]", + "description": "Initially zoom in on a section of the graph. Is of the form [earliest, latest], where earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the values in dateWindow must also be numbers." + }, + "showRoller": { + "default": "false", + "labels": ["Interactive Elements", "Rolling Averages"], + "type": "boolean", + "description": "If the rolling average period text box should be shown." + }, + "sigma": { + "default": "2.0", + "labels": ["Error Bars"], + "type": "float", + "description": "When errorBars is set, shade this many standard deviations above/below each point." + }, + "customBars": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "When set, parse each CSV cell as \"low;middle;high\". Custom high/low bands will be drawn for each point between low and high, with the series itself going through middle." + }, + "colorValue": { + "default": "1.0", + "labels": ["Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description": "If colors is not specified, value of the data series colors, as in hue/saturation/value. (0.0-1.0, default 0.5)" + }, + "errorBars": { + "default": "false", + "labels": ["CSV parsing", "Error Bars"], + "type": "boolean", + "description": "Does the data contain standard deviations? Setting this to true alters the input format (see above)." + }, + "displayAnnotations": { + "default": "false", + "labels": ["Annotations"], + "type": "boolean", + "description": "Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data series to be interpreted as annotations on points in that series. This is the same format used by Google’s AnnotatedTimeLine chart." + }, + "panEdgeFraction": { + "default": "null", + "labels": ["Axis display", "Interactive Elements"], + "type": "float", + "description": "A value representing the farthest a graph may be panned, in percent of the display. For example, a value of 0.1 means that the graph can only be panned 10% passed the edges of the displayed values. null means no bounds." + }, + "title": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display above the chart. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the “dygraph-label” or “dygraph-title” classes." + }, + "titleHeight": { + "default": "18", + "labels": ["Chart labels"], + "type": "integer", + "description": "Height of the chart title, in pixels. This also controls the default font size of the title. If you style the title on your own, this controls how much space is set aside above the chart for the title’s div." + }, + "xlabel": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display below the chart’s x-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the “dygraph-label” or “dygraph-xlabel” classes." + }, + "xLabelHeight": { + "labels": ["Chart labels"], + "type": "integer", + "default": "18", + "description": "Height of the x-axis label, in pixels. This also controls the default font size of the x-axis label. If you style the label on your own, this controls how much space is set aside below the chart for the x-axis label’s div." + }, + "ylabel": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display to the left of the chart’s y-axis. You can supply any HTML for this value, not just text. If you wish to style it using CSS, use the “dygraph-label” or “dygraph-ylabel” classes. The text will be rotated 90 degrees by default, so CSS rules may behave in unintuitive ways. No additional space is set aside for a y-axis label. If you need more space, increase the width of the y-axis tick labels using the per-axis axisLabelWidth option on the y axis. If you need a wider div for the y-axis label, either style it that way with CSS (but remember that it’s rotated, so width is controlled by the “height” property) or set the yLabelWidth option." + }, + "y2label": { + "labels": ["Chart labels"], + "type": "string", + "default": "null", + "description": "Text to display to the right of the chart’s secondary y-axis. This label is only displayed if a secondary y-axis is present. See this test for an example of how to do this. The comments for the “ylabel” option generally apply here as well. This label gets a “dygraph-y2label” instead of a “dygraph-ylabel” class." + }, + "yLabelWidth": { + "labels": ["Chart labels"], + "type": "integer", + "default": "18", + "description": "Width of the div which contains the y-axis label. Since the y-axis label appears rotated 90 degrees, this actually affects the height of its div." + }, + "drawGrid": { + "default": "true for x and y, false for y2", + "labels": ["Grid"], + "type": "boolean", + "description": "Whether to display gridlines in the chart. This may be set on a per-axis basis to define the visibility of each axis’ grid separately." + }, + "independentTicks": { + "default": "true for y, false for y2", + "labels": ["Axis display", "Grid"], + "type": "boolean", + "description": "Only valid for y and y2, has no effect on x: This option defines whether the y axes should align their ticks or if they should be independent. Possible combinations: [1.] y=true, y2=false (default): y is the primary axis and the y2 ticks are aligned to the the ones of y. (only 1 grid) [2.] y=false, y2=true: y2 is the primary axis and the y ticks are aligned to the the ones of y2. (only 1 grid) [3.] y=true, y2=true: Both axis are independent and have their own ticks. (2 grids) [4.] y=false, y2=false: Invalid configuration causes an error." + }, + "drawAxis": { + "default": "true for x and y, false for y2", + "labels": ["Axis display"], + "type": "boolean", + "description": "Whether to draw the specified axis. This may be set on a per-axis basis to define the visibility of each axis separately. Setting this to false also prevents axis ticks from being drawn and reclaims the space for the chart grid/lines." + }, + "gridLineWidth": { + "default": "0.3", + "labels": ["Grid"], + "type": "float", + "description": "Thickness (in pixels) of the gridlines drawn under the chart. The vertical/horizontal gridlines can be turned off entirely by using the drawGrid option. This may be set on a per-axis basis to define each axis’ grid separately." + }, + "axisLineWidth": { + "default": "0.3", + "labels": ["Axis display"], + "type": "float", + "description": "Thickness (in pixels) of the x- and y-axis lines." + }, + "axisLineColor": { + "default": "black", + "labels": ["Axis display"], + "type": "string", + "description": "Color of the x- and y-axis lines. Accepts any value which the HTML canvas strokeStyle attribute understands, e.g. 'black' or 'rgb(0, 100, 255)'." + }, + "fillAlpha": { + "default": "0.15", + "labels": ["Error Bars", "Data Series Colors"], + "type": "float (0.0 - 1.0)", + "description": "Custom or sigma-based high/low bands for each series are drawn in the same colour as the series, but with partial transparency. This sets the transparency. A value of 0.0 means that the bands will not be drawn, whereas a value of 1.0 means that the bands will be as dark as the line for the series itself. This can be used to produce chart lines whose thickness varies at each point." + }, + "axisLabelWidth": { + "default": "50 (y-axis), 60 (x-axis)", + "labels": ["Axis display", "Chart labels"], + "type": "integer", + "description": "Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this also controls the width of the y-axis. Note that for the x-axis, this is independent from pixelsPerLabel, which controls the spacing between labels." + }, + "sigFigs": { + "default": "null", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "By default, dygraphs displays numbers with a fixed number of digits after the decimal point. If you’d prefer to have a fixed number of significant figures, set this option to that number of sig figs. A value of 2, for instance, would cause 1 to be display as 1.0 and 1234 to be displayed as 1.23e+3." + }, + "digitsAfterDecimal": { + "default": "2", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "Unless it’s run in scientific mode (see the sigFigs option), dygraphs displays numbers with digitsAfterDecimal digits after the decimal point. Trailing zeros are not displayed, so with a value of 2 you’ll get '0', '0.1', '0.12', '123.45' but not '123.456' (it will be rounded to '123.46'). Numbers with absolute value less than 0.1^digitsAfterDecimal (i.e. those which would show up as '0.00') will be displayed in scientific notation." + }, + "maxNumberWidth": { + "default": "6", + "labels": ["Value display/formatting"], + "type": "integer", + "description": "When displaying numbers in normal (not scientific) mode, large numbers will be displayed with many trailing zeros (e.g. 100000000 instead of 1e9). This can lead to unwieldy y-axis labels. If there are more than maxNumberWidth digits to the left of the decimal in a number, dygraphs will switch to scientific notation, even when not operating in scientific mode. If you’d like to see all those digits, set this to something large, like 20 or 30." + }, + "file": { + "default": "(set when constructed)", + "labels": ["Data"], + "type": "string (URL of CSV or CSV), GViz DataTable or 2D Array", + "description": "Sets the data being displayed in the chart. This can only be set when calling updateOptions; it cannot be set from the constructor. For a full description of valid data formats, see the Data Formats page." + }, + "timingName": { + "default": "null", + "labels": ["Debugging", "Deprecated"], + "type": "string", + "description": "Set this option to log timing information. The value of the option will be logged along with the timimg, so that you can distinguish multiple dygraphs on the same page." + }, + "showRangeSelector": { + "default": "false", + "labels": ["Range Selector"], + "type": "boolean", + "description": "Show or hide the range selector widget." + }, + "rangeSelectorHeight": { + "default": "40", + "labels": ["Range Selector"], + "type": "integer", + "description": "Height, in pixels, of the range selector widget. This option can only be specified at Dygraph creation time." + }, + "rangeSelectorPlotStrokeColor": { + "default": "#808FAB", + "labels": ["Range Selector"], + "type": "string", + "description": "The range selector mini plot stroke color. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\". You can also specify null or \"\" to turn off stroke." + }, + "rangeSelectorPlotFillColor": { + "default": "#A7B1C4", + "labels": ["Range Selector"], + "type": "string", + "description": "The range selector mini plot fill color. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\". You can also specify null or \"\" to turn off fill." + }, + "rangeSelectorPlotFillGradientColor": { + "default": "white", + "labels": ["Range Selector"], + "type": "string", + "description": "The top color for the range selector mini plot fill color gradient. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"rgba(255,100,200,42)\" or \"yellow\". You can also specify null or \"\" to disable the gradient and fill with one single color." + }, + "rangeSelectorBackgroundStrokeColor": { + "default": "gray", + "labels": ["Range Selector"], + "type": "string", + "description": "The color of the lines below and on both sides of the range selector mini plot. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\"." + }, + "rangeSelectorBackgroundLineWidth": { + "default": "1", + "labels": ["Range Selector"], + "type": "float", + "description": "The width of the lines below and on both sides of the range selector mini plot." + }, + "rangeSelectorPlotLineWidth": { + "default": "1.5", + "labels": ["Range Selector"], + "type": "float", + "description": "The width of the range selector mini plot line." + }, + "rangeSelectorForegroundStrokeColor": { + "default": "black", + "labels": ["Range Selector"], + "type": "string", + "description": "The color of the lines in the interactive layer of the range selector. This can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\"." + }, + "rangeSelectorForegroundLineWidth": { + "default": "1", + "labels": ["Range Selector"], + "type": "float", + "description": "The width the lines in the interactive layer of the range selector." + }, + "rangeSelectorAlpha": { + "default": "0.6", + "labels": ["Range Selector"], + "type": "float (0.0 - 1.0)", + "description": "The transparency of the veil that is drawn over the unselected portions of the range selector mini plot. A value of 0 represents full transparency and the unselected portions of the mini plot will appear as normal. A value of 1 represents full opacity and the unselected portions of the mini plot will be hidden." + }, + "rangeSelectorVeilColour": { + "default": "null", + "labels": ["Range Selector"], + "type": "string", + "description": "The fillStyle for the veil of the range selector (e.g. \"rgba(240, 240, 240, 0.6)\"); if set, the rangeSelectorAlpha option is ignored." + }, + "showInRangeSelector": { + "default": "null", + "labels": ["Range Selector"], + "type": "boolean", + "description": "Mark this series for inclusion in the range selector. The mini plot curve will be an average of all such series. If this is not specified for any series, the default behavior is to average all the visible series. Setting it for one series will result in that series being charted alone in the range selector. Once it’s set for a single series, it needs to be set for all series which should be included (regardless of visibility)." + }, + "animatedZooms": { + "default": "false", + "labels": ["Interactive Elements"], + "type": "boolean", + "description": "Set this option to animate the transition between zoom windows. Applies to programmatic and interactive zooms. Note that if you also set a drawCallback, it will be called several times on each zoom. If you set a zoomCallback, it will only be called after the animation is complete." + }, + "plotter": { + "default": "[DygraphCanvasRenderer.Plotters.fillPlotter, DygraphCanvasRenderer.Plotters.errorPlotter, DygraphCanvasRenderer.Plotters.linePlotter]", + "labels": ["Data Line display"], + "type": "array or function", + "description": "A function (or array of functions) which plot each data series on the chart. TODO(danvk): more details! May be set per-series." + }, + "axes": { + "default": "null", + "labels": ["Configuration"], + "type": "Object", + "description": "Defines per-axis options. Valid keys are 'x', 'y' and 'y2'. Only some options may be set on a per-axis basis. If an option may be set in this way, it will be noted on this page. See also documentation on per-series and per-axis options." + }, + "series": { + "default": "null", + "labels": ["Series"], + "type": "Object", + "description": "Defines per-series options. Its keys match the y-axis label names, and the values are dictionaries themselves that contain options specific to that series." + }, + "plugins": { + "default": "[]", + "labels": ["Configuration"], + "type": "Array of plugins", + "description": "Defines per-graph plugins. Useful for per-graph customization" + }, + "dataHandler": { + "default": "(depends on data)", + "labels": ["Data"], + "type": "Dygraph.DataHandler", + "description": "Custom DataHandler. This is an advanced customisation. See docs/datahandler-proposal.pdf." + } + }; //
    + // NOTE: in addition to parsing as JS, this snippet is expected to be valid + // JSON. This assumption cannot be checked in JS, but it will be checked when + // documentation is generated by the generate-documentation.py script. For the + // most part, this just means that you should always use double quotes. + + // Do a quick sanity check on the options reference. + var warn = function warn(msg) { + if (window.console) window.console.warn(msg); + }; + var flds = ['type', 'default', 'description']; + var valid_cats = + // + { + "Annotations": "", + "Axis display": "", + "CSV parsing": "", + "Callbacks": "", + "Chart labels": "", + "Configuration": "", + "Data Line display": "", + "Data Series Colors": "", + "Data": "", + "Debugging": "", + "Deprecated": "", + "Error Bars": "These are actually high/low bands, not error bars; the misnomer is historic.", + "Grid": "", + "Interactive Elements": "", + "Legend": "", + "Overall display": "", + "Range Selector": "", + "Rolling Averages": "", + "Series": "", + "Value display/formatting": "" + }; // + for (var k in OPTIONS_REFERENCE) { + if (!OPTIONS_REFERENCE.hasOwnProperty(k)) continue; + var op = OPTIONS_REFERENCE[k]; + for (var i = 0; i < flds.length; i++) { + if (!op.hasOwnProperty(flds[i])) { + warn('Option ' + k + ' missing "' + flds[i] + '" property'); + } else if (typeof op[flds[i]] != 'string') { + warn(k + '.' + flds[i] + ' must be of type string'); + } + } + var labels = op.labels; + if (!Array.isArray(labels)) { + warn('Option "' + k + '" is missing a "labels": [...] option'); + } else { + for (var _i = 0; _i < labels.length; _i++) { + if (!valid_cats.hasOwnProperty(labels[_i])) { + warn('Option "' + k + '" has label "' + labels[_i] + '", which is invalid.'); + } + } + } + } +} +var _default = OPTIONS_REFERENCE; +exports["default"] = _default; +module.exports = exports.default; + +},{}],"dygraphs/src/dygraph-options.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview DygraphOptions is responsible for parsing and returning + * information about options. + */ + +// TODO: remove this jshint directive & fix the warnings. +/*jshint sub:true */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +var _dygraphDefaultAttrs = _interopRequireDefault(require("./dygraph-default-attrs")); +var _dygraphOptionsReference = _interopRequireDefault(require("./dygraph-options-reference")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/* + * Interesting member variables: (REMOVING THIS LIST AS I CLOSURIZE) + * global_ - global attributes (common among all graphs, AIUI) + * user - attributes set by the user + * series_ - { seriesName -> { idx, yAxis, options }} + */ + +/** + * This parses attributes into an object that can be easily queried. + * + * It doesn't necessarily mean that all options are available, specifically + * if labels are not yet available, since those drive details of the per-series + * and per-axis options. + * + * @param {Dygraph} dygraph The chart to which these options belong. + * @constructor + */ +var DygraphOptions = function DygraphOptions(dygraph) { + /** + * The dygraph. + * @type {!Dygraph} + */ + this.dygraph_ = dygraph; + + /** + * Array of axis index to { series : [ series names ] , options : { axis-specific options. } } + * @type {Array.<{series : Array., options : Object}>} @private + */ + this.yAxes_ = []; + + /** + * Contains x-axis specific options, which are stored in the options key. + * This matches the yAxes_ object structure (by being a dictionary with an + * options element) allowing for shared code. + * @type {options: Object} @private + */ + this.xAxis_ = {}; + this.series_ = {}; + + // Once these two objects are initialized, you can call get(); + this.global_ = this.dygraph_.attrs_; + this.user_ = this.dygraph_.user_attrs_ || {}; + + /** + * A list of series in columnar order. + * @type {Array.} + */ + this.labels_ = []; + this.highlightSeries_ = this.get("highlightSeriesOpts") || {}; + this.reparseSeries(); +}; + +/** + * Not optimal, but does the trick when you're only using two axes. + * If we move to more axes, this can just become a function. + * + * @type {Object.} + * @private + */ +DygraphOptions.AXIS_STRING_MAPPINGS_ = { + 'y': 0, + 'Y': 0, + 'y1': 0, + 'Y1': 0, + 'y2': 1, + 'Y2': 1 +}; + +/** + * @param {string|number} axis + * @private + */ +DygraphOptions.axisToIndex_ = function (axis) { + if (typeof axis == "string") { + if (DygraphOptions.AXIS_STRING_MAPPINGS_.hasOwnProperty(axis)) { + return DygraphOptions.AXIS_STRING_MAPPINGS_[axis]; + } + throw "Unknown axis : " + axis; + } + if (typeof axis == "number") { + if (axis === 0 || axis === 1) { + return axis; + } + throw "Dygraphs only supports two y-axes, indexed from 0-1."; + } + if (axis) { + throw "Unknown axis : " + axis; + } + // No axis specification means axis 0. + return 0; +}; + +/** + * Reparses options that are all related to series. This typically occurs when + * options are either updated, or source data has been made available. + * + * TODO(konigsberg): The method name is kind of weak; fix. + */ +DygraphOptions.prototype.reparseSeries = function () { + var labels = this.get("labels"); + if (!labels) { + return; // -- can't do more for now, will parse after getting the labels. + } + + this.labels_ = labels.slice(1); + this.yAxes_ = [{ + series: [], + options: {} + }]; // Always one axis at least. + this.xAxis_ = { + options: {} + }; + this.series_ = {}; + + // Series are specified in the series element: + // + // { + // labels: [ "X", "foo", "bar" ], + // pointSize: 3, + // series : { + // foo : {}, // options for foo + // bar : {} // options for bar + // } + // } + // + // So, if series is found, it's expected to contain per-series data, + // otherwise set a default. + var seriesDict = this.user_.series || {}; + for (var idx = 0; idx < this.labels_.length; idx++) { + var seriesName = this.labels_[idx]; + var optionsForSeries = seriesDict[seriesName] || {}; + var yAxis = DygraphOptions.axisToIndex_(optionsForSeries["axis"]); + this.series_[seriesName] = { + idx: idx, + yAxis: yAxis, + options: optionsForSeries + }; + if (!this.yAxes_[yAxis]) { + this.yAxes_[yAxis] = { + series: [seriesName], + options: {} + }; + } else { + this.yAxes_[yAxis].series.push(seriesName); + } + } + var axis_opts = this.user_["axes"] || {}; + utils.update(this.yAxes_[0].options, axis_opts["y"] || {}); + if (this.yAxes_.length > 1) { + utils.update(this.yAxes_[1].options, axis_opts["y2"] || {}); + } + utils.update(this.xAxis_.options, axis_opts["x"] || {}); + if (true) { + // For "production" code, this gets removed by uglifyjs. + this.validateOptions_(); + } +}; + +/** + * Get a global value. + * + * @param {string} name the name of the option. + */ +DygraphOptions.prototype.get = function (name) { + var result = this.getGlobalUser_(name); + if (result !== null) { + return result; + } + return this.getGlobalDefault_(name); +}; +DygraphOptions.prototype.getGlobalUser_ = function (name) { + if (this.user_.hasOwnProperty(name)) { + return this.user_[name]; + } + return null; +}; +DygraphOptions.prototype.getGlobalDefault_ = function (name) { + if (this.global_.hasOwnProperty(name)) { + return this.global_[name]; + } + if (_dygraphDefaultAttrs["default"].hasOwnProperty(name)) { + return _dygraphDefaultAttrs["default"][name]; + } + return null; +}; + +/** + * Get a value for a specific axis. If there is no specific value for the axis, + * the global value is returned. + * + * @param {string} name the name of the option. + * @param {string|number} axis the axis to search. Can be the string representation + * ("y", "y2") or the axis number (0, 1). + */ +DygraphOptions.prototype.getForAxis = function (name, axis) { + var axisIdx; + var axisString; + + // Since axis can be a number or a string, straighten everything out here. + if (typeof axis == 'number') { + axisIdx = axis; + axisString = axisIdx === 0 ? "y" : "y2"; + } else { + if (axis == "y1") { + axis = "y"; + } // Standardize on 'y'. Is this bad? I think so. + if (axis == "y") { + axisIdx = 0; + } else if (axis == "y2") { + axisIdx = 1; + } else if (axis == "x") { + axisIdx = -1; // simply a placeholder for below. + } else { + throw "Unknown axis " + axis; + } + axisString = axis; + } + var userAxis = axisIdx == -1 ? this.xAxis_ : this.yAxes_[axisIdx]; + + // Search the user-specified axis option first. + if (userAxis) { + // This condition could be removed if we always set up this.yAxes_ for y2. + var axisOptions = userAxis.options; + if (axisOptions.hasOwnProperty(name)) { + return axisOptions[name]; + } + } + + // User-specified global options second. + // But, hack, ignore globally-specified 'logscale' for 'x' axis declaration. + if (!(axis === 'x' && name === 'logscale')) { + var result = this.getGlobalUser_(name); + if (result !== null) { + return result; + } + } + // Default axis options third. + var defaultAxisOptions = _dygraphDefaultAttrs["default"].axes[axisString]; + if (defaultAxisOptions.hasOwnProperty(name)) { + return defaultAxisOptions[name]; + } + + // Default global options last. + return this.getGlobalDefault_(name); +}; + +/** + * Get a value for a specific series. If there is no specific value for the series, + * the value for the axis is returned (and afterwards, the global value.) + * + * @param {string} name the name of the option. + * @param {string} series the series to search. + */ +DygraphOptions.prototype.getForSeries = function (name, series) { + // Honors indexes as series. + if (series === this.dygraph_.getHighlightSeries()) { + if (this.highlightSeries_.hasOwnProperty(name)) { + return this.highlightSeries_[name]; + } + } + if (!this.series_.hasOwnProperty(series)) { + throw "Unknown series: " + series; + } + var seriesObj = this.series_[series]; + var seriesOptions = seriesObj["options"]; + if (seriesOptions.hasOwnProperty(name)) { + return seriesOptions[name]; + } + return this.getForAxis(name, seriesObj["yAxis"]); +}; + +/** + * Returns the number of y-axes on the chart. + * @return {number} the number of axes. + */ +DygraphOptions.prototype.numAxes = function () { + return this.yAxes_.length; +}; + +/** + * Return the y-axis for a given series, specified by name. + */ +DygraphOptions.prototype.axisForSeries = function (series) { + return this.series_[series].yAxis; +}; + +/** + * Returns the options for the specified axis. + */ +// TODO(konigsberg): this is y-axis specific. Support the x axis. +DygraphOptions.prototype.axisOptions = function (yAxis) { + return this.yAxes_[yAxis].options; +}; + +/** + * Return the series associated with an axis. + */ +DygraphOptions.prototype.seriesForAxis = function (yAxis) { + return this.yAxes_[yAxis].series; +}; + +/** + * Return the list of all series, in their columnar order. + */ +DygraphOptions.prototype.seriesNames = function () { + return this.labels_; +}; +if (true) { + // For "production" code, this gets removed by uglifyjs. + + /** + * Validate all options. + * This requires OPTIONS_REFERENCE, which is only available in debug builds. + * @private + */ + DygraphOptions.prototype.validateOptions_ = function () { + if (typeof _dygraphOptionsReference["default"] === 'undefined') { + throw 'Called validateOptions_ in prod build.'; + } + var that = this; + var validateOption = function validateOption(optionName) { + if (!_dygraphOptionsReference["default"][optionName]) { + that.warnInvalidOption_(optionName); + } + }; + var optionsDicts = [this.xAxis_.options, this.yAxes_[0].options, this.yAxes_[1] && this.yAxes_[1].options, this.global_, this.user_, this.highlightSeries_]; + var names = this.seriesNames(); + for (var i = 0; i < names.length; i++) { + var name = names[i]; + if (this.series_.hasOwnProperty(name)) { + optionsDicts.push(this.series_[name].options); + } + } + for (var i = 0; i < optionsDicts.length; i++) { + var dict = optionsDicts[i]; + if (!dict) continue; + for (var optionName in dict) { + if (dict.hasOwnProperty(optionName)) { + validateOption(optionName); + } + } + } + }; + var WARNINGS = {}; // Only show any particular warning once. + + /** + * Logs a warning about invalid options. + * TODO: make this throw for testing + * @private + */ + DygraphOptions.prototype.warnInvalidOption_ = function (optionName) { + if (!WARNINGS[optionName]) { + WARNINGS[optionName] = true; + var isSeries = this.labels_.indexOf(optionName) >= 0; + if (isSeries) { + console.warn('Use new-style per-series options (saw ' + optionName + ' as top-level options key). See http://blog.dygraphs.com/2012/12/the-new-and-better-way-to-specify.html (The New and Better Way to Specify Series and Axis Options).'); + } else { + console.warn('Unknown option ' + optionName + ' (see https://dygraphs.com/options.html for the full list of options)'); + } + throw "invalid option " + optionName; + } + }; + + // Reset list of previously-shown warnings. Used for testing. + DygraphOptions.resetWarnings_ = function () { + WARNINGS = {}; + }; +} +var _default = DygraphOptions; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph-default-attrs":"dygraphs/src/dygraph-default-attrs.js","./dygraph-options-reference":"dygraphs/src/dygraph-options-reference.js","./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-tickers.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview Description of this file. + * @author danvk@google.com (Dan Vanderkam) + */ + +/* + * A ticker is a function with the following interface: + * + * function(a, b, pixels, options_view, dygraph, forced_values); + * -> [ { v: tick1_v, label: tick1_label[, label_v: label_v1] }, + * { v: tick2_v, label: tick2_label[, label_v: label_v2] }, + * ... + * ] + * + * The returned value is called a "tick list". + * + * Arguments + * --------- + * + * [a, b] is the range of the axis for which ticks are being generated. For a + * numeric axis, these will simply be numbers. For a date axis, these will be + * millis since epoch (convertable to Date objects using "new Date(a)" and "new + * Date(b)"). + * + * opts provides access to chart- and axis-specific options. It can be used to + * access number/date formatting code/options, check for a log scale, etc. + * + * pixels is the length of the axis in pixels. opts('pixelsPerLabel') is the + * minimum amount of space to be allotted to each label. For instance, if + * pixels=400 and opts('pixelsPerLabel')=40 then the ticker should return + * between zero and ten (400/40) ticks. + * + * dygraph is the Dygraph object for which an axis is being constructed. + * + * forced_values is used for secondary y-axes. The tick positions are typically + * set by the primary y-axis, so the secondary y-axis has no choice in where to + * put these. It simply has to generate labels for these data values. + * + * Tick lists + * ---------- + * Typically a tick will have both a grid/tick line and a label at one end of + * that line (at the bottom for an x-axis, at left or right for the y-axis). + * + * A tick may be missing one of these two components: + * - If "label_v" is specified instead of "v", then there will be no tick or + * gridline, just a label. + * - Similarly, if "label" is not specified, then there will be a gridline + * without a label. + * + * This flexibility is useful in a few situations: + * - For log scales, some of the tick lines may be too close to all have labels. + * - For date scales where years are being displayed, it is desirable to display + * tick marks at the beginnings of years but labels (e.g. "2006") in the + * middle of the years. + */ + +/*jshint sub:true */ +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.pickDateTickGranularity = exports.numericTicks = exports.numericLinearTicks = exports.getDateAxis = exports.dateTicker = exports.Granularity = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** @typedef {Array.<{v:number, label:string, label_v:(string|undefined)}>} */ +var TickList = undefined; // the ' = undefined' keeps jshint happy. + +/** @typedef {function( + * number, + * number, + * number, + * function(string):*, + * Dygraph=, + * Array.= + * ): TickList} + */ +var Ticker = undefined; // the ' = undefined' keeps jshint happy. + +/** @type {Ticker} */ +var numericLinearTicks = function numericLinearTicks(a, b, pixels, opts, dygraph, vals) { + var nonLogscaleOpts = function nonLogscaleOpts(opt) { + if (opt === 'logscale') return false; + return opts(opt); + }; + return numericTicks(a, b, pixels, nonLogscaleOpts, dygraph, vals); +}; + +/** @type {Ticker} */ +exports.numericLinearTicks = numericLinearTicks; +var numericTicks = function numericTicks(a, b, pixels, opts, dygraph, vals) { + var pixels_per_tick = /** @type{number} */opts('pixelsPerLabel'); + var ticks = []; + var i, j, tickV, nTicks; + if (vals) { + for (i = 0; i < vals.length; i++) { + ticks.push({ + v: vals[i] + }); + } + } else { + // TODO(danvk): factor this log-scale block out into a separate function. + if (opts("logscale")) { + nTicks = Math.floor(pixels / pixels_per_tick); + var minIdx = utils.binarySearch(a, PREFERRED_LOG_TICK_VALUES, 1); + var maxIdx = utils.binarySearch(b, PREFERRED_LOG_TICK_VALUES, -1); + if (minIdx == -1) { + minIdx = 0; + } + if (maxIdx == -1) { + maxIdx = PREFERRED_LOG_TICK_VALUES.length - 1; + } + // Count the number of tick values would appear, if we can get at least + // nTicks / 4 accept them. + var lastDisplayed = null; + if (maxIdx - minIdx >= nTicks / 4) { + for (var idx = maxIdx; idx >= minIdx; idx--) { + var tickValue = PREFERRED_LOG_TICK_VALUES[idx]; + var pixel_coord = Math.log(tickValue / a) / Math.log(b / a) * pixels; + var tick = { + v: tickValue + }; + if (lastDisplayed === null) { + lastDisplayed = { + tickValue: tickValue, + pixel_coord: pixel_coord + }; + } else { + if (Math.abs(pixel_coord - lastDisplayed.pixel_coord) >= pixels_per_tick) { + lastDisplayed = { + tickValue: tickValue, + pixel_coord: pixel_coord + }; + } else { + tick.label = ""; + } + } + ticks.push(tick); + } + // Since we went in backwards order. + ticks.reverse(); + } + } + + // ticks.length won't be 0 if the log scale function finds values to insert. + if (ticks.length === 0) { + // Basic idea: + // Try labels every 1, 2, 5, 10, 20, 50, 100, etc. + // Calculate the resulting tick spacing (i.e. this.height_ / nTicks). + // The first spacing greater than pixelsPerYLabel is what we use. + // TODO(danvk): version that works on a log scale. + var kmg2 = opts("labelsKMG2"); + var mults, base; + if (kmg2) { + mults = [1, 2, 4, 8, 16, 32, 64, 128, 256]; + base = 16; + } else { + mults = [1, 2, 5, 10, 20, 50, 100]; + base = 10; + } + + // Get the maximum number of permitted ticks based on the + // graph's pixel size and pixels_per_tick setting. + var max_ticks = Math.ceil(pixels / pixels_per_tick); + + // Now calculate the data unit equivalent of this tick spacing. + // Use abs() since graphs may have a reversed Y axis. + var units_per_tick = Math.abs(b - a) / max_ticks; + + // Based on this, get a starting scale which is the largest + // integer power of the chosen base (10 or 16) that still remains + // below the requested pixels_per_tick spacing. + var base_power = Math.floor(Math.log(units_per_tick) / Math.log(base)); + var base_scale = Math.pow(base, base_power); + + // Now try multiples of the starting scale until we find one + // that results in tick marks spaced sufficiently far apart. + // The "mults" array should cover the range 1 .. base^2 to + // adjust for rounding and edge effects. + var scale, low_val, high_val, spacing; + for (j = 0; j < mults.length; j++) { + scale = base_scale * mults[j]; + low_val = Math.floor(a / scale) * scale; + high_val = Math.ceil(b / scale) * scale; + nTicks = Math.abs(high_val - low_val) / scale; + spacing = pixels / nTicks; + if (spacing > pixels_per_tick) break; + } + + // Construct the set of ticks. + // Allow reverse y-axis if it's explicitly requested. + if (low_val > high_val) scale *= -1; + for (i = 0; i <= nTicks; i++) { + tickV = low_val + i * scale; + ticks.push({ + v: tickV + }); + } + } + } + var formatter = /**@type{AxisLabelFormatter}*/opts('axisLabelFormatter'); + + // Add labels to the ticks. + for (i = 0; i < ticks.length; i++) { + if (ticks[i].label !== undefined) continue; // Use current label. + // TODO(danvk): set granularity to something appropriate here. + ticks[i].label = formatter.call(dygraph, ticks[i].v, 0, opts, dygraph); + } + return ticks; +}; + +/** @type {Ticker} */ +exports.numericTicks = numericTicks; +var dateTicker = function dateTicker(a, b, pixels, opts, dygraph, vals) { + var chosen = pickDateTickGranularity(a, b, pixels, opts); + if (chosen >= 0) { + return getDateAxis(a, b, chosen, opts, dygraph); + } else { + // this can happen if self.width_ is zero. + return []; + } +}; + +// Time granularity enumeration +exports.dateTicker = dateTicker; +var Granularity = { + MILLISECONDLY: 0, + TWO_MILLISECONDLY: 1, + FIVE_MILLISECONDLY: 2, + TEN_MILLISECONDLY: 3, + FIFTY_MILLISECONDLY: 4, + HUNDRED_MILLISECONDLY: 5, + FIVE_HUNDRED_MILLISECONDLY: 6, + SECONDLY: 7, + TWO_SECONDLY: 8, + FIVE_SECONDLY: 9, + TEN_SECONDLY: 10, + THIRTY_SECONDLY: 11, + MINUTELY: 12, + TWO_MINUTELY: 13, + FIVE_MINUTELY: 14, + TEN_MINUTELY: 15, + THIRTY_MINUTELY: 16, + HOURLY: 17, + TWO_HOURLY: 18, + SIX_HOURLY: 19, + DAILY: 20, + TWO_DAILY: 21, + WEEKLY: 22, + MONTHLY: 23, + QUARTERLY: 24, + BIANNUAL: 25, + ANNUAL: 26, + DECADAL: 27, + CENTENNIAL: 28, + NUM_GRANULARITIES: 29 +}; + +// Date components enumeration (in the order of the arguments in Date) +// TODO: make this an @enum +exports.Granularity = Granularity; +var DateField = { + DATEFIELD_Y: 0, + DATEFIELD_M: 1, + DATEFIELD_D: 2, + DATEFIELD_HH: 3, + DATEFIELD_MM: 4, + DATEFIELD_SS: 5, + DATEFIELD_MS: 6, + NUM_DATEFIELDS: 7 +}; + +/** + * The value of datefield will start at an even multiple of "step", i.e. + * if datefield=SS and step=5 then the first tick will be on a multiple of 5s. + * + * For granularities <= HOURLY, ticks are generated every `spacing` ms. + * + * At coarser granularities, ticks are generated by incrementing `datefield` by + * `step`. In this case, the `spacing` value is only used to estimate the + * number of ticks. It should roughly correspond to the spacing between + * adjacent ticks. + * + * @type {Array.<{datefield:number, step:number, spacing:number}>} + */ +var TICK_PLACEMENT = []; +TICK_PLACEMENT[Granularity.MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 1, + spacing: 1 +}; +TICK_PLACEMENT[Granularity.TWO_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 2, + spacing: 2 +}; +TICK_PLACEMENT[Granularity.FIVE_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 5, + spacing: 5 +}; +TICK_PLACEMENT[Granularity.TEN_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 10, + spacing: 10 +}; +TICK_PLACEMENT[Granularity.FIFTY_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 50, + spacing: 50 +}; +TICK_PLACEMENT[Granularity.HUNDRED_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 100, + spacing: 100 +}; +TICK_PLACEMENT[Granularity.FIVE_HUNDRED_MILLISECONDLY] = { + datefield: DateField.DATEFIELD_MS, + step: 500, + spacing: 500 +}; +TICK_PLACEMENT[Granularity.SECONDLY] = { + datefield: DateField.DATEFIELD_SS, + step: 1, + spacing: 1000 * 1 +}; +TICK_PLACEMENT[Granularity.TWO_SECONDLY] = { + datefield: DateField.DATEFIELD_SS, + step: 2, + spacing: 1000 * 2 +}; +TICK_PLACEMENT[Granularity.FIVE_SECONDLY] = { + datefield: DateField.DATEFIELD_SS, + step: 5, + spacing: 1000 * 5 +}; +TICK_PLACEMENT[Granularity.TEN_SECONDLY] = { + datefield: DateField.DATEFIELD_SS, + step: 10, + spacing: 1000 * 10 +}; +TICK_PLACEMENT[Granularity.THIRTY_SECONDLY] = { + datefield: DateField.DATEFIELD_SS, + step: 30, + spacing: 1000 * 30 +}; +TICK_PLACEMENT[Granularity.MINUTELY] = { + datefield: DateField.DATEFIELD_MM, + step: 1, + spacing: 1000 * 60 +}; +TICK_PLACEMENT[Granularity.TWO_MINUTELY] = { + datefield: DateField.DATEFIELD_MM, + step: 2, + spacing: 1000 * 60 * 2 +}; +TICK_PLACEMENT[Granularity.FIVE_MINUTELY] = { + datefield: DateField.DATEFIELD_MM, + step: 5, + spacing: 1000 * 60 * 5 +}; +TICK_PLACEMENT[Granularity.TEN_MINUTELY] = { + datefield: DateField.DATEFIELD_MM, + step: 10, + spacing: 1000 * 60 * 10 +}; +TICK_PLACEMENT[Granularity.THIRTY_MINUTELY] = { + datefield: DateField.DATEFIELD_MM, + step: 30, + spacing: 1000 * 60 * 30 +}; +TICK_PLACEMENT[Granularity.HOURLY] = { + datefield: DateField.DATEFIELD_HH, + step: 1, + spacing: 1000 * 3600 +}; +TICK_PLACEMENT[Granularity.TWO_HOURLY] = { + datefield: DateField.DATEFIELD_HH, + step: 2, + spacing: 1000 * 3600 * 2 +}; +TICK_PLACEMENT[Granularity.SIX_HOURLY] = { + datefield: DateField.DATEFIELD_HH, + step: 6, + spacing: 1000 * 3600 * 6 +}; +TICK_PLACEMENT[Granularity.DAILY] = { + datefield: DateField.DATEFIELD_D, + step: 1, + spacing: 1000 * 86400 +}; +TICK_PLACEMENT[Granularity.TWO_DAILY] = { + datefield: DateField.DATEFIELD_D, + step: 2, + spacing: 1000 * 86400 * 2 +}; +TICK_PLACEMENT[Granularity.WEEKLY] = { + datefield: DateField.DATEFIELD_D, + step: 7, + spacing: 1000 * 604800 +}; +TICK_PLACEMENT[Granularity.MONTHLY] = { + datefield: DateField.DATEFIELD_M, + step: 1, + spacing: 1000 * 7200 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 / 12 +TICK_PLACEMENT[Granularity.QUARTERLY] = { + datefield: DateField.DATEFIELD_M, + step: 3, + spacing: 1000 * 21600 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 / 4 +TICK_PLACEMENT[Granularity.BIANNUAL] = { + datefield: DateField.DATEFIELD_M, + step: 6, + spacing: 1000 * 43200 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 / 2 +TICK_PLACEMENT[Granularity.ANNUAL] = { + datefield: DateField.DATEFIELD_Y, + step: 1, + spacing: 1000 * 86400 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 * 1 +TICK_PLACEMENT[Granularity.DECADAL] = { + datefield: DateField.DATEFIELD_Y, + step: 10, + spacing: 1000 * 864000 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 * 10 +TICK_PLACEMENT[Granularity.CENTENNIAL] = { + datefield: DateField.DATEFIELD_Y, + step: 100, + spacing: 1000 * 8640000 * 365.2425 +}; // 1e3 * 60 * 60 * 24 * 365.2425 * 100 + +/** + * This is a list of human-friendly values at which to show tick marks on a log + * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so: + * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ... + * NOTE: this assumes that utils.LOG_SCALE = 10. + * @type {Array.} + */ +var PREFERRED_LOG_TICK_VALUES = function () { + var vals = []; + for (var power = -39; power <= 39; power++) { + var range = Math.pow(10, power); + for (var mult = 1; mult <= 9; mult++) { + var val = range * mult; + vals.push(val); + } + } + return vals; +}(); + +/** + * Determine the correct granularity of ticks on a date axis. + * + * @param {number} a Left edge of the chart (ms) + * @param {number} b Right edge of the chart (ms) + * @param {number} pixels Size of the chart in the relevant dimension (width). + * @param {function(string):*} opts Function mapping from option name -> value. + * @return {number} The appropriate axis granularity for this chart. See the + * enumeration of possible values in dygraph-tickers.js. + */ +var pickDateTickGranularity = function pickDateTickGranularity(a, b, pixels, opts) { + var pixels_per_tick = /** @type{number} */opts('pixelsPerLabel'); + for (var i = 0; i < Granularity.NUM_GRANULARITIES; i++) { + var num_ticks = numDateTicks(a, b, i); + if (pixels / num_ticks >= pixels_per_tick) { + return i; + } + } + return -1; +}; + +/** + * Compute the number of ticks on a date axis for a given granularity. + * @param {number} start_time + * @param {number} end_time + * @param {number} granularity (one of the granularities enumerated above) + * @return {number} (Approximate) number of ticks that would result. + */ +exports.pickDateTickGranularity = pickDateTickGranularity; +var numDateTicks = function numDateTicks(start_time, end_time, granularity) { + var spacing = TICK_PLACEMENT[granularity].spacing; + return Math.round(1.0 * (end_time - start_time) / spacing); +}; + +/** + * Compute the positions and labels of ticks on a date axis for a given granularity. + * @param {number} start_time + * @param {number} end_time + * @param {number} granularity (one of the granularities enumerated above) + * @param {function(string):*} opts Function mapping from option name -> value. + * @param {Dygraph=} dg + * @return {!TickList} + */ +var getDateAxis = function getDateAxis(start_time, end_time, granularity, opts, dg) { + var formatter = /** @type{AxisLabelFormatter} */ + opts("axisLabelFormatter"); + var utc = opts("labelsUTC"); + var accessors = utc ? utils.DateAccessorsUTC : utils.DateAccessorsLocal; + var datefield = TICK_PLACEMENT[granularity].datefield; + var step = TICK_PLACEMENT[granularity].step; + var spacing = TICK_PLACEMENT[granularity].spacing; + + // Choose a nice tick position before the initial instant. + // Currently, this code deals properly with the existent daily granularities: + // DAILY (with step of 1) and WEEKLY (with step of 7 but specially handled). + // Other daily granularities (say TWO_DAILY) should also be handled specially + // by setting the start_date_offset to 0. + var start_date = new Date(start_time); + var date_array = []; + date_array[DateField.DATEFIELD_Y] = accessors.getFullYear(start_date); + date_array[DateField.DATEFIELD_M] = accessors.getMonth(start_date); + date_array[DateField.DATEFIELD_D] = accessors.getDate(start_date); + date_array[DateField.DATEFIELD_HH] = accessors.getHours(start_date); + date_array[DateField.DATEFIELD_MM] = accessors.getMinutes(start_date); + date_array[DateField.DATEFIELD_SS] = accessors.getSeconds(start_date); + date_array[DateField.DATEFIELD_MS] = accessors.getMilliseconds(start_date); + var start_date_offset = date_array[datefield] % step; + if (granularity == Granularity.WEEKLY) { + // This will put the ticks on Sundays. + start_date_offset = accessors.getDay(start_date); + } + date_array[datefield] -= start_date_offset; + for (var df = datefield + 1; df < DateField.NUM_DATEFIELDS; df++) { + // The minimum value is 1 for the day of month, and 0 for all other fields. + date_array[df] = df === DateField.DATEFIELD_D ? 1 : 0; + } + + // Generate the ticks. + // For granularities not coarser than HOURLY we use the fact that: + // the number of milliseconds between ticks is constant + // and equal to the defined spacing. + // Otherwise we rely on the 'roll over' property of the Date functions: + // when some date field is set to a value outside of its logical range, + // the excess 'rolls over' the next (more significant) field. + // However, when using local time with DST transitions, + // there are dates that do not represent any time value at all + // (those in the hour skipped at the 'spring forward'), + // and the JavaScript engines usually return an equivalent value. + // Hence we have to check that the date is properly increased at each step, + // returning a date at a nice tick position. + var ticks = []; + var tick_date = accessors.makeDate.apply(null, date_array); + var tick_time = tick_date.getTime(); + if (granularity <= Granularity.HOURLY) { + if (tick_time < start_time) { + tick_time += spacing; + tick_date = new Date(tick_time); + } + while (tick_time <= end_time) { + ticks.push({ + v: tick_time, + label: formatter.call(dg, tick_date, granularity, opts, dg) + }); + tick_time += spacing; + tick_date = new Date(tick_time); + } + } else { + if (tick_time < start_time) { + date_array[datefield] += step; + tick_date = accessors.makeDate.apply(null, date_array); + tick_time = tick_date.getTime(); + } + while (tick_time <= end_time) { + if (granularity >= Granularity.DAILY || accessors.getHours(tick_date) % step === 0) { + ticks.push({ + v: tick_time, + label: formatter.call(dg, tick_date, granularity, opts, dg) + }); + } + date_array[datefield] += step; + tick_date = accessors.makeDate.apply(null, date_array); + tick_time = tick_date.getTime(); + } + } + return ticks; +}; +exports.getDateAxis = getDateAxis; + +},{"./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/dygraph-utils.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/** + * @fileoverview This file contains utility functions used by dygraphs. These + * are typically static (i.e. not related to any particular dygraph). Examples + * include date/time formatting functions, basic algorithms (e.g. binary + * search) and generic DOM-manipulation functions. + */ + +/*global Dygraph:false, Node:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HORIZONTAL = exports.DateAccessorsUTC = exports.DateAccessorsLocal = exports.DOT_DASH_LINE = exports.DOTTED_LINE = exports.DASHED_LINE = exports.Circles = void 0; +exports.Iterator = Iterator; +exports.addEvent = exports.VERTICAL = exports.LOG_SCALE = exports.LN_TEN = void 0; +exports.binarySearch = binarySearch; +exports.cancelEvent = cancelEvent; +exports.clone = clone; +exports.createCanvas = createCanvas; +exports.createIterator = createIterator; +exports.dateAxisLabelFormatter = dateAxisLabelFormatter; +exports.dateParser = dateParser; +exports.dateStrToMillis = dateStrToMillis; +exports.dateString_ = dateString_; +exports.dateValueFormatter = dateValueFormatter; +exports.detectLineDelimiter = detectLineDelimiter; +exports.dragGetX_ = dragGetX_; +exports.dragGetY_ = dragGetY_; +exports.findPos = findPos; +exports.floatFormat = floatFormat; +exports.getContext = void 0; +exports.getContextPixelRatio = getContextPixelRatio; +exports.hmsString_ = hmsString_; +exports.hsvToRGB = hsvToRGB; +exports.isArrayLike = isArrayLike; +exports.isCanvasSupported = isCanvasSupported; +exports.isDateLike = isDateLike; +exports.isNodeContainedBy = isNodeContainedBy; +exports.isOK = isOK; +exports.isPixelChangingOptionList = isPixelChangingOptionList; +exports.isValidPoint = isValidPoint; +exports.logRangeFraction = exports.log10 = void 0; +exports.numberAxisLabelFormatter = numberAxisLabelFormatter; +exports.numberValueFormatter = numberValueFormatter; +exports.pageX = pageX; +exports.pageY = pageY; +exports.parseFloat_ = parseFloat_; +exports.pow = pow; +exports.removeEvent = removeEvent; +exports.repeatAndCleanup = repeatAndCleanup; +exports.requestAnimFrame = void 0; +exports.round_ = round_; +exports.setupDOMready_ = setupDOMready_; +exports.toRGB_ = toRGB_; +exports.type = type; +exports.typeArrayLike = typeArrayLike; +exports.update = update; +exports.updateDeep = updateDeep; +exports.zeropad = zeropad; +var DygraphTickers = _interopRequireWildcard(require("./dygraph-tickers")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * @param {*} o + * @return {string} + * @private + */ +function type(o) { + return o === null ? 'null' : typeof o; +} +var LOG_SCALE = 10; +exports.LOG_SCALE = LOG_SCALE; +var LN_TEN = Math.log(LOG_SCALE); + +/** + * @private + * @param {number} x + * @return {number} + */ +exports.LN_TEN = LN_TEN; +var log10 = function log10(x) { + return Math.log(x) / LN_TEN; +}; + +/** + * @private + * @param {number} r0 + * @param {number} r1 + * @param {number} pct + * @return {number} + */ +exports.log10 = log10; +var logRangeFraction = function logRangeFraction(r0, r1, pct) { + // Computing the inverse of toPercentXCoord. The function was arrived at with + // the following steps: + // + // Original calcuation: + // pct = (log(x) - log(xRange[0])) / (log(xRange[1]) - log(xRange[0])); + // + // Multiply both sides by the right-side denominator. + // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0]) + // + // add log(xRange[0]) to both sides + // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))) = log(x); + // + // Swap both sides of the equation, + // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))) + // + // Use both sides as the exponent in 10^exp and we're done. + // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))) + + var logr0 = log10(r0); + var logr1 = log10(r1); + var exponent = logr0 + pct * (logr1 - logr0); + var value = Math.pow(LOG_SCALE, exponent); + return value; +}; + +/** A dotted line stroke pattern. */ +exports.logRangeFraction = logRangeFraction; +var DOTTED_LINE = [2, 2]; +/** A dashed line stroke pattern. */ +exports.DOTTED_LINE = DOTTED_LINE; +var DASHED_LINE = [7, 3]; +/** A dot dash stroke pattern. */ +exports.DASHED_LINE = DASHED_LINE; +var DOT_DASH_LINE = [7, 2, 2, 2]; + +// Directions for panning and zooming. Use bit operations when combined +// values are possible. +exports.DOT_DASH_LINE = DOT_DASH_LINE; +var HORIZONTAL = 1; +exports.HORIZONTAL = HORIZONTAL; +var VERTICAL = 2; + +/** + * Return the 2d context for a dygraph canvas. + * + * This method is only exposed for the sake of replacing the function in + * automated tests. + * + * @param {!HTMLCanvasElement} canvas + * @return {!CanvasRenderingContext2D} + * @private + */ +exports.VERTICAL = VERTICAL; +var getContext = function getContext(canvas) { + return (/** @type{!CanvasRenderingContext2D}*/canvas.getContext("2d") + ); +}; + +/** + * Add an event handler. + * @param {!Node} elem The element to add the event to. + * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. + * @param {function(Event):(boolean|undefined)} fn The function to call + * on the event. The function takes one parameter: the event object. + * @private + */ +exports.getContext = getContext; +var addEvent = function addEvent(elem, type, fn) { + elem.addEventListener(type, fn, false); +}; + +/** + * Remove an event handler. + * @param {!Node} elem The element to remove the event from. + * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. + * @param {function(Event):(boolean|undefined)} fn The function to call + * on the event. The function takes one parameter: the event object. + */ +exports.addEvent = addEvent; +function removeEvent(elem, type, fn) { + elem.removeEventListener(type, fn, false); +} + +/** + * Cancels further processing of an event. This is useful to prevent default + * browser actions, e.g. highlighting text on a double-click. + * Based on the article at + * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel + * @param {!Event} e The event whose normal behavior should be canceled. + * @private + */ +function cancelEvent(e) { + e = e ? e : window.event; + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.preventDefault) { + e.preventDefault(); + } + e.cancelBubble = true; + e.cancel = true; + e.returnValue = false; + return false; +} + +/** + * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This + * is used to generate default series colors which are evenly spaced on the + * color wheel. + * @param {number} hue Range is 0.0-1.0. + * @param {number} saturation Range is 0.0-1.0. + * @param {number} value Range is 0.0-1.0. + * @return {string} "rgb(r,g,b)" where r, g and b range from 0-255. + * @private + */ +function hsvToRGB(hue, saturation, value) { + var red; + var green; + var blue; + if (saturation === 0) { + red = value; + green = value; + blue = value; + } else { + var i = Math.floor(hue * 6); + var f = hue * 6 - i; + var p = value * (1 - saturation); + var q = value * (1 - saturation * f); + var t = value * (1 - saturation * (1 - f)); + switch (i) { + case 1: + red = q; + green = value; + blue = p; + break; + case 2: + red = p; + green = value; + blue = t; + break; + case 3: + red = p; + green = q; + blue = value; + break; + case 4: + red = t; + green = p; + blue = value; + break; + case 5: + red = value; + green = p; + blue = q; + break; + case 6: // fall through + case 0: + red = value; + green = t; + blue = p; + break; + } + } + red = Math.floor(255 * red + 0.5); + green = Math.floor(255 * green + 0.5); + blue = Math.floor(255 * blue + 0.5); + return 'rgb(' + red + ',' + green + ',' + blue + ')'; +} + +/** + * Find the coordinates of an object relative to the top left of the page. + * + * @param {Node} obj + * @return {{x:number,y:number}} + * @private + */ +function findPos(obj) { + var p = obj.getBoundingClientRect(), + w = window, + d = document.documentElement; + return { + x: p.left + (w.pageXOffset || d.scrollLeft), + y: p.top + (w.pageYOffset || d.scrollTop) + }; +} + +/** + * Returns the x-coordinate of the event in a coordinate system where the + * top-left corner of the page (not the window) is (0,0). + * Taken from MochiKit.Signal + * @param {!Event} e + * @return {number} + * @private + */ +function pageX(e) { + return !e.pageX || e.pageX < 0 ? 0 : e.pageX; +} + +/** + * Returns the y-coordinate of the event in a coordinate system where the + * top-left corner of the page (not the window) is (0,0). + * Taken from MochiKit.Signal + * @param {!Event} e + * @return {number} + * @private + */ +function pageY(e) { + return !e.pageY || e.pageY < 0 ? 0 : e.pageY; +} + +/** + * Converts page the x-coordinate of the event to pixel x-coordinates on the + * canvas (i.e. DOM Coords). + * @param {!Event} e Drag event. + * @param {!DygraphInteractionContext} context Interaction context object. + * @return {number} The amount by which the drag has moved to the right. + */ +function dragGetX_(e, context) { + return pageX(e) - context.px; +} + +/** + * Converts page the y-coordinate of the event to pixel y-coordinates on the + * canvas (i.e. DOM Coords). + * @param {!Event} e Drag event. + * @param {!DygraphInteractionContext} context Interaction context object. + * @return {number} The amount by which the drag has moved down. + */ +function dragGetY_(e, context) { + return pageY(e) - context.py; +} + +/** + * This returns true unless the parameter is 0, null, undefined or NaN. + * TODO(danvk): rename this function to something like 'isNonZeroNan'. + * + * @param {number} x The number to consider. + * @return {boolean} Whether the number is zero or NaN. + * @private + */ +function isOK(x) { + return !!x && !isNaN(x); +} + +/** + * @param {{x:?number,y:?number,yval:?number}} p The point to consider, valid + * points are {x, y} objects + * @param {boolean=} opt_allowNaNY Treat point with y=NaN as valid + * @return {boolean} Whether the point has numeric x and y. + * @private + */ +function isValidPoint(p, opt_allowNaNY) { + if (!p) return false; // null or undefined object + if (p.yval === null) return false; // missing point + if (p.x === null || p.x === undefined) return false; + if (p.y === null || p.y === undefined) return false; + if (isNaN(p.x) || !opt_allowNaNY && isNaN(p.y)) return false; + return true; +} + +/** + * Number formatting function which mimics the behavior of %g in printf, i.e. + * either exponential or fixed format (without trailing 0s) is used depending on + * the length of the generated string. The advantage of this format is that + * there is a predictable upper bound on the resulting string length, + * significant figures are not dropped, and normal numbers are not displayed in + * exponential notation. + * + * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. + * It creates strings which are too long for absolute values between 10^-4 and + * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for + * output examples. + * + * @param {number} x The number to format + * @param {number=} opt_precision The precision to use, default 2. + * @return {string} A string formatted like %g in printf. The max generated + * string length should be precision + 6 (e.g 1.123e+300). + */ +function floatFormat(x, opt_precision) { + // Avoid invalid precision values; [1, 21] is the valid range. + var p = Math.min(Math.max(1, opt_precision || 2), 21); + + // This is deceptively simple. The actual algorithm comes from: + // + // Max allowed length = p + 4 + // where 4 comes from 'e+n' and '.'. + // + // Length of fixed format = 2 + y + p + // where 2 comes from '0.' and y = # of leading zeroes. + // + // Equating the two and solving for y yields y = 2, or 0.00xxxx which is + // 1.0e-3. + // + // Since the behavior of toPrecision() is identical for larger numbers, we + // don't have to worry about the other bound. + // + // Finally, the argument for toExponential() is the number of trailing digits, + // so we take off 1 for the value before the '.'. + return Math.abs(x) < 1.0e-3 && x !== 0.0 ? x.toExponential(p - 1) : x.toPrecision(p); +} + +/** + * Converts '9' to '09' (useful for dates) + * @param {number} x + * @return {string} + * @private + */ +function zeropad(x) { + if (x < 10) return "0" + x;else return "" + x; +} + +/** + * Date accessors to get the parts of a calendar date (year, month, + * day, hour, minute, second and millisecond) according to local time, + * and factory method to call the Date constructor with an array of arguments. + */ +var DateAccessorsLocal = { + getFullYear: function getFullYear(d) { + return d.getFullYear(); + }, + getMonth: function getMonth(d) { + return d.getMonth(); + }, + getDate: function getDate(d) { + return d.getDate(); + }, + getHours: function getHours(d) { + return d.getHours(); + }, + getMinutes: function getMinutes(d) { + return d.getMinutes(); + }, + getSeconds: function getSeconds(d) { + return d.getSeconds(); + }, + getMilliseconds: function getMilliseconds(d) { + return d.getMilliseconds(); + }, + getDay: function getDay(d) { + return d.getDay(); + }, + makeDate: function makeDate(y, m, d, hh, mm, ss, ms) { + return new Date(y, m, d, hh, mm, ss, ms); + } +}; + +/** + * Date accessors to get the parts of a calendar date (year, month, + * day of month, hour, minute, second and millisecond) according to UTC time, + * and factory method to call the Date constructor with an array of arguments. + */ +exports.DateAccessorsLocal = DateAccessorsLocal; +var DateAccessorsUTC = { + getFullYear: function getFullYear(d) { + return d.getUTCFullYear(); + }, + getMonth: function getMonth(d) { + return d.getUTCMonth(); + }, + getDate: function getDate(d) { + return d.getUTCDate(); + }, + getHours: function getHours(d) { + return d.getUTCHours(); + }, + getMinutes: function getMinutes(d) { + return d.getUTCMinutes(); + }, + getSeconds: function getSeconds(d) { + return d.getUTCSeconds(); + }, + getMilliseconds: function getMilliseconds(d) { + return d.getUTCMilliseconds(); + }, + getDay: function getDay(d) { + return d.getUTCDay(); + }, + makeDate: function makeDate(y, m, d, hh, mm, ss, ms) { + return new Date(Date.UTC(y, m, d, hh, mm, ss, ms)); + } +}; + +/** + * Return a string version of the hours, minutes and seconds portion of a date. + * @param {number} hh The hours (from 0-23) + * @param {number} mm The minutes (from 0-59) + * @param {number} ss The seconds (from 0-59) + * @return {string} A time of the form "HH:MM" or "HH:MM:SS" + * @private + */ +exports.DateAccessorsUTC = DateAccessorsUTC; +function hmsString_(hh, mm, ss, ms) { + var ret = zeropad(hh) + ":" + zeropad(mm); + if (ss) { + ret += ":" + zeropad(ss); + if (ms) { + var str = "" + ms; + ret += "." + ('000' + str).substring(str.length); + } + } + return ret; +} + +/** + * Convert a JS date (millis since epoch) to a formatted string. + * @param {number} time The JavaScript time value (ms since epoch) + * @param {boolean} utc Whether output UTC or local time + * @return {string} A date of one of these forms: + * "YYYY/MM/DD", "YYYY/MM/DD HH:MM" or "YYYY/MM/DD HH:MM:SS" + * @private + */ +function dateString_(time, utc) { + var accessors = utc ? DateAccessorsUTC : DateAccessorsLocal; + var date = new Date(time); + var y = accessors.getFullYear(date); + var m = accessors.getMonth(date); + var d = accessors.getDate(date); + var hh = accessors.getHours(date); + var mm = accessors.getMinutes(date); + var ss = accessors.getSeconds(date); + var ms = accessors.getMilliseconds(date); + // Get a year string: + var year = "" + y; + // Get a 0 padded month string + var month = zeropad(m + 1); //months are 0-offset, sigh + // Get a 0 padded day string + var day = zeropad(d); + var frac = hh * 3600 + mm * 60 + ss + 1e-3 * ms; + var ret = year + "/" + month + "/" + day; + if (frac) { + ret += " " + hmsString_(hh, mm, ss, ms); + } + return ret; +} + +/** + * Round a number to the specified number of digits past the decimal point. + * @param {number} num The number to round + * @param {number} places The number of decimals to which to round + * @return {number} The rounded number + * @private + */ +function round_(num, places) { + var shift = Math.pow(10, places); + return Math.round(num * shift) / shift; +} + +/** + * Implementation of binary search over an array. + * Currently does not work when val is outside the range of arry's values. + * @param {number} val the value to search for + * @param {Array.} arry is the value over which to search + * @param {number} abs If abs > 0, find the lowest entry greater than val + * If abs < 0, find the highest entry less than val. + * If abs == 0, find the entry that equals val. + * @param {number=} low The first index in arry to consider (optional) + * @param {number=} high The last index in arry to consider (optional) + * @return {number} Index of the element, or -1 if it isn't found. + * @private + */ +function binarySearch(val, arry, abs, low, high) { + if (low === null || low === undefined || high === null || high === undefined) { + low = 0; + high = arry.length - 1; + } + if (low > high) { + return -1; + } + if (abs === null || abs === undefined) { + abs = 0; + } + var validIndex = function validIndex(idx) { + return idx >= 0 && idx < arry.length; + }; + var mid = parseInt((low + high) / 2, 10); + var element = arry[mid]; + var idx; + if (element == val) { + return mid; + } else if (element > val) { + if (abs > 0) { + // Accept if element > val, but also if prior element < val. + idx = mid - 1; + if (validIndex(idx) && arry[idx] < val) { + return mid; + } + } + return binarySearch(val, arry, abs, low, mid - 1); + } else if (element < val) { + if (abs < 0) { + // Accept if element < val, but also if prior element > val. + idx = mid + 1; + if (validIndex(idx) && arry[idx] > val) { + return mid; + } + } + return binarySearch(val, arry, abs, mid + 1, high); + } + return -1; // can't actually happen, but makes closure compiler happy +} + +/** + * Parses a date, returning the number of milliseconds since epoch. This can be + * passed in as an xValueParser in the Dygraph constructor. + * TODO(danvk): enumerate formats that this understands. + * + * @param {string} dateStr A date in a variety of possible string formats. + * @return {number} Milliseconds since epoch. + * @private + */ +function dateParser(dateStr) { + var dateStrSlashed; + var d; + + // Let the system try the format first, with one caveat: + // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers. + // dygraphs displays dates in local time, so this will result in surprising + // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS), + // then you probably know what you're doing, so we'll let you go ahead. + // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255 + if (dateStr.search("-") == -1 || dateStr.search("T") != -1 || dateStr.search("Z") != -1) { + d = dateStrToMillis(dateStr); + if (d && !isNaN(d)) return d; + } + if (dateStr.search("-") != -1) { + // e.g. '2009-7-12' or '2009-07-12' + dateStrSlashed = dateStr.replace("-", "/", "g"); + while (dateStrSlashed.search("-") != -1) { + dateStrSlashed = dateStrSlashed.replace("-", "/"); + } + d = dateStrToMillis(dateStrSlashed); + } else { + // Any format that Date.parse will accept, e.g. "2009/07/12" or + // "2009/07/12 12:34:56" + d = dateStrToMillis(dateStr); + } + if (!d || isNaN(d)) { + console.error("Couldn't parse " + dateStr + " as a date"); + } + return d; +} + +/** + * This is identical to JavaScript's built-in Date.parse() method, except that + * it doesn't get replaced with an incompatible method by aggressive JS + * libraries like MooTools or Joomla. + * @param {string} str The date string, e.g. "2011/05/06" + * @return {number} millis since epoch + * @private + */ +function dateStrToMillis(str) { + return new Date(str).getTime(); +} + +// These functions are all based on MochiKit. +/** + * Copies all the properties from o to self. + * + * @param {!Object} self + * @param {!Object} o + * @return {!Object} + */ +function update(self, o) { + if (typeof o != 'undefined' && o !== null) { + for (var k in o) { + if (o.hasOwnProperty(k)) { + self[k] = o[k]; + } + } + } + return self; +} + +// internal: check if o is a DOM node, and we know it’s not null +var _isNode = typeof Node !== 'undefined' && Node !== null && typeof Node === 'object' ? function _isNode(o) { + return o instanceof Node; +} : function _isNode(o) { + return typeof o === 'object' && typeof o.nodeType === 'number' && typeof o.nodeName === 'string'; +}; + +/** + * Copies all the properties from o to self. + * + * @param {!Object} self + * @param {!Object} o + * @return {!Object} + * @private + */ +function updateDeep(self, o) { + if (typeof o != 'undefined' && o !== null) { + for (var k in o) { + if (o.hasOwnProperty(k)) { + var v = o[k]; + if (v === null) { + self[k] = null; + } else if (isArrayLike(v)) { + self[k] = v.slice(); + } else if (_isNode(v)) { + // DOM objects are shallowly-copied. + self[k] = v; + } else if (typeof v == 'object') { + if (typeof self[k] != 'object' || self[k] === null) { + self[k] = {}; + } + updateDeep(self[k], v); + } else { + self[k] = v; + } + } + } + } + return self; +} + +/** + * @param {*} o + * @return {string} + * @private + */ +function typeArrayLike(o) { + if (o === null) return 'null'; + var t = typeof o; + if ((t === 'object' || t === 'function' && typeof o.item === 'function') && typeof o.length === 'number' && o.nodeType !== 3 && o.nodeType !== 4) return 'array'; + return t; +} + +/** + * @param {*} o + * @return {boolean} + * @private + */ +function isArrayLike(o) { + var t = typeof o; + return o !== null && (t === 'object' || t === 'function' && typeof o.item === 'function') && typeof o.length === 'number' && o.nodeType !== 3 && o.nodeType !== 4; +} + +/** + * @param {Object} o + * @return {boolean} + * @private + */ +function isDateLike(o) { + return o !== null && typeof o === 'object' && typeof o.getTime === 'function'; +} + +/** + * Note: this only seems to work for arrays. + * @param {!Array} o + * @return {!Array} + * @private + */ +function clone(o) { + // TODO(danvk): figure out how MochiKit's version works + var r = []; + for (var i = 0; i < o.length; i++) { + if (isArrayLike(o[i])) { + r.push(clone(o[i])); + } else { + r.push(o[i]); + } + } + return r; +} + +/** + * Create a new canvas element. + * + * @return {!HTMLCanvasElement} + * @private + */ +function createCanvas() { + return document.createElement('canvas'); +} + +/** + * Returns the context's pixel ratio, which is the ratio between the device + * pixel ratio and the backing store ratio. Typically this is 1 for conventional + * displays, and > 1 for HiDPI displays (such as the Retina MBP). + * See http://www.html5rocks.com/en/tutorials/canvas/hidpi/ for more details. + * + * @param {!CanvasRenderingContext2D} context The canvas's 2d context. + * @return {number} The ratio of the device pixel ratio and the backing store + * ratio for the specified context. + */ +function getContextPixelRatio(context) { + try { + var devicePixelRatio = window.devicePixelRatio; + var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; + if (devicePixelRatio !== undefined) { + return devicePixelRatio / backingStoreRatio; + } else { + // At least devicePixelRatio must be defined for this ratio to make sense. + // We default backingStoreRatio to 1: this does not exist on some browsers + // (i.e. desktop Chrome). + return 1; + } + } catch (e) { + return 1; + } +} + +/** + * TODO(danvk): use @template here when it's better supported for classes. + * @param {!Array} array + * @param {number} start + * @param {number} length + * @param {function(!Array,?):boolean=} predicate + * @constructor + */ +function Iterator(array, start, length, predicate) { + start = start || 0; + length = length || array.length; + this.hasNext = true; // Use to identify if there's another element. + this.peek = null; // Use for look-ahead + this.start_ = start; + this.array_ = array; + this.predicate_ = predicate; + this.end_ = Math.min(array.length, start + length); + this.nextIdx_ = start - 1; // use -1 so initial advance works. + this.next(); // ignoring result. +} + +/** + * @return {Object} + */ +Iterator.prototype.next = function () { + if (!this.hasNext) { + return null; + } + var obj = this.peek; + var nextIdx = this.nextIdx_ + 1; + var found = false; + while (nextIdx < this.end_) { + if (!this.predicate_ || this.predicate_(this.array_, nextIdx)) { + this.peek = this.array_[nextIdx]; + found = true; + break; + } + nextIdx++; + } + this.nextIdx_ = nextIdx; + if (!found) { + this.hasNext = false; + this.peek = null; + } + return obj; +}; + +/** + * Returns a new iterator over array, between indexes start and + * start + length, and only returns entries that pass the accept function + * + * @param {!Array} array the array to iterate over. + * @param {number} start the first index to iterate over, 0 if absent. + * @param {number} length the number of elements in the array to iterate over. + * This, along with start, defines a slice of the array, and so length + * doesn't imply the number of elements in the iterator when accept doesn't + * always accept all values. array.length when absent. + * @param {function(?):boolean=} opt_predicate a function that takes + * parameters array and idx, which returns true when the element should be + * returned. If omitted, all elements are accepted. + * @private + */ +function createIterator(array, start, length, opt_predicate) { + return new Iterator(array, start, length, opt_predicate); +} + +// Shim layer with setTimeout fallback. +// From: http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// Should be called with the window context: +// Dygraph.requestAnimFrame.call(window, function() {}) +var requestAnimFrame = function () { + return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { + window.setTimeout(callback, 1000 / 60); + }; +}(); + +/** + * Call a function at most maxFrames times at an attempted interval of + * framePeriodInMillis, then call a cleanup function once. repeatFn is called + * once immediately, then at most (maxFrames - 1) times asynchronously. If + * maxFrames==1, then cleanup_fn() is also called synchronously. This function + * is used to sequence animation. + * @param {function(number)} repeatFn Called repeatedly -- takes the frame + * number (from 0 to maxFrames-1) as an argument. + * @param {number} maxFrames The max number of times to call repeatFn + * @param {number} framePeriodInMillis Max requested time between frames. + * @param {function()} cleanupFn A function to call after all repeatFn calls. + * @private + */ +exports.requestAnimFrame = requestAnimFrame; +function repeatAndCleanup(repeatFn, maxFrames, framePeriodInMillis, cleanupFn) { + var frameNumber = 0; + var previousFrameNumber; + var startTime = new Date().getTime(); + repeatFn(frameNumber); + if (maxFrames == 1) { + cleanupFn(); + return; + } + var maxFrameArg = maxFrames - 1; + (function loop() { + if (frameNumber >= maxFrames) return; + requestAnimFrame.call(window, function () { + // Determine which frame to draw based on the delay so far. Will skip + // frames if necessary. + var currentTime = new Date().getTime(); + var delayInMillis = currentTime - startTime; + previousFrameNumber = frameNumber; + frameNumber = Math.floor(delayInMillis / framePeriodInMillis); + var frameDelta = frameNumber - previousFrameNumber; + // If we predict that the subsequent repeatFn call will overshoot our + // total frame target, so our last call will cause a stutter, then jump to + // the last call immediately. If we're going to cause a stutter, better + // to do it faster than slower. + var predictOvershootStutter = frameNumber + frameDelta > maxFrameArg; + if (predictOvershootStutter || frameNumber >= maxFrameArg) { + repeatFn(maxFrameArg); // Ensure final call with maxFrameArg. + cleanupFn(); + } else { + if (frameDelta !== 0) { + // Don't call repeatFn with duplicate frames. + repeatFn(frameNumber); + } + loop(); + } + }); + })(); +} + +// A whitelist of options that do not change pixel positions. +var pixelSafeOptions = { + 'annotationClickHandler': true, + 'annotationDblClickHandler': true, + 'annotationMouseOutHandler': true, + 'annotationMouseOverHandler': true, + 'axisLineColor': true, + 'axisLineWidth': true, + 'clickCallback': true, + 'drawCallback': true, + 'drawHighlightPointCallback': true, + 'drawPoints': true, + 'drawPointCallback': true, + 'drawGrid': true, + 'fillAlpha': true, + 'gridLineColor': true, + 'gridLineWidth': true, + 'hideOverlayOnMouseOut': true, + 'highlightCallback': true, + 'highlightCircleSize': true, + 'interactionModel': true, + 'labelsDiv': true, + 'labelsKMB': true, + 'labelsKMG2': true, + 'labelsSeparateLines': true, + 'labelsShowZeroValues': true, + 'legend': true, + 'panEdgeFraction': true, + 'pixelsPerYLabel': true, + 'pointClickCallback': true, + 'pointSize': true, + 'rangeSelectorPlotFillColor': true, + 'rangeSelectorPlotFillGradientColor': true, + 'rangeSelectorPlotStrokeColor': true, + 'rangeSelectorBackgroundStrokeColor': true, + 'rangeSelectorBackgroundLineWidth': true, + 'rangeSelectorPlotLineWidth': true, + 'rangeSelectorForegroundStrokeColor': true, + 'rangeSelectorForegroundLineWidth': true, + 'rangeSelectorAlpha': true, + 'showLabelsOnHighlight': true, + 'showRoller': true, + 'strokeWidth': true, + 'underlayCallback': true, + 'unhighlightCallback': true, + 'zoomCallback': true +}; + +/** + * This function will scan the option list and determine if they + * require us to recalculate the pixel positions of each point. + * TODO: move this into dygraph-options.js + * @param {!Array.} labels a list of options to check. + * @param {!Object} attrs + * @return {boolean} true if the graph needs new points else false. + * @private + */ +function isPixelChangingOptionList(labels, attrs) { + // Assume that we do not require new points. + // This will change to true if we actually do need new points. + + // Create a dictionary of series names for faster lookup. + // If there are no labels, then the dictionary stays empty. + var seriesNamesDictionary = {}; + if (labels) { + for (var i = 1; i < labels.length; i++) { + seriesNamesDictionary[labels[i]] = true; + } + } + + // Scan through a flat (i.e. non-nested) object of options. + // Returns true/false depending on whether new points are needed. + var scanFlatOptions = function scanFlatOptions(options) { + for (var property in options) { + if (options.hasOwnProperty(property) && !pixelSafeOptions[property]) { + return true; + } + } + return false; + }; + + // Iterate through the list of updated options. + for (var property in attrs) { + if (!attrs.hasOwnProperty(property)) continue; + + // Find out of this field is actually a series specific options list. + if (property == 'highlightSeriesOpts' || seriesNamesDictionary[property] && !attrs.series) { + // This property value is a list of options for this series. + if (scanFlatOptions(attrs[property])) return true; + } else if (property == 'series' || property == 'axes') { + // This is twice-nested options list. + var perSeries = attrs[property]; + for (var series in perSeries) { + if (perSeries.hasOwnProperty(series) && scanFlatOptions(perSeries[series])) { + return true; + } + } + } else { + // If this was not a series specific option list, + // check if it's a pixel-changing property. + if (!pixelSafeOptions[property]) return true; + } + } + return false; +} +var Circles = { + DEFAULT: function DEFAULT(g, name, ctx, canvasx, canvasy, color, radius) { + ctx.beginPath(); + ctx.fillStyle = color; + ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false); + ctx.fill(); + } + // For more shapes, include extras/shapes.js +}; + +/** + * Determine whether |data| is delimited by CR, CRLF, LF, LFCR. + * @param {string} data + * @return {?string} the delimiter that was detected (or null on failure). + */ +exports.Circles = Circles; +function detectLineDelimiter(data) { + for (var i = 0; i < data.length; i++) { + var code = data.charAt(i); + if (code === '\r') { + // Might actually be "\r\n". + if (i + 1 < data.length && data.charAt(i + 1) === '\n') { + return '\r\n'; + } + return code; + } + if (code === '\n') { + // Might actually be "\n\r". + if (i + 1 < data.length && data.charAt(i + 1) === '\r') { + return '\n\r'; + } + return code; + } + } + return null; +} + +/** + * Is one node contained by another? + * @param {Node} containee The contained node. + * @param {Node} container The container node. + * @return {boolean} Whether containee is inside (or equal to) container. + * @private + */ +function isNodeContainedBy(containee, container) { + if (container === null || containee === null) { + return false; + } + var containeeNode = /** @type {Node} */containee; + while (containeeNode && containeeNode !== container) { + containeeNode = containeeNode.parentNode; + } + return containeeNode === container; +} + +// This masks some numeric issues in older versions of Firefox, +// where 1.0/Math.pow(10,2) != Math.pow(10,-2). +/** @type {function(number,number):number} */ +function pow(base, exp) { + if (exp < 0) { + return 1.0 / Math.pow(base, -exp); + } + return Math.pow(base, exp); +} +var RGBAxRE = /^#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})?$/; +var RGBA_RE = /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*([01](?:\.\d+)?))?\)$/; + +/** + * Helper for toRGB_ which parses strings of the form: + * #RRGGBB (hex) + * #RRGGBBAA (hex) + * rgb(123, 45, 67) + * rgba(123, 45, 67, 0.5) + * @return parsed {r,g,b,a?} tuple or null. + */ +function parseRGBA(rgbStr) { + var bits, + r, + g, + b, + a = null; + if (bits = RGBAxRE.exec(rgbStr)) { + r = parseInt(bits[1], 16); + g = parseInt(bits[2], 16); + b = parseInt(bits[3], 16); + if (bits[4]) a = parseInt(bits[4], 16); + } else if (bits = RGBA_RE.exec(rgbStr)) { + r = parseInt(bits[1], 10); + g = parseInt(bits[2], 10); + b = parseInt(bits[3], 10); + if (bits[4]) a = parseFloat(bits[4]); + } else return null; + if (a !== null) return { + "r": r, + "g": g, + "b": b, + "a": a + }; + return { + "r": r, + "g": g, + "b": b + }; +} + +/** + * Converts any valid CSS color (hex, rgb(), named color) to an RGB tuple. + * + * @param {!string} colorStr Any valid CSS color string. + * @return {{r:number,g:number,b:number,a:number?}} Parsed RGB tuple. + * @private + */ +function toRGB_(colorStr) { + // Strategy: First try to parse colorStr directly. This is fast & avoids DOM + // manipulation. If that fails (e.g. for named colors like 'red'), then + // create a hidden DOM element and parse its computed color. + var rgb = parseRGBA(colorStr); + if (rgb) return rgb; + var div = document.createElement('div'); + div.style.backgroundColor = colorStr; + div.style.visibility = 'hidden'; + document.body.appendChild(div); + var rgbStr = window.getComputedStyle(div, null).backgroundColor; + document.body.removeChild(div); + return parseRGBA(rgbStr); +} + +/** + * Checks whether the browser supports the <canvas> tag. + * @param {HTMLCanvasElement=} opt_canvasElement Pass a canvas element as an + * optimization if you have one. + * @return {boolean} Whether the browser supports canvas. + */ +function isCanvasSupported(opt_canvasElement) { + try { + var canvas = opt_canvasElement || document.createElement("canvas"); + canvas.getContext("2d"); + } catch (e) { + return false; + } + return true; +} + +/** + * Parses the value as a floating point number. This is like the parseFloat() + * built-in, but with a few differences: + * - the empty string is parsed as null, rather than NaN. + * - if the string cannot be parsed at all, an error is logged. + * If the string can't be parsed, this method returns null. + * @param {string} x The string to be parsed + * @param {number=} opt_line_no The line number from which the string comes. + * @param {string=} opt_line The text of the line from which the string comes. + */ +function parseFloat_(x, opt_line_no, opt_line) { + var val = parseFloat(x); + if (!isNaN(val)) return val; + + // Try to figure out what happeend. + // If the value is the empty string, parse it as null. + if (/^ *$/.test(x)) return null; + + // If it was actually "NaN", return it as NaN. + if (/^ *nan *$/i.test(x)) return NaN; + + // Looks like a parsing error. + var msg = "Unable to parse '" + x + "' as a number"; + if (opt_line !== undefined && opt_line_no !== undefined) { + msg += " on line " + (1 + (opt_line_no || 0)) + " ('" + opt_line + "') of CSV."; + } + console.error(msg); + return null; +} + +// Label constants for the labelsKMB and labelsKMG2 options. +// (i.e. '100000' -> '100k') +var KMB_LABELS_LARGE = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; +var KMB_LABELS_SMALL = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']; +var KMG2_LABELS_LARGE = ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi']; +var KMG2_LABELS_SMALL = ['p-10', 'p-20', 'p-30', 'p-40', 'p-50', 'p-60', 'p-70', 'p-80']; +/* if both are given (legacy/deprecated use only) */ +var KMB2_LABELS_LARGE = ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; +var KMB2_LABELS_SMALL = KMB_LABELS_SMALL; + +/** + * @private + * Return a string version of a number. This respects the digitsAfterDecimal + * and maxNumberWidth options. + * @param {number} x The number to be formatted + * @param {Dygraph} opts An options view + */ +function numberValueFormatter(x, opts) { + var sigFigs = opts('sigFigs'); + if (sigFigs !== null) { + // User has opted for a fixed number of significant figures. + return floatFormat(x, sigFigs); + } + + // shortcut 0 so later code does not need to worry about it + if (x === 0.0) return '0'; + var digits = opts('digitsAfterDecimal'); + var maxNumberWidth = opts('maxNumberWidth'); + var kmb = opts('labelsKMB'); + var kmg2 = opts('labelsKMG2'); + var label; + var absx = Math.abs(x); + if (kmb || kmg2) { + var k; + var k_labels = []; + var m_labels = []; + if (kmb) { + k = 1000; + k_labels = KMB_LABELS_LARGE; + m_labels = KMB_LABELS_SMALL; + } + if (kmg2) { + k = 1024; + k_labels = KMG2_LABELS_LARGE; + m_labels = KMG2_LABELS_SMALL; + if (kmb) { + k_labels = KMB2_LABELS_LARGE; + m_labels = KMB2_LABELS_SMALL; + } + } + var n; + var j; + if (absx >= k) { + j = k_labels.length; + while (j > 0) { + n = pow(k, j); + --j; + if (absx >= n) { + // guaranteed to hit because absx >= k (pow(k, 1)) + // if immensely large still switch to scientific notation + if (absx / n >= Math.pow(10, maxNumberWidth)) label = x.toExponential(digits);else label = round_(x / n, digits) + k_labels[j]; + return label; + } + } + // not reached, fall through safely though should it ever be + } else if (absx < 1 /* && (m_labels.length > 0) */) { + j = 0; + while (j < m_labels.length) { + ++j; + n = pow(k, j); + if (absx * n >= 1) break; + } + // if _still_ too small, switch to scientific notation instead + if (absx * n < Math.pow(10, -digits)) label = x.toExponential(digits);else label = round_(x * n, digits) + m_labels[j - 1]; + return label; + } + // else fall through + } + + if (absx >= Math.pow(10, maxNumberWidth) || absx < Math.pow(10, -digits)) { + // switch to scientific notation if we underflow or overflow fixed display + label = x.toExponential(digits); + } else { + label = '' + round_(x, digits); + } + return label; +} + +/** + * variant for use as an axisLabelFormatter. + * @private + */ +function numberAxisLabelFormatter(x, granularity, opts) { + return numberValueFormatter.call(this, x, opts); +} + +/** + * @type {!Array.} + * @private + * @constant + */ +var SHORT_MONTH_NAMES_ = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/** + * Convert a JS date to a string appropriate to display on an axis that + * is displaying values at the stated granularity. This respects the + * labelsUTC option. + * @param {Date} date The date to format + * @param {number} granularity One of the Dygraph granularity constants + * @param {Dygraph} opts An options view + * @return {string} The date formatted as local time + * @private + */ +function dateAxisLabelFormatter(date, granularity, opts) { + var utc = opts('labelsUTC'); + var accessors = utc ? DateAccessorsUTC : DateAccessorsLocal; + var year = accessors.getFullYear(date), + month = accessors.getMonth(date), + day = accessors.getDate(date), + hours = accessors.getHours(date), + mins = accessors.getMinutes(date), + secs = accessors.getSeconds(date), + millis = accessors.getMilliseconds(date); + if (granularity >= DygraphTickers.Granularity.DECADAL) { + return '' + year; + } else if (granularity >= DygraphTickers.Granularity.MONTHLY) { + return SHORT_MONTH_NAMES_[month] + ' ' + year; + } else { + var frac = hours * 3600 + mins * 60 + secs + 1e-3 * millis; + if (frac === 0 || granularity >= DygraphTickers.Granularity.DAILY) { + // e.g. '21 Jan' (%d%b) + return zeropad(day) + ' ' + SHORT_MONTH_NAMES_[month]; + } else if (granularity < DygraphTickers.Granularity.SECONDLY) { + // e.g. 40.310 (meaning 40 seconds and 310 milliseconds) + var str = "" + millis; + return zeropad(secs) + "." + ('000' + str).substring(str.length); + } else if (granularity > DygraphTickers.Granularity.MINUTELY) { + return hmsString_(hours, mins, secs, 0); + } else { + return hmsString_(hours, mins, secs, millis); + } + } +} + +/** + * Return a string version of a JS date for a value label. This respects the + * labelsUTC option. + * @param {Date} date The date to be formatted + * @param {Dygraph} opts An options view + * @private + */ +function dateValueFormatter(d, opts) { + return dateString_(d, opts('labelsUTC')); +} + +// stuff for simple onDOMready implementation +var deferDOM_callbacks = []; +var deferDOM_handlerCalled = false; + +// onDOMready once DOM is ready +/** + * Simple onDOMready implementation + * @param {function()} cb The callback to run once the DOM is ready. + * @return {boolean} whether the DOM is currently ready + */ +function deferDOM_ready(cb) { + if (typeof cb === "function") cb(); + return true; +} + +/** + * Setup a simple onDOMready implementation on the given objct. + * @param {*} self the object to update .onDOMready on + * @private + */ +function setupDOMready_(self) { + // only attach if there’s a DOM + if (typeof document !== "undefined") { + // called by browser + var handler = function deferDOM_handler() { + /* execute only once */ + if (deferDOM_handlerCalled) return; + deferDOM_handlerCalled = true; + /* subsequent calls must not enqueue */ + self.onDOMready = deferDOM_ready; + /* clear event handlers */ + document.removeEventListener("DOMContentLoaded", handler, false); + window.removeEventListener("load", handler, false); + /* run user callbacks */ + for (var i = 0; i < deferDOM_callbacks.length; ++i) deferDOM_callbacks[i](); + deferDOM_callbacks = null; //gc + }; + + // make callable (mutating, do not copy) + self.onDOMready = function deferDOM_initial(cb) { + /* if possible, skip all that */ + if (document.readyState === "complete") { + self.onDOMready = deferDOM_ready; + return deferDOM_ready(cb); + } + // onDOMready, after setup, before DOM is ready + var enqfn = function deferDOM_enqueue(cb) { + if (typeof cb === "function") deferDOM_callbacks.push(cb); + return false; + }; + /* subsequent calls will enqueue */ + self.onDOMready = enqfn; + /* set up handler */ + document.addEventListener("DOMContentLoaded", handler, false); + /* last resort: always works, but later than possible */ + window.addEventListener("load", handler, false); + /* except if DOM got ready in the meantime */ + if (document.readyState === "complete") { + /* undo all that attaching */ + handler(); + /* goto finish */ + self.onDOMready = deferDOM_ready; + return deferDOM_ready(cb); + } + /* just enqueue that */ + return enqfn(cb); + }; + } +} + +},{"./dygraph-tickers":"dygraphs/src/dygraph-tickers.js"}],"dygraphs/src/dygraph.js":[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _dygraphLayout = _interopRequireDefault(require("./dygraph-layout")); +var _dygraphCanvas = _interopRequireDefault(require("./dygraph-canvas")); +var _dygraphOptions = _interopRequireDefault(require("./dygraph-options")); +var _dygraphInteractionModel = _interopRequireDefault(require("./dygraph-interaction-model")); +var DygraphTickers = _interopRequireWildcard(require("./dygraph-tickers")); +var utils = _interopRequireWildcard(require("./dygraph-utils")); +var _dygraphDefaultAttrs = _interopRequireDefault(require("./dygraph-default-attrs")); +var _dygraphOptionsReference = _interopRequireDefault(require("./dygraph-options-reference")); +var _iframeTarp = _interopRequireDefault(require("./iframe-tarp")); +var _default2 = _interopRequireDefault(require("./datahandler/default")); +var _barsError = _interopRequireDefault(require("./datahandler/bars-error")); +var _barsCustom = _interopRequireDefault(require("./datahandler/bars-custom")); +var _defaultFractions = _interopRequireDefault(require("./datahandler/default-fractions")); +var _barsFractions = _interopRequireDefault(require("./datahandler/bars-fractions")); +var _bars = _interopRequireDefault(require("./datahandler/bars")); +var _annotations = _interopRequireDefault(require("./plugins/annotations")); +var _axes = _interopRequireDefault(require("./plugins/axes")); +var _chartLabels = _interopRequireDefault(require("./plugins/chart-labels")); +var _grid = _interopRequireDefault(require("./plugins/grid")); +var _legend = _interopRequireDefault(require("./plugins/legend")); +var _rangeSelector = _interopRequireDefault(require("./plugins/range-selector")); +var _dygraphGviz = _interopRequireDefault(require("./dygraph-gviz")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +"use strict"; + +/** + * @class Creates an interactive, zoomable chart. + * @name Dygraph + * + * @constructor + * @param {div | String} div A div or the id of a div into which to construct + * the chart. Must not have any padding. + * @param {String | Function} file A file containing CSV data or a function + * that returns this data. The most basic expected format for each line is + * "YYYY/MM/DD,val1,val2,...". For more information, see + * http://dygraphs.com/data.html. + * @param {Object} attrs Various other attributes, e.g. errorBars determines + * whether the input data contains error ranges. For a complete list of + * options, see http://dygraphs.com/options.html. + */ +var Dygraph = function Dygraph(div, data, opts) { + this.__init__(div, data, opts); +}; +Dygraph.NAME = "Dygraph"; +Dygraph.VERSION = "2.2.1"; + +// internal autoloader workaround +var _addrequire = {}; +Dygraph._require = function require(what) { + return what in _addrequire ? _addrequire[what] : Dygraph._require._b(what); +}; +Dygraph._require._b = null; // set by xfrmmodmap-dy.js +Dygraph._require.add = function add(what, towhat) { + _addrequire[what] = towhat; +}; + +// Various default values +Dygraph.DEFAULT_ROLL_PERIOD = 1; +Dygraph.DEFAULT_WIDTH = 480; +Dygraph.DEFAULT_HEIGHT = 320; + +// For max 60 Hz. animation: +Dygraph.ANIMATION_STEPS = 12; +Dygraph.ANIMATION_DURATION = 200; + +/** + * Standard plotters. These may be used by clients. + * Available plotters are: + * - Dygraph.Plotters.linePlotter: draws central lines (most common) + * - Dygraph.Plotters.errorPlotter: draws high/low bands + * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph) + * + * By default, the plotter is [fillPlotter, errorPlotter, linePlotter]. + * This causes all the lines to be drawn over all the fills/bands. + */ +Dygraph.Plotters = _dygraphCanvas["default"]._Plotters; + +// Used for initializing annotation CSS rules only once. +Dygraph.addedAnnotationCSS = false; + +/** + * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit + * and context <canvas> inside of it. See the constructor for details. + * on the parameters. + * @param {Element} div the Element to render the graph into. + * @param {string | Function} file Source data + * @param {Object} attrs Miscellaneous other options + * @private + */ +Dygraph.prototype.__init__ = function (div, file, attrs) { + this.is_initial_draw_ = true; + this.readyFns_ = []; + + // Support two-argument constructor + if (attrs === null || attrs === undefined) { + attrs = {}; + } + attrs = Dygraph.copyUserAttrs_(attrs); + if (typeof div == 'string') { + div = document.getElementById(div); + } + if (!div) { + throw new Error('Constructing dygraph with a non-existent div!'); + } + + // Copy the important bits into the object + // TODO(danvk): most of these should just stay in the attrs_ dictionary. + this.maindiv_ = div; + this.file_ = file; + this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD; + this.previousVerticalX_ = -1; + this.fractions_ = attrs.fractions || false; + this.dateWindow_ = attrs.dateWindow || null; + this.annotations_ = []; + + // Clear the div. This ensure that, if multiple dygraphs are passed the same + // div, then only one will be drawn. + div.innerHTML = ""; + var resolved = window.getComputedStyle(div, null); + if (resolved.paddingLeft !== "0px" || resolved.paddingRight !== "0px" || resolved.paddingTop !== "0px" || resolved.paddingBottom !== "0px") console.error('Main div contains padding; graph will misbehave'); + + // For historical reasons, the 'width' and 'height' options trump all CSS + // rules _except_ for an explicit 'width' or 'height' on the div. + // As an added convenience, if the div has zero height (like
    does + // without any styles), then we use a default height/width. + if (div.style.width === '' && attrs.width) { + div.style.width = attrs.width + "px"; + } + if (div.style.height === '' && attrs.height) { + div.style.height = attrs.height + "px"; + } + if (div.style.height === '' && div.clientHeight === 0) { + div.style.height = Dygraph.DEFAULT_HEIGHT + "px"; + if (div.style.width === '') { + div.style.width = Dygraph.DEFAULT_WIDTH + "px"; + } + } + // These will be zero if the dygraph's div is hidden. In that case, + // use the user-specified attributes if present. If not, use zero + // and assume the user will call resize to fix things later. + this.width_ = div.clientWidth || attrs.width || 0; + this.height_ = div.clientHeight || attrs.height || 0; + + // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_. + if (attrs.stackedGraph) { + attrs.fillGraph = true; + // TODO(nikhilk): Add any other stackedGraph checks here. + } + + // DEPRECATION WARNING: All option processing should be moved from + // attrs_ and user_attrs_ to options_, which holds all this information. + // + // Dygraphs has many options, some of which interact with one another. + // To keep track of everything, we maintain two sets of options: + // + // this.user_attrs_ only options explicitly set by the user. + // this.attrs_ defaults, options derived from user_attrs_, data. + // + // Options are then accessed this.attr_('attr'), which first looks at + // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent + // defaults without overriding behavior that the user specifically asks for. + this.user_attrs_ = {}; + utils.update(this.user_attrs_, attrs); + + // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified. + this.attrs_ = {}; + utils.updateDeep(this.attrs_, _dygraphDefaultAttrs["default"]); + this.boundaryIds_ = []; + this.setIndexByName_ = {}; + this.datasetIndex_ = []; + this.registeredEvents_ = []; + this.eventListeners_ = {}; + this.attributes_ = new _dygraphOptions["default"](this); + + // Create the containing DIV and other interactive elements + this.createInterface_(); + + // Activate plugins. + this.plugins_ = []; + var plugins = Dygraph.PLUGINS.concat(this.getOption('plugins')); + for (var i = 0; i < plugins.length; i++) { + // the plugins option may contain either plugin classes or instances. + // Plugin instances contain an activate method. + var Plugin = plugins[i]; // either a constructor or an instance. + var pluginInstance; + if (typeof Plugin.activate !== 'undefined') { + pluginInstance = Plugin; + } else { + pluginInstance = new Plugin(); + } + var pluginDict = { + plugin: pluginInstance, + events: {}, + options: {}, + pluginOptions: {} + }; + var handlers = pluginInstance.activate(this); + for (var eventName in handlers) { + if (!handlers.hasOwnProperty(eventName)) continue; + // TODO(danvk): validate eventName. + pluginDict.events[eventName] = handlers[eventName]; + } + this.plugins_.push(pluginDict); + } + + // At this point, plugins can no longer register event handlers. + // Construct a map from event -> ordered list of [callback, plugin]. + for (var i = 0; i < this.plugins_.length; i++) { + var plugin_dict = this.plugins_[i]; + for (var eventName in plugin_dict.events) { + if (!plugin_dict.events.hasOwnProperty(eventName)) continue; + var callback = plugin_dict.events[eventName]; + var pair = [plugin_dict.plugin, callback]; + if (!(eventName in this.eventListeners_)) { + this.eventListeners_[eventName] = [pair]; + } else { + this.eventListeners_[eventName].push(pair); + } + } + } + this.createDragInterface_(); + this.start_(); +}; + +/** + * Triggers a cascade of events to the various plugins which are interested in them. + * Returns true if the "default behavior" should be prevented, i.e. if one + * of the event listeners called event.preventDefault(). + * @private + */ +Dygraph.prototype.cascadeEvents_ = function (name, extra_props) { + if (!(name in this.eventListeners_)) return false; + + // QUESTION: can we use objects & prototypes to speed this up? + var e = { + dygraph: this, + cancelable: false, + defaultPrevented: false, + preventDefault: function preventDefault() { + if (!e.cancelable) throw "Cannot call preventDefault on non-cancelable event."; + e.defaultPrevented = true; + }, + propagationStopped: false, + stopPropagation: function stopPropagation() { + e.propagationStopped = true; + } + }; + utils.update(e, extra_props); + var callback_plugin_pairs = this.eventListeners_[name]; + if (callback_plugin_pairs) { + for (var i = callback_plugin_pairs.length - 1; i >= 0; i--) { + var plugin = callback_plugin_pairs[i][0]; + var callback = callback_plugin_pairs[i][1]; + callback.call(plugin, e); + if (e.propagationStopped) break; + } + } + return e.defaultPrevented; +}; + +/** + * Fetch a plugin instance of a particular class. Only for testing. + * @private + * @param {!Class} type The type of the plugin. + * @return {Object} Instance of the plugin, or null if there is none. + */ +Dygraph.prototype.getPluginInstance_ = function (type) { + for (var i = 0; i < this.plugins_.length; i++) { + var p = this.plugins_[i]; + if (p.plugin instanceof type) { + return p.plugin; + } + } + return null; +}; + +/** + * Returns the zoomed status of the chart for one or both axes. + * + * Axis is an optional parameter. Can be set to 'x' or 'y'. + * + * The zoomed status for an axis is set whenever a user zooms using the mouse + * or when the dateWindow or valueRange are updated. Double-clicking or calling + * resetZoom() resets the zoom status for the chart. + */ +Dygraph.prototype.isZoomed = function (axis) { + var isZoomedX = !!this.dateWindow_; + if (axis === 'x') return isZoomedX; + var isZoomedY = this.axes_.map(function (axis) { + return !!axis.valueRange; + }).indexOf(true) >= 0; + if (axis === null || axis === undefined) { + return isZoomedX || isZoomedY; + } + if (axis === 'y') return isZoomedY; + throw new Error("axis parameter is [".concat(axis, "] must be null, 'x' or 'y'.")); +}; + +/** + * Returns information about the Dygraph object, including its containing ID. + */ +Dygraph.prototype.toString = function () { + var maindiv = this.maindiv_; + var id = maindiv && maindiv.id ? maindiv.id : maindiv; + return "[Dygraph " + id + "]"; +}; + +/** + * @private + * Returns the value of an option. This may be set by the user (either in the + * constructor or by calling updateOptions) or by dygraphs, and may be set to a + * per-series value. + * @param {string} name The name of the option, e.g. 'rollPeriod'. + * @param {string} [seriesName] The name of the series to which the option + * will be applied. If no per-series value of this option is available, then + * the global value is returned. This is optional. + * @return {...} The value of the option. + */ +Dygraph.prototype.attr_ = function (name, seriesName) { + if (true) { + // For "production" code, this gets removed by uglifyjs. + if (typeof _dygraphOptionsReference["default"] === 'undefined') { + console.error('Must include options reference JS for testing'); + } else if (!_dygraphOptionsReference["default"].hasOwnProperty(name)) { + console.error('Dygraphs is using property ' + name + ', which has no ' + 'entry in the Dygraphs.OPTIONS_REFERENCE listing.'); + // Only log this error once. + _dygraphOptionsReference["default"][name] = true; + } + } + return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name); +}; + +/** + * Returns the current value for an option, as set in the constructor or via + * updateOptions. You may pass in an (optional) series name to get per-series + * values for the option. + * + * All values returned by this method should be considered immutable. If you + * modify them, there is no guarantee that the changes will be honored or that + * dygraphs will remain in a consistent state. If you want to modify an option, + * use updateOptions() instead. + * + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {*} The value of the option. + */ +Dygraph.prototype.getOption = function (name, opt_seriesName) { + return this.attr_(name, opt_seriesName); +}; + +/** + * Like getOption(), but specifically returns a number. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {number} The value of the option. + * @private + */ +Dygraph.prototype.getNumericOption = function (name, opt_seriesName) { + return (/** @type{number} */this.getOption(name, opt_seriesName) + ); +}; + +/** + * Like getOption(), but specifically returns a string. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {string} The value of the option. + * @private + */ +Dygraph.prototype.getStringOption = function (name, opt_seriesName) { + return (/** @type{string} */this.getOption(name, opt_seriesName) + ); +}; + +/** + * Like getOption(), but specifically returns a boolean. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {boolean} The value of the option. + * @private + */ +Dygraph.prototype.getBooleanOption = function (name, opt_seriesName) { + return (/** @type{boolean} */this.getOption(name, opt_seriesName) + ); +}; + +/** + * Like getOption(), but specifically returns a function. + * This is a convenience function for working with the Closure Compiler. + * @param {string} name The name of the option (e.g. 'strokeWidth') + * @param {string=} opt_seriesName Series name to get per-series values. + * @return {function(...)} The value of the option. + * @private + */ +Dygraph.prototype.getFunctionOption = function (name, opt_seriesName) { + return (/** @type{function(...)} */this.getOption(name, opt_seriesName) + ); +}; +Dygraph.prototype.getOptionForAxis = function (name, axis) { + return this.attributes_.getForAxis(name, axis); +}; + +/** + * @private + * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2') + * @return {...} A function mapping string -> option value + */ +Dygraph.prototype.optionsViewForAxis_ = function (axis) { + var self = this; + return function (opt) { + var axis_opts = self.user_attrs_.axes; + if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) { + return axis_opts[axis][opt]; + } + + // I don't like that this is in a second spot. + if (axis === 'x' && opt === 'logscale') { + // return the default value. + // TODO(konigsberg): pull the default from a global default. + return false; + } + + // user-specified attributes always trump defaults, even if they're less + // specific. + if (typeof self.user_attrs_[opt] != 'undefined') { + return self.user_attrs_[opt]; + } + axis_opts = self.attrs_.axes; + if (axis_opts && axis_opts[axis] && axis_opts[axis].hasOwnProperty(opt)) { + return axis_opts[axis][opt]; + } + // check old-style axis options + // TODO(danvk): add a deprecation warning if either of these match. + if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) { + return self.axes_[0][opt]; + } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) { + return self.axes_[1][opt]; + } + return self.attr_(opt); + }; +}; + +/** + * Returns the current rolling period, as set by the user or an option. + * @return {number} The number of points in the rolling window + */ +Dygraph.prototype.rollPeriod = function () { + return this.rollPeriod_; +}; + +/** + * Returns the currently-visible x-range. This can be affected by zooming, + * panning or a call to updateOptions. + * Returns a two-element array: [left, right]. + * If the Dygraph has dates on the x-axis, these will be millis since epoch. + */ +Dygraph.prototype.xAxisRange = function () { + return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes(); +}; + +/** + * Returns the lower- and upper-bound x-axis values of the data set. + */ +Dygraph.prototype.xAxisExtremes = function () { + var pad = this.getNumericOption('xRangePad') / this.plotter_.area.w; + if (this.numRows() === 0) { + return [0 - pad, 1 + pad]; + } + var left = this.rawData_[0][0]; + var right = this.rawData_[this.rawData_.length - 1][0]; + if (pad) { + // Must keep this in sync with dygraph-layout _evaluateLimits() + var range = right - left; + left -= range * pad; + right += range * pad; + } + return [left, right]; +}; + +/** + * Returns the lower- and upper-bound y-axis values for each axis. These are + * the ranges you'll get if you double-click to zoom out or call resetZoom(). + * The return value is an array of [low, high] tuples, one for each y-axis. + */ +Dygraph.prototype.yAxisExtremes = function () { + // TODO(danvk): this is pretty inefficient + var packed = this.gatherDatasets_(this.rolledSeries_, null); + var extremes = packed.extremes; + var saveAxes = this.axes_; + this.computeYAxisRanges_(extremes); + var newAxes = this.axes_; + this.axes_ = saveAxes; + return newAxes.map(function (axis) { + return axis.extremeRange; + }); +}; + +/** + * Returns the currently-visible y-range for an axis. This can be affected by + * zooming, panning or a call to updateOptions. Axis indices are zero-based. If + * called with no arguments, returns the range of the first axis. + * Returns a two-element array: [bottom, top]. + */ +Dygraph.prototype.yAxisRange = function (idx) { + if (typeof idx == "undefined") idx = 0; + if (idx < 0 || idx >= this.axes_.length) { + return null; + } + var axis = this.axes_[idx]; + return [axis.computedValueRange[0], axis.computedValueRange[1]]; +}; + +/** + * Returns the currently-visible y-ranges for each axis. This can be affected by + * zooming, panning, calls to updateOptions, etc. + * Returns an array of [bottom, top] pairs, one for each y-axis. + */ +Dygraph.prototype.yAxisRanges = function () { + var ret = []; + for (var i = 0; i < this.axes_.length; i++) { + ret.push(this.yAxisRange(i)); + } + return ret; +}; + +// TODO(danvk): use these functions throughout dygraphs. +/** + * Convert from data coordinates to canvas/div X/Y coordinates. + * If specified, do this conversion for the coordinate system of a particular + * axis. Uses the first axis by default. + * Returns a two-element array: [X, Y] + * + * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord + * instead of toDomCoords(null, y, axis). + */ +Dygraph.prototype.toDomCoords = function (x, y, axis) { + return [this.toDomXCoord(x), this.toDomYCoord(y, axis)]; +}; + +/** + * Convert from data x coordinates to canvas/div X coordinate. + * If specified, do this conversion for the coordinate system of a particular + * axis. + * Returns a single value or null if x is null. + */ +Dygraph.prototype.toDomXCoord = function (x) { + if (x === null) { + return null; + } + var area = this.plotter_.area; + var xRange = this.xAxisRange(); + return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w; +}; + +/** + * Convert from data x coordinates to canvas/div Y coordinate and optional + * axis. Uses the first axis by default. + * + * returns a single value or null if y is null. + */ +Dygraph.prototype.toDomYCoord = function (y, axis) { + var pct = this.toPercentYCoord(y, axis); + if (pct === null) { + return null; + } + var area = this.plotter_.area; + return area.y + pct * area.h; +}; + +/** + * Convert from canvas/div coords to data coordinates. + * If specified, do this conversion for the coordinate system of a particular + * axis. Uses the first axis by default. + * Returns a two-element array: [X, Y]. + * + * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord + * instead of toDataCoords(null, y, axis). + */ +Dygraph.prototype.toDataCoords = function (x, y, axis) { + return [this.toDataXCoord(x), this.toDataYCoord(y, axis)]; +}; + +/** + * Convert from canvas/div x coordinate to data coordinate. + * + * If x is null, this returns null. + */ +Dygraph.prototype.toDataXCoord = function (x) { + if (x === null) { + return null; + } + var area = this.plotter_.area; + var xRange = this.xAxisRange(); + if (!this.attributes_.getForAxis("logscale", 'x')) { + return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]); + } else { + var pct = (x - area.x) / area.w; + return utils.logRangeFraction(xRange[0], xRange[1], pct); + } +}; + +/** + * Convert from canvas/div y coord to value. + * + * If y is null, this returns null. + * if axis is null, this uses the first axis. + */ +Dygraph.prototype.toDataYCoord = function (y, axis) { + if (y === null) { + return null; + } + var area = this.plotter_.area; + var yRange = this.yAxisRange(axis); + if (typeof axis == "undefined") axis = 0; + if (!this.attributes_.getForAxis("logscale", axis)) { + return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]); + } else { + // Computing the inverse of toDomCoord. + var pct = (y - area.y) / area.h; + // Note reversed yRange, y1 is on top with pct==0. + return utils.logRangeFraction(yRange[1], yRange[0], pct); + } +}; + +/** + * Converts a y for an axis to a percentage from the top to the + * bottom of the drawing area. + * + * If the coordinate represents a value visible on the canvas, then + * the value will be between 0 and 1, where 0 is the top of the canvas. + * However, this method will return values outside the range, as + * values can fall outside the canvas. + * + * If y is null, this returns null. + * if axis is null, this uses the first axis. + * + * @param {number} y The data y-coordinate. + * @param {number} [axis] The axis number on which the data coordinate lives. + * @return {number} A fraction in [0, 1] where 0 = the top edge. + */ +Dygraph.prototype.toPercentYCoord = function (y, axis) { + if (y === null) { + return null; + } + if (typeof axis == "undefined") axis = 0; + var yRange = this.yAxisRange(axis); + var pct; + var logscale = this.attributes_.getForAxis("logscale", axis); + if (logscale) { + var logr0 = utils.log10(yRange[0]); + var logr1 = utils.log10(yRange[1]); + pct = (logr1 - utils.log10(y)) / (logr1 - logr0); + } else { + // yRange[1] - y is unit distance from the bottom. + // yRange[1] - yRange[0] is the scale of the range. + // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom. + pct = (yRange[1] - y) / (yRange[1] - yRange[0]); + } + return pct; +}; + +/** + * Converts an x value to a percentage from the left to the right of + * the drawing area. + * + * If the coordinate represents a value visible on the canvas, then + * the value will be between 0 and 1, where 0 is the left of the canvas. + * However, this method will return values outside the range, as + * values can fall outside the canvas. + * + * If x is null, this returns null. + * @param {number} x The data x-coordinate. + * @return {number} A fraction in [0, 1] where 0 = the left edge. + */ +Dygraph.prototype.toPercentXCoord = function (x) { + if (x === null) { + return null; + } + var xRange = this.xAxisRange(); + var pct; + var logscale = this.attributes_.getForAxis("logscale", 'x'); + if (logscale === true) { + // logscale can be null so we test for true explicitly. + var logr0 = utils.log10(xRange[0]); + var logr1 = utils.log10(xRange[1]); + pct = (utils.log10(x) - logr0) / (logr1 - logr0); + } else { + // x - xRange[0] is unit distance from the left. + // xRange[1] - xRange[0] is the scale of the range. + // The full expression below is the % from the left. + pct = (x - xRange[0]) / (xRange[1] - xRange[0]); + } + return pct; +}; + +/** + * Returns the number of columns (including the independent variable). + * @return {number} The number of columns. + */ +Dygraph.prototype.numColumns = function () { + if (!this.rawData_) return 0; + return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length; +}; + +/** + * Returns the number of rows (excluding any header/label row). + * @return {number} The number of rows, less any header. + */ +Dygraph.prototype.numRows = function () { + if (!this.rawData_) return 0; + return this.rawData_.length; +}; + +/** + * Returns the value in the given row and column. If the row and column exceed + * the bounds on the data, returns null. Also returns null if the value is + * missing. + * @param {number} row The row number of the data (0-based). Row 0 is the + * first row of data, not a header row. + * @param {number} col The column number of the data (0-based) + * @return {number} The value in the specified cell or null if the row/col + * were out of range. + */ +Dygraph.prototype.getValue = function (row, col) { + if (row < 0 || row >= this.rawData_.length) return null; + if (col < 0 || col >= this.rawData_[row].length) return null; + return this.rawData_[row][col]; +}; + +/** + * Generates interface elements for the Dygraph: a containing div, a div to + * display the current point, and a textbox to adjust the rolling average + * period. Also creates the Renderer/Layout elements. + * @private + */ +Dygraph.prototype.createInterface_ = function () { + // Create the all-enclosing graph div + var enclosing = this.maindiv_; + this.graphDiv = document.createElement("div"); + + // TODO(danvk): any other styles that are useful to set here? + this.graphDiv.style.textAlign = 'left'; // This is a CSS "reset" + this.graphDiv.style.position = 'relative'; + enclosing.appendChild(this.graphDiv); + + // Create the canvas for interactive parts of the chart. + this.canvas_ = utils.createCanvas(); + this.canvas_.style.position = "absolute"; + this.canvas_.style.top = 0; + this.canvas_.style.left = 0; + + // ... and for static parts of the chart. + this.hidden_ = this.createPlotKitCanvas_(this.canvas_); + this.canvas_ctx_ = utils.getContext(this.canvas_); + this.hidden_ctx_ = utils.getContext(this.hidden_); + this.resizeElements_(); + + // The interactive parts of the graph are drawn on top of the chart. + this.graphDiv.appendChild(this.hidden_); + this.graphDiv.appendChild(this.canvas_); + this.mouseEventElement_ = this.createMouseEventElement_(); + + // Create the grapher + this.layout_ = new _dygraphLayout["default"](this); + var dygraph = this; + this.mouseMoveHandler_ = function (e) { + dygraph.mouseMove_(e); + }; + this.mouseOutHandler_ = function (e) { + // The mouse has left the chart if: + // 1. e.target is inside the chart + // 2. e.relatedTarget is outside the chart + var target = e.target || e.fromElement; + var relatedTarget = e.relatedTarget || e.toElement; + if (utils.isNodeContainedBy(target, dygraph.graphDiv) && !utils.isNodeContainedBy(relatedTarget, dygraph.graphDiv)) { + dygraph.mouseOut_(e); + } + }; + this.addAndTrackEvent(window, 'mouseout', this.mouseOutHandler_); + this.addAndTrackEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_); + + // Don't recreate and register the resize handler on subsequent calls. + // This happens when the graph is resized. + if (!this.resizeHandler_) { + this.resizeHandler_ = function (e) { + dygraph.resize(); + }; + + // Update when the window is resized. + // TODO(danvk): drop frames depending on complexity of the chart. + this.addAndTrackEvent(window, 'resize', this.resizeHandler_); + this.resizeObserver_ = null; + var resizeMode = this.getStringOption('resizable'); + if (typeof ResizeObserver === 'undefined' && resizeMode !== "no") { + console.error('ResizeObserver unavailable; ignoring resizable property'); + resizeMode = "no"; + } + if (resizeMode === "horizontal" || resizeMode === "vertical" || resizeMode === "both") { + enclosing.style.resize = resizeMode; + } else if (resizeMode !== "passive") { + resizeMode = "no"; + } + if (resizeMode !== "no") { + var maindivOverflow = window.getComputedStyle(enclosing).overflow; + if (window.getComputedStyle(enclosing).overflow === 'visible') enclosing.style.overflow = 'hidden'; + this.resizeObserver_ = new ResizeObserver(this.resizeHandler_); + this.resizeObserver_.observe(enclosing); + } + } +}; +Dygraph.prototype.resizeElements_ = function () { + this.graphDiv.style.width = this.width_ + "px"; + this.graphDiv.style.height = this.height_ + "px"; + var pixelRatioOption = this.getNumericOption('pixelRatio'); + var canvasScale = pixelRatioOption || utils.getContextPixelRatio(this.canvas_ctx_); + this.canvas_.width = this.width_ * canvasScale; + this.canvas_.height = this.height_ * canvasScale; + this.canvas_.style.width = this.width_ + "px"; // for IE + this.canvas_.style.height = this.height_ + "px"; // for IE + if (canvasScale !== 1) { + this.canvas_ctx_.scale(canvasScale, canvasScale); + } + var hiddenScale = pixelRatioOption || utils.getContextPixelRatio(this.hidden_ctx_); + this.hidden_.width = this.width_ * hiddenScale; + this.hidden_.height = this.height_ * hiddenScale; + this.hidden_.style.width = this.width_ + "px"; // for IE + this.hidden_.style.height = this.height_ + "px"; // for IE + if (hiddenScale !== 1) { + this.hidden_ctx_.scale(hiddenScale, hiddenScale); + } +}; + +/** + * Detach DOM elements in the dygraph and null out all data references. + * Calling this when you're done with a dygraph can dramatically reduce memory + * usage. See, e.g., the tests/perf.html example. + */ +Dygraph.prototype.destroy = function () { + this.canvas_ctx_.restore(); + this.hidden_ctx_.restore(); + + // Destroy any plugins, in the reverse order that they were registered. + for (var i = this.plugins_.length - 1; i >= 0; i--) { + var p = this.plugins_.pop(); + if (p.plugin.destroy) p.plugin.destroy(); + } + var removeRecursive = function removeRecursive(node) { + while (node.hasChildNodes()) { + removeRecursive(node.firstChild); + node.removeChild(node.firstChild); + } + }; + this.removeTrackedEvents_(); + + // remove mouse event handlers (This may not be necessary anymore) + utils.removeEvent(window, 'mouseout', this.mouseOutHandler_); + utils.removeEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_); + + // dispose of resizing handlers + if (this.resizeObserver_) { + this.resizeObserver_.disconnect(); + this.resizeObserver_ = null; + } + utils.removeEvent(window, 'resize', this.resizeHandler_); + this.resizeHandler_ = null; + removeRecursive(this.maindiv_); + var nullOut = function nullOut(obj) { + for (var n in obj) { + if (typeof obj[n] === 'object') { + obj[n] = null; + } + } + }; + // These may not all be necessary, but it can't hurt... + nullOut(this.layout_); + nullOut(this.plotter_); + nullOut(this); +}; + +/** + * Creates the canvas on which the chart will be drawn. Only the Renderer ever + * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots + * or the zoom rectangles) is done on this.canvas_. + * @param {Object} canvas The Dygraph canvas over which to overlay the plot + * @return {Object} The newly-created canvas + * @private + */ +Dygraph.prototype.createPlotKitCanvas_ = function (canvas) { + var h = utils.createCanvas(); + h.style.position = "absolute"; + // TODO(danvk): h should be offset from canvas. canvas needs to include + // some extra area to make it easier to zoom in on the far left and far + // right. h needs to be precisely the plot area, so that clipping occurs. + h.style.top = canvas.style.top; + h.style.left = canvas.style.left; + h.width = this.width_; + h.height = this.height_; + h.style.width = this.width_ + "px"; // for IE + h.style.height = this.height_ + "px"; // for IE + return h; +}; + +/** + * Creates an overlay element used to handle mouse events. + * @return {Object} The mouse event element. + * @private + */ +Dygraph.prototype.createMouseEventElement_ = function () { + return this.canvas_; +}; + +/** + * Generate a set of distinct colors for the data series. This is done with a + * color wheel. Saturation/Value are customizable, and the hue is + * equally-spaced around the color wheel. If a custom set of colors is + * specified, that is used instead. + * @private + */ +Dygraph.prototype.setColors_ = function () { + var labels = this.getLabels(); + var num = labels.length - 1; + this.colors_ = []; + this.colorsMap_ = {}; + + // These are used for when no custom colors are specified. + var sat = this.getNumericOption('colorSaturation') || 1.0; + var val = this.getNumericOption('colorValue') || 0.5; + var half = Math.ceil(num / 2); + var colors = this.getOption('colors'); + var visibility = this.visibility(); + for (var i = 0; i < num; i++) { + if (!visibility[i]) { + continue; + } + var label = labels[i + 1]; + var colorStr = this.attributes_.getForSeries('color', label); + if (!colorStr) { + if (colors) { + colorStr = colors[i % colors.length]; + } else { + // alternate colors for high contrast. + var idx = i % 2 ? half + (i + 1) / 2 : Math.ceil((i + 1) / 2); + var hue = 1.0 * idx / (1 + num); + colorStr = utils.hsvToRGB(hue, sat, val); + } + } + this.colors_.push(colorStr); + this.colorsMap_[label] = colorStr; + } +}; + +/** + * Return the list of colors. This is either the list of colors passed in the + * attributes or the autogenerated list of rgb(r,g,b) strings. + * This does not return colors for invisible series. + * @return {Array.} The list of colors. + */ +Dygraph.prototype.getColors = function () { + return this.colors_; +}; + +/** + * Returns a few attributes of a series, i.e. its color, its visibility, which + * axis it's assigned to, and its column in the original data. + * Returns null if the series does not exist. + * Otherwise, returns an object with column, visibility, color and axis properties. + * The "axis" property will be set to 1 for y1 and 2 for y2. + * The "column" property can be fed back into getValue(row, column) to get + * values for this series. + */ +Dygraph.prototype.getPropertiesForSeries = function (series_name) { + var idx = -1; + var labels = this.getLabels(); + for (var i = 1; i < labels.length; i++) { + if (labels[i] == series_name) { + idx = i; + break; + } + } + if (idx == -1) return null; + return { + name: series_name, + column: idx, + visible: this.visibility()[idx - 1], + color: this.colorsMap_[series_name], + axis: 1 + this.attributes_.axisForSeries(series_name) + }; +}; + +/** + * Create the text box to adjust the averaging period + * @private + */ +Dygraph.prototype.createRollInterface_ = function () { + // Create a roller if one doesn't exist already. + var roller = this.roller_; + if (!roller) { + this.roller_ = roller = document.createElement("input"); + roller.type = "text"; + roller.style.display = "none"; + roller.className = 'dygraph-roller'; + this.graphDiv.appendChild(roller); + } + var display = this.getBooleanOption('showRoller') ? 'block' : 'none'; + var area = this.getArea(); + var textAttr = { + "top": area.y + area.h - 25 + "px", + "left": area.x + 1 + "px", + "display": display + }; + roller.size = "2"; + roller.value = this.rollPeriod_; + utils.update(roller.style, textAttr); + var that = this; + roller.onchange = function onchange() { + return that.adjustRoll(roller.value); + }; +}; + +/** + * Set up all the mouse handlers needed to capture dragging behavior for zoom + * events. + * @private + */ +Dygraph.prototype.createDragInterface_ = function () { + var context = { + // Tracks whether the mouse is down right now + isZooming: false, + isPanning: false, + // is this drag part of a pan? + is2DPan: false, + // if so, is that pan 1- or 2-dimensional? + dragStartX: null, + // pixel coordinates + dragStartY: null, + // pixel coordinates + dragEndX: null, + // pixel coordinates + dragEndY: null, + // pixel coordinates + dragDirection: null, + prevEndX: null, + // pixel coordinates + prevEndY: null, + // pixel coordinates + prevDragDirection: null, + cancelNextDblclick: false, + // see comment in dygraph-interaction-model.js + + // The value on the left side of the graph when a pan operation starts. + initialLeftmostDate: null, + // The number of units each pixel spans. (This won't be valid for log + // scales) + xUnitsPerPixel: null, + // TODO(danvk): update this comment + // The range in second/value units that the viewport encompasses during a + // panning operation. + dateRange: null, + // Top-left corner of the canvas, in DOM coords + // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY. + px: 0, + py: 0, + // Values for use with panEdgeFraction, which limit how far outside the + // graph's data boundaries it can be panned. + boundedDates: null, + // [minDate, maxDate] + boundedValues: null, + // [[minValue, maxValue] ...] + + // We cover iframes during mouse interactions. See comments in + // dygraph-utils.js for more info on why this is a good idea. + tarp: new _iframeTarp["default"](), + // contextB is the same thing as this context object but renamed. + initializeMouseDown: function initializeMouseDown(event, g, contextB) { + // prevents mouse drags from selecting page text. + if (event.preventDefault) { + event.preventDefault(); // Firefox, Chrome, etc. + } else { + event.returnValue = false; // IE + event.cancelBubble = true; + } + var canvasPos = utils.findPos(g.canvas_); + contextB.px = canvasPos.x; + contextB.py = canvasPos.y; + contextB.dragStartX = utils.dragGetX_(event, contextB); + contextB.dragStartY = utils.dragGetY_(event, contextB); + contextB.cancelNextDblclick = false; + contextB.tarp.cover(); + }, + destroy: function destroy() { + var context = this; + if (context.isZooming || context.isPanning) { + context.isZooming = false; + context.dragStartX = null; + context.dragStartY = null; + } + if (context.isPanning) { + context.isPanning = false; + context.draggingDate = null; + context.dateRange = null; + for (var i = 0; i < self.axes_.length; i++) { + delete self.axes_[i].draggingValue; + delete self.axes_[i].dragValueRange; + } + } + context.tarp.uncover(); + } + }; + var interactionModel = this.getOption("interactionModel"); + + // Self is the graph. + var self = this; + + // Function that binds the graph and context to the handler. + var bindHandler = function bindHandler(handler) { + return function (event) { + handler(event, self, context); + }; + }; + for (var eventName in interactionModel) { + if (!interactionModel.hasOwnProperty(eventName)) continue; + this.addAndTrackEvent(this.mouseEventElement_, eventName, bindHandler(interactionModel[eventName])); + } + + // If the user releases the mouse button during a drag, but not over the + // canvas, then it doesn't count as a zooming action. + if (!interactionModel.willDestroyContextMyself) { + var mouseUpHandler = function mouseUpHandler(event) { + context.destroy(); + }; + this.addAndTrackEvent(document, 'mouseup', mouseUpHandler); + } +}; + +/** + * Draw a gray zoom rectangle over the desired area of the canvas. Also clears + * up any previous zoom rectangles that were drawn. This could be optimized to + * avoid extra redrawing, but it's tricky to avoid interactions with the status + * dots. + * + * @param {number} direction the direction of the zoom rectangle. Acceptable + * values are utils.HORIZONTAL and utils.VERTICAL. + * @param {number} startX The X position where the drag started, in canvas + * coordinates. + * @param {number} endX The current X position of the drag, in canvas coords. + * @param {number} startY The Y position where the drag started, in canvas + * coordinates. + * @param {number} endY The current Y position of the drag, in canvas coords. + * @param {number} prevDirection the value of direction on the previous call to + * this function. Used to avoid excess redrawing + * @param {number} prevEndX The value of endX on the previous call to this + * function. Used to avoid excess redrawing + * @param {number} prevEndY The value of endY on the previous call to this + * function. Used to avoid excess redrawing + * @private + */ +Dygraph.prototype.drawZoomRect_ = function (direction, startX, endX, startY, endY, prevDirection, prevEndX, prevEndY) { + var ctx = this.canvas_ctx_; + + // Clean up from the previous rect if necessary + if (prevDirection == utils.HORIZONTAL) { + ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y, Math.abs(startX - prevEndX), this.layout_.getPlotArea().h); + } else if (prevDirection == utils.VERTICAL) { + ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY), this.layout_.getPlotArea().w, Math.abs(startY - prevEndY)); + } + + // Draw a light-grey rectangle to show the new viewing area + if (direction == utils.HORIZONTAL) { + if (endX && startX) { + ctx.fillStyle = "rgba(128,128,128,0.33)"; + ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y, Math.abs(endX - startX), this.layout_.getPlotArea().h); + } + } else if (direction == utils.VERTICAL) { + if (endY && startY) { + ctx.fillStyle = "rgba(128,128,128,0.33)"; + ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY), this.layout_.getPlotArea().w, Math.abs(endY - startY)); + } + } +}; + +/** + * Clear the zoom rectangle (and perform no zoom). + * @private + */ +Dygraph.prototype.clearZoomRect_ = function () { + this.currentZoomRectArgs_ = null; + this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_); +}; + +/** + * Zoom to something containing [lowX, highX]. These are pixel coordinates in + * the canvas. The exact zoom window may be slightly larger if there are no data + * points near lowX or highX. Don't confuse this function with doZoomXDates, + * which accepts dates that match the raw data. This function redraws the graph. + * + * @param {number} lowX The leftmost pixel value that should be visible. + * @param {number} highX The rightmost pixel value that should be visible. + * @private + */ +Dygraph.prototype.doZoomX_ = function (lowX, highX) { + this.currentZoomRectArgs_ = null; + // Find the earliest and latest dates contained in this canvasx range. + // Convert the call to date ranges of the raw data. + var minDate = this.toDataXCoord(lowX); + var maxDate = this.toDataXCoord(highX); + this.doZoomXDates_(minDate, maxDate); +}; + +/** + * Zoom to something containing [minDate, maxDate] values. Don't confuse this + * method with doZoomX which accepts pixel coordinates. This function redraws + * the graph. + * + * @param {number} minDate The minimum date that should be visible. + * @param {number} maxDate The maximum date that should be visible. + * @private + */ +Dygraph.prototype.doZoomXDates_ = function (minDate, maxDate) { + // TODO(danvk): when xAxisRange is null (i.e. "fit to data", the animation + // can produce strange effects. Rather than the x-axis transitioning slowly + // between values, it can jerk around.) + var old_window = this.xAxisRange(); + var new_window = [minDate, maxDate]; + var zoomCallback = this.getFunctionOption('zoomCallback'); + var that = this; + this.doAnimatedZoom(old_window, new_window, null, null, function animatedZoomCallback() { + if (zoomCallback) { + zoomCallback.call(that, minDate, maxDate, that.yAxisRanges()); + } + }); +}; + +/** + * Zoom to something containing [lowY, highY]. These are pixel coordinates in + * the canvas. This function redraws the graph. + * + * @param {number} lowY The topmost pixel value that should be visible. + * @param {number} highY The lowest pixel value that should be visible. + * @private + */ +Dygraph.prototype.doZoomY_ = function (lowY, highY) { + this.currentZoomRectArgs_ = null; + // Find the highest and lowest values in pixel range for each axis. + // Note that lowY (in pixels) corresponds to the max Value (in data coords). + // This is because pixels increase as you go down on the screen, whereas data + // coordinates increase as you go up the screen. + var oldValueRanges = this.yAxisRanges(); + var newValueRanges = []; + for (var i = 0; i < this.axes_.length; i++) { + var hi = this.toDataYCoord(lowY, i); + var low = this.toDataYCoord(highY, i); + newValueRanges.push([low, hi]); + } + var zoomCallback = this.getFunctionOption('zoomCallback'); + var that = this; + this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function animatedZoomCallback() { + if (zoomCallback) { + var _that$xAxisRange = that.xAxisRange(), + _that$xAxisRange2 = _slicedToArray(_that$xAxisRange, 2), + minX = _that$xAxisRange2[0], + maxX = _that$xAxisRange2[1]; + zoomCallback.call(that, minX, maxX, that.yAxisRanges()); + } + }); +}; + +/** + * Transition function to use in animations. Returns values between 0.0 + * (totally old values) and 1.0 (totally new values) for each frame. + * @private + */ +Dygraph.zoomAnimationFunction = function (frame, numFrames) { + var k = 1.5; + return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames)); +}; + +/** + * Reset the zoom to the original view coordinates. This is the same as + * double-clicking on the graph. + */ +Dygraph.prototype.resetZoom = function () { + var dirtyX = this.isZoomed('x'); + var dirtyY = this.isZoomed('y'); + var dirty = dirtyX || dirtyY; + + // Clear any selection, since it's likely to be drawn in the wrong place. + this.clearSelection(); + if (!dirty) return; + + // Calculate extremes to avoid lack of padding on reset. + var _this$xAxisExtremes = this.xAxisExtremes(), + _this$xAxisExtremes2 = _slicedToArray(_this$xAxisExtremes, 2), + minDate = _this$xAxisExtremes2[0], + maxDate = _this$xAxisExtremes2[1]; + var animatedZooms = this.getBooleanOption('animatedZooms'); + var zoomCallback = this.getFunctionOption('zoomCallback'); + + // TODO(danvk): merge this block w/ the code below. + // TODO(danvk): factor out a generic, public zoomTo method. + if (!animatedZooms) { + this.dateWindow_ = null; + this.axes_.forEach(function (axis) { + if (axis.valueRange) delete axis.valueRange; + }); + this.drawGraph_(); + if (zoomCallback) { + zoomCallback.call(this, minDate, maxDate, this.yAxisRanges()); + } + return; + } + var oldWindow = null, + newWindow = null, + oldValueRanges = null, + newValueRanges = null; + if (dirtyX) { + oldWindow = this.xAxisRange(); + newWindow = [minDate, maxDate]; + } + if (dirtyY) { + oldValueRanges = this.yAxisRanges(); + newValueRanges = this.yAxisExtremes(); + } + var that = this; + this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges, function animatedZoomCallback() { + that.dateWindow_ = null; + that.axes_.forEach(function (axis) { + if (axis.valueRange) delete axis.valueRange; + }); + if (zoomCallback) { + zoomCallback.call(that, minDate, maxDate, that.yAxisRanges()); + } + }); +}; + +/** + * Combined animation logic for all zoom functions. + * either the x parameters or y parameters may be null. + * @private + */ +Dygraph.prototype.doAnimatedZoom = function (oldXRange, newXRange, oldYRanges, newYRanges, callback) { + var steps = this.getBooleanOption("animatedZooms") ? Dygraph.ANIMATION_STEPS : 1; + var windows = []; + var valueRanges = []; + var step, frac; + if (oldXRange !== null && newXRange !== null) { + for (step = 1; step <= steps; step++) { + frac = Dygraph.zoomAnimationFunction(step, steps); + windows[step - 1] = [oldXRange[0] * (1 - frac) + frac * newXRange[0], oldXRange[1] * (1 - frac) + frac * newXRange[1]]; + } + } + if (oldYRanges !== null && newYRanges !== null) { + for (step = 1; step <= steps; step++) { + frac = Dygraph.zoomAnimationFunction(step, steps); + var thisRange = []; + for (var j = 0; j < this.axes_.length; j++) { + thisRange.push([oldYRanges[j][0] * (1 - frac) + frac * newYRanges[j][0], oldYRanges[j][1] * (1 - frac) + frac * newYRanges[j][1]]); + } + valueRanges[step - 1] = thisRange; + } + } + var that = this; + utils.repeatAndCleanup(function (step) { + if (valueRanges.length) { + for (var i = 0; i < that.axes_.length; i++) { + var w = valueRanges[step][i]; + that.axes_[i].valueRange = [w[0], w[1]]; + } + } + if (windows.length) { + that.dateWindow_ = windows[step]; + } + that.drawGraph_(); + }, steps, Dygraph.ANIMATION_DURATION / steps, callback); +}; + +/** + * Get the current graph's area object. + * + * Returns: {x, y, w, h} + */ +Dygraph.prototype.getArea = function () { + return this.plotter_.area; +}; + +/** + * Convert a mouse event to DOM coordinates relative to the graph origin. + * + * Returns a two-element array: [X, Y]. + */ +Dygraph.prototype.eventToDomCoords = function (event) { + if (event.offsetX && event.offsetY) { + return [event.offsetX, event.offsetY]; + } else { + var eventElementPos = utils.findPos(this.mouseEventElement_); + var canvasx = utils.pageX(event) - eventElementPos.x; + var canvasy = utils.pageY(event) - eventElementPos.y; + return [canvasx, canvasy]; + } +}; + +/** + * Given a canvas X coordinate, find the closest row. + * @param {number} domX graph-relative DOM X coordinate + * Returns {number} row number. + * @private + */ +Dygraph.prototype.findClosestRow = function (domX) { + var minDistX = Infinity; + var closestRow = -1; + var sets = this.layout_.points; + for (var i = 0; i < sets.length; i++) { + var points = sets[i]; + var len = points.length; + for (var j = 0; j < len; j++) { + var point = points[j]; + if (!utils.isValidPoint(point, true)) continue; + var dist = Math.abs(point.canvasx - domX); + if (dist < minDistX) { + minDistX = dist; + closestRow = point.idx; + } + } + } + return closestRow; +}; + +/** + * Given canvas X,Y coordinates, find the closest point. + * + * This finds the individual data point across all visible series + * that's closest to the supplied DOM coordinates using the standard + * Euclidean X,Y distance. + * + * @param {number} domX graph-relative DOM X coordinate + * @param {number} domY graph-relative DOM Y coordinate + * Returns: {row, seriesName, point} + * @private + */ +Dygraph.prototype.findClosestPoint = function (domX, domY) { + var minDist = Infinity; + var dist, dx, dy, point, closestPoint, closestSeries, closestRow; + for (var setIdx = this.layout_.points.length - 1; setIdx >= 0; --setIdx) { + var points = this.layout_.points[setIdx]; + for (var i = 0; i < points.length; ++i) { + point = points[i]; + if (!utils.isValidPoint(point)) continue; + dx = point.canvasx - domX; + dy = point.canvasy - domY; + dist = dx * dx + dy * dy; + if (dist < minDist) { + minDist = dist; + closestPoint = point; + closestSeries = setIdx; + closestRow = point.idx; + } + } + } + var name = this.layout_.setNames[closestSeries]; + return { + row: closestRow, + seriesName: name, + point: closestPoint + }; +}; + +/** + * Given canvas X,Y coordinates, find the touched area in a stacked graph. + * + * This first finds the X data point closest to the supplied DOM X coordinate, + * then finds the series which puts the Y coordinate on top of its filled area, + * using linear interpolation between adjacent point pairs. + * + * @param {number} domX graph-relative DOM X coordinate + * @param {number} domY graph-relative DOM Y coordinate + * Returns: {row, seriesName, point} + * @private + */ +Dygraph.prototype.findStackedPoint = function (domX, domY) { + var row = this.findClosestRow(domX); + var closestPoint, closestSeries; + for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) { + var boundary = this.getLeftBoundary_(setIdx); + var rowIdx = row - boundary; + var points = this.layout_.points[setIdx]; + if (rowIdx >= points.length) continue; + var p1 = points[rowIdx]; + if (!utils.isValidPoint(p1)) continue; + var py = p1.canvasy; + if (domX > p1.canvasx && rowIdx + 1 < points.length) { + // interpolate series Y value using next point + var p2 = points[rowIdx + 1]; + if (utils.isValidPoint(p2)) { + var dx = p2.canvasx - p1.canvasx; + if (dx > 0) { + var r = (domX - p1.canvasx) / dx; + py += r * (p2.canvasy - p1.canvasy); + } + } + } else if (domX < p1.canvasx && rowIdx > 0) { + // interpolate series Y value using previous point + var p0 = points[rowIdx - 1]; + if (utils.isValidPoint(p0)) { + var dx = p1.canvasx - p0.canvasx; + if (dx > 0) { + var r = (p1.canvasx - domX) / dx; + py += r * (p0.canvasy - p1.canvasy); + } + } + } + // Stop if the point (domX, py) is above this series' upper edge + if (setIdx === 0 || py < domY) { + closestPoint = p1; + closestSeries = setIdx; + } + } + var name = this.layout_.setNames[closestSeries]; + return { + row: row, + seriesName: name, + point: closestPoint + }; +}; + +/** + * When the mouse moves in the canvas, display information about a nearby data + * point and draw dots over those points in the data series. This function + * takes care of cleanup of previously-drawn dots. + * @param {Object} event The mousemove event from the browser. + * @private + */ +Dygraph.prototype.mouseMove_ = function (event) { + // This prevents JS errors when mousing over the canvas before data loads. + var points = this.layout_.points; + if (points === undefined || points === null) return; + var canvasCoords = this.eventToDomCoords(event); + var canvasx = canvasCoords[0]; + var canvasy = canvasCoords[1]; + var highlightSeriesOpts = this.getOption("highlightSeriesOpts"); + var selectionChanged = false; + if (highlightSeriesOpts && !this.isSeriesLocked()) { + var closest; + if (this.getBooleanOption("stackedGraph")) { + closest = this.findStackedPoint(canvasx, canvasy); + } else { + closest = this.findClosestPoint(canvasx, canvasy); + } + selectionChanged = this.setSelection(closest.row, closest.seriesName); + } else { + var idx = this.findClosestRow(canvasx); + selectionChanged = this.setSelection(idx); + } + var callback = this.getFunctionOption("highlightCallback"); + if (callback && selectionChanged) { + callback.call(this, event, this.lastx_, this.selPoints_, this.lastRow_, this.highlightSet_); + } +}; + +/** + * Fetch left offset from the specified set index or if not passed, the + * first defined boundaryIds record (see bug #236). + * @private + */ +Dygraph.prototype.getLeftBoundary_ = function (setIdx) { + if (this.boundaryIds_[setIdx]) { + return this.boundaryIds_[setIdx][0]; + } else { + for (var i = 0; i < this.boundaryIds_.length; i++) { + if (this.boundaryIds_[i] !== undefined) { + return this.boundaryIds_[i][0]; + } + } + return 0; + } +}; +Dygraph.prototype.animateSelection_ = function (direction) { + var totalSteps = 10; + var millis = 30; + if (this.fadeLevel === undefined) this.fadeLevel = 0; + if (this.animateId === undefined) this.animateId = 0; + var start = this.fadeLevel; + var steps = direction < 0 ? start : totalSteps - start; + if (steps <= 0) { + if (this.fadeLevel) { + this.updateSelection_(1.0); + } + return; + } + var thisId = ++this.animateId; + var that = this; + var cleanupIfClearing = function cleanupIfClearing() { + // if we haven't reached fadeLevel 0 in the max frame time, + // ensure that the clear happens and just go to 0 + if (that.fadeLevel !== 0 && direction < 0) { + that.fadeLevel = 0; + that.clearSelection(); + } + }; + utils.repeatAndCleanup(function (n) { + // ignore simultaneous animations + if (that.animateId != thisId) return; + that.fadeLevel += direction; + if (that.fadeLevel === 0) { + that.clearSelection(); + } else { + that.updateSelection_(that.fadeLevel / totalSteps); + } + }, steps, millis, cleanupIfClearing); +}; + +/** + * Draw dots over the selectied points in the data series. This function + * takes care of cleanup of previously-drawn dots. + * @private + */ +Dygraph.prototype.updateSelection_ = function (opt_animFraction) { + /*var defaultPrevented = */ + this.cascadeEvents_('select', { + selectedRow: this.lastRow_ === -1 ? undefined : this.lastRow_, + selectedX: this.lastx_ === null ? undefined : this.lastx_, + selectedPoints: this.selPoints_ + }); + // TODO(danvk): use defaultPrevented here? + + // Clear the previously drawn vertical, if there is one + var i; + var ctx = this.canvas_ctx_; + if (this.getOption('highlightSeriesOpts')) { + ctx.clearRect(0, 0, this.width_, this.height_); + var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha'); + var backgroundColor = utils.toRGB_(this.getOption('highlightSeriesBackgroundColor')); + if (alpha) { + // Activating background fade includes an animation effect for a gradual + // fade. TODO(klausw): make this independently configurable if it causes + // issues? Use a shared preference to control animations? + var animateBackgroundFade = this.getBooleanOption('animateBackgroundFade'); + if (animateBackgroundFade) { + if (opt_animFraction === undefined) { + // start a new animation + this.animateSelection_(1); + return; + } + alpha *= opt_animFraction; + } + ctx.fillStyle = 'rgba(' + backgroundColor.r + ',' + backgroundColor.g + ',' + backgroundColor.b + ',' + alpha + ')'; + ctx.fillRect(0, 0, this.width_, this.height_); + } + + // Redraw only the highlighted series in the interactive canvas (not the + // static plot canvas, which is where series are usually drawn). + this.plotter_._renderLineChart(this.highlightSet_, ctx); + } else if (this.previousVerticalX_ >= 0) { + // Determine the maximum highlight circle size. + var maxCircleSize = 0; + var labels = this.attr_('labels'); + for (i = 1; i < labels.length; i++) { + var r = this.getNumericOption('highlightCircleSize', labels[i]); + if (r > maxCircleSize) maxCircleSize = r; + } + var px = this.previousVerticalX_; + ctx.clearRect(px - maxCircleSize - 1, 0, 2 * maxCircleSize + 2, this.height_); + } + if (this.selPoints_.length > 0) { + // Draw colored circles over the center of each selected point + var canvasx = this.selPoints_[0].canvasx; + ctx.save(); + for (i = 0; i < this.selPoints_.length; i++) { + var pt = this.selPoints_[i]; + if (isNaN(pt.canvasy)) continue; + var circleSize = this.getNumericOption('highlightCircleSize', pt.name); + var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name); + var color = this.plotter_.colors[pt.name]; + if (!callback) { + callback = utils.Circles.DEFAULT; + } + ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name); + ctx.strokeStyle = color; + ctx.fillStyle = color; + callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy, color, circleSize, pt.idx); + } + ctx.restore(); + this.previousVerticalX_ = canvasx; + } +}; + +/** + * Manually set the selected points and display information about them in the + * legend. The selection can be cleared using clearSelection() and queried + * using getSelection(). + * + * To set a selected series but not a selected point, call setSelection with + * row=false and the selected series name. + * + * @param {number} row Row number that should be highlighted (i.e. appear with + * hover dots on the chart). + * @param {seriesName} optional series name to highlight that series with the + * the highlightSeriesOpts setting. + * @param {locked} optional If true, keep seriesName selected when mousing + * over the graph, disabling closest-series highlighting. Call clearSelection() + * to unlock it. + * @param {trigger_highlight_callback} optional If true, trigger any + * user-defined highlightCallback if highlightCallback has been set. + */ +Dygraph.prototype.setSelection = function setSelection(row, opt_seriesName, opt_locked, opt_trigger_highlight_callback) { + // Extract the points we've selected + this.selPoints_ = []; + var changed = false; + if (row !== false && row >= 0) { + if (row != this.lastRow_) changed = true; + this.lastRow_ = row; + for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) { + var points = this.layout_.points[setIdx]; + // Check if the point at the appropriate index is the point we're looking + // for. If it is, just use it, otherwise search the array for a point + // in the proper place. + var setRow = row - this.getLeftBoundary_(setIdx); + if (setRow >= 0 && setRow < points.length && points[setRow].idx == row) { + var point = points[setRow]; + if (point.yval !== null) this.selPoints_.push(point); + } else { + for (var pointIdx = 0; pointIdx < points.length; ++pointIdx) { + var point = points[pointIdx]; + if (point.idx == row) { + if (point.yval !== null) { + this.selPoints_.push(point); + } + break; + } + } + } + } + } else { + if (this.lastRow_ >= 0) changed = true; + this.lastRow_ = -1; + } + if (this.selPoints_.length) { + this.lastx_ = this.selPoints_[0].xval; + } else { + this.lastx_ = null; + } + if (opt_seriesName !== undefined) { + if (this.highlightSet_ !== opt_seriesName) changed = true; + this.highlightSet_ = opt_seriesName; + } + if (opt_locked !== undefined) { + this.lockedSet_ = opt_locked; + } + if (changed) { + this.updateSelection_(undefined); + if (opt_trigger_highlight_callback) { + var callback = this.getFunctionOption("highlightCallback"); + if (callback) { + var event = {}; + callback.call(this, event, this.lastx_, this.selPoints_, this.lastRow_, this.highlightSet_); + } + } + } + return changed; +}; + +/** + * The mouse has left the canvas. Clear out whatever artifacts remain + * @param {Object} event the mouseout event from the browser. + * @private + */ +Dygraph.prototype.mouseOut_ = function (event) { + if (this.getFunctionOption("unhighlightCallback")) { + this.getFunctionOption("unhighlightCallback").call(this, event); + } + if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) { + this.clearSelection(); + } +}; + +/** + * Clears the current selection (i.e. points that were highlighted by moving + * the mouse over the chart). + */ +Dygraph.prototype.clearSelection = function () { + this.cascadeEvents_('deselect', {}); + this.lockedSet_ = false; + // Get rid of the overlay data + if (this.fadeLevel) { + this.animateSelection_(-1); + return; + } + this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_); + this.fadeLevel = 0; + this.selPoints_ = []; + this.lastx_ = null; + this.lastRow_ = -1; + this.highlightSet_ = null; +}; + +/** + * Returns the number of the currently selected row. To get data for this row, + * you can use the getValue method. + * @return {number} row number, or -1 if nothing is selected + */ +Dygraph.prototype.getSelection = function () { + if (!this.selPoints_ || this.selPoints_.length < 1) { + return -1; + } + for (var setIdx = 0; setIdx < this.layout_.points.length; setIdx++) { + var points = this.layout_.points[setIdx]; + for (var row = 0; row < points.length; row++) { + if (points[row].x == this.selPoints_[0].x) { + return points[row].idx; + } + } + } + return -1; +}; + +/** + * Returns the name of the currently-highlighted series. + * Only available when the highlightSeriesOpts option is in use. + */ +Dygraph.prototype.getHighlightSeries = function () { + return this.highlightSet_; +}; + +/** + * Returns true if the currently-highlighted series was locked + * via setSelection(..., seriesName, true). + */ +Dygraph.prototype.isSeriesLocked = function () { + return this.lockedSet_; +}; + +/** + * Fires when there's data available to be graphed. + * @param {string} data Raw CSV data to be plotted + * @private + */ +Dygraph.prototype.loadedEvent_ = function (data) { + this.rawData_ = this.parseCSV_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); +}; + +/** + * Add ticks on the x-axis representing years, months, quarters, weeks, or days + * @private + */ +Dygraph.prototype.addXTicks_ = function () { + // Determine the correct ticks scale on the x-axis: quarterly, monthly, ... + var range; + if (this.dateWindow_) { + range = [this.dateWindow_[0], this.dateWindow_[1]]; + } else { + range = this.xAxisExtremes(); + } + var xAxisOptionsView = this.optionsViewForAxis_('x'); + var xTicks = xAxisOptionsView('ticker')(range[0], range[1], this.plotter_.area.w, + // TODO(danvk): should be area.width + xAxisOptionsView, this); + // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks); + // console.log(msg); + this.layout_.setXTicks(xTicks); +}; + +/** + * Returns the correct handler class for the currently set options. + * @private + */ +Dygraph.prototype.getHandlerClass_ = function () { + var handlerClass; + if (this.attr_('dataHandler')) { + handlerClass = this.attr_('dataHandler'); + } else if (this.fractions_) { + if (this.getBooleanOption('errorBars')) { + handlerClass = _barsFractions["default"]; + } else { + handlerClass = _defaultFractions["default"]; + } + } else if (this.getBooleanOption('customBars')) { + handlerClass = _barsCustom["default"]; + } else if (this.getBooleanOption('errorBars')) { + handlerClass = _barsError["default"]; + } else { + handlerClass = _default2["default"]; + } + return handlerClass; +}; + +/** + * @private + * This function is called once when the chart's data is changed or the options + * dictionary is updated. It is _not_ called when the user pans or zooms. The + * idea is that values derived from the chart's data can be computed here, + * rather than every time the chart is drawn. This includes things like the + * number of axes, rolling averages, etc. + */ +Dygraph.prototype.predraw_ = function () { + var start = new Date(); + + // Create the correct dataHandler + this.dataHandler_ = new (this.getHandlerClass_())(); + this.layout_.computePlotArea(); + + // TODO(danvk): move more computations out of drawGraph_ and into here. + this.computeYAxes_(); + if (!this.is_initial_draw_) { + this.canvas_ctx_.restore(); + this.hidden_ctx_.restore(); + } + this.canvas_ctx_.save(); + this.hidden_ctx_.save(); + + // Create a new plotter. + this.plotter_ = new _dygraphCanvas["default"](this, this.hidden_, this.hidden_ctx_, this.layout_); + + // The roller sits in the bottom left corner of the chart. We don't know where + // this will be until the options are available, so it's positioned here. + this.createRollInterface_(); + this.cascadeEvents_('predraw'); + + // Convert the raw data (a 2D array) into the internal format and compute + // rolling averages. + this.rolledSeries_ = [null]; // x-axis is the first series and it's special + for (var i = 1; i < this.numColumns(); i++) { + // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too. + var series = this.dataHandler_.extractSeries(this.rawData_, i, this.attributes_); + if (this.rollPeriod_ > 1) { + series = this.dataHandler_.rollingAverage(series, this.rollPeriod_, this.attributes_, i); + } + this.rolledSeries_.push(series); + } + + // If the data or options have changed, then we'd better redraw. + this.drawGraph_(); + + // This is used to determine whether to do various animations. + var end = new Date(); + this.drawingTimeMs_ = end - start; +}; + +/** + * Point structure. + * + * xval_* and yval_* are the original unscaled data values, + * while x_* and y_* are scaled to the range (0.0-1.0) for plotting. + * yval_stacked is the cumulative Y value used for stacking graphs, + * and bottom/top/minus/plus are used for high/low band graphs. + * + * @typedef {{ + * idx: number, + * name: string, + * x: ?number, + * xval: ?number, + * y_bottom: ?number, + * y: ?number, + * y_stacked: ?number, + * y_top: ?number, + * yval_minus: ?number, + * yval: ?number, + * yval_plus: ?number, + * yval_stacked + * }} + */ +Dygraph.PointType = undefined; + +/** + * Calculates point stacking for stackedGraph=true. + * + * For stacking purposes, interpolate or extend neighboring data across + * NaN values based on stackedGraphNaNFill settings. This is for display + * only, the underlying data value as shown in the legend remains NaN. + * + * @param {Array.} points Point array for a single series. + * Updates each Point's yval_stacked property. + * @param {Array.} cumulativeYval Accumulated top-of-graph stacked Y + * values for the series seen so far. Index is the row number. Updated + * based on the current series's values. + * @param {Array.} seriesExtremes Min and max values, updated + * to reflect the stacked values. + * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or + * 'none'. + * @private + */ +Dygraph.stackPoints_ = function (points, cumulativeYval, seriesExtremes, fillMethod) { + var lastXval = null; + var prevPoint = null; + var nextPoint = null; + var nextPointIdx = -1; + + // Find the next stackable point starting from the given index. + var updateNextPoint = function updateNextPoint(idx) { + // If we've previously found a non-NaN point and haven't gone past it yet, + // just use that. + if (nextPointIdx >= idx) return; + + // We haven't found a non-NaN point yet or have moved past it, + // look towards the right to find a non-NaN point. + for (var j = idx; j < points.length; ++j) { + // Clear out a previously-found point (if any) since it's no longer + // valid, we shouldn't use it for interpolation anymore. + nextPoint = null; + if (!isNaN(points[j].yval) && points[j].yval !== null) { + nextPointIdx = j; + nextPoint = points[j]; + break; + } + } + }; + for (var i = 0; i < points.length; ++i) { + var point = points[i]; + var xval = point.xval; + if (cumulativeYval[xval] === undefined) { + cumulativeYval[xval] = 0; + } + var actualYval = point.yval; + if (isNaN(actualYval) || actualYval === null) { + if (fillMethod == 'none') { + actualYval = 0; + } else { + // Interpolate/extend for stacking purposes if possible. + updateNextPoint(i); + if (prevPoint && nextPoint && fillMethod != 'none') { + // Use linear interpolation between prevPoint and nextPoint. + actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) * ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval)); + } else if (prevPoint && fillMethod == 'all') { + actualYval = prevPoint.yval; + } else if (nextPoint && fillMethod == 'all') { + actualYval = nextPoint.yval; + } else { + actualYval = 0; + } + } + } else { + prevPoint = point; + } + var stackedYval = cumulativeYval[xval]; + if (lastXval != xval) { + // If an x-value is repeated, we ignore the duplicates. + stackedYval += actualYval; + cumulativeYval[xval] = stackedYval; + } + lastXval = xval; + point.yval_stacked = stackedYval; + if (stackedYval > seriesExtremes[1]) { + seriesExtremes[1] = stackedYval; + } + if (stackedYval < seriesExtremes[0]) { + seriesExtremes[0] = stackedYval; + } + } +}; + +/** + * Loop over all fields and create datasets, calculating extreme y-values for + * each series and extreme x-indices as we go. + * + * dateWindow is passed in as an explicit parameter so that we can compute + * extreme values "speculatively", i.e. without actually setting state on the + * dygraph. + * + * @param {Array.)>>} rolledSeries, where + * rolledSeries[seriesIndex][row] = raw point, where + * seriesIndex is the column number starting with 1, and + * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]]. + * @param {?Array.} dateWindow [xmin, xmax] pair, or null. + * @return {{ + * points: Array.>, + * seriesExtremes: Array.>, + * boundaryIds: Array.}} + * @private + */ +Dygraph.prototype.gatherDatasets_ = function (rolledSeries, dateWindow) { + var boundaryIds = []; + var points = []; + var cumulativeYval = []; // For stacked series. + var extremes = {}; // series name -> [low, high] + var seriesIdx, sampleIdx; + var firstIdx, lastIdx; + var axisIdx; + + // Loop over the fields (series). Go from the last to the first, + // because if they're stacked that's how we accumulate the values. + var num_series = rolledSeries.length - 1; + var series; + for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) { + if (!this.visibility()[seriesIdx - 1]) continue; + + // Prune down to the desired range, if necessary (for zooming) + // Because there can be lines going to points outside of the visible area, + // we actually prune to visible points, plus one on either side. + if (dateWindow) { + series = rolledSeries[seriesIdx]; + var low = dateWindow[0]; + var high = dateWindow[1]; + + // TODO(danvk): do binary search instead of linear search. + // TODO(danvk): pass firstIdx and lastIdx directly to the renderer. + firstIdx = null; + lastIdx = null; + for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) { + if (series[sampleIdx][0] >= low && firstIdx === null) { + firstIdx = sampleIdx; + } + if (series[sampleIdx][0] <= high) { + lastIdx = sampleIdx; + } + } + if (firstIdx === null) firstIdx = 0; + var correctedFirstIdx = firstIdx; + var isInvalidValue = true; + while (isInvalidValue && correctedFirstIdx > 0) { + correctedFirstIdx--; + // check if the y value is null. + isInvalidValue = series[correctedFirstIdx][1] === null; + } + if (lastIdx === null) lastIdx = series.length - 1; + var correctedLastIdx = lastIdx; + isInvalidValue = true; + while (isInvalidValue && correctedLastIdx < series.length - 1) { + correctedLastIdx++; + isInvalidValue = series[correctedLastIdx][1] === null; + } + if (correctedFirstIdx !== firstIdx) { + firstIdx = correctedFirstIdx; + } + if (correctedLastIdx !== lastIdx) { + lastIdx = correctedLastIdx; + } + boundaryIds[seriesIdx - 1] = [firstIdx, lastIdx]; + + // .slice's end is exclusive, we want to include lastIdx. + series = series.slice(firstIdx, lastIdx + 1); + } else { + series = rolledSeries[seriesIdx]; + boundaryIds[seriesIdx - 1] = [0, series.length - 1]; + } + var seriesName = this.attr_("labels")[seriesIdx]; + var seriesExtremes = this.dataHandler_.getExtremeYValues(series, dateWindow, this.getBooleanOption("stepPlot", seriesName)); + var seriesPoints = this.dataHandler_.seriesToPoints(series, seriesName, boundaryIds[seriesIdx - 1][0]); + if (this.getBooleanOption("stackedGraph")) { + axisIdx = this.attributes_.axisForSeries(seriesName); + if (cumulativeYval[axisIdx] === undefined) { + cumulativeYval[axisIdx] = []; + } + Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes, this.getBooleanOption("stackedGraphNaNFill")); + } + extremes[seriesName] = seriesExtremes; + points[seriesIdx] = seriesPoints; + } + return { + points: points, + extremes: extremes, + boundaryIds: boundaryIds + }; +}; + +/** + * Update the graph with new data. This method is called when the viewing area + * has changed. If the underlying data or options have changed, predraw_ will + * be called before drawGraph_ is called. + * + * @private + */ +Dygraph.prototype.drawGraph_ = function () { + var start = new Date(); + + // This is used to set the second parameter to drawCallback, below. + var is_initial_draw = this.is_initial_draw_; + this.is_initial_draw_ = false; + this.layout_.removeAllDatasets(); + this.setColors_(); + this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize'); + var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_); + var points = packed.points; + var extremes = packed.extremes; + this.boundaryIds_ = packed.boundaryIds; + this.setIndexByName_ = {}; + var labels = this.attr_("labels"); + var dataIdx = 0; + for (var i = 1; i < points.length; i++) { + if (!this.visibility()[i - 1]) continue; + this.layout_.addDataset(labels[i], points[i]); + this.datasetIndex_[i] = dataIdx++; + } + for (var i = 0; i < labels.length; i++) { + this.setIndexByName_[labels[i]] = i; + } + this.computeYAxisRanges_(extremes); + this.layout_.setYAxes(this.axes_); + this.addXTicks_(); + + // Tell PlotKit to use this new data and render itself + this.layout_.evaluate(); + this.renderGraph_(is_initial_draw); + if (this.getStringOption("timingName")) { + var end = new Date(); + console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms"); + } +}; + +/** + * This does the work of drawing the chart. It assumes that the layout and axis + * scales have already been set (e.g. by predraw_). + * + * @private + */ +Dygraph.prototype.renderGraph_ = function (is_initial_draw) { + this.cascadeEvents_('clearChart'); + this.plotter_.clear(); + var underlayCallback = this.getFunctionOption('underlayCallback'); + if (underlayCallback) { + // NOTE: we pass the dygraph object to this callback twice to avoid breaking + // users who expect a deprecated form of this callback. + underlayCallback.call(this, this.hidden_ctx_, this.layout_.getPlotArea(), this, this); + } + var e = { + canvas: this.hidden_, + drawingContext: this.hidden_ctx_ + }; + this.cascadeEvents_('willDrawChart', e); + this.plotter_.render(); + this.cascadeEvents_('didDrawChart', e); + this.lastRow_ = -1; // because plugins/legend.js clears the legend + + // TODO(danvk): is this a performance bottleneck when panning? + // The interaction canvas should already be empty in that situation. + this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_); + var drawCallback = this.getFunctionOption("drawCallback"); + if (drawCallback !== null) { + drawCallback.call(this, this, is_initial_draw); + } + if (is_initial_draw) { + this.readyFired_ = true; + while (this.readyFns_.length > 0) { + var fn = this.readyFns_.pop(); + fn(this); + } + } +}; + +/** + * @private + * Determine properties of the y-axes which are independent of the data + * currently being displayed. This includes things like the number of axes and + * the style of the axes. It does not include the range of each axis and its + * tick marks. + * This fills in this.axes_. + * axes_ = [ { options } ] + * indices are into the axes_ array. + */ +Dygraph.prototype.computeYAxes_ = function () { + var axis, index, opts, v; + + // this.axes_ doesn't match this.attributes_.axes_.options. It's used for + // data computation as well as options storage. + // Go through once and add all the axes. + this.axes_ = []; + for (axis = 0; axis < this.attributes_.numAxes(); axis++) { + // Add a new axis, making a copy of its per-axis options. + opts = { + g: this + }; + utils.update(opts, this.attributes_.axisOptions(axis)); + this.axes_[axis] = opts; + } + for (axis = 0; axis < this.axes_.length; axis++) { + if (axis === 0) { + opts = this.optionsViewForAxis_('y' + (axis ? '2' : '')); + v = opts("valueRange"); + if (v) this.axes_[axis].valueRange = v; + } else { + // To keep old behavior + var axes = this.user_attrs_.axes; + if (axes && axes.y2) { + v = axes.y2.valueRange; + if (v) this.axes_[axis].valueRange = v; + } + } + } +}; + +/** + * Returns the number of y-axes on the chart. + * @return {number} the number of axes. + */ +Dygraph.prototype.numAxes = function () { + return this.attributes_.numAxes(); +}; + +/** + * @private + * Returns axis properties for the given series. + * @param {string} setName The name of the series for which to get axis + * properties, e.g. 'Y1'. + * @return {Object} The axis properties. + */ +Dygraph.prototype.axisPropertiesForSeries = function (series) { + // TODO(danvk): handle errors. + return this.axes_[this.attributes_.axisForSeries(series)]; +}; + +/** + * @private + * Determine the value range and tick marks for each axis. + * @param {Object} extremes A mapping from seriesName -> [low, high] + * This fills in the valueRange and ticks fields in each entry of this.axes_. + */ +Dygraph.prototype.computeYAxisRanges_ = function (extremes) { + var isNullUndefinedOrNaN = function isNullUndefinedOrNaN(num) { + return isNaN(parseFloat(num)); + }; + var numAxes = this.attributes_.numAxes(); + var ypadCompat, span, series, ypad; + var p_axis; + + // Compute extreme values, a span and tick marks for each axis. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + var logscale = this.attributes_.getForAxis("logscale", i); + var includeZero = this.attributes_.getForAxis("includeZero", i); + var independentTicks = this.attributes_.getForAxis("independentTicks", i); + series = this.attributes_.seriesForAxis(i); + + // Add some padding. This supports two Y padding operation modes: + // + // - backwards compatible (yRangePad not set): + // 10% padding for automatic Y ranges, but not for user-supplied + // ranges, and move a close-to-zero edge to zero, since drawing at the edge + // results in invisible lines. Unfortunately lines drawn at the edge of a + // user-supplied range will still be invisible. If logscale is + // set, add a variable amount of padding at the top but + // none at the bottom. + // + // - new-style (yRangePad set by the user): + // always add the specified Y padding. + // + ypadCompat = true; + ypad = 0.1; // add 10% + var yRangePad = this.getNumericOption('yRangePad'); + if (yRangePad !== null) { + ypadCompat = false; + // Convert pixel padding to ratio + ypad = yRangePad / this.plotter_.area.h; + } + if (series.length === 0) { + // If no series are defined or visible then use a reasonable default + axis.extremeRange = [0, 1]; + } else { + // Calculate the extremes of extremes. + var minY = Infinity; // extremes[series[0]][0]; + var maxY = -Infinity; // extremes[series[0]][1]; + var extremeMinY, extremeMaxY; + for (var j = 0; j < series.length; j++) { + // this skips invisible series + if (!extremes.hasOwnProperty(series[j])) continue; + + // Only use valid extremes to stop null data series' from corrupting the scale. + extremeMinY = extremes[series[j]][0]; + if (extremeMinY !== null) { + minY = Math.min(extremeMinY, minY); + } + extremeMaxY = extremes[series[j]][1]; + if (extremeMaxY !== null) { + maxY = Math.max(extremeMaxY, maxY); + } + } + + // Include zero if requested by the user. + if (includeZero && !logscale) { + if (minY > 0) minY = 0; + if (maxY < 0) maxY = 0; + } + + // Ensure we have a valid scale, otherwise default to [0, 1] for safety. + if (minY == Infinity) minY = 0; + if (maxY == -Infinity) maxY = 1; + span = maxY - minY; + // special case: if we have no sense of scale, center on the sole value. + if (span === 0) { + if (maxY !== 0) { + span = Math.abs(maxY); + } else { + // ... and if the sole value is zero, use range 0-1. + maxY = 1; + span = 1; + } + } + var maxAxisY = maxY, + minAxisY = minY; + if (ypadCompat) { + if (logscale) { + maxAxisY = maxY + ypad * span; + minAxisY = minY; + } else { + maxAxisY = maxY + ypad * span; + minAxisY = minY - ypad * span; + + // Backwards-compatible behavior: Move the span to start or end at zero if it's + // close to zero. + if (minAxisY < 0 && minY >= 0) minAxisY = 0; + if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0; + } + } + axis.extremeRange = [minAxisY, maxAxisY]; + } + if (axis.valueRange) { + // This is a user-set value range for this axis. + var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0]; + var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1]; + axis.computedValueRange = [y0, y1]; + } else { + axis.computedValueRange = axis.extremeRange; + } + if (!ypadCompat) { + // When using yRangePad, adjust the upper/lower bounds to add + // padding unless the user has zoomed/panned the Y axis range. + + y0 = axis.computedValueRange[0]; + y1 = axis.computedValueRange[1]; + + // special case #781: if we have no sense of scale, center on the sole value. + if (y0 === y1) { + if (y0 === 0) { + y1 = 1; + } else { + var delta = Math.abs(y0 / 10); + y0 -= delta; + y1 += delta; + } + } + if (logscale) { + var y0pct = ypad / (2 * ypad - 1); + var y1pct = (ypad - 1) / (2 * ypad - 1); + axis.computedValueRange[0] = utils.logRangeFraction(y0, y1, y0pct); + axis.computedValueRange[1] = utils.logRangeFraction(y0, y1, y1pct); + } else { + span = y1 - y0; + axis.computedValueRange[0] = y0 - span * ypad; + axis.computedValueRange[1] = y1 + span * ypad; + } + } + if (independentTicks) { + axis.independentTicks = independentTicks; + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + axis.ticks = ticker(axis.computedValueRange[0], axis.computedValueRange[1], this.plotter_.area.h, opts, this); + // Define the first independent axis as primary axis. + if (!p_axis) p_axis = axis; + } + } + if (p_axis === undefined) { + throw "Configuration Error: At least one axis has to have the \"independentTicks\" option activated."; + } + // Add ticks. By default, all axes inherit the tick positions of the + // primary axis. However, if an axis is specifically marked as having + // independent ticks, then that is permissible as well. + for (var i = 0; i < numAxes; i++) { + var axis = this.axes_[i]; + if (!axis.independentTicks) { + var opts = this.optionsViewForAxis_('y' + (i ? '2' : '')); + var ticker = opts('ticker'); + var p_ticks = p_axis.ticks; + var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0]; + var scale = axis.computedValueRange[1] - axis.computedValueRange[0]; + var tick_values = []; + for (var k = 0; k < p_ticks.length; k++) { + var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale; + var y_val = axis.computedValueRange[0] + y_frac * scale; + tick_values.push(y_val); + } + axis.ticks = ticker(axis.computedValueRange[0], axis.computedValueRange[1], this.plotter_.area.h, opts, this, tick_values); + } + } +}; + +/** + * Detects the type of the str (date or numeric) and sets the various + * formatting attributes in this.attrs_ based on this type. + * @param {string} str An x value. + * @private + */ +Dygraph.prototype.detectTypeFromString_ = function (str) { + var isDate = false; + var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2 + if (dashPos > 0 && str[dashPos - 1] != 'e' && str[dashPos - 1] != 'E' || str.indexOf('/') >= 0 || isNaN(parseFloat(str))) { + isDate = true; + } + this.setXAxisOptions_(isDate); +}; +Dygraph.prototype.setXAxisOptions_ = function (isDate) { + if (isDate) { + this.attrs_.xValueParser = utils.dateParser; + this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter; + this.attrs_.axes.x.ticker = DygraphTickers.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter; + } else { + /** @private (shut up, jsdoc!) */ + this.attrs_.xValueParser = function (x) { + return parseFloat(x); + }; + // TODO(danvk): use Dygraph.numberValueFormatter here? + /** @private (shut up, jsdoc!) */ + this.attrs_.axes.x.valueFormatter = function (x) { + return x; + }; + this.attrs_.axes.x.ticker = DygraphTickers.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter; + } +}; + +/** + * @private + * Parses a string in a special csv format. We expect a csv file where each + * line is a date point, and the first field in each line is the date string. + * We also expect that all remaining fields represent series. + * if the errorBars attribute is set, then interpret the fields as: + * date, series1, stddev1, series2, stddev2, ... + * @param {[Object]} data See above. + * + * @return [Object] An array with one entry for each row. These entries + * are an array of cells in that row. The first entry is the parsed x-value for + * the row. The second, third, etc. are the y-values. These can take on one of + * three forms, depending on the CSV and constructor parameters: + * 1. numeric value + * 2. [ value, stddev ] + * 3. [ low value, center value, high value ] + */ +Dygraph.prototype.parseCSV_ = function (data) { + var ret = []; + var line_delimiter = utils.detectLineDelimiter(data); + var lines = data.split(line_delimiter || "\n"); + var vals, j; + + // Use the default delimiter or fall back to a tab if that makes sense. + var delim = this.getStringOption('delimiter'); + if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) { + delim = '\t'; + } + var start = 0; + if (!('labels' in this.user_attrs_)) { + // User hasn't explicitly set labels, so they're (presumably) in the CSV. + start = 1; + this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_. + this.attributes_.reparseSeries(); + } + var line_no = 0; + var xParser; + var defaultParserSet = false; // attempt to auto-detect x value type + var expectedCols = this.attr_("labels").length; + var outOfOrder = false; + for (var i = start; i < lines.length; i++) { + var line = lines[i]; + line_no = i; + if (line.length === 0) continue; // skip blank lines + if (line[0] == '#') continue; // skip comment lines + var inFields = line.split(delim); + if (inFields.length < 2) continue; + var fields = []; + if (!defaultParserSet) { + this.detectTypeFromString_(inFields[0]); + xParser = this.getFunctionOption("xValueParser"); + defaultParserSet = true; + } + fields[0] = xParser(inFields[0], this); + + // If fractions are expected, parse the numbers as "A/B" + if (this.fractions_) { + for (j = 1; j < inFields.length; j++) { + // TODO(danvk): figure out an appropriate way to flag parse errors. + vals = inFields[j].split("/"); + if (vals.length != 2) { + console.error('Expected fractional "num/den" values in CSV data ' + "but found a value '" + inFields[j] + "' on line " + (1 + i) + " ('" + line + "') which is not of this form."); + fields[j] = [0, 0]; + } else { + fields[j] = [utils.parseFloat_(vals[0], i, line), utils.parseFloat_(vals[1], i, line)]; + } + } + } else if (this.getBooleanOption("errorBars")) { + // If there are sigma-based high/low bands, values are (value, stddev) pairs + if (inFields.length % 2 != 1) { + console.error('Expected alternating (value, stdev.) pairs in CSV data ' + 'but line ' + (1 + i) + ' has an odd number of values (' + (inFields.length - 1) + "): '" + line + "'"); + } + for (j = 1; j < inFields.length; j += 2) { + fields[(j + 1) / 2] = [utils.parseFloat_(inFields[j], i, line), utils.parseFloat_(inFields[j + 1], i, line)]; + } + } else if (this.getBooleanOption("customBars")) { + // Custom high/low bands are a low;centre;high tuple + for (j = 1; j < inFields.length; j++) { + var val = inFields[j]; + if (/^ *$/.test(val)) { + fields[j] = [null, null, null]; + } else { + vals = val.split(";"); + if (vals.length == 3) { + fields[j] = [utils.parseFloat_(vals[0], i, line), utils.parseFloat_(vals[1], i, line), utils.parseFloat_(vals[2], i, line)]; + } else { + console.warn('When using customBars, values must be either blank ' + 'or "low;center;high" tuples (got "' + val + '" on line ' + (1 + i) + ')'); + } + } + } + } else { + // Values are just numbers + for (j = 1; j < inFields.length; j++) { + fields[j] = utils.parseFloat_(inFields[j], i, line); + } + } + if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) { + outOfOrder = true; + } + if (fields.length != expectedCols) { + console.error("Number of columns in line " + i + " (" + fields.length + ") does not agree with number of labels (" + expectedCols + ") " + line); + } + + // If the user specified the 'labels' option and none of the cells of the + // first row parsed correctly, then they probably double-specified the + // labels. We go with the values set in the option, discard this row and + // log a warning to the JS console. + if (i === 0 && this.attr_('labels')) { + var all_null = true; + for (j = 0; all_null && j < fields.length; j++) { + if (fields[j]) all_null = false; + } + if (all_null) { + console.warn("The dygraphs 'labels' option is set, but the first row " + "of CSV data ('" + line + "') appears to also contain " + "labels. Will drop the CSV labels and use the option " + "labels."); + continue; + } + } + ret.push(fields); + } + if (outOfOrder) { + console.warn("CSV is out of order; order it correctly to speed loading."); + ret.sort(function (a, b) { + return a[0] - b[0]; + }); + } + return ret; +}; + +// In native format, all values must be dates or numbers. +// This check isn't perfect but will catch most mistaken uses of strings. +function validateNativeFormat(data) { + var firstRow = data[0]; + var firstX = firstRow[0]; + if (typeof firstX !== 'number' && !utils.isDateLike(firstX)) { + throw new Error("Expected number or date but got ".concat(typeof firstX, ": ").concat(firstX, ".")); + } + for (var i = 1; i < firstRow.length; i++) { + var val = firstRow[i]; + if (val === null || val === undefined) continue; + if (typeof val === 'number') continue; + if (utils.isArrayLike(val)) continue; // e.g. errorBars or customBars + throw new Error("Expected number or array but got ".concat(typeof val, ": ").concat(val, ".")); + } +} + +/** + * The user has provided their data as a pre-packaged JS array. If the x values + * are numeric, this is the same as dygraphs' internal format. If the x values + * are dates, we need to convert them from Date objects to ms since epoch. + * @param {!Array} data + * @return {Object} data with numeric x values. + * @private + */ +Dygraph.prototype.parseArray_ = function (data) { + // Peek at the first x value to see if it's numeric. + if (data.length === 0) { + data = [[0]]; + } + if (data[0].length === 0) { + console.error("Data set cannot contain an empty row"); + return null; + } + validateNativeFormat(data); + var i; + if (this.attr_("labels") === null) { + console.warn("Using default labels. Set labels explicitly via 'labels' " + "in the options parameter"); + this.attrs_.labels = ["X"]; + for (i = 1; i < data[0].length; i++) { + this.attrs_.labels.push("Y" + i); // Not user_attrs_. + } + + this.attributes_.reparseSeries(); + } else { + var num_labels = this.attr_("labels"); + if (num_labels.length != data[0].length) { + console.error("Mismatch between number of labels (" + num_labels + ")" + " and number of columns in array (" + data[0].length + ")"); + return null; + } + } + if (utils.isDateLike(data[0][0])) { + // Some intelligent defaults for a date x-axis. + this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter; + this.attrs_.axes.x.ticker = DygraphTickers.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter; + + // Assume they're all dates. + var parsedData = utils.clone(data); + for (i = 0; i < data.length; i++) { + if (parsedData[i].length === 0) { + console.error("Row " + (1 + i) + " of data is empty"); + return null; + } + if (parsedData[i][0] === null || typeof parsedData[i][0].getTime != 'function' || isNaN(parsedData[i][0].getTime())) { + console.error("x value in row " + (1 + i) + " is not a Date"); + return null; + } + parsedData[i][0] = parsedData[i][0].getTime(); + } + return parsedData; + } else { + // Some intelligent defaults for a numeric x-axis. + /** @private (shut up, jsdoc!) */ + this.attrs_.axes.x.valueFormatter = function (x) { + return x; + }; + this.attrs_.axes.x.ticker = DygraphTickers.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = utils.numberAxisLabelFormatter; + return data; + } +}; + +/** + * Parses a DataTable object from gviz. + * The data is expected to have a first column that is either a date or a + * number. All subsequent columns must be numbers. If there is a clear mismatch + * between this.xValueParser_ and the type of the first column, it will be + * fixed. Fills out rawData_. + * @param {!google.visualization.DataTable} data See above. + * @private + */ +Dygraph.prototype.parseDataTable_ = function (data) { + var shortTextForAnnotationNum = function shortTextForAnnotationNum(num) { + // converts [0-9]+ [A-Z][a-z]* + // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab + // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz + var shortText = String.fromCharCode(65 /* A */ + num % 26); + num = Math.floor(num / 26); + while (num > 0) { + shortText = String.fromCharCode(65 /* A */ + (num - 1) % 26) + shortText.toLowerCase(); + num = Math.floor((num - 1) / 26); + } + return shortText; + }; + var cols = data.getNumberOfColumns(); + var rows = data.getNumberOfRows(); + var indepType = data.getColumnType(0); + if (indepType == 'date' || indepType == 'datetime') { + this.attrs_.xValueParser = utils.dateParser; + this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter; + this.attrs_.axes.x.ticker = DygraphTickers.dateTicker; + this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter; + } else if (indepType == 'number') { + this.attrs_.xValueParser = function (x) { + return parseFloat(x); + }; + this.attrs_.axes.x.valueFormatter = function (x) { + return x; + }; + this.attrs_.axes.x.ticker = DygraphTickers.numericTicks; + this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter; + } else { + throw new Error("only 'date', 'datetime' and 'number' types are supported " + "for column 1 of DataTable input (Got '" + indepType + "')"); + } + + // Array of the column indices which contain data (and not annotations). + var colIdx = []; + var annotationCols = {}; // data index -> [annotation cols] + var hasAnnotations = false; + var i, j; + for (i = 1; i < cols; i++) { + var type = data.getColumnType(i); + if (type == 'number') { + colIdx.push(i); + } else if (type == 'string' && this.getBooleanOption('displayAnnotations')) { + // This is OK -- it's an annotation column. + var dataIdx = colIdx[colIdx.length - 1]; + if (!annotationCols.hasOwnProperty(dataIdx)) { + annotationCols[dataIdx] = [i]; + } else { + annotationCols[dataIdx].push(i); + } + hasAnnotations = true; + } else { + throw new Error("Only 'number' is supported as a dependent type with Gviz." + " 'string' is only supported if displayAnnotations is true"); + } + } + + // Read column labels + // TODO(danvk): add support back for errorBars + var labels = [data.getColumnLabel(0)]; + for (i = 0; i < colIdx.length; i++) { + labels.push(data.getColumnLabel(colIdx[i])); + if (this.getBooleanOption("errorBars")) i += 1; + } + this.attrs_.labels = labels; + cols = labels.length; + var ret = []; + var outOfOrder = false; + var annotations = []; + for (i = 0; i < rows; i++) { + var row = []; + if (typeof data.getValue(i, 0) === 'undefined' || data.getValue(i, 0) === null) { + console.warn("Ignoring row " + i + " of DataTable because of undefined or null first column."); + continue; + } + if (indepType == 'date' || indepType == 'datetime') { + row.push(data.getValue(i, 0).getTime()); + } else { + row.push(data.getValue(i, 0)); + } + if (!this.getBooleanOption("errorBars")) { + for (j = 0; j < colIdx.length; j++) { + var col = colIdx[j]; + row.push(data.getValue(i, col)); + if (hasAnnotations && annotationCols.hasOwnProperty(col) && data.getValue(i, annotationCols[col][0]) !== null) { + var ann = {}; + ann.series = data.getColumnLabel(col); + ann.xval = row[0]; + ann.shortText = shortTextForAnnotationNum(annotations.length); + ann.text = ''; + for (var k = 0; k < annotationCols[col].length; k++) { + if (k) ann.text += "\n"; + ann.text += data.getValue(i, annotationCols[col][k]); + } + annotations.push(ann); + } + } + + // Strip out infinities, which give dygraphs problems later on. + for (j = 0; j < row.length; j++) { + if (!isFinite(row[j])) row[j] = null; + } + } else { + for (j = 0; j < cols - 1; j++) { + row.push([data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j)]); + } + } + if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) { + outOfOrder = true; + } + ret.push(row); + } + if (outOfOrder) { + console.warn("DataTable is out of order; order it correctly to speed loading."); + ret.sort(function (a, b) { + return a[0] - b[0]; + }); + } + this.rawData_ = ret; + if (annotations.length > 0) { + this.setAnnotations(annotations, true); + } + this.attributes_.reparseSeries(); +}; + +/** + * Signals to plugins that the chart data has updated. + * This happens after the data has updated but before the chart has redrawn. + * @private + */ +Dygraph.prototype.cascadeDataDidUpdateEvent_ = function () { + // TODO(danvk): there are some issues checking xAxisRange() and using + // toDomCoords from handlers of this event. The visible range should be set + // when the chart is drawn, not derived from the data. + this.cascadeEvents_('dataDidUpdate', {}); +}; + +/** + * Get the CSV data. If it's in a function, call that function. If it's in a + * file, do an XMLHttpRequest to get it. + * @private + */ +Dygraph.prototype.start_ = function () { + var data = this.file_; + + // Functions can return references of all other types. + if (typeof data == 'function') { + data = data(); + } + var datatype = utils.typeArrayLike(data); + if (datatype == 'array') { + this.rawData_ = this.parseArray_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); + } else if (datatype == 'object' && typeof data.getColumnRange == 'function') { + // must be a DataTable from gviz. + this.parseDataTable_(data); + this.cascadeDataDidUpdateEvent_(); + this.predraw_(); + } else if (datatype == 'string') { + // Heuristic: a newline means it's CSV data. Otherwise it's an URL. + var line_delimiter = utils.detectLineDelimiter(data); + if (line_delimiter) { + this.loadedEvent_(data); + } else { + // REMOVE_FOR_IE + var req; + if (window.XMLHttpRequest) { + // Firefox, Opera, IE7, and other browsers will use the native object + req = new XMLHttpRequest(); + } else { + // IE 5 and 6 will use the ActiveX control + req = new ActiveXObject("Microsoft.XMLHTTP"); + } + var caller = this; + req.onreadystatechange = function () { + if (req.readyState == 4) { + if (req.status === 200 || + // Normal http + req.status === 0) { + // Chrome w/ --allow-file-access-from-files + caller.loadedEvent_(req.responseText); + } + } + }; + req.open("GET", data, true); + req.send(null); + } + } else { + console.error("Unknown data format: " + datatype); + } +}; + +/** + * Changes various properties of the graph. These can include: + *
      + *
    • file: changes the source data for the graph
    • + *
    • errorBars: changes whether the data contains stddev
    • + *
    + * + * There's a huge variety of options that can be passed to this method. For a + * full list, see http://dygraphs.com/options.html. + * + * @param {Object} input_attrs The new properties and values + * @param {boolean} block_redraw Usually the chart is redrawn after every + * call to updateOptions(). If you know better, you can pass true to + * explicitly block the redraw. This can be useful for chaining + * updateOptions() calls, avoiding the occasional infinite loop and + * preventing redraws when it's not necessary (e.g. when updating a + * callback). + */ +Dygraph.prototype.updateOptions = function (input_attrs, block_redraw) { + if (typeof block_redraw == 'undefined') block_redraw = false; + + // copyUserAttrs_ drops the "file" parameter as a convenience to us. + var file = input_attrs.file; + var attrs = Dygraph.copyUserAttrs_(input_attrs); + var prevNumAxes = this.attributes_.numAxes(); + + // TODO(danvk): this is a mess. Move these options into attr_. + if ('rollPeriod' in attrs) { + this.rollPeriod_ = attrs.rollPeriod; + } + if ('dateWindow' in attrs) { + this.dateWindow_ = attrs.dateWindow; + } + + // TODO(danvk): validate per-series options. + // Supported: + // strokeWidth + // pointSize + // drawPoints + // highlightCircleSize + + // Check if this set options will require new points. + var requiresNewPoints = utils.isPixelChangingOptionList(this.attr_("labels"), attrs); + utils.updateDeep(this.user_attrs_, attrs); + this.attributes_.reparseSeries(); + if (prevNumAxes < this.attributes_.numAxes()) this.plotter_.clear(); + if (file) { + // This event indicates that the data is about to change, but hasn't yet. + // TODO(danvk): support cancellation of the update via this event. + this.cascadeEvents_('dataWillUpdate', {}); + this.file_ = file; + if (!block_redraw) this.start_(); + } else { + if (!block_redraw) { + if (requiresNewPoints) { + this.predraw_(); + } else { + this.renderGraph_(false); + } + } + } +}; + +/** + * Make a copy of input attributes, removing file as a convenience. + * @private + */ +Dygraph.copyUserAttrs_ = function (attrs) { + var my_attrs = {}; + for (var k in attrs) { + if (!attrs.hasOwnProperty(k)) continue; + if (k == 'file') continue; + if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k]; + } + return my_attrs; +}; + +/** + * Resizes the dygraph. If no parameters are specified, resizes to fill the + * containing div (which has presumably changed size since the dygraph was + * instantiated). If the width/height are specified, the div will be resized. + * + * This is far more efficient than destroying and re-instantiating a + * Dygraph, since it doesn't have to reparse the underlying data. + * + * @param {number} width Width (in pixels) + * @param {number} height Height (in pixels) + */ +Dygraph.prototype.resize = function (width, height) { + if (this.resize_lock) { + return; + } + this.resize_lock = true; + if (width === null != (height === null)) { + console.warn("Dygraph.resize() should be called with zero parameters or " + "two non-NULL parameters. Pretending it was zero."); + width = height = null; + } + var old_width = this.width_; + var old_height = this.height_; + if (width) { + this.maindiv_.style.width = width + "px"; + this.maindiv_.style.height = height + "px"; + this.width_ = width; + this.height_ = height; + } else { + this.width_ = this.maindiv_.clientWidth; + this.height_ = this.maindiv_.clientHeight; + } + if (old_width != this.width_ || old_height != this.height_) { + // Resizing a canvas erases it, even when the size doesn't change, so + // any resize needs to be followed by a redraw. + this.resizeElements_(); + this.predraw_(); + } + this.resize_lock = false; +}; + +/** + * Adjusts the number of points in the rolling average. Updates the graph to + * reflect the new averaging period. + * @param {number} length Number of points over which to average the data. + */ +Dygraph.prototype.adjustRoll = function (length) { + this.rollPeriod_ = length; + this.predraw_(); +}; + +/** + * Returns a boolean array of visibility statuses. + */ +Dygraph.prototype.visibility = function () { + // Do lazy-initialization, so that this happens after we know the number of + // data series. + if (!this.getOption("visibility")) { + this.attrs_.visibility = []; + } + // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs. + while (this.getOption("visibility").length < this.numColumns() - 1) { + this.attrs_.visibility.push(true); + } + return this.getOption("visibility"); +}; + +/** + * Changes the visibility of one or more series. + * + * @param {number|number[]|object} num the series index or an array of series indices + * or a boolean array of visibility states by index + * or an object mapping series numbers, as keys, to + * visibility state (boolean values) + * @param {boolean} value the visibility state expressed as a boolean + */ +Dygraph.prototype.setVisibility = function (num, value) { + var x = this.visibility(); + var numIsObject = false; + if (!Array.isArray(num)) { + if (num !== null && typeof num === 'object') { + numIsObject = true; + } else { + num = [num]; + } + } + if (numIsObject) { + for (var i in num) { + if (num.hasOwnProperty(i)) { + if (i < 0 || i >= x.length) { + console.warn("Invalid series number in setVisibility: " + i); + } else { + x[i] = num[i]; + } + } + } + } else { + for (var i = 0; i < num.length; i++) { + if (typeof num[i] === 'boolean') { + if (i >= x.length) { + console.warn("Invalid series number in setVisibility: " + i); + } else { + x[i] = num[i]; + } + } else { + if (num[i] < 0 || num[i] >= x.length) { + console.warn("Invalid series number in setVisibility: " + num[i]); + } else { + x[num[i]] = value; + } + } + } + } + this.predraw_(); +}; + +/** + * How large of an area will the dygraph render itself in? + * This is used for testing. + * @return A {width: w, height: h} object. + * @private + */ +Dygraph.prototype.size = function () { + return { + width: this.width_, + height: this.height_ + }; +}; + +/** + * Update the list of annotations and redraw the chart. + * See dygraphs.com/annotations.html for more info on how to use annotations. + * @param ann {Array} An array of annotation objects. + * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional). + */ +Dygraph.prototype.setAnnotations = function (ann, suppressDraw) { + // Only add the annotation CSS rule once we know it will be used. + this.annotations_ = ann; + if (!this.layout_) { + console.warn("Tried to setAnnotations before dygraph was ready. " + "Try setting them in a ready() block. See " + "dygraphs.com/tests/annotation.html"); + return; + } + this.layout_.setAnnotations(this.annotations_); + if (!suppressDraw) { + this.predraw_(); + } +}; + +/** + * Return the list of annotations. + */ +Dygraph.prototype.annotations = function () { + return this.annotations_; +}; + +/** + * Get the list of label names for this graph. The first column is the + * x-axis, so the data series names start at index 1. + * + * Returns null when labels have not yet been defined. + */ +Dygraph.prototype.getLabels = function () { + var labels = this.attr_("labels"); + return labels ? labels.slice() : null; +}; + +/** + * Get the index of a series (column) given its name. The first column is the + * x-axis, so the data series start with index 1. + */ +Dygraph.prototype.indexFromSetName = function (name) { + return this.setIndexByName_[name]; +}; + +/** + * Find the row number corresponding to the given x-value. + * Returns null if there is no such x-value in the data. + * If there are multiple rows with the same x-value, this will return the + * first one. + * @param {number} xVal The x-value to look for (e.g. millis since epoch). + * @return {?number} The row number, which you can pass to getValue(), or null. + */ +Dygraph.prototype.getRowForX = function (xVal) { + var low = 0, + high = this.numRows() - 1; + while (low <= high) { + var idx = high + low >> 1; + var x = this.getValue(idx, 0); + if (x < xVal) { + low = idx + 1; + } else if (x > xVal) { + high = idx - 1; + } else if (low != idx) { + // equal, but there may be an earlier match. + high = idx; + } else { + return idx; + } + } + return null; +}; + +/** + * Trigger a callback when the dygraph has drawn itself and is ready to be + * manipulated. This is primarily useful when dygraphs has to do an XHR for the + * data (i.e. a URL is passed as the data source) and the chart is drawn + * asynchronously. If the chart has already drawn, the callback will fire + * immediately. + * + * This is a good place to call setAnnotation(). + * + * @param {function(!Dygraph)} callback The callback to trigger when the chart + * is ready. + */ +Dygraph.prototype.ready = function (callback) { + if (this.is_initial_draw_) { + this.readyFns_.push(callback); + } else { + callback.call(this, this); + } +}; + +/** + * Add an event handler. This event handler is kept until the graph is + * destroyed with a call to graph.destroy(). + * + * @param {!Node} elem The element to add the event to. + * @param {string} type The type of the event, e.g. 'click' or 'mousemove'. + * @param {function(Event):(boolean|undefined)} fn The function to call + * on the event. The function takes one parameter: the event object. + * @private + */ +Dygraph.prototype.addAndTrackEvent = function (elem, type, fn) { + utils.addEvent(elem, type, fn); + this.registeredEvents_.push({ + elem: elem, + type: type, + fn: fn + }); +}; +Dygraph.prototype.removeTrackedEvents_ = function () { + if (this.registeredEvents_) { + for (var idx = 0; idx < this.registeredEvents_.length; idx++) { + var reg = this.registeredEvents_[idx]; + utils.removeEvent(reg.elem, reg.type, reg.fn); + } + } + this.registeredEvents_ = []; +}; + +// Installed plugins, in order of precedence (most-general to most-specific). +Dygraph.PLUGINS = [_legend["default"], _axes["default"], _rangeSelector["default"], +// Has to be before ChartLabels so that its callbacks are called after ChartLabels' callbacks. +_chartLabels["default"], _annotations["default"], _grid["default"]]; + +// There are many symbols which have historically been available through the +// Dygraph class. These are exported here for backwards compatibility. +Dygraph.GVizChart = _dygraphGviz["default"]; +Dygraph.DASHED_LINE = utils.DASHED_LINE; +Dygraph.DOT_DASH_LINE = utils.DOT_DASH_LINE; +Dygraph.dateAxisLabelFormatter = utils.dateAxisLabelFormatter; +Dygraph.toRGB_ = utils.toRGB_; +Dygraph.findPos = utils.findPos; +Dygraph.pageX = utils.pageX; +Dygraph.pageY = utils.pageY; +Dygraph.dateString_ = utils.dateString_; +Dygraph.defaultInteractionModel = _dygraphInteractionModel["default"].defaultModel; +Dygraph.nonInteractiveModel = Dygraph.nonInteractiveModel_ = _dygraphInteractionModel["default"].nonInteractiveModel_; +Dygraph.Circles = utils.Circles; +Dygraph.Plugins = { + Legend: _legend["default"], + Axes: _axes["default"], + Annotations: _annotations["default"], + ChartLabels: _chartLabels["default"], + Grid: _grid["default"], + RangeSelector: _rangeSelector["default"] +}; +Dygraph.DataHandlers = { + DefaultHandler: _default2["default"], + BarsHandler: _bars["default"], + CustomBarsHandler: _barsCustom["default"], + DefaultFractionHandler: _defaultFractions["default"], + ErrorBarsHandler: _barsError["default"], + FractionsBarsHandler: _barsFractions["default"] +}; +Dygraph.startPan = _dygraphInteractionModel["default"].startPan; +Dygraph.startZoom = _dygraphInteractionModel["default"].startZoom; +Dygraph.movePan = _dygraphInteractionModel["default"].movePan; +Dygraph.moveZoom = _dygraphInteractionModel["default"].moveZoom; +Dygraph.endPan = _dygraphInteractionModel["default"].endPan; +Dygraph.endZoom = _dygraphInteractionModel["default"].endZoom; +Dygraph.numericLinearTicks = DygraphTickers.numericLinearTicks; +Dygraph.numericTicks = DygraphTickers.numericTicks; +Dygraph.dateTicker = DygraphTickers.dateTicker; +Dygraph.Granularity = DygraphTickers.Granularity; +Dygraph.getDateAxis = DygraphTickers.getDateAxis; +Dygraph.floatFormat = utils.floatFormat; +utils.setupDOMready_(Dygraph); +var _default = Dygraph; +exports["default"] = _default; +module.exports = exports.default; + +},{"./datahandler/bars":"dygraphs/src/datahandler/bars.js","./datahandler/bars-custom":"dygraphs/src/datahandler/bars-custom.js","./datahandler/bars-error":"dygraphs/src/datahandler/bars-error.js","./datahandler/bars-fractions":"dygraphs/src/datahandler/bars-fractions.js","./datahandler/default":"dygraphs/src/datahandler/default.js","./datahandler/default-fractions":"dygraphs/src/datahandler/default-fractions.js","./dygraph-canvas":"dygraphs/src/dygraph-canvas.js","./dygraph-default-attrs":"dygraphs/src/dygraph-default-attrs.js","./dygraph-gviz":"dygraphs/src/dygraph-gviz.js","./dygraph-interaction-model":"dygraphs/src/dygraph-interaction-model.js","./dygraph-layout":"dygraphs/src/dygraph-layout.js","./dygraph-options":"dygraphs/src/dygraph-options.js","./dygraph-options-reference":"dygraphs/src/dygraph-options-reference.js","./dygraph-tickers":"dygraphs/src/dygraph-tickers.js","./dygraph-utils":"dygraphs/src/dygraph-utils.js","./iframe-tarp":"dygraphs/src/iframe-tarp.js","./plugins/annotations":"dygraphs/src/plugins/annotations.js","./plugins/axes":"dygraphs/src/plugins/axes.js","./plugins/chart-labels":"dygraphs/src/plugins/chart-labels.js","./plugins/grid":"dygraphs/src/plugins/grid.js","./plugins/legend":"dygraphs/src/plugins/legend.js","./plugins/range-selector":"dygraphs/src/plugins/range-selector.js"}],"dygraphs/src/iframe-tarp.js":[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("./dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * To create a "drag" interaction, you typically register a mousedown event + * handler on the element where the drag begins. In that handler, you register a + * mouseup handler on the window to determine when the mouse is released, + * wherever that release happens. This works well, except when the user releases + * the mouse over an off-domain iframe. In that case, the mouseup event is + * handled by the iframe and never bubbles up to the window handler. + * + * To deal with this issue, we cover iframes with high z-index divs to make sure + * they don't capture mouseup. + * + * Usage: + * element.addEventListener('mousedown', function() { + * var tarper = new IFrameTarp(); + * tarper.cover(); + * var mouseUpHandler = function() { + * ... + * window.removeEventListener(mouseUpHandler); + * tarper.uncover(); + * }; + * window.addEventListener('mouseup', mouseUpHandler); + * }); + * + * @constructor + */ + +function IFrameTarp() { + /** @type {Array.} */ + this.tarps = []; +} + +/** + * Find all the iframes in the document and cover them with high z-index + * transparent divs. + */ +IFrameTarp.prototype.cover = function () { + var iframes = document.getElementsByTagName("iframe"); + for (var i = 0; i < iframes.length; i++) { + var iframe = iframes[i]; + var pos = utils.findPos(iframe), + x = pos.x, + y = pos.y, + width = iframe.offsetWidth, + height = iframe.offsetHeight; + var div = document.createElement("div"); + div.style.position = "absolute"; + div.style.left = x + 'px'; + div.style.top = y + 'px'; + div.style.width = width + 'px'; + div.style.height = height + 'px'; + div.style.zIndex = 999; + document.body.appendChild(div); + this.tarps.push(div); + } +}; + +/** + * Remove all the iframe covers. You should call this in a mouseup handler. + */ +IFrameTarp.prototype.uncover = function () { + for (var i = 0; i < this.tarps.length; i++) { + this.tarps[i].parentNode.removeChild(this.tarps[i]); + } + this.tarps = []; +}; +var _default = IFrameTarp; +exports["default"] = _default; +module.exports = exports.default; + +},{"./dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/plugins/annotations.js":[function(require,module,exports){ +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/*global Dygraph:false */ + +"use strict"; + +/** +Current bits of jankiness: +- Uses dygraph.layout_ to get the parsed annotations. +- Uses dygraph.plotter_.area + +It would be nice if the plugin didn't require so much special support inside +the core dygraphs classes, but annotations involve quite a bit of parsing and +layout. + +TODO(danvk): cache DOM elements. +*/ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var annotations = function annotations() { + this.annotations_ = []; +}; +annotations.prototype.toString = function () { + return "Annotations Plugin"; +}; +annotations.prototype.activate = function (g) { + return { + clearChart: this.clearChart, + didDrawChart: this.didDrawChart + }; +}; +annotations.prototype.detachLabels = function () { + for (var i = 0; i < this.annotations_.length; i++) { + var a = this.annotations_[i]; + if (a.parentNode) a.parentNode.removeChild(a); + this.annotations_[i] = null; + } + this.annotations_ = []; +}; +annotations.prototype.clearChart = function (e) { + this.detachLabels(); +}; +annotations.prototype.didDrawChart = function (e) { + var g = e.dygraph; + + // Early out in the (common) case of zero annotations. + var points = g.layout_.annotated_points; + if (!points || points.length === 0) return; + var containerDiv = e.canvas.parentNode; + var bindEvt = function bindEvt(eventName, classEventName, pt) { + return function (annotation_event) { + var a = pt.annotation; + if (a.hasOwnProperty(eventName)) { + a[eventName](a, pt, g, annotation_event); + } else if (g.getOption(classEventName)) { + g.getOption(classEventName)(a, pt, g, annotation_event); + } + }; + }; + + // Add the annotations one-by-one. + var area = e.dygraph.getArea(); + + // x-coord to sum of previous annotation's heights (used for stacking). + var xToUsedHeight = {}; + for (var i = 0; i < points.length; i++) { + var p = points[i]; + if (p.canvasx < area.x || p.canvasx > area.x + area.w || p.canvasy < area.y || p.canvasy > area.y + area.h) { + continue; + } + var a = p.annotation; + var tick_height = 6; + if (a.hasOwnProperty("tickHeight")) { + tick_height = a.tickHeight; + } + + // TODO: deprecate axisLabelFontSize in favor of CSS + var div = document.createElement("div"); + div.style['fontSize'] = g.getOption('axisLabelFontSize') + "px"; + var className = 'dygraph-annotation'; + if (!a.hasOwnProperty('icon')) { + // camelCase class names are deprecated. + className += ' dygraphDefaultAnnotation dygraph-default-annotation'; + } + if (a.hasOwnProperty('cssClass')) { + className += " " + a.cssClass; + } + div.className = className; + var width = a.hasOwnProperty('width') ? a.width : 16; + var height = a.hasOwnProperty('height') ? a.height : 16; + if (a.hasOwnProperty('icon')) { + var img = document.createElement("img"); + img.src = a.icon; + img.width = width; + img.height = height; + div.appendChild(img); + } else if (p.annotation.hasOwnProperty('shortText')) { + div.appendChild(document.createTextNode(p.annotation.shortText)); + } + var left = p.canvasx - width / 2; + div.style.left = left + "px"; + var divTop = 0; + if (a.attachAtBottom) { + var y = area.y + area.h - height - tick_height; + if (xToUsedHeight[left]) { + y -= xToUsedHeight[left]; + } else { + xToUsedHeight[left] = 0; + } + xToUsedHeight[left] += tick_height + height; + divTop = y; + } else { + divTop = p.canvasy - height - tick_height; + } + div.style.top = divTop + "px"; + div.style.width = width + "px"; + div.style.height = height + "px"; + div.title = p.annotation.text; + div.style.color = g.colorsMap_[p.name]; + div.style.borderColor = g.colorsMap_[p.name]; + a.div = div; + g.addAndTrackEvent(div, 'click', bindEvt('clickHandler', 'annotationClickHandler', p, this)); + g.addAndTrackEvent(div, 'mouseover', bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this)); + g.addAndTrackEvent(div, 'mouseout', bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this)); + g.addAndTrackEvent(div, 'dblclick', bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this)); + containerDiv.appendChild(div); + this.annotations_.push(div); + var ctx = e.drawingContext; + ctx.save(); + ctx.strokeStyle = a.hasOwnProperty('tickColor') ? a.tickColor : g.colorsMap_[p.name]; + ctx.lineWidth = a.hasOwnProperty('tickWidth') ? a.tickWidth : g.getOption('strokeWidth'); + ctx.beginPath(); + if (!a.attachAtBottom) { + ctx.moveTo(p.canvasx, p.canvasy); + ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height); + } else { + var y = divTop + height; + ctx.moveTo(p.canvasx, y); + ctx.lineTo(p.canvasx, y + tick_height); + } + ctx.closePath(); + ctx.stroke(); + ctx.restore(); + } +}; +annotations.prototype.destroy = function () { + this.detachLabels(); +}; +var _default = annotations; +exports["default"] = _default; +module.exports = exports.default; + +},{}],"dygraphs/src/plugins/axes.js":[function(require,module,exports){ +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ + +/*global Dygraph:false */ + +'use strict'; + +/* +Bits of jankiness: +- Direct layout access +- Direct area access +- Should include calculation of ticks, not just the drawing. + +Options left to make axis-friendly. + ('drawAxesAtZero') + ('xAxisHeight') +*/ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("../dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * Draws the axes. This includes the labels on the x- and y-axes, as well + * as the tick marks on the axes. + * It does _not_ draw the grid lines which span the entire chart. + */ +var axes = function axes() { + this.xlabels_ = []; + this.ylabels_ = []; +}; +axes.prototype.toString = function () { + return 'Axes Plugin'; +}; +axes.prototype.activate = function (g) { + return { + layout: this.layout, + clearChart: this.clearChart, + willDrawChart: this.willDrawChart + }; +}; +axes.prototype.layout = function (e) { + var g = e.dygraph; + if (g.getOptionForAxis('drawAxis', 'y')) { + var w = g.getOptionForAxis('axisLabelWidth', 'y') + 2 * g.getOptionForAxis('axisTickSize', 'y'); + e.reserveSpaceLeft(w); + } + if (g.getOptionForAxis('drawAxis', 'x')) { + var h; + // NOTE: I think this is probably broken now, since g.getOption() now + // hits the dictionary. (That is, g.getOption('xAxisHeight') now always + // has a value.) + if (g.getOption('xAxisHeight')) { + h = g.getOption('xAxisHeight'); + } else { + h = g.getOptionForAxis('axisLabelFontSize', 'x') + 2 * g.getOptionForAxis('axisTickSize', 'x'); + } + e.reserveSpaceBottom(h); + } + if (g.numAxes() == 2) { + if (g.getOptionForAxis('drawAxis', 'y2')) { + var w = g.getOptionForAxis('axisLabelWidth', 'y2') + 2 * g.getOptionForAxis('axisTickSize', 'y2'); + e.reserveSpaceRight(w); + } + } else if (g.numAxes() > 2) { + g.error('Only two y-axes are supported at this time. (Trying ' + 'to use ' + g.numAxes() + ')'); + } +}; +axes.prototype.detachLabels = function () { + function removeArray(ary) { + for (var i = 0; i < ary.length; i++) { + var el = ary[i]; + if (el.parentNode) el.parentNode.removeChild(el); + } + } + removeArray(this.xlabels_); + removeArray(this.ylabels_); + this.xlabels_ = []; + this.ylabels_ = []; +}; +axes.prototype.clearChart = function (e) { + this.detachLabels(); +}; +axes.prototype.willDrawChart = function (e) { + var g = e.dygraph; + if (!g.getOptionForAxis('drawAxis', 'x') && !g.getOptionForAxis('drawAxis', 'y') && !g.getOptionForAxis('drawAxis', 'y2')) { + return; + } + + // Round pixels to half-integer boundaries for crisper drawing. + function halfUp(x) { + return Math.round(x) + 0.5; + } + function halfDown(y) { + return Math.round(y) - 0.5; + } + var context = e.drawingContext; + var containerDiv = e.canvas.parentNode; + var canvasWidth = g.width_; // e.canvas.width is affected by pixel ratio. + var canvasHeight = g.height_; + var label, x, y, tick, i; + var makeLabelStyle = function makeLabelStyle(axis) { + return { + position: 'absolute', + fontSize: g.getOptionForAxis('axisLabelFontSize', axis) + 'px', + width: g.getOptionForAxis('axisLabelWidth', axis) + 'px' + }; + }; + var labelStyles = { + x: makeLabelStyle('x'), + y: makeLabelStyle('y'), + y2: makeLabelStyle('y2') + }; + var makeDiv = function makeDiv(txt, axis, prec_axis) { + /* + * This seems to be called with the following three sets of axis/prec_axis: + * x: undefined + * y: y1 + * y: y2 + */ + var div = document.createElement('div'); + var labelStyle = labelStyles[prec_axis == 'y2' ? 'y2' : axis]; + utils.update(div.style, labelStyle); + // TODO: combine outer & inner divs + var inner_div = document.createElement('div'); + inner_div.className = 'dygraph-axis-label' + ' dygraph-axis-label-' + axis + (prec_axis ? ' dygraph-axis-label-' + prec_axis : ''); + inner_div.innerHTML = txt; + div.appendChild(inner_div); + return div; + }; + + // axis lines + context.save(); + var layout = g.layout_; + var area = e.dygraph.plotter_.area; + + // Helper for repeated axis-option accesses. + var makeOptionGetter = function makeOptionGetter(axis) { + return function (option) { + return g.getOptionForAxis(option, axis); + }; + }; + var that = this; + if (g.getOptionForAxis('drawAxis', 'y') || g.numAxes() == 2 && g.getOptionForAxis('drawAxis', 'y2')) { + if (layout.yticks && layout.yticks.length > 0) { + var num_axes = g.numAxes(); + var getOptions = [makeOptionGetter('y'), makeOptionGetter('y2')]; + layout.yticks.forEach(function (tick) { + if (tick.label === undefined) return; // this tick only has a grid line. + x = area.x; + var sgn = 1; + var prec_axis = 'y1'; + var getAxisOption = getOptions[0]; + if (tick.axis == 1) { + // right-side y-axis + x = area.x + area.w; + sgn = -1; + prec_axis = 'y2'; + getAxisOption = getOptions[1]; + } + if (!getAxisOption('drawAxis')) return; + var fontSize = getAxisOption('axisLabelFontSize'); + y = area.y + tick.pos * area.h; + + /* Tick marks are currently clipped, so don't bother drawing them. + context.beginPath(); + context.moveTo(halfUp(x), halfDown(y)); + context.lineTo(halfUp(x - sgn * that.attr_('axisTickSize')), halfDown(y)); + context.closePath(); + context.stroke(); + */ + + label = makeDiv(tick.label, 'y', num_axes == 2 ? prec_axis : null); + var top = y - fontSize / 2; + if (top < 0) top = 0; + if (top + fontSize + 3 > canvasHeight) { + label.style.bottom = '0'; + } else { + // The lowest tick on the y-axis often overlaps with the leftmost + // tick on the x-axis. Shift the bottom tick up a little bit to + // compensate if necessary. + label.style.top = Math.min(top, canvasHeight - 2 * fontSize) + 'px'; + } + // TODO: replace these with css classes? + if (tick.axis === 0) { + label.style.left = area.x - getAxisOption('axisLabelWidth') - getAxisOption('axisTickSize') + 'px'; + label.style.textAlign = 'right'; + } else if (tick.axis == 1) { + label.style.left = area.x + area.w + getAxisOption('axisTickSize') + 'px'; + label.style.textAlign = 'left'; + } + label.style.width = getAxisOption('axisLabelWidth') + 'px'; + containerDiv.appendChild(label); + that.ylabels_.push(label); + }); + } + + // draw a vertical line on the left to separate the chart from the labels. + var axisX; + if (g.getOption('drawAxesAtZero')) { + var r = g.toPercentXCoord(0); + if (r > 1 || r < 0 || isNaN(r)) r = 0; + axisX = halfUp(area.x + r * area.w); + } else { + axisX = halfUp(area.x); + } + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'y'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'y'); + context.beginPath(); + context.moveTo(axisX, halfDown(area.y)); + context.lineTo(axisX, halfDown(area.y + area.h)); + context.closePath(); + context.stroke(); + + // if there's a secondary y-axis, draw a vertical line for that, too. + if (g.numAxes() == 2 && g.getOptionForAxis('drawAxis', 'y2')) { + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'y2'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'y2'); + context.beginPath(); + context.moveTo(halfDown(area.x + area.w), halfDown(area.y)); + context.lineTo(halfDown(area.x + area.w), halfDown(area.y + area.h)); + context.closePath(); + context.stroke(); + } + } + if (g.getOptionForAxis('drawAxis', 'x')) { + if (layout.xticks) { + var getAxisOption = makeOptionGetter('x'); + layout.xticks.forEach(function (tick) { + if (tick.label === undefined) return; // this tick only has a grid line. + x = area.x + tick.pos * area.w; + y = area.y + area.h; + + /* Tick marks are currently clipped, so don't bother drawing them. + context.beginPath(); + context.moveTo(halfUp(x), halfDown(y)); + context.lineTo(halfUp(x), halfDown(y + that.attr_('axisTickSize'))); + context.closePath(); + context.stroke(); + */ + + label = makeDiv(tick.label, 'x'); + label.style.textAlign = 'center'; + label.style.top = y + getAxisOption('axisTickSize') + 'px'; + var left = x - getAxisOption('axisLabelWidth') / 2; + if (left + getAxisOption('axisLabelWidth') > canvasWidth) { + left = canvasWidth - getAxisOption('axisLabelWidth'); + label.style.textAlign = 'right'; + } + if (left < 0) { + left = 0; + label.style.textAlign = 'left'; + } + label.style.left = left + 'px'; + label.style.width = getAxisOption('axisLabelWidth') + 'px'; + containerDiv.appendChild(label); + that.xlabels_.push(label); + }); + } + context.strokeStyle = g.getOptionForAxis('axisLineColor', 'x'); + context.lineWidth = g.getOptionForAxis('axisLineWidth', 'x'); + context.beginPath(); + var axisY; + if (g.getOption('drawAxesAtZero')) { + var r = g.toPercentYCoord(0, 0); + if (r > 1 || r < 0) r = 1; + axisY = halfDown(area.y + r * area.h); + } else { + axisY = halfDown(area.y + area.h); + } + context.moveTo(halfUp(area.x), axisY); + context.lineTo(halfUp(area.x + area.w), axisY); + context.closePath(); + context.stroke(); + } + context.restore(); +}; +var _default = axes; +exports["default"] = _default; +module.exports = exports.default; + +},{"../dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/plugins/chart-labels.js":[function(require,module,exports){ +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ +/*global Dygraph:false */ + +"use strict"; + +// TODO(danvk): move chart label options out of dygraphs and into the plugin. +// TODO(danvk): only tear down & rebuild the DIVs when it's necessary. +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var chart_labels = function chart_labels() { + this.title_div_ = null; + this.xlabel_div_ = null; + this.ylabel_div_ = null; + this.y2label_div_ = null; +}; +chart_labels.prototype.toString = function () { + return "ChartLabels Plugin"; +}; +chart_labels.prototype.activate = function (g) { + return { + layout: this.layout, + // clearChart: this.clearChart, + didDrawChart: this.didDrawChart + }; +}; + +// QUESTION: should there be a plugin-utils.js? +var createDivInRect = function createDivInRect(r) { + var div = document.createElement('div'); + div.style.position = 'absolute'; + div.style.left = r.x + 'px'; + div.style.top = r.y + 'px'; + div.style.width = r.w + 'px'; + div.style.height = r.h + 'px'; + return div; +}; + +// Detach and null out any existing nodes. +chart_labels.prototype.detachLabels_ = function () { + var els = [this.title_div_, this.xlabel_div_, this.ylabel_div_, this.y2label_div_]; + for (var i = 0; i < els.length; i++) { + var el = els[i]; + if (!el) continue; + if (el.parentNode) el.parentNode.removeChild(el); + } + this.title_div_ = null; + this.xlabel_div_ = null; + this.ylabel_div_ = null; + this.y2label_div_ = null; +}; +var createRotatedDiv = function createRotatedDiv(g, box, axis, classes, html) { + // TODO(danvk): is this outer div actually necessary? + var div = document.createElement("div"); + div.style.position = 'absolute'; + if (axis == 1) { + // NOTE: this is cheating. Should be positioned relative to the box. + div.style.left = '0px'; + } else { + div.style.left = box.x + 'px'; + } + div.style.top = box.y + 'px'; + div.style.width = box.w + 'px'; + div.style.height = box.h + 'px'; + div.style.fontSize = g.getOption('yLabelWidth') - 2 + 'px'; + var inner_div = document.createElement("div"); + inner_div.style.position = 'absolute'; + inner_div.style.width = box.h + 'px'; + inner_div.style.height = box.w + 'px'; + inner_div.style.top = box.h / 2 - box.w / 2 + 'px'; + inner_div.style.left = box.w / 2 - box.h / 2 + 'px'; + // TODO: combine inner_div and class_div. + inner_div.className = 'dygraph-label-rotate-' + (axis == 1 ? 'right' : 'left'); + var class_div = document.createElement("div"); + class_div.className = classes; + class_div.innerHTML = html; + inner_div.appendChild(class_div); + div.appendChild(inner_div); + return div; +}; +chart_labels.prototype.layout = function (e) { + this.detachLabels_(); + var g = e.dygraph; + var div = e.chart_div; + if (g.getOption('title')) { + // QUESTION: should this return an absolutely-positioned div instead? + var title_rect = e.reserveSpaceTop(g.getOption('titleHeight')); + this.title_div_ = createDivInRect(title_rect); + this.title_div_.style.fontSize = g.getOption('titleHeight') - 8 + 'px'; + var class_div = document.createElement("div"); + class_div.className = 'dygraph-label dygraph-title'; + class_div.innerHTML = g.getOption('title'); + this.title_div_.appendChild(class_div); + div.appendChild(this.title_div_); + } + if (g.getOption('xlabel')) { + var x_rect = e.reserveSpaceBottom(g.getOption('xLabelHeight')); + this.xlabel_div_ = createDivInRect(x_rect); + this.xlabel_div_.style.fontSize = g.getOption('xLabelHeight') - 2 + 'px'; + var class_div = document.createElement("div"); + class_div.className = 'dygraph-label dygraph-xlabel'; + class_div.innerHTML = g.getOption('xlabel'); + this.xlabel_div_.appendChild(class_div); + div.appendChild(this.xlabel_div_); + } + if (g.getOption('ylabel')) { + // It would make sense to shift the chart here to make room for the y-axis + // label, but the default yAxisLabelWidth is large enough that this results + // in overly-padded charts. The y-axis label should fit fine. If it + // doesn't, the yAxisLabelWidth option can be increased. + var y_rect = e.reserveSpaceLeft(0); + this.ylabel_div_ = createRotatedDiv(g, y_rect, 1, + // primary (left) y-axis + 'dygraph-label dygraph-ylabel', g.getOption('ylabel')); + div.appendChild(this.ylabel_div_); + } + if (g.getOption('y2label') && g.numAxes() == 2) { + // same logic applies here as for ylabel. + var y2_rect = e.reserveSpaceRight(0); + this.y2label_div_ = createRotatedDiv(g, y2_rect, 2, + // secondary (right) y-axis + 'dygraph-label dygraph-y2label', g.getOption('y2label')); + div.appendChild(this.y2label_div_); + } +}; +chart_labels.prototype.didDrawChart = function (e) { + var g = e.dygraph; + if (this.title_div_) { + this.title_div_.children[0].innerHTML = g.getOption('title'); + } + if (this.xlabel_div_) { + this.xlabel_div_.children[0].innerHTML = g.getOption('xlabel'); + } + if (this.ylabel_div_) { + this.ylabel_div_.children[0].children[0].innerHTML = g.getOption('ylabel'); + } + if (this.y2label_div_) { + this.y2label_div_.children[0].children[0].innerHTML = g.getOption('y2label'); + } +}; +chart_labels.prototype.clearChart = function () {}; +chart_labels.prototype.destroy = function () { + this.detachLabels_(); +}; +var _default = chart_labels; +exports["default"] = _default; +module.exports = exports.default; + +},{}],"dygraphs/src/plugins/grid.js":[function(require,module,exports){ +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ +/*global Dygraph:false */ + +/* + +Current bits of jankiness: +- Direct layout access +- Direct area access + +*/ + +"use strict"; + +/** + * Draws the gridlines, i.e. the gray horizontal & vertical lines running the + * length of the chart. + * + * @constructor + */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var grid = function grid() {}; +grid.prototype.toString = function () { + return "Gridline Plugin"; +}; +grid.prototype.activate = function (g) { + return { + willDrawChart: this.willDrawChart + }; +}; +grid.prototype.willDrawChart = function (e) { + // Draw the new X/Y grid. Lines appear crisper when pixels are rounded to + // half-integers. This prevents them from drawing in two rows/cols. + var g = e.dygraph; + var ctx = e.drawingContext; + var layout = g.layout_; + var area = e.dygraph.plotter_.area; + function halfUp(x) { + return Math.round(x) + 0.5; + } + function halfDown(y) { + return Math.round(y) - 0.5; + } + var x, y, i, ticks; + if (g.getOptionForAxis('drawGrid', 'y')) { + var axes = ["y", "y2"]; + var strokeStyles = [], + lineWidths = [], + drawGrid = [], + stroking = [], + strokePattern = []; + for (var i = 0; i < axes.length; i++) { + drawGrid[i] = g.getOptionForAxis('drawGrid', axes[i]); + if (drawGrid[i]) { + strokeStyles[i] = g.getOptionForAxis('gridLineColor', axes[i]); + lineWidths[i] = g.getOptionForAxis('gridLineWidth', axes[i]); + strokePattern[i] = g.getOptionForAxis('gridLinePattern', axes[i]); + stroking[i] = strokePattern[i] && strokePattern[i].length >= 2; + } + } + ticks = layout.yticks; + ctx.save(); + // draw grids for the different y axes + ticks.forEach(function (tick) { + if (!tick.has_tick) return; + var axis = tick.axis; + if (drawGrid[axis]) { + ctx.save(); + if (stroking[axis]) { + if (ctx.setLineDash) ctx.setLineDash(strokePattern[axis]); + } + ctx.strokeStyle = strokeStyles[axis]; + ctx.lineWidth = lineWidths[axis]; + x = halfUp(area.x); + y = halfDown(area.y + tick.pos * area.h); + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x + area.w, y); + ctx.stroke(); + ctx.restore(); + } + }); + ctx.restore(); + } + + // draw grid for x axis + if (g.getOptionForAxis('drawGrid', 'x')) { + ticks = layout.xticks; + ctx.save(); + var strokePattern = g.getOptionForAxis('gridLinePattern', 'x'); + var stroking = strokePattern && strokePattern.length >= 2; + if (stroking) { + if (ctx.setLineDash) ctx.setLineDash(strokePattern); + } + ctx.strokeStyle = g.getOptionForAxis('gridLineColor', 'x'); + ctx.lineWidth = g.getOptionForAxis('gridLineWidth', 'x'); + ticks.forEach(function (tick) { + if (!tick.has_tick) return; + x = halfUp(area.x + tick.pos * area.w); + y = halfDown(area.y + area.h); + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x, area.y); + ctx.stroke(); + }); + if (stroking) { + if (ctx.setLineDash) ctx.setLineDash([]); + } + ctx.restore(); + } +}; +grid.prototype.destroy = function () {}; +var _default = grid; +exports["default"] = _default; +module.exports = exports.default; + +},{}],"dygraphs/src/plugins/legend.js":[function(require,module,exports){ +/** + * @license + * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ +/*global Dygraph:false */ + +/* +Current bits of jankiness: +- Uses two private APIs: + 1. Dygraph.optionsViewForAxis_ + 2. dygraph.plotter_.area +- Registers for a "predraw" event, which should be renamed. +- I call calculateEmWidthInDiv more often than needed. +*/ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("../dygraph-utils")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +/** + * Creates the legend, which appears when the user hovers over the chart. + * The legend can be either a user-specified or generated div. + * + * @constructor + */ +var Legend = function Legend() { + this.legend_div_ = null; + this.is_generated_div_ = false; // do we own this div, or was it user-specified? +}; + +Legend.prototype.toString = function () { + return "Legend Plugin"; +}; + +/** + * This is called during the dygraph constructor, after options have been set + * but before the data is available. + * + * Proper tasks to do here include: + * - Reading your own options + * - DOM manipulation + * - Registering event listeners + * + * @param {Dygraph} g Graph instance. + * @return {object.} Mapping of event names to callbacks. + */ +Legend.prototype.activate = function (g) { + var div; + var userLabelsDiv = g.getOption('labelsDiv'); + if (userLabelsDiv && null !== userLabelsDiv) { + if (typeof userLabelsDiv == "string" || userLabelsDiv instanceof String) { + div = document.getElementById(userLabelsDiv); + } else { + div = userLabelsDiv; + } + } else { + div = document.createElement("div"); + div.className = "dygraph-legend"; + // TODO(danvk): come up with a cleaner way to expose this. + g.graphDiv.appendChild(div); + this.is_generated_div_ = true; + } + this.legend_div_ = div; + this.one_em_width_ = 10; // just a guess, will be updated. + + return { + select: this.select, + deselect: this.deselect, + // TODO(danvk): rethink the name "predraw" before we commit to it in any API. + predraw: this.predraw, + didDrawChart: this.didDrawChart + }; +}; + +// Needed for dashed lines. +var calculateEmWidthInDiv = function calculateEmWidthInDiv(div) { + var sizeSpan = document.createElement('span'); + sizeSpan.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;'); + div.appendChild(sizeSpan); + var oneEmWidth = sizeSpan.offsetWidth; + div.removeChild(sizeSpan); + return oneEmWidth; +}; +var escapeHTML = function escapeHTML(str) { + return str.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); +}; +Legend.prototype.select = function (e) { + var xValue = e.selectedX; + var points = e.selectedPoints; + var row = e.selectedRow; + var legendMode = e.dygraph.getOption('legend'); + if (legendMode === 'never') { + this.legend_div_.style.display = 'none'; + return; + } + var html = Legend.generateLegendHTML(e.dygraph, xValue, points, this.one_em_width_, row); + if (html instanceof Node && html.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + this.legend_div_.innerHTML = ''; + this.legend_div_.appendChild(html); + } else this.legend_div_.innerHTML = html; + // must be done now so offsetWidth isn’t 0… + this.legend_div_.style.display = ''; + if (legendMode === 'follow') { + // create floating legend div + var area = e.dygraph.plotter_.area; + var labelsDivWidth = this.legend_div_.offsetWidth; + var yAxisLabelWidth = e.dygraph.getOptionForAxis('axisLabelWidth', 'y'); + // find the closest data point by checking the currently highlighted series, + // or fall back to using the first data point available + var highlightSeries = e.dygraph.getHighlightSeries(); + var point; + if (highlightSeries) { + point = points.find(function (p) { + return p.name === highlightSeries; + }); + if (!point) point = points[0]; + } else point = points[0]; + // determine floating [left, top] coordinates of the legend div + // within the plotter_ area + // offset 50 px to the right and down from the first selection point + // 50 px is guess based on mouse cursor size + var followOffsetX = e.dygraph.getNumericOption('legendFollowOffsetX'); + var followOffsetY = e.dygraph.getNumericOption('legendFollowOffsetY'); + var leftLegend = point.x * area.w + followOffsetX; + var topLegend = point.y * area.h + followOffsetY; + + // if legend floats to end of the chart area, it flips to the other + // side of the selection point + if (leftLegend + labelsDivWidth + 1 > area.w) { + leftLegend = leftLegend - 2 * followOffsetX - labelsDivWidth - (yAxisLabelWidth - area.x); + } + this.legend_div_.style.left = yAxisLabelWidth + leftLegend + "px"; + this.legend_div_.style.top = topLegend + "px"; + } else if (legendMode === 'onmouseover' && this.is_generated_div_) { + // synchronise this with Legend.prototype.predraw below + var area = e.dygraph.plotter_.area; + var labelsDivWidth = this.legend_div_.offsetWidth; + this.legend_div_.style.left = area.x + area.w - labelsDivWidth - 1 + "px"; + this.legend_div_.style.top = area.y + "px"; + } +}; +Legend.prototype.deselect = function (e) { + var legendMode = e.dygraph.getOption('legend'); + if (legendMode !== 'always') { + this.legend_div_.style.display = "none"; + } + + // Have to do this every time, since styles might have changed. + var oneEmWidth = calculateEmWidthInDiv(this.legend_div_); + this.one_em_width_ = oneEmWidth; + var html = Legend.generateLegendHTML(e.dygraph, undefined, undefined, oneEmWidth, null); + if (html instanceof Node && html.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + this.legend_div_.innerHTML = ''; + this.legend_div_.appendChild(html); + } else this.legend_div_.innerHTML = html; +}; +Legend.prototype.didDrawChart = function (e) { + this.deselect(e); +}; + +// Right edge should be flush with the right edge of the charting area (which +// may not be the same as the right edge of the div, if we have two y-axes). +// TODO(danvk): is any of this really necessary? Could just set "right" in "activate". +/** + * Position the labels div so that: + * - its right edge is flush with the right edge of the charting area + * - its top edge is flush with the top edge of the charting area + * @private + */ +Legend.prototype.predraw = function (e) { + // Don't touch a user-specified labelsDiv. + if (!this.is_generated_div_) return; + + // TODO(danvk): only use real APIs for this. + e.dygraph.graphDiv.appendChild(this.legend_div_); + // synchronise this with Legend.prototype.select above + var area = e.dygraph.plotter_.area; + var labelsDivWidth = this.legend_div_.offsetWidth; + this.legend_div_.style.left = area.x + area.w - labelsDivWidth - 1 + "px"; + this.legend_div_.style.top = area.y + "px"; +}; + +/** + * Called when dygraph.destroy() is called. + * You should null out any references and detach any DOM elements. + */ +Legend.prototype.destroy = function () { + this.legend_div_ = null; +}; + +/** + * Generates HTML for the legend which is displayed when hovering over the + * chart. If no selected points are specified, a default legend is returned + * (this may just be the empty string). + * @param {number} x The x-value of the selected points. + * @param {Object} sel_points List of selected points for the given + * x-value. Should have properties like 'name', 'yval' and 'canvasy'. + * @param {number} oneEmWidth The pixel width for 1em in the legend. Only + * relevant when displaying a legend with no selection (i.e. {legend: + * 'always'}) and with dashed lines. + * @param {number} row The selected row index. + * @private + */ +Legend.generateLegendHTML = function (g, x, sel_points, oneEmWidth, row) { + // Data about the selection to pass to legendFormatter + var data = { + dygraph: g, + x: x, + i: row, + series: [] + }; + var labelToSeries = {}; + var labels = g.getLabels(); + if (labels) { + for (var i = 1; i < labels.length; i++) { + var series = g.getPropertiesForSeries(labels[i]); + var strokePattern = g.getOption('strokePattern', labels[i]); + var seriesData = { + dashHTML: generateLegendDashHTML(strokePattern, series.color, oneEmWidth), + label: labels[i], + labelHTML: escapeHTML(labels[i]), + isVisible: series.visible, + color: series.color + }; + data.series.push(seriesData); + labelToSeries[labels[i]] = seriesData; + } + } + if (typeof x !== 'undefined') { + var xOptView = g.optionsViewForAxis_('x'); + var xvf = xOptView('valueFormatter'); + data.xHTML = xvf.call(g, x, xOptView, labels[0], g, row, 0); + var yOptViews = []; + var num_axes = g.numAxes(); + for (var i = 0; i < num_axes; i++) { + // TODO(danvk): remove this use of a private API + yOptViews[i] = g.optionsViewForAxis_('y' + (i ? 1 + i : '')); + } + var showZeros = g.getOption('labelsShowZeroValues'); + var highlightSeries = g.getHighlightSeries(); + for (i = 0; i < sel_points.length; i++) { + var pt = sel_points[i]; + var seriesData = labelToSeries[pt.name]; + seriesData.y = pt.yval; + if (pt.yval === 0 && !showZeros || isNaN(pt.canvasy)) { + seriesData.isVisible = false; + continue; + } + var series = g.getPropertiesForSeries(pt.name); + var yOptView = yOptViews[series.axis - 1]; + var fmtFunc = yOptView('valueFormatter'); + var yHTML = fmtFunc.call(g, pt.yval, yOptView, pt.name, g, row, labels.indexOf(pt.name)); + utils.update(seriesData, { + yHTML: yHTML + }); + if (pt.name == highlightSeries) { + seriesData.isHighlighted = true; + } + } + } + var formatter = g.getOption('legendFormatter') || Legend.defaultFormatter; + return formatter.call(g, data); +}; +Legend.defaultFormatter = function (data) { + var g = data.dygraph; + + // TODO(danvk): deprecate this option in place of {legend: 'never'} + // XXX should this logic be in the formatter? + if (g.getOption('showLabelsOnHighlight') !== true) return ''; + var sepLines = g.getOption('labelsSeparateLines'); + var html; + if (typeof data.x === 'undefined') { + // TODO: this check is duplicated in generateLegendHTML. Put it in one place. + if (g.getOption('legend') != 'always') { + return ''; + } + html = ''; + for (var i = 0; i < data.series.length; i++) { + var series = data.series[i]; + if (!series.isVisible) continue; + if (html !== '') html += sepLines ? '
    ' : ' '; + html += "").concat(series.dashHTML, " ").concat(series.labelHTML, ""); + } + return html; + } + html = data.xHTML + ':'; + for (var i = 0; i < data.series.length; i++) { + var series = data.series[i]; + if (!series.y && !series.yHTML) continue; + if (!series.isVisible) continue; + if (sepLines) html += '
    '; + var cls = series.isHighlighted ? ' class="highlight"' : ''; + html += " ").concat(series.labelHTML, ": ").concat(series.yHTML, ""); + } + return html; +}; + +/** + * Generates html for the "dash" displayed on the legend when using "legend: always". + * In particular, this works for dashed lines with any stroke pattern. It will + * try to scale the pattern to fit in 1em width. Or if small enough repeat the + * pattern for 1em width. + * + * @param strokePattern The pattern + * @param color The color of the series. + * @param oneEmWidth The width in pixels of 1em in the legend. + * @private + */ +// TODO(danvk): cache the results of this +function generateLegendDashHTML(strokePattern, color, oneEmWidth) { + // Easy, common case: a solid line + if (!strokePattern || strokePattern.length <= 1) { + return "
    "); + } + var i, j, paddingLeft, marginRight; + var strokePixelLength = 0, + segmentLoop = 0; + var normalizedPattern = []; + var loop; + + // Compute the length of the pixels including the first segment twice, + // since we repeat it. + for (i = 0; i <= strokePattern.length; i++) { + strokePixelLength += strokePattern[i % strokePattern.length]; + } + + // See if we can loop the pattern by itself at least twice. + loop = Math.floor(oneEmWidth / (strokePixelLength - strokePattern[0])); + if (loop > 1) { + // This pattern fits at least two times, no scaling just convert to em; + for (i = 0; i < strokePattern.length; i++) { + normalizedPattern[i] = strokePattern[i] / oneEmWidth; + } + // Since we are repeating the pattern, we don't worry about repeating the + // first segment in one draw. + segmentLoop = normalizedPattern.length; + } else { + // If the pattern doesn't fit in the legend we scale it to fit. + loop = 1; + for (i = 0; i < strokePattern.length; i++) { + normalizedPattern[i] = strokePattern[i] / strokePixelLength; + } + // For the scaled patterns we do redraw the first segment. + segmentLoop = normalizedPattern.length + 1; + } + + // Now make the pattern. + var dash = ""; + for (j = 0; j < loop; j++) { + for (i = 0; i < segmentLoop; i += 2) { + // The padding is the drawn segment. + paddingLeft = normalizedPattern[i % normalizedPattern.length]; + if (i < strokePattern.length) { + // The margin is the space segment. + marginRight = normalizedPattern[(i + 1) % normalizedPattern.length]; + } else { + // The repeated first segment has no right margin. + marginRight = 0; + } + dash += "
    "); + } + } + return dash; +} +var _default = Legend; +exports["default"] = _default; +module.exports = exports.default; + +},{"../dygraph-utils":"dygraphs/src/dygraph-utils.js"}],"dygraphs/src/plugins/range-selector.js":[function(require,module,exports){ +/** + * @license + * Copyright 2011 Paul Felix (paul.eric.felix@gmail.com) + * MIT-licenced: https://opensource.org/licenses/MIT + */ +/*global Dygraph:false,TouchEvent:false */ + +/** + * @fileoverview This file contains the RangeSelector plugin used to provide + * a timeline range selector widget for dygraphs. + */ + +/*global Dygraph:false */ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var utils = _interopRequireWildcard(require("../dygraph-utils")); +var _dygraphInteractionModel = _interopRequireDefault(require("../dygraph-interaction-model")); +var _iframeTarp = _interopRequireDefault(require("../iframe-tarp")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +var rangeSelector = function rangeSelector() { + this.hasTouchInterface_ = typeof TouchEvent != 'undefined'; + this.isMobileDevice_ = /mobile|android/gi.test(navigator.appVersion); + this.interfaceCreated_ = false; +}; +rangeSelector.prototype.toString = function () { + return "RangeSelector Plugin"; +}; +rangeSelector.prototype.activate = function (dygraph) { + this.dygraph_ = dygraph; + if (this.getOption_('showRangeSelector')) { + this.createInterface_(); + } + return { + layout: this.reserveSpace_, + predraw: this.renderStaticLayer_, + didDrawChart: this.renderInteractiveLayer_ + }; +}; +rangeSelector.prototype.destroy = function () { + this.bgcanvas_ = null; + this.fgcanvas_ = null; + this.leftZoomHandle_ = null; + this.rightZoomHandle_ = null; +}; + +//------------------------------------------------------------------ +// Private methods +//------------------------------------------------------------------ + +rangeSelector.prototype.getOption_ = function (name, opt_series) { + return this.dygraph_.getOption(name, opt_series); +}; +rangeSelector.prototype.setDefaultOption_ = function (name, value) { + this.dygraph_.attrs_[name] = value; +}; + +/** + * @private + * Creates the range selector elements and adds them to the graph. + */ +rangeSelector.prototype.createInterface_ = function () { + this.createCanvases_(); + this.createZoomHandles_(); + this.initInteraction_(); + + // Range selector and animatedZooms have a bad interaction. See issue 359. + if (this.getOption_('animatedZooms')) { + console.warn('Animated zooms and range selector are not compatible; disabling animatedZooms.'); + this.dygraph_.updateOptions({ + animatedZooms: false + }, true); + } + this.interfaceCreated_ = true; + this.addToGraph_(); +}; + +/** + * @private + * Adds the range selector to the graph. + */ +rangeSelector.prototype.addToGraph_ = function () { + var graphDiv = this.graphDiv_ = this.dygraph_.graphDiv; + graphDiv.appendChild(this.bgcanvas_); + graphDiv.appendChild(this.fgcanvas_); + graphDiv.appendChild(this.leftZoomHandle_); + graphDiv.appendChild(this.rightZoomHandle_); +}; + +/** + * @private + * Removes the range selector from the graph. + */ +rangeSelector.prototype.removeFromGraph_ = function () { + var graphDiv = this.graphDiv_; + graphDiv.removeChild(this.bgcanvas_); + graphDiv.removeChild(this.fgcanvas_); + graphDiv.removeChild(this.leftZoomHandle_); + graphDiv.removeChild(this.rightZoomHandle_); + this.graphDiv_ = null; +}; + +/** + * @private + * Called by Layout to allow range selector to reserve its space. + */ +rangeSelector.prototype.reserveSpace_ = function (e) { + if (this.getOption_('showRangeSelector')) { + e.reserveSpaceBottom(this.getOption_('rangeSelectorHeight') + 4); + } +}; + +/** + * @private + * Renders the static portion of the range selector at the predraw stage. + */ +rangeSelector.prototype.renderStaticLayer_ = function () { + if (!this.updateVisibility_()) { + return; + } + this.resize_(); + this.drawStaticLayer_(); +}; + +/** + * @private + * Renders the interactive portion of the range selector after the chart has been drawn. + */ +rangeSelector.prototype.renderInteractiveLayer_ = function () { + if (!this.updateVisibility_() || this.isChangingRange_) { + return; + } + this.placeZoomHandles_(); + this.drawInteractiveLayer_(); +}; + +/** + * @private + * Check to see if the range selector is enabled/disabled and update visibility accordingly. + */ +rangeSelector.prototype.updateVisibility_ = function () { + var enabled = this.getOption_('showRangeSelector'); + if (enabled) { + if (!this.interfaceCreated_) { + this.createInterface_(); + } else if (!this.graphDiv_ || !this.graphDiv_.parentNode) { + this.addToGraph_(); + } + } else if (this.graphDiv_) { + this.removeFromGraph_(); + var dygraph = this.dygraph_; + setTimeout(function () { + dygraph.width_ = 0; + dygraph.resize(); + }, 1); + } + return enabled; +}; + +/** + * @private + * Resizes the range selector. + */ +rangeSelector.prototype.resize_ = function () { + function setElementRect(canvas, context, rect, pixelRatioOption) { + var canvasScale = pixelRatioOption || utils.getContextPixelRatio(context); + canvas.style.top = rect.y + 'px'; + canvas.style.left = rect.x + 'px'; + canvas.width = rect.w * canvasScale; + canvas.height = rect.h * canvasScale; + canvas.style.width = rect.w + 'px'; + canvas.style.height = rect.h + 'px'; + if (canvasScale != 1) { + context.scale(canvasScale, canvasScale); + } + } + var plotArea = this.dygraph_.layout_.getPlotArea(); + var xAxisLabelHeight = 0; + if (this.dygraph_.getOptionForAxis('drawAxis', 'x')) { + xAxisLabelHeight = this.getOption_('xAxisHeight') || this.getOption_('axisLabelFontSize') + 2 * this.getOption_('axisTickSize'); + } + this.canvasRect_ = { + x: plotArea.x, + y: plotArea.y + plotArea.h + xAxisLabelHeight + 4, + w: plotArea.w, + h: this.getOption_('rangeSelectorHeight') + }; + var pixelRatioOption = this.dygraph_.getNumericOption('pixelRatio'); + setElementRect(this.bgcanvas_, this.bgcanvas_ctx_, this.canvasRect_, pixelRatioOption); + setElementRect(this.fgcanvas_, this.fgcanvas_ctx_, this.canvasRect_, pixelRatioOption); +}; + +/** + * @private + * Creates the background and foreground canvases. + */ +rangeSelector.prototype.createCanvases_ = function () { + this.bgcanvas_ = utils.createCanvas(); + this.bgcanvas_.className = 'dygraph-rangesel-bgcanvas'; + this.bgcanvas_.style.position = 'absolute'; + this.bgcanvas_.style.zIndex = 9; + this.bgcanvas_ctx_ = utils.getContext(this.bgcanvas_); + this.fgcanvas_ = utils.createCanvas(); + this.fgcanvas_.className = 'dygraph-rangesel-fgcanvas'; + this.fgcanvas_.style.position = 'absolute'; + this.fgcanvas_.style.zIndex = 9; + this.fgcanvas_.style.cursor = 'default'; + this.fgcanvas_ctx_ = utils.getContext(this.fgcanvas_); +}; + +/** + * @private + * Creates the zoom handle elements. + */ +rangeSelector.prototype.createZoomHandles_ = function () { + var img = new Image(); + img.className = 'dygraph-rangesel-zoomhandle'; + img.style.position = 'absolute'; + img.style.zIndex = 10; + img.style.visibility = 'hidden'; // Initially hidden so they don't show up in the wrong place. + img.style.cursor = 'col-resize'; + // TODO: change image to more options + img.width = 9; + img.height = 16; + img.src = 'data:image/png;base64,' + 'iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAA' + 'zwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENv' + 'bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl' + '6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7s' + 'qSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII='; + if (this.isMobileDevice_) { + img.width *= 2; + img.height *= 2; + } + this.leftZoomHandle_ = img; + this.rightZoomHandle_ = img.cloneNode(false); +}; + +/** + * @private + * Sets up the interaction for the range selector. + */ +rangeSelector.prototype.initInteraction_ = function () { + var self = this; + var topElem = document; + var clientXLast = 0; + var handle = null; + var isZooming = false; + var isPanning = false; + var dynamic = !this.isMobileDevice_; + + // We cover iframes during mouse interactions. See comments in + // dygraph-utils.js for more info on why this is a good idea. + var tarp = new _iframeTarp["default"](); + + // functions, defined below. Defining them this way (rather than with + // "function foo() {...}") makes JSHint happy. + var toXDataWindow, onZoomStart, onZoom, _onZoomEnd, doZoom, isMouseInPanZone, onPanStart, onPan, _onPanEnd, doPan, onCanvasHover; + + // Touch event functions + var onZoomHandleTouchEvent, onCanvasTouchEvent, addTouchEvents; + toXDataWindow = function toXDataWindow(zoomHandleStatus) { + var xDataLimits = self.dygraph_.xAxisExtremes(); + var fact = (xDataLimits[1] - xDataLimits[0]) / self.canvasRect_.w; + var xDataMin = xDataLimits[0] + (zoomHandleStatus.leftHandlePos - self.canvasRect_.x) * fact; + var xDataMax = xDataLimits[0] + (zoomHandleStatus.rightHandlePos - self.canvasRect_.x) * fact; + return [xDataMin, xDataMax]; + }; + onZoomStart = function onZoomStart(e) { + utils.cancelEvent(e); + isZooming = true; + clientXLast = e.clientX; + handle = e.target ? e.target : e.srcElement; + if (e.type === 'mousedown' || e.type === 'dragstart') { + // These events are removed manually. + utils.addEvent(topElem, 'mousemove', onZoom); + utils.addEvent(topElem, 'mouseup', _onZoomEnd); + } + self.fgcanvas_.style.cursor = 'col-resize'; + tarp.cover(); + return true; + }; + onZoom = function onZoom(e) { + if (!isZooming) { + return false; + } + utils.cancelEvent(e); + var delX = e.clientX - clientXLast; + if (Math.abs(delX) < 4) { + return true; + } + clientXLast = e.clientX; + + // Move handle. + var zoomHandleStatus = self.getZoomHandleStatus_(); + var newPos; + if (handle == self.leftZoomHandle_) { + newPos = zoomHandleStatus.leftHandlePos + delX; + newPos = Math.min(newPos, zoomHandleStatus.rightHandlePos - handle.width - 3); + newPos = Math.max(newPos, self.canvasRect_.x); + } else { + newPos = zoomHandleStatus.rightHandlePos + delX; + newPos = Math.min(newPos, self.canvasRect_.x + self.canvasRect_.w); + newPos = Math.max(newPos, zoomHandleStatus.leftHandlePos + handle.width + 3); + } + var halfHandleWidth = handle.width / 2; + handle.style.left = newPos - halfHandleWidth + 'px'; + self.drawInteractiveLayer_(); + + // Zoom on the fly. + if (dynamic) { + doZoom(); + } + return true; + }; + _onZoomEnd = function onZoomEnd(e) { + if (!isZooming) { + return false; + } + isZooming = false; + tarp.uncover(); + utils.removeEvent(topElem, 'mousemove', onZoom); + utils.removeEvent(topElem, 'mouseup', _onZoomEnd); + self.fgcanvas_.style.cursor = 'default'; + + // If on a slower device, zoom now. + if (!dynamic) { + doZoom(); + } + return true; + }; + doZoom = function doZoom() { + try { + var zoomHandleStatus = self.getZoomHandleStatus_(); + self.isChangingRange_ = true; + if (!zoomHandleStatus.isZoomed) { + self.dygraph_.resetZoom(); + } else { + var xDataWindow = toXDataWindow(zoomHandleStatus); + self.dygraph_.doZoomXDates_(xDataWindow[0], xDataWindow[1]); + } + } finally { + self.isChangingRange_ = false; + } + }; + isMouseInPanZone = function isMouseInPanZone(e) { + var rect = self.leftZoomHandle_.getBoundingClientRect(); + var leftHandleClientX = rect.left + rect.width / 2; + rect = self.rightZoomHandle_.getBoundingClientRect(); + var rightHandleClientX = rect.left + rect.width / 2; + return e.clientX > leftHandleClientX && e.clientX < rightHandleClientX; + }; + onPanStart = function onPanStart(e) { + if (!isPanning && isMouseInPanZone(e) && self.getZoomHandleStatus_().isZoomed) { + utils.cancelEvent(e); + isPanning = true; + clientXLast = e.clientX; + if (e.type === 'mousedown') { + // These events are removed manually. + utils.addEvent(topElem, 'mousemove', onPan); + utils.addEvent(topElem, 'mouseup', _onPanEnd); + } + return true; + } + return false; + }; + onPan = function onPan(e) { + if (!isPanning) { + return false; + } + utils.cancelEvent(e); + var delX = e.clientX - clientXLast; + if (Math.abs(delX) < 4) { + return true; + } + clientXLast = e.clientX; + + // Move range view + var zoomHandleStatus = self.getZoomHandleStatus_(); + var leftHandlePos = zoomHandleStatus.leftHandlePos; + var rightHandlePos = zoomHandleStatus.rightHandlePos; + var rangeSize = rightHandlePos - leftHandlePos; + if (leftHandlePos + delX <= self.canvasRect_.x) { + leftHandlePos = self.canvasRect_.x; + rightHandlePos = leftHandlePos + rangeSize; + } else if (rightHandlePos + delX >= self.canvasRect_.x + self.canvasRect_.w) { + rightHandlePos = self.canvasRect_.x + self.canvasRect_.w; + leftHandlePos = rightHandlePos - rangeSize; + } else { + leftHandlePos += delX; + rightHandlePos += delX; + } + var halfHandleWidth = self.leftZoomHandle_.width / 2; + self.leftZoomHandle_.style.left = leftHandlePos - halfHandleWidth + 'px'; + self.rightZoomHandle_.style.left = rightHandlePos - halfHandleWidth + 'px'; + self.drawInteractiveLayer_(); + + // Do pan on the fly. + if (dynamic) { + doPan(); + } + return true; + }; + _onPanEnd = function onPanEnd(e) { + if (!isPanning) { + return false; + } + isPanning = false; + utils.removeEvent(topElem, 'mousemove', onPan); + utils.removeEvent(topElem, 'mouseup', _onPanEnd); + // If on a slower device, do pan now. + if (!dynamic) { + doPan(); + } + return true; + }; + doPan = function doPan() { + try { + self.isChangingRange_ = true; + self.dygraph_.dateWindow_ = toXDataWindow(self.getZoomHandleStatus_()); + self.dygraph_.drawGraph_(false); + } finally { + self.isChangingRange_ = false; + } + }; + onCanvasHover = function onCanvasHover(e) { + if (isZooming || isPanning) { + return; + } + var cursor = isMouseInPanZone(e) ? 'move' : 'default'; + if (cursor != self.fgcanvas_.style.cursor) { + self.fgcanvas_.style.cursor = cursor; + } + }; + onZoomHandleTouchEvent = function onZoomHandleTouchEvent(e) { + if (e.type == 'touchstart' && e.targetTouches.length == 1) { + if (onZoomStart(e.targetTouches[0])) { + utils.cancelEvent(e); + } + } else if (e.type == 'touchmove' && e.targetTouches.length == 1) { + if (onZoom(e.targetTouches[0])) { + utils.cancelEvent(e); + } + } else { + _onZoomEnd(e); + } + }; + onCanvasTouchEvent = function onCanvasTouchEvent(e) { + if (e.type == 'touchstart' && e.targetTouches.length == 1) { + if (onPanStart(e.targetTouches[0])) { + utils.cancelEvent(e); + } + } else if (e.type == 'touchmove' && e.targetTouches.length == 1) { + if (onPan(e.targetTouches[0])) { + utils.cancelEvent(e); + } + } else { + _onPanEnd(e); + } + }; + addTouchEvents = function addTouchEvents(elem, fn) { + var types = ['touchstart', 'touchend', 'touchmove', 'touchcancel']; + for (var i = 0; i < types.length; i++) { + self.dygraph_.addAndTrackEvent(elem, types[i], fn); + } + }; + this.setDefaultOption_('interactionModel', _dygraphInteractionModel["default"].dragIsPanInteractionModel); + this.setDefaultOption_('panEdgeFraction', 0.0001); + var dragStartEvent = window.opera ? 'mousedown' : 'dragstart'; + this.dygraph_.addAndTrackEvent(this.leftZoomHandle_, dragStartEvent, onZoomStart); + this.dygraph_.addAndTrackEvent(this.rightZoomHandle_, dragStartEvent, onZoomStart); + this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousedown', onPanStart); + this.dygraph_.addAndTrackEvent(this.fgcanvas_, 'mousemove', onCanvasHover); + + // Touch events + if (this.hasTouchInterface_) { + addTouchEvents(this.leftZoomHandle_, onZoomHandleTouchEvent); + addTouchEvents(this.rightZoomHandle_, onZoomHandleTouchEvent); + addTouchEvents(this.fgcanvas_, onCanvasTouchEvent); + } +}; + +/** + * @private + * Draws the static layer in the background canvas. + */ +rangeSelector.prototype.drawStaticLayer_ = function () { + var ctx = this.bgcanvas_ctx_; + ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); + try { + this.drawMiniPlot_(); + } catch (ex) { + console.warn(ex); + } + var margin = 0.5; + this.bgcanvas_ctx_.lineWidth = this.getOption_('rangeSelectorBackgroundLineWidth'); + ctx.strokeStyle = this.getOption_('rangeSelectorBackgroundStrokeColor'); + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(margin, this.canvasRect_.h - margin); + ctx.lineTo(this.canvasRect_.w - margin, this.canvasRect_.h - margin); + ctx.lineTo(this.canvasRect_.w - margin, margin); + ctx.stroke(); +}; + +/** + * @private + * Draws the mini plot in the background canvas. + */ +rangeSelector.prototype.drawMiniPlot_ = function () { + var fillStyle = this.getOption_('rangeSelectorPlotFillColor'); + var fillGradientStyle = this.getOption_('rangeSelectorPlotFillGradientColor'); + var strokeStyle = this.getOption_('rangeSelectorPlotStrokeColor'); + if (!fillStyle && !strokeStyle) { + return; + } + var stepPlot = this.getOption_('stepPlot'); + var combinedSeriesData = this.computeCombinedSeriesAndLimits_(); + var yRange = combinedSeriesData.yMax - combinedSeriesData.yMin; + + // Draw the mini plot. + var ctx = this.bgcanvas_ctx_; + var margin = 0.5; + var xExtremes = this.dygraph_.xAxisExtremes(); + var xRange = Math.max(xExtremes[1] - xExtremes[0], 1.e-30); + var xFact = (this.canvasRect_.w - margin) / xRange; + var yFact = (this.canvasRect_.h - margin) / yRange; + var canvasWidth = this.canvasRect_.w - margin; + var canvasHeight = this.canvasRect_.h - margin; + var prevX = null, + prevY = null; + ctx.beginPath(); + ctx.moveTo(margin, canvasHeight); + for (var i = 0; i < combinedSeriesData.data.length; i++) { + var dataPoint = combinedSeriesData.data[i]; + var x = dataPoint[0] !== null ? (dataPoint[0] - xExtremes[0]) * xFact : NaN; + var y = dataPoint[1] !== null ? canvasHeight - (dataPoint[1] - combinedSeriesData.yMin) * yFact : NaN; + + // Skip points that don't change the x-value. Overly fine-grained points + // can cause major slowdowns with the ctx.fill() call below. + if (!stepPlot && prevX !== null && Math.round(x) == Math.round(prevX)) { + continue; + } + if (isFinite(x) && isFinite(y)) { + if (prevX === null) { + ctx.lineTo(x, canvasHeight); + } else if (stepPlot) { + ctx.lineTo(x, prevY); + } + ctx.lineTo(x, y); + prevX = x; + prevY = y; + } else { + if (prevX !== null) { + if (stepPlot) { + ctx.lineTo(x, prevY); + ctx.lineTo(x, canvasHeight); + } else { + ctx.lineTo(prevX, canvasHeight); + } + } + prevX = prevY = null; + } + } + ctx.lineTo(canvasWidth, canvasHeight); + ctx.closePath(); + if (fillStyle) { + var lingrad = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, canvasHeight); + if (fillGradientStyle) { + lingrad.addColorStop(0, fillGradientStyle); + } + lingrad.addColorStop(1, fillStyle); + this.bgcanvas_ctx_.fillStyle = lingrad; + ctx.fill(); + } + if (strokeStyle) { + this.bgcanvas_ctx_.strokeStyle = strokeStyle; + this.bgcanvas_ctx_.lineWidth = this.getOption_('rangeSelectorPlotLineWidth'); + ctx.stroke(); + } +}; + +/** + * @private + * Computes and returns the combined series data along with min/max for the mini plot. + * The combined series consists of averaged values for all series. + * When series have error bars, the error bars are ignored. + * @return {Object} An object containing combined series array, ymin, ymax. + */ +rangeSelector.prototype.computeCombinedSeriesAndLimits_ = function () { + var g = this.dygraph_; + var logscale = this.getOption_('logscale'); + var i; + + // Select series to combine. By default, all series are combined. + var numColumns = g.numColumns(); + var labels = g.getLabels(); + var includeSeries = new Array(numColumns); + var anySet = false; + var visibility = g.visibility(); + var inclusion = []; + for (i = 1; i < numColumns; i++) { + var include = this.getOption_('showInRangeSelector', labels[i]); + inclusion.push(include); + if (include !== null) anySet = true; // it's set explicitly for this series + } + + if (anySet) { + for (i = 1; i < numColumns; i++) { + includeSeries[i] = inclusion[i - 1]; + } + } else { + for (i = 1; i < numColumns; i++) { + includeSeries[i] = visibility[i - 1]; + } + } + + // Create a combined series (average of selected series values). + // TODO(danvk): short-circuit if there's only one series. + var rolledSeries = []; + var dataHandler = g.dataHandler_; + var options = g.attributes_; + for (i = 1; i < g.numColumns(); i++) { + if (!includeSeries[i]) continue; + var series = dataHandler.extractSeries(g.rawData_, i, options); + if (g.rollPeriod() > 1) { + series = dataHandler.rollingAverage(series, g.rollPeriod(), options, i); + } + rolledSeries.push(series); + } + var combinedSeries = []; + for (i = 0; i < rolledSeries[0].length; i++) { + var sum = 0; + var count = 0; + for (var j = 0; j < rolledSeries.length; j++) { + var y = rolledSeries[j][i][1]; + if (y === null || isNaN(y)) continue; + count++; + sum += y; + } + combinedSeries.push([rolledSeries[0][i][0], sum / count]); + } + + // Compute the y range. + var yMin = Number.MAX_VALUE; + var yMax = -Number.MAX_VALUE; + for (i = 0; i < combinedSeries.length; i++) { + var yVal = combinedSeries[i][1]; + if (yVal !== null && isFinite(yVal) && (!logscale || yVal > 0)) { + yMin = Math.min(yMin, yVal); + yMax = Math.max(yMax, yVal); + } + } + + // Convert Y data to log scale if needed. + // Also, expand the Y range to compress the mini plot a little. + var extraPercent = 0.25; + if (logscale) { + yMax = utils.log10(yMax); + yMax += yMax * extraPercent; + yMin = utils.log10(yMin); + for (i = 0; i < combinedSeries.length; i++) { + combinedSeries[i][1] = utils.log10(combinedSeries[i][1]); + } + } else { + var yExtra; + var yRange = yMax - yMin; + if (yRange <= Number.MIN_VALUE) { + yExtra = yMax * extraPercent; + } else { + yExtra = yRange * extraPercent; + } + yMax += yExtra; + yMin -= yExtra; + } + return { + data: combinedSeries, + yMin: yMin, + yMax: yMax + }; +}; + +/** + * @private + * Places the zoom handles in the proper position based on the current X data window. + */ +rangeSelector.prototype.placeZoomHandles_ = function () { + var xExtremes = this.dygraph_.xAxisExtremes(); + var xWindowLimits = this.dygraph_.xAxisRange(); + var xRange = xExtremes[1] - xExtremes[0]; + var leftPercent = Math.max(0, (xWindowLimits[0] - xExtremes[0]) / xRange); + var rightPercent = Math.max(0, (xExtremes[1] - xWindowLimits[1]) / xRange); + var leftCoord = this.canvasRect_.x + this.canvasRect_.w * leftPercent; + var rightCoord = this.canvasRect_.x + this.canvasRect_.w * (1 - rightPercent); + var handleTop = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height) / 2); + var halfHandleWidth = this.leftZoomHandle_.width / 2; + this.leftZoomHandle_.style.left = leftCoord - halfHandleWidth + 'px'; + this.leftZoomHandle_.style.top = handleTop + 'px'; + this.rightZoomHandle_.style.left = rightCoord - halfHandleWidth + 'px'; + this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top; + this.leftZoomHandle_.style.visibility = 'visible'; + this.rightZoomHandle_.style.visibility = 'visible'; +}; + +/** + * @private + * Draws the interactive layer in the foreground canvas. + */ +rangeSelector.prototype.drawInteractiveLayer_ = function () { + var ctx = this.fgcanvas_ctx_; + ctx.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); + var margin = 1; + var width = this.canvasRect_.w - margin; + var height = this.canvasRect_.h - margin; + var zoomHandleStatus = this.getZoomHandleStatus_(); + ctx.strokeStyle = this.getOption_('rangeSelectorForegroundStrokeColor'); + ctx.lineWidth = this.getOption_('rangeSelectorForegroundLineWidth'); + if (!zoomHandleStatus.isZoomed) { + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(margin, height); + ctx.lineTo(width, height); + ctx.lineTo(width, margin); + ctx.stroke(); + } else { + var leftHandleCanvasPos = Math.max(margin, zoomHandleStatus.leftHandlePos - this.canvasRect_.x); + var rightHandleCanvasPos = Math.min(width, zoomHandleStatus.rightHandlePos - this.canvasRect_.x); + var veilColour = this.getOption_('rangeSelectorVeilColour'); + ctx.fillStyle = veilColour ? veilColour : 'rgba(240, 240, 240, ' + this.getOption_('rangeSelectorAlpha').toString() + ')'; + ctx.fillRect(0, 0, leftHandleCanvasPos, this.canvasRect_.h); + ctx.fillRect(rightHandleCanvasPos, 0, this.canvasRect_.w - rightHandleCanvasPos, this.canvasRect_.h); + ctx.beginPath(); + ctx.moveTo(margin, margin); + ctx.lineTo(leftHandleCanvasPos, margin); + ctx.lineTo(leftHandleCanvasPos, height); + ctx.lineTo(rightHandleCanvasPos, height); + ctx.lineTo(rightHandleCanvasPos, margin); + ctx.lineTo(width, margin); + ctx.stroke(); + } +}; + +/** + * @private + * Returns the current zoom handle position information. + * @return {Object} The zoom handle status. + */ +rangeSelector.prototype.getZoomHandleStatus_ = function () { + var halfHandleWidth = this.leftZoomHandle_.width / 2; + var leftHandlePos = parseFloat(this.leftZoomHandle_.style.left) + halfHandleWidth; + var rightHandlePos = parseFloat(this.rightZoomHandle_.style.left) + halfHandleWidth; + return { + leftHandlePos: leftHandlePos, + rightHandlePos: rightHandlePos, + isZoomed: leftHandlePos - 1 > this.canvasRect_.x || rightHandlePos + 1 < this.canvasRect_.x + this.canvasRect_.w + }; +}; +var _default = rangeSelector; +exports["default"] = _default; +module.exports = exports.default; + +},{"../dygraph-interaction-model":"dygraphs/src/dygraph-interaction-model.js","../dygraph-utils":"dygraphs/src/dygraph-utils.js","../iframe-tarp":"dygraphs/src/iframe-tarp.js"}]},{},[1,"dygraphs/src/dygraph.js"]);var x=r("dygraphs/src/dygraph.js");x._require._b=r;return x}); +//# sourceMappingURL=dygraph.js.map diff --git a/www/vicidial/dygraph_functions.php b/www/vicidial/dygraph_functions.php new file mode 100644 index 00000000..4fc41ce3 --- /dev/null +++ b/www/vicidial/dygraph_functions.php @@ -0,0 +1,356 @@ +, Joe Johnson LICENSE: AGPLv2 +# +# CHANGES +# 230508-0247 - First build +# + +require("dbconnect_mysqli.php"); +require("functions.php"); + +$php_script = 'dygraph_functions.php'; + +$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER']; +$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW']; +$PHP_SELF=$_SERVER['PHP_SELF']; +$PHP_SELF = preg_replace('/\.php.*/i','.php',$PHP_SELF); +if (isset($_GET["DB"])) {$DB=$_GET["DB"];} + elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];} +if (isset($_GET["user"])) {$user=$_GET["user"];} + elseif (isset($_POST["user"])) {$user=$_POST["user"];} +if (isset($_GET["log_date"])) {$log_date=$_GET["log_date"];} + elseif (isset($_POST["log_date"])) {$log_date=$_POST["log_date"];} +if (isset($_GET["web_ip"])) {$web_ip=$_GET["web_ip"];} + elseif (isset($_POST["web_ip"])) {$web_ip=$_POST["web_ip"];} +if (isset($_GET["ACTION"])) {$ACTION=$_GET["ACTION"];} + elseif (isset($_POST["ACTION"])) {$ACTION=$_POST["ACTION"];} + + +############################################# +##### START SYSTEM_SETTINGS LOOKUP ##### +$VUselected_language = ''; +$stmt = "SELECT use_non_latin,enable_languages,language_method,default_language,allow_web_debug FROM system_settings;"; +$rslt=mysql_to_mysqli($stmt, $link); + if ($mel > 0) {mysql_error_logging($NOW_TIME,$link,$mel,$stmt,'00XXX',$user,$server_ip,$session_name,$one_mysql_log);} +#if ($DB) {echo "$stmt\n";} +$qm_conf_ct = mysqli_num_rows($rslt); +if ($qm_conf_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $non_latin = $row[0]; + $SSenable_languages = $row[1]; + $SSlanguage_method = $row[2]; + $SSdefault_language = $row[3]; + $SSallow_web_debug = $row[4]; + } +$VUselected_language = $SSdefault_language; +if ($SSallow_web_debug < 1) {$DB=0;} +##### END SETTINGS LOOKUP ##### +########################################### + +$DB = preg_replace('/[^-_0-9a-zA-Z]/', '', $DB); +$log_date = preg_replace('/[^-_0-9a-zA-Z]/', '', $log_date); +$web_ip = preg_replace('/[^-:\._0-9a-zA-Z]/', '', $web_ip); +$ACTION = preg_replace('/[^-_0-9a-zA-Z]/', '', $ACTION); + +if ($non_latin < 1) + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW); + $user = preg_replace('/[^-_0-9a-zA-Z]/', '', $user); + } +else + { + $PHP_AUTH_USER = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_USER); + $PHP_AUTH_PW = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_PW); + $user = preg_replace('/[^-_0-9\p{L}]/u', '', $user); + } + +$stmt="SELECT selected_language,user_group from vicidial_users where user='$PHP_AUTH_USER';"; +if ($DB) {echo "|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$sl_ct = mysqli_num_rows($rslt); +if ($sl_ct > 0) + { + $row=mysqli_fetch_row($rslt); + $VUselected_language = $row[0]; + $LOGuser_group = $row[1]; + } + +$auth=0; +$reports_auth=0; +$admin_auth=0; +$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'',1,0); +if ($auth_message == 'GOOD') + {$auth=1;} + +if ($auth > 0) + { + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $admin_auth=$row[0]; + + $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports='1';"; + if ($DB) {echo "|$stmt|\n";} + $rslt=mysql_to_mysqli($stmt, $link); + $row=mysqli_fetch_row($rslt); + $reports_auth=$row[0]; + + if ($reports_auth < 1) + { + $VDdisplayMESSAGE = _QXZ("You are not allowed to view reports"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ( ($reports_auth > 0) and ($admin_auth < 1) ) + { + $ADD=999999; + $reports_only_user=1; + } + } +else + { + $VDdisplayMESSAGE = _QXZ("Login incorrect, please try again"); + if ($auth_message == 'LOCK') + { + $VDdisplayMESSAGE = _QXZ("Too many login attempts, try again in 15 minutes"); + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + if ($auth_message == 'IPBLOCK') + { + $VDdisplayMESSAGE = _QXZ("Your IP Address is not allowed") . ": $ip"; + Header ("Content-type: text/html; charset=utf-8"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; + exit; + } + Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); + Header("HTTP/1.0 401 Unauthorized"); + echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n"; + exit; + } + +$stmt="SELECT modify_campaigns,user_group from vicidial_users where user='$PHP_AUTH_USER';"; +$rslt=mysql_to_mysqli($stmt, $link); +$row=mysqli_fetch_row($rslt); +$LOGmodify_campaigns = $row[0]; +$LOGuser_group = $row[1]; + +$stmt="SELECT allowed_campaigns,allowed_reports,admin_viewable_groups,admin_viewable_call_times from vicidial_user_groups where user_group='$LOGuser_group';"; +if ($DB) {$HTML_text.="|$stmt|\n";} +$rslt=mysql_to_mysqli($stmt, $link); +$row=mysqli_fetch_row($rslt); +$LOGallowed_campaigns = $row[0]; +$LOGallowed_reports = $row[1]; +$LOGadmin_viewable_groups = $row[2]; +$LOGadmin_viewable_call_times = $row[3]; + +$LOGallowed_campaignsSQL=''; +$whereLOGallowed_campaignsSQL=''; +if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) ) + { + $rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns); + $rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL); + $LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')"; + $whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')"; + } +$regexLOGallowed_campaigns = " $LOGallowed_campaigns "; + +$admin_viewable_groupsALL=0; +$LOGadmin_viewable_groupsSQL=''; +$whereLOGadmin_viewable_groupsSQL=''; +$valLOGadmin_viewable_groupsSQL=''; +$vmLOGadmin_viewable_groupsSQL=''; +if ( (!preg_match('/\-\-ALL\-\-/i',$LOGadmin_viewable_groups)) and (strlen($LOGadmin_viewable_groups) > 3) ) + { + $rawLOGadmin_viewable_groupsSQL = preg_replace("/ -/",'',$LOGadmin_viewable_groups); + $rawLOGadmin_viewable_groupsSQL = preg_replace("/ /","','",$rawLOGadmin_viewable_groupsSQL); + $LOGadmin_viewable_groupsSQL = "and user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')"; + $whereLOGadmin_viewable_groupsSQL = "where user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')"; + $valLOGadmin_viewable_groupsSQL = "and val.user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')"; + $vmLOGadmin_viewable_groupsSQL = "and vm.user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')"; + } +else + {$admin_viewable_groupsALL=1;} +$regexLOGadmin_viewable_groups = " $LOGadmin_viewable_groups "; + + +# if options file exists, use the override values for the above variables +# see the options-example.php file for more information +if (file_exists('options.php')) + { + require_once('options.php'); + } + +header ("Content-type: text/html; charset=utf-8"); +header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 +header ("Pragma: no-cache"); // HTTP/1.0 + +if ($ACTION=="latency_by_user" && $user && $log_date && $web_ip) + { + if ($log_date!=date("Y-m-d")) {$latency_tbl="vicidial_agent_latency_log_archive";} else {$latency_tbl="vicidial_agent_latency_log";} + if (!preg_match('/\-\-\-ALL\-\-\-/', $web_ip)) + { + $ip_clause="and web_ip='$web_ip'"; + } + else + { + $ip_clause=""; + } + + if (!preg_match('/\-\-\-ALL\-\-\-/', $user)) + { + $user_clause="and user='$user'"; + } + else + { + $user_clause=""; + } + + $stmt="select log_date, latency, unix_timestamp(log_date) from ".$latency_tbl." where date(log_date)='$log_date' $LOGadmin_viewable_groupsSQL $user_clause $ip_clause order by log_date asc"; + $rslt=mysql_to_mysqli($stmt, $link); + $output="Date/Time,Latency\n"; + while ($row=mysqli_fetch_row($rslt)) + { + if ($prev_ldate && $row[2]>($prev_ldate+1)) + { + $dummy_ldate=date("Y-m-d H:i:s", floor(($row[2]+$prev_ldate)/2)); + $output.="$dummy_ldate,\n"; + } + $output.="$row[0],$row[1]\n"; + $prev_ldate=$row[2]; + } + echo $output; + exit; + } + +if ($ACTION=="all_agent_latency" && $log_date) + { + if ($log_date!=date("Y-m-d")) {$latency_tbl="vicidial_agent_latency_log_archive";} else {$latency_tbl="vicidial_agent_latency_log";} + + $group_array=array(); + $user_array=array(); + + $full_name_array=array(); + $fn_stmt="select user, full_name from vicidial_users where user>0 $LOGadmin_viewable_groupsSQL"; + $fn_rslt=mysql_to_mysqli($fn_stmt, $link); + while ($fn_row=mysqli_fetch_row($fn_rslt)) + { + # $user_split=explode("_", $fn_row[1]); + $full_name_array["$fn_row[0]"]="$fn_row[0] - $fn_row[1]"; + } + + $stmt="select log_date, latency, user, unix_timestamp(log_date) from ".$latency_tbl." where date(log_date)='$log_date' $LOGadmin_viewable_groupsSQL order by user, log_date asc"; + $rslt=mysql_to_mysqli($stmt, $link); + $output=""; + while ($row=mysqli_fetch_row($rslt)) + { + $user_array["$row[2]"]++; + $group_array["$row[0]"]["$row[2]"]=$row[1]; + } + + $output="Date/Time"; + foreach ($user_array as $user => $lags) + { + $output.=",".$full_name_array["$user"]; + } + $output.="\n"; + + foreach($group_array as $log_date => $agents) + { + + if ($prev_ldate && strtotime($log_date)>($prev_ldate+1)) + { + $dummy_ldate=date("Y-m-d H:i:s", floor((strtotime($log_date)+$prev_ldate)/2)); + $output.="$dummy_ldate"; + foreach ($user_array as $user => $lags) + { + $output.=","; + } + $output.="\n"; + } + + $output.="$log_date"; + foreach ($user_array as $user => $lags) + { + $output.=",".$group_array["$log_date"]["$user"]; + } + $output.="\n"; + + $prev_ldate=strtotime($log_date); + } + + echo $output; + } + +if ($ACTION=="latency_gaps" && $log_date) + { + if ($archive_flag) {$latency_tbl="vicidial_latency_gaps_archive";} else {$latency_tbl="vicidial_latency_gaps";} + + $group_array=array(); + $user_array=array(); + + $full_name_array=array(); + $fn_stmt="select user, full_name from vicidial_users where user>0 $LOGadmin_viewable_groupsSQL"; + if($DB){echo $fn_stmt."
    \n";} + $fn_rslt=mysql_to_mysqli($fn_stmt, $link); + while ($fn_row=mysqli_fetch_row($fn_rslt)) + { + # $user_split=explode("_", $fn_row[1]); + $full_name_array["$fn_row[0]"]="$fn_row[0] - $fn_row[1]"; + } + + if ($user && !preg_match('/\-\-\-ALL\-\-\-/', $user)) + { + $user_SQL="and user='$user'"; + } + + $stmt="select gap_date, gap_length, user, unix_timestamp(gap_date) from ".$latency_tbl." where date(gap_date)='$log_date' $user_SQL $LOGadmin_viewable_groupsSQL order by gap_date, user asc"; + if($DB){echo $stmt."
    \n";} + $rslt=mysql_to_mysqli($stmt, $link); + $output=""; + while ($row=mysqli_fetch_row($rslt)) + { + $user_array["$row[2]"]++; + $group_array["$row[0]"]["$row[2]"]=$row[1]; + } + + $output="Date/Time"; + foreach ($user_array as $user => $lags) + { + $output.=",".$full_name_array["$user"]; + } + $output.="\n"; + + foreach($group_array as $gap_date => $agents) + { + + if ($prev_ldate && strtotime($gap_date)>($prev_ldate+1)) + { + $dummy_ldate=date("Y-m-d H:i:s", floor((strtotime($gap_date)+$prev_ldate)/2)); + $output.="$dummy_ldate"; + foreach ($user_array as $user => $lags) + { + $output.=","; + } + $output.="\n"; + } + + $output.="$gap_date"; + foreach ($user_array as $user => $lags) + { + $output.=",".$group_array["$gap_date"]["$user"]; + } + $output.="\n"; + + $prev_ldate=strtotime($gap_date); + } + + echo $output; + } diff --git a/www/vicidial/help_documentation.txt b/www/vicidial/help_documentation.txt index 24ba4933..138beba3 100644 --- a/www/vicidial/help_documentation.txt +++ b/www/vicidial/help_documentation.txt @@ -1,4 +1,4 @@ -# version: 20230421085001 +# version: 20230515164601 users-user User ID This field is where you put the users ID number, can be up to 20 digits in length, Must be at least 2 characters in length. We strongly recommend not reusing user accounts for different users, for reporting accuracy. To disable a user account, set the Active option to -N-. users-pass Password This field is where you put the users password. Must be at least 2 characters in length. Only letters and numbers are allowed in user passwords. A medium strength user password will be at least 10 characters in length, and a strong user password will be at least 20 characters in length and have letters as well as at least one number. It is recommended that you use a longer password if possible, stringing together several unrelated words with no spaces, and a number somewhere in the string. The maximum size of a password is 100 characters. users-force_change_password Force Change Password If this option is set to Y then the user will be prompted to change their password the next time they log in to the administration webpage or the agent screen. Default is N. @@ -147,6 +147,10 @@ campaigns-manual_dial_hopper_check Manual Dial Hopper Check Setting this to campaigns-lead_filter_id Lead Filter This is a method of filtering your leads using a fragment of a SQL query. Use this feature with caution, it is easy to stop dialing accidentally with the slightest alteration to the SQL statement. Default is NONE. campaigns-auto_active_list_new Auto Active List New This setting will automatically set an inactive list to active when it contains dialable NEW status leads and the campaign has less than this setting number of NEW status leads to be dialed. The order in which the next list is set to active is determined by the List Auto Active List Rank. This feature will only work if there has been calling on this campaign within the last hour. If no leads have been dialed within the last hour in this campaign, then this feature will not function. Default is DISABLED. This feature will only work if the Call Quota Lead Ranking feature is also enabled. campaigns-call_quota_lead_ranking Call Quota Lead Ranking This setting will allow you to choose a Settings Container which has the settings you want to use for Call Quota Lead Ranking. Default is DISABLED. +campaigns-demographic_quotas Demographic Quotas This setting will enable or disable the Demographic Quotas feature for this campaign. For these features to work, you will need to select a value Container in the setting below. This feature is not related to Call Quota Lead Ranking and the two features should not be active on any single campaign at the same time. For more information, read the DEMOGRAPHIC_QUOTAS.txt document. Default is DISABLED. +campaigns-demographic_quotas_rerank Demographic Quotas Force Re-Rank By default, Demographic Quotas will only re-rank the leads in the campaign lists either when a quota has been reached or the campaign has run out of leads to dial. But this setting can force the system to re-rank the leads once using NOW, every hour using HOUR or every minute using the MINUTE setting. Keep in mind that depending on your system capacity and the number of leads in the campaign lists, this re-ranking process may lead to temporary system disruption, especially if it is run very frequently. When NOW is used, after the re-ranking process, the value of this setting will go back to NO. Default is NO. +campaigns-demographic_quotas_list_resets Demographic Quotas List Resets This optional setting can reset the active lists in this campaign if there are leads within the call time available and there are no more dialable leads in the campaign lists. We do not recommend activating this setting in most cases because it can result in customers being called an excessive number of times in a single day. Default is MANUAL. +campaigns-demographic_quotas_container Demographic Quotas Container This setting is where you select a DEMOGRAPHIC_QUOTAS container to be used for the Demographic Quota features to use for quota goals. For more information, read the DEMOGRAPHIC_QUOTAS.txt document. Default is DISABLED. campaigns-call_count_limit Call Count Limit This enforces a limit on the number of call attempts for the leads dialed in this campaign. A lead may go over this limit slightly if Lead Recycling or Auto-Alt-Dialing is enabled. Default is 0 for no limit. campaigns-call_count_target Call Count Target This option is only used for reporting purposes and has no effect on leads dialed. Default is 3. campaigns-daily_call_count_limit Daily Call Count Limit This feature, if enabled, will limit the number of times a lead can be called in a single day. Once a lead has reached this set limit, if the lead is selected to be dialed again, the called-since-last-reset flag on the lead will be changed to -Y- and the call will not be dialed. If you want to raise this daily limit during the day, you might need to reset your lists to be able to dial the leads that hit the previous limit earlier in the day. This feature may conflict with Auto-Alt-Dial features if they are enabled on a campaign. Default is 0 for disabled. @@ -1141,6 +1145,7 @@ settings-user_new_lead_limit New Leads Per List Limit This setting enables settings-daily_call_count_limit Enable Daily Called Count Limits Enabling this setting will allow you to define a daily called count limit on a per campaign basis. Default is 0 for disabled. settings-call_limit_24hour Enable 24-Hour Called Count Limits Enabling this setting will allow you to define a 24-hour called count limit on a per campaign basis. Default is 0 for disabled. settings-call_quota_lead_ranking Call Quota Lead Ranking This setting allows you to use the campaign setting for Call Quota Lead Ranking, which allows for a complex set of recycle dialing priorities for non-contact calls. Default is 0 for disabled. +settings-demographic_quotas Demographic Quotas This setting allows you to use the campaign Demographic Quotas feature, which allows for a dialing pattern that is based around a set of demographic types and values with associated quota goals. This feature is not related to Call Quota Lead Ranking and the two features should not be active on any single campaign at the same time. For more information, read the DEMOGRAPHIC_QUOTAS.txt document. Default is 0 for disabled. settings-custom_fields_enabled Enable Custom List Fields This setting enables the custom list fields feature that allows for custom data fields to be defined in the administration web interface on a per-list basis and then have those fields available in a FORM tab to the agent in the agent web interface. Default is 0 for disabled. settings-expanded_list_stats Enable Expanded List Stats This setting enables two additional columns to be displayed on most of the List status breakdown tables on the list modification and campaign modification pages. Penetration is defined as the percent of leads that are at or above the campaign Call Count Limit and-or the status is marked as Completed. Default is 1 for enabled. settings-hide_inactive_lists Hide Inactive Lists This setting allows you to hide inactive lists from the Lists Listing page. Similar to the default Users feature, a link to display all lists will be available at the top of the listings section. Default is 0 for disabled. @@ -1153,6 +1158,7 @@ settings-enable_drop_lists Enable Drop Lists This setting if enabled will m settings-source_id_display Admin Lead Source ID Display This setting will make the Source ID lead field show up in the Admin Modify Lead screen. Default is 0 for disabled. settings-allow_web_debug Allow Web DB Debug This option will allow the DB query string option to be used in most web pages on this system to show debug output. Default is 0 for disabled. settings-agent_debug_logging Agent Screen Debug Logging This setting if enabled will log almost all agent screen mouse clicks and AJAX processes triggered by the agent screen. To enable for all agents, set this option to 1. To enable only for one agent on the system, set this option to the user that you want to log. Warning, this feature can log hundreds of entries per phone call, so use with caution. These agent debug records are deleted after 7 days. Default is 0 for disabled. +settings-log_latency_gaps Agent Latency Gaps Logging This setting if enabled will look for gaps in the latency logging for agents logged into the agent screen. This process can be configured in the AGENT_LATENCY_LOGGING Settings Container. For more information on this feature, read the AGENT_SCREEN_LOGGING.txt document. Default is 1 for enabled. settings-agent_screen_timer Agent Screen Timer This will select the method of JavaScript timer to be used by the Agent Screen. The original method is setTimeout, which maintains the timer directly in JavaScript. An alternative method is setTimeoutAudioLoop, which uses the HTML -audio- tag with the -loop- option to play a 20Hz audio sound repeatedly to keep the browser tab active, this method will break Agent Browser Call Alerts if enabled. Another alternative is EventSource, which uses a script on the server to trigger the timer. You may want to use EventSource if your agents are using a Chromium-based web browser that has limitations on how native JavaScript timers work, although using this method may possibly cause issues if you have a poor network connection to the server or are on an older network or proxy that does not handle streaming web services well. Default is setTimeout settings-enhanced_disconnect_logging Enhanced Disconnect Logging This setting, set to 1, enables logging of calls that get a CONGESTION signal with a cause code of 1, 19, 21, 34 or 38. Setting this to 2 will additionally log calls with cause codes of 18-CHANUNAVAIL and 102. Setting this to 3 will alternatively prevent some temporary error SIP messages on failed calls from sending the lead to ADC status. Instead, the status will be set as HUCXXX where XXX is the hangup_cause code. Eg. HUC18 for Cause 18 (SIP 408 Request timeout). Default is 0 for disabled. settings-sip_event_logging SIP Event Logging This setting will enable logging of SIP events on outbound phone calls for servers that are running patched versions of Asterisk 13 or higher. Default is 0 for disabled. @@ -1349,6 +1355,7 @@ usergroup_login User Group Login Report This report includes information on agent_timeclock_detail User Timeclock Detail Report Pulls all timeclock records for agents meeting the selected parameters.
    TIME CLOCK = Total amount of time agent spent logged in.
    TIME CLOCK PUNCHES = A list of the punch-in and punch-out times for each agent. Punch-out times marked with an asterisk (*) denotes AUTOLOGOUT from timeclock. campaign_status_list_report Campaign Status List Report This report is designed to show the breakdown by list_id of the calls and their statuses for all lists within a campaign for a set time period.
    DISPOSITION = The distinct dispositions made for the list within the time frame specified.
    CALLS = The number of calls ending with the disposition listed.
    DURATION = Sum of the length of the calls ending with the disposition listed.
    HANDLE TIME = Sum of the time the calls ending with the disposition listed were handled by an agent (TALK + DEAD).

    TOTAL CALLS = Number of calls placed to leads belonging to lists in this campaign within the time frame specified.
    STATUS FLAGS BREAKDOWN = Breakdown of the total calls into status categories, including counts per category and percentage relative to the number of calls to leads in the list within the time frame specified. campaign_debug Campaign Debug Shows campaign stats and debug output for a selected campaign. +DQreport Demographic Quotas Report This report will show the details of a single campaigns Demographic Quota settings, goals and other basic campaign calling information all on one screen. As quota goals are filled, the goal rows will change from a green to a purple background color. The numbers in this report are updated once per minute, but the -count- column can also be updated as agents disposition calls. It is possible for the -count- column to be higher than it really is if a call is dispositioned at the same time as the back-end process runs, but this will not impact the function of this feature and the numbers will be corrected within one minute. There are also links near the top of the report to go to the campaign modify page and the debug page to see more information on the last time the Demographic Quotas process ran. user_logins_report User Logins Report This report will show the last login information for a user on the last several days that they logged into the system user_latency_report User Latency Report This report will show the agent screen web connection latency information for agents that are currently or recently logged in to the agent screen. carrier_log_report Carrier Log Report This report will show dial status breakdowns, SIP error reason breakdowns, and carrier log records for a selected date, and can be filtered by server. diff --git a/www/vicidial/user_latency_report.php b/www/vicidial/user_latency_report.php index 53662bc1..9ec37df6 100644 --- a/www/vicidial/user_latency_report.php +++ b/www/vicidial/user_latency_report.php @@ -1,11 +1,12 @@ LICENSE: AGPLv2 +# Copyright (C) 2023 Matt Florell , Joe Johnson LICENSE: AGPLv2 # # CHANGES # 230421-0843 - First build # 230422-0820 - Header fixes and no-records output +# 230508-0247 - Graph links added # $startMS = microtime(); @@ -283,6 +284,123 @@ $NWE = "')\" WIDTH=20 HEIGHT=20 BORDER=0 ALT=\"HELP\" ALIGN=TOP>"; .purple {color: white; background-color: purple} --> + + + \n"; @@ -334,7 +452,7 @@ else $multi_user=0; $latencies_to_print=0; $Hlatencies_to_print=0; - $stmt="SELECT vlad.user,vlad.update_date,vlad.web_ip,vlad.latency,vlad.latency_min_avg,vlad.latency_min_peak,vlad.latency_hour_avg,vlad.latency_hour_peak,vlad.latency_today_avg,vlad.latency_today_peak from vicidial_live_agents_details vlad where vlad.user='" . mysqli_real_escape_string($link, $user) . "' $vmLOGadmin_viewable_groupsSQL order by user limit 1000;"; + $stmt="SELECT vlad.user,vlad.update_date,vlad.web_ip,vlad.latency,vlad.latency_min_avg,vlad.latency_min_peak,vlad.latency_hour_avg,vlad.latency_hour_peak,vlad.latency_today_avg,vlad.latency_today_peak from vicidial_live_agents_details vlad where vlad.user='" . mysqli_real_escape_string($link, $user) . "' $LOGadmin_viewable_groupsSQL order by user limit 1000;"; if ($user == '--ACTIVE-USERS-TODAY--') { $multi_user=1; @@ -353,7 +471,7 @@ else $archive_output .= "| ".sprintf("%-20s", $row[0])." |"; $archive_output .= " ".sprintf("%-19s", $row[1])." |"; - $archive_output .= " ".sprintf("%-20s", $row[2])." |"; + $archive_output .= " ".sprintf("%-20s", $row[2])." |"; $archive_output .= " ".sprintf("%-10s", $row[3])." |"; $archive_output .= " ".sprintf("%-10s", $row[4])." |"; $archive_output .= " ".sprintf("%-10s", $row[5])." |"; @@ -369,7 +487,7 @@ else if ($multi_user < 1) { - $stmt="select user,log_date,web_ip,latency_avg,latency_peak from vicidial_agent_latency_summary_log where user='" . mysqli_real_escape_string($link, $user) . "' $LOGadmin_viewable_groupsSQL order by log_date desc,web_ip limit 1000;"; + $stmt="select user,log_date,web_ip,latency_avg,latency_peak,if(date(log_date)>=date(now()-INTERVAL 7 DAY), 1, 0) as show_link from vicidial_agent_latency_summary_log where user='" . mysqli_real_escape_string($link, $user) . "' $LOGadmin_viewable_groupsSQL order by log_date desc,web_ip limit 1000;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {echo "$stmt\n";} $Hlatencies_to_print = mysqli_num_rows($rslt); @@ -382,7 +500,14 @@ else echo "| ".sprintf("%-20s", $row[0])." |"; echo " ".sprintf("%-19s", $row[1])." |"; - echo " ".sprintf("%-20s", $row[2])." |"; + if ($row[5]) + { + echo " ".sprintf("%-20s", $row[2])." |"; + } + else + { + echo " ".sprintf("%-20s", $row[2])." |"; + } echo " ".sprintf("%-10s", ' ')." |"; echo " ".sprintf("%-10s", ' ')." |"; echo " ".sprintf("%-10s", ' ')." |"; @@ -394,8 +519,26 @@ else $i++; } } + else + { + echo "+----------------------+---------------------+----------------------+------------+------------+------------+------------+------------+------------+------------+\n"; + echo "| GRAPH AGENTS BY DATE: [ ".date("Y-m-d")." ]"; + $date_stmt="select distinct date(log_date) as ldate from vicidial_agent_latency_log_archive order by ldate desc"; + $date_rslt=mysql_to_mysqli($date_stmt, $link); + $col_width=119; + while ($date_row=mysqli_fetch_row($date_rslt)) + { + echo " [ $date_row[0] ]"; + $col_width-=17; + } + echo sprintf("%-".$col_width."s", ' ')."|\n"; + echo "+----------------------+---------------------+----------------------+------------+------------+------------+------------+------------+------------+------------+\n"; + } if ( ($latencies_to_print < 1) and ($Hlatencies_to_print < 1) ) {echo _QXZ("No records to report");} + else + { + } echo "\n"; } @@ -423,6 +566,73 @@ $rslt=mysql_to_mysqli($stmt, $link); - + + + + + +
    + + +
    +
    +
    +
    +
    +