#!/usr/bin/perl # # Use Reverse Number Database on the net to add name to callerid info # Currently only trys to query anywho.com, but other lookups can be added easily # # If your callerid is only passed as a 7 digit number, # you can pass this script an argument with the default area code # # extensions.conf example: # exten => s,1,AGI,calleridnamelookup.agi # exten => s,2,Dial,Zap,1 # # Written by: James Golovich # use Asterisk::AGI; use LWP::UserAgent; #SET $CACHELOOKUPS to 1 to cachelookups locally, default is disabled $CACHELOOKUPS = 0; #You must create this directory if you enable $CACHELOOKUPS, or caching will fail $CACHEDIR = '/var/spool/asterisk/calleridlookups'; #TIMEOUT is maximum number of seconds for http requests (we don't want to take too long) $TIMEOUT = 2; $VERSION = '0.01'; $AGI = new Asterisk::AGI; my %input = $AGI->ReadParse(); my $callerid = $input{'callerid'}; #Exit quickly if there is already a name in callerid or if the callerid field is empty if (!$callerid || $callerid =~ /[A-Za-z]+/) { exit(0); } $defaultnpa = $ARGV[0] if (defined($ARGV[0])); #remove everything non numeric from callerid string $callerid =~ s/[^\d]//g; if ($callerid =~ /^(\d{3})(\d{3})(\d{4})$/) { $npa = $1; $nxx = $2; $station = $3; } elsif (defined($defaultnpa) && ($callerid =~ /^(\d{3})(\d{4})$/)) { $npa = $defaultnpa; $nxx = $1; $station = $2; } else { exit(0); } if ($name = lookup($npa, $nxx, $station)) { $newcallerid = "\"$name <($npa) $nxx-$station>\""; $AGI->set_callerid($newcallerid); } exit(0); sub lookup { my $name = ''; if ($name = cache_lookup(@_)) { return $name; #Add other lookups here, always keep best db first in list } elsif ($name = anywho_lookup(@_)) { } #we cache everything, even negative results cacheadd($npa, $nxx, $station, $name); return $name; } sub cacheadd { my ($npa, $nxx, $station, $name) = @_; return 0 if (!$CACHELOOKUPS); open(CACHE, ">$CACHEDIR/$npa$nxx$station") || return 0; print CACHE "$name\n"; close(CACHE) || return 0; return 1; } sub cache_lookup { my ($npa, $nxx, $station) = @_; return 0 if (!$CACHELOOKUPS); my $name = ''; open(CACHE, "<$CACHEDIR/$npa$nxx$station") || return ''; $name = ; chomp($name); close(CACHE); #must be a negatively cached result so just add a blank space so it will pass the other tests $name = ' ' if ($name eq ''); return $name; } sub anywho_lookup { my ($npa, $nxx, $station) = @_; my $ua = LWP::UserAgent->new( timeout => $TIMEOUT); my $URL = 'http://www.anywho.com/qry/wp_rl'; $URL .= '?npa=' . $npa . '&telephone=' . $nxx . $station; $ua->agent('AsteriskAGIQuery/$VERSION'); my $req = new HTTP::Request GET => $URL; my $res = $ua->request($req); if ($res->is_success()) { if ($res->content =~ /(.*)/s) { my $listing = $1; if ($listing =~ /(.*)<\/B>/) { my $clidname = $1; return $clidname; } } } return ''; }