Pagina 14 di 14

MessaggioInviato: ven giu 04, 2010 9:32 am
da Omega
Aggiornamento che magari vi può essere di aiuto:
se modifico "[cidlookup]" dentro "extension_additional.conf" facendolo diventare nel seguente modo:
Codice: Seleziona tutto
[cidlookup]
include => cidlookup-custom
exten => cidlookup_1,1,LookupCIDName
exten => cidlookup_1,n,Return()
exten => cidlookup_return,1,LookupCIDName
exten => cidlookup_return,n,Return()


la risoluzione funziona correttamente, mostrandomi però, il nome che ho salvato con il comando
Codice: Seleziona tutto
database put cidname numero "nome"
(si parla quindi del database locale di Asterisk).


La conclusione è che il problema vero è o nello script di richiamo di superfecta, o nella sua risoluzione.




Per spiegarmi meglio posto le due configurazioni:
Codice: Seleziona tutto
[cidlookup]
include => cidlookup-custom
exten => cidlookup_1,1,Set(CALLERID(name)=${CURL(http://localhost:80/callerid.php?thenumber=${CALLERID(num)})})
exten => cidlookup_1,n,Return()
exten => cidlookup_return,1,LookupCIDName
exten => cidlookup_return,n,Return()

(ho già provato a modificare la seconda riga, sia con utente:password@ prima di "localhost", sia mettendo un altro percorso e quindi un altro file dopo la porta "80", cioè /admin/modules/superfecta/bin/callerid.php).




Per quel che riguarda i due file "callerid.php" eccoli.


Primo caso:
Codice: Seleziona tutto
<?php


/*** Original script by Nerd Vittles. (Google for Caller Id Trifecta or CallerID Superfecta)
     Current code is always maintained at http://bestof.nerdvittles.com/applications/callerid
        whitepages.ca "Submitted by taiter on Mon, 03/12/2007 - 9:55pm"
        M Joyner updated the whitepages.ca to account for apparent changes
        they have made over time. (2008-06-22-18-20) mjoyner _at_ vbservices *dot* net
        12/17/2008 - Added Whocalled.us and Telcodata sites and npa validation - Dave M.
        2/18/2009 - Updated Anywho.com and Whocalled.us lookup - Dave M.
        3/1/2009 - enhanced to use CURL with timeout - Dave M.
        4/25/09 - Added Whitepages and Yellowpages from Addresses.com - Uncle Ward
***/

$thenumber=$_REQUEST['thenumber'];

// Setting the variables below to 1 activates each of the respective searches.
// The phonebook searches are executed in the order shown.
// When a match is bound during a search, the callerid script ends with that result.
// E.g. if there is a match in AsteriDex, then the Google and AnyWho searches aren't executed.

$AsteriDex = '1' ;
$WhoCalled = '0' ;
$PhoneSpamFilter = '0' ;
$Google = '0' ;
$Addresses = '0' ;
$WhitePagesCAD = '0';
$YellowPages = '0' ;
$AnyWho = '0' ;
$Telcodata = '0' ;

$WhoCalled_name      = '' ;      // Whocalled Username
$WhoCalled_pass      = '' ;     // Whocalled Password
$WhoCalled_threshold = '10' ;            // Whocalled threshold

$SPAM_CNAM           = 'SPAM-CALLER';   // CNAM to return if pass threshold

$PhoneSpamFilter_threshold = '10' ;     // PhoneSpamFilter threshold

$debug = '0' ;
$timeout    = 3 ;
$getContent = true ;
$offset     = 0 ;
$maxLen     = 50 ;

if (strlen($thenumber)>10) :
 $thenumber = substr($thenumber, -10);
endif;


if (strlen($thenumber)<>10) :
exit ;
endif;

$npa = substr($thenumber,0,3);
$nxx = substr($thenumber,3,3);
$station = substr($thenumber,6,4);
$qp=substr($thenumber,3,7);

// Check for Toll-Free numbers
if ($npa=='800'||$npa=='866'||$npa=='877'||$npa=='888') :
  $TFnpa = '1';
else :
  $TFnpa = '0';
endif ;

// Check for valid US NPA
$npalist = array(
   "201", "202", "203", "204", "205", "206", "207", "208", "209", "210",
   "212", "213", "214", "215", "216", "217", "218", "219", "224", "225",
   "226", "228", "229", "231", "234", "239", "240", "242", "246", "248",
   "250", "251", "252", "253", "254", "256", "260", "262", "264", "267",
   "268", "269", "270", "276", "281", "284", "289", "301", "302", "303",
   "304", "305", "306", "307", "308", "309", "310", "312", "313", "314",
   "315", "316", "317", "318", "319", "320", "321", "323", "325", "330",
   "331", "334", "336", "337", "339", "340", "345", "347", "351", "352",
   "360", "361", "386", "401", "402", "403", "404", "405", "406", "407",
   "408", "409", "410", "412", "413", "414", "415", "416", "417", "418",
   "419", "423", "424", "425", "430", "432", "434", "435", "438", "440",
   "441", "443", "450", "456", "469", "473", "478", "479", "480", "484",
   "500", "501", "502", "503", "504", "505", "506", "507", "508", "509",
   "510", "512", "513", "514", "515", "516", "517", "518", "519", "520",
   "530", "540", "541", "551", "559", "561", "562", "563", "567", "570",
   "571", "573", "574", "575", "580", "585", "586", "600", "601", "602",
   "603", "604", "605", "606", "607", "608", "609", "610", "612", "613",
   "614", "615", "616", "617", "618", "619", "620", "623", "626", "630",
   "631", "636", "641", "646", "647", "649", "650", "651", "660", "661",
   "662", "664", "670", "671", "678", "682", "684", "700", "701", "702",
   "703", "704", "705", "706", "707", "708", "709", "710", "712", "713",
   "714", "715", "716", "717", "718", "719", "720", "724", "727", "731",
   "732", "734", "740", "754", "757", "758", "760", "762", "763", "765",
   "767", "769", "770", "772", "773", "774", "775", "778", "779", "780",
   "781", "784", "785", "786", "787", "800", "801", "802", "803", "804",
   "805", "806", "807", "808", "809", "810", "812", "813", "814", "815",
   "816", "817", "818", "819", "828", "829", "830", "831", "832", "843",
   "845", "847", "848", "850", "856", "857", "858", "859", "860", "862",
   "863", "864", "865", "866", "867", "868", "869", "870", "876", "877",
   "878", "888", "900", "901", "902", "903", "904", "905", "906", "907",
   "908", "909", "910", "912", "913", "914", "915", "916", "917", "918",
   "919", "920", "925", "928", "931", "936", "937", "939", "940", "941",
   "947", "949", "951", "952", "954", "956", "970", "971", "972", "973",
   "978", "979", "980", "985", "989"
);

if (in_array($npa, $npalist)) :
  $validnpa = 1;
  if ($debug=='1') :
    echo "Found valid US npa: ", $npa, "-", $nxx, "-", $station,"\n" ;
  endif ;
else :
  $validnpa = 0;
  if ($debug=='1') :
      echo "Invalid npa: ", $npa, "-", $nxx, "-", $station,"\n" ;
  endif ;
endif ;


// ---------- Don't fiddle around below this line --------------------


$value="" ;
if ($AsteriDex=='1') :
  if ($debug=='1') :
    echo "<br />AsteriDex lookup ....", "\n" ;
  endif ;
  $link = mysql_connect("localhost", "utente", "password")
      or die("AsteriDex connection failed");
  mysql_select_db("asteridex")
      or die("AsteriDex data base open failed");
  $query = "SELECT * FROM `user1` where `out` LIKE '$thenumber'";
  $result = mysql_query($query)
      or die("AsteriDex query failed");
  if (mysql_num_rows($result)>0) :
    $row = mysql_fetch_array($result);
    $value=$row["name"];
// else :
//  $query = "SELECT * FROM user1 where id>0";
//  $result = mysql_query($query)
//    or die("AsteriDex query failed");
//  $row = mysql_fetch_array($result);
//  $value=$row["name"];
//  $value="";
  endif ;
  mysql_close($link);
  if (strlen($value)>0) :
    echo $value;
  if ($debug<>'1') :
   exit ;
  endif;
  endif ;
endif ;

if ($WhoCalled=='1' && $validnpa=='1') :
  if ($debug=='1') :
    echo "<br />WhoCalled lookup ....", "\n" ;
  endif ;
  $url = "http://whocalled.us/do?action=getScore&name=$WhoCalled_name&pass=$WhoCalled_pass&phoneNumber=$thenumber";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $st_success = strstr($value, "success");
    $st_score = strstr($value, "score");
    $success = substr($st_success,8,1);
    $score = substr($st_score,6);
    if ($success=='1') :
      if ($score>$WhoCalled_threshold) :
        echo $SPAM_CNAM ;
  if ($debug<>'1') :
   exit ;
  endif;
      endif ;
    endif ;
  endif ;
endif ;

if ($PhoneSpamFilter=='1' && $validnpa=='1') :
  if ($debug=='1') :
    echo "<br />PhoneSpamFilter lookup ....", "\n" ;
  endif ;
  $url = "http://www.phonespamfilter.com/check.php?phone=$thenumber";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $score = $value ;
    if ($score>$PhoneSpamFilter_threshold) :
      echo $SPAM_CNAM ;
  if ($debug<>'1') :
   exit ;
  endif;
    endif ;
  endif ;
endif ;

if ($Google=='1') :
  if ($debug=='1') :
    echo "<br />Google lookup ....", "\n" ;
  endif ;
  $url = "http://www.google.com/search?rls=en&q=phonebook:$thenumber&ie=UTF-8&oe=UTF-8";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $start= strpos($value, "Phonebook</b>");
    $value = substr($value,$start+13);
    $start=strpos($value, "<tr bgcolor=#e5ecf9><td>");
    $value = substr($value,$start+24);
    $end=strpos($value, "<td>(");
    $value = substr($value,0,$end);
    if (strlen($value)>1) :
      echo $value;
  if ($debug<>'1') :
   exit ;
  endif;
    endif;
  endif ;
endif ;

if ($Addresses=='1' && $TFnpa=='0' && $validnpa=='1') :
 if ($debug=='1') :
  echo "<br />Addresses.com lookup ....", "\n" ;
 endif ;

 $value = "";
 $url="http://phonenumbers.addresses.com/results.php?ReportType=33&qfilter[pro]=on&qi=0&qk=10&qnpa=$npa&qp=$qp";
 $value = UrlGetContentsCurl($url, $timeout, $debug);
 if ($value) :
  $start= strpos($value, "wp_listing_name");
  if ($start>1) :
   $value = substr($value,$start);
   $start= strpos($value, ">");
   $value = substr($value,$start+1);
   $end= strpos($value, "</div>");
   $name = substr($value,0,$end);
   $name = str_replace( chr(13), "", $name );
   $name = str_replace( chr(10), "", $name );
   $name = str_replace( "<div>", "", $name );
   $name = str_replace( "</a>", "", $name );
   $name = trim(str_replace( " ", "", $name ));
   echo strip_tags($name) ;
   if ($debug<>'1') :
    exit ;
   endif;
  else :
   $value="";
  endif ;
 endif;
endif ;

if ($WhitePagesCAD=='1' && $TFnpa=='0' && $validnpa=='1') :
  if ($debug=='1') :
    echo "<br />WhitePagesCAD lookup ....", "\n" ;
  endif ;
  $url = "http://www.whitepages.com/search/ReversePhone?full_phone=$thenumber";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $notfound = strpos($value, "PHONE_USER_ERROR");
    $patternFirst = "/FIRST.*?\"(.*?)\",/";
    $patternLast = "/LAST.*?\"(.*?)\",/";
    $patternCity = "/CITY.*?\"(.*?)\",/";
    $patternState = "/STATE.*?\"(.*?)\",/";
    $patternType = "/Type: *(.*?)<\/span>/";
    preg_match($patternFirst, $value, $first);
    preg_match($patternLast, $value, $last);
    $name = $last[1]." ".$first[1];
    if ($name==" "):
      preg_match($patternCity, $value, $city);
      preg_match($patternState, $value, $state);
      preg_match($patternType, $value, $type);
//      $type = str_replace( "<strong>", "", $type );
//      $type = str_replace( "</strong>", "", $type );
      $name = $city[1].", ".$state[1]." ".$type[1];
    endif;
    if ($notfound):
      $name="";
    endif;
    if (strlen($name)>1) :
      echo strip_tags($name);
     if ($debug<>'1') :
      exit ;
     endif;
    endif;
  endif ;
endif ;

if ($YellowPages=='1' && $TFnpa=='0' && $validnpa=='1') :
 if ($debug=='1') :
  echo "<br />YellowPages lookup ....", "\n" ;
 endif ;

 $value = "";
 $url="http://yellowpages.addresses.com/yellow-pages/phone:$thenumber/listings.html";
 $value = UrlGetContentsCurl($url, $timeout, $debug);
 if ($value) :
 $start= strpos($value, "listing_name");
 if ($start>1) :
  $value = substr($value,$start);
  $start= strpos($value, ">");
  $value = substr($value,$start+1);
  $end= strpos($value, "</div>");

  $name = substr($value,0,$end);
  $name = str_replace( chr(13), "", $name );
  $name = str_replace( chr(10), "", $name );
  $name = str_replace( "<div>", "", $name );
  $name = str_replace( "</a>", "", $name );
  $name = trim(str_replace( " ", "", $name ));

  echo strip_tags($name) ;
  if ($debug<>'1') :
   exit ;
  endif;
 else :
  $value="";
 endif ;
 endif;
endif ;

if ($AnyWho=='1' && $TFnpa=='0' && $validnpa=='1') :
  if ($debug=='1') :
    echo "<br />AnyWho lookup ....", "\n" ;
  endif ;
  $npa=substr($thenumber,0,3);
  $telephone=substr($thenumber,3,7);
  $url = "http://whitepages.anywho.com/results.php?&qnpa=$npa&qp=$telephone";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $notfound = strpos($value, "class=\"NoResultBar\"");
    $start= strpos($value, "class=\"singleName\"");
    if (!$start) :
       $start= strpos($value, "class=\"resultName\"");
    endif;
    $value = substr($value,$start+17);
    $start=strpos($value, "\">");
    $value = substr($value,$start+2);
    $end=strpos($value, "</div>");
    $value = substr($value,0,$end);
    $value = strip_tags($value);
    if ($notfound) :
   $value="";
    endif;
    if (strlen($value)>1) :
   echo strip_tags($value);
       if ($debug<>'1') :
        exit ;
       endif;
    endif;
  endif ;
endif ;

if ($Telcodata=='1' && $TFnpa=='0' && $validnpa=='1') :
  if ($debug=='1') :
    echo "<br />Telcodata lookup ....", "\n" ;
  endif ;
  $url = "http://www.telcodata.us/query/queryexchangexml.html?npa=$npa&nxx=$nxx";
  $value = UrlGetContentsCurl($url, $timeout, $debug);
  if ($value) :
    $start = strpos($value, "<ratecenter>");
    $ratecenter = substr($value,$start+12);
    $end = strpos($ratecenter, "</ratecenter>");
    $ratecenter = substr($ratecenter,0,$end);

    $start = strpos($value, "<state>");
    $state = substr($value,$start+7);
    $end = strpos($state, "</state>");
    $state = substr($state,0,$end);

    $value = $ratecenter.", ".$state ;

    if (strlen($ratecenter)>1) :
      echo $value ;
      exit ;
    endif;
  endif ;
endif ;


if ($TFnpa=='1') :
  echo "TOLL FREE CALL" ;
else :
  echo $thenumber ;
endif ;
exit ;

function UrlGetContentsCurl(){
  // parse the argument passed and set default values
  $arg_names    = array('url', 'timeout', 'debug', 'getContent', 'offset', 'maxLen');
  $arg_passed   = func_get_args();
  $arg_nb       = count($arg_passed);
  if (!$arg_nb){
    echo 'At least one argument is needed for this function';
    return false;
  }
  $arg = array (
    'url'       => null,
    'timeout'   => ini_get('max_execution_time'),
    'debug'     => null,
    'getContent'=> true,
    'offset'    => 0,
    'maxLen'    => null
  );
  foreach ($arg_passed as $k=>$v){
    $arg[$arg_names[$k]] = $v;
  }

  // CURL connection and result
  $ch = curl_init($arg['url']);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
  curl_setopt($ch, CURLOPT_RESUME_FROM, $arg['offset']);
  curl_setopt($ch, CURLOPT_TIMEOUT, $arg['timeout']);
  $result  = curl_exec($ch);
  $elapsed = curl_getinfo ($ch, CURLINFO_TOTAL_TIME);
  $CurlErr = curl_error($ch);
  curl_close($ch);
  if ($arg['debug']=='1') :
    echo "Elapsed time : ", $elapsed, "\n";
  endif ;
  if ($CurlErr) {
    if ($arg['debug']=='1') :
      echo "Curl Error : ", $CurlErr, "\n";
    endif ;
    return false;
  }elseif ($arg['getContent']){
    return $arg['maxLen']
      ? substr($result, 0, $arg['maxLen'])
      : $result;
  }
  return $elapsed;
}


?>

MessaggioInviato: ven giu 04, 2010 9:34 am
da Omega
Secondo caso:
Codice: Seleziona tutto
<?php
/*** Original script by Nerd Vittles. (Google for Caller Id Trifecta)
    3/12/2009     Put into module format by Tony Shiffer & Jerry Swordsteel
         commented out fixed variables.  Added db code to get values from db.
   3/30/2009     New SugarCRM by jpeterman is now included.
   4/8/2009     Removed dependancy on default id/pw for db connection. now parses amportal.conf
   5-8-2009   Version 2.0.0 Major update - Tickets: Tickets: #7, #10, #15, #17, #36, and #19.(projects.colsolgrp.net)(jjacobs)
   8-18-2009   Version 2.2.0  CID Schemes and online update for data sources (projects.colsolgrp.net)(jjacobs)
   10-26-2009  Version 2.2.2  http://projects.colsolgrp.net/versions/show/55 (projects.colsolgrp.net) (patrick_elx)
***/

require_once("../../../functions.inc.php");

$caller_id = '';
$charsetIA5 = true;
$first_caller_id = '';
$prefix = '';
$cache_found = false;
$spam = false;
$winning_source = '';
$usage_mode = 'get caller id';
$thenumber_orig = trim($_REQUEST['thenumber']);
$scheme = (isset($_REQUEST['scheme']))? trim($_REQUEST['scheme']) : '';
//$thenumber_orig = ereg_replace('[^0-9]+', '', $thenumber_orig);
$debug_val = (isset($_REQUEST['debug'])) ? $_REQUEST['debug'] : '';
$debug = ($debug_val == 'yes') ? true : false;

if($debug)
{
   $start_time_whole = mctime_float();
   $end_time_whole = 0;
}

// new code - causes config values to be pulled from db  3/12/2009
require_once 'DB.php';
define("AMP_CONF", "/etc/amportal.conf");

$amp_conf = parse_amportal_conf(AMP_CONF);
if(count($amp_conf) == 0)
{
   fatal("FAILED");
}

$dsn = array(
    'phptype'  => 'mysql',
    'username' => $amp_conf['AMPDBUSER'],
    'password' => $amp_conf['AMPDBPASS'],
    'hostspec' => $amp_conf['AMPDBHOST'],
    'database' => $amp_conf['AMPDBNAME'],
);
$options = array();
$db =& DB::connect($dsn, $options);
if(PEAR::isError($db))
{
   die($db->getMessage());
}

//connect to the asterisk manager
require_once('../../../common/php-asmanager.php');
$astman   = new AGI_AsteriskManager();

// attempt to connect to asterisk manager proxy
if(!isset($amp_conf["ASTMANAGERPROXYPORT"]) || !$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPROXYPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off'))
{
   // attempt to connect directly to asterisk, if no proxy or if proxy failed
   if (!$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off'))
   {
      // couldn't connect at all
      unset( $astman );
   }
}

//get the DID for this call using the PHP Asterisk Manager
$DID = "";
$value = $astman->command('core show channels concise');
$chan_array = split("\n",$value['data']);
foreach($chan_array as $val)
{
   $this_chan_array = split("!",$val);
   if(isset($this_chan_array[7]))
   {
      $this_chan_array[7]=trim($this_chan_array[7]);
//      if($thenumber_orig == substr($this_chan_array[7],-10))
      if($thenumber_orig == $this_chan_array[7])
      {
         $value = $astman->command('core show channel '.$this_chan_array[0]);
         $this_array = split("\n",$value['data']);
         foreach($this_array as $val2)
         {
            if(strpos($val2,'FROM_DID=') !== false)
            {
               $DID = trim(str_replace('FROM_DID=','',$val2));
               break;
            }
         }
         
         //break out if the value is set.
         if($DID != '')
         {
            break;
         }
      }
   }
}

$param = array();
$query = "SELECT * FROM superfectaconfig";
$res = $db->query($query);
while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC))
{
   $param[$row['source']][$row['field']] = $row['value'];
}

if($debug)
{
   print "Debugging Enabled, will not stop after first result.<br>\n";
}

//loop through schemes
$query = "SELECT      source
               FROM         superfectaconfig
               WHERE         field = 'order'
               AND            value > 0";
if($debug && ($scheme != ""))
{
   $query .= " AND      source = '$scheme'";
}
$query .= " ORDER BY value";
$res = $db->query($query);
while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC))
{
   $this_scheme = $row['source'];
   $run_this_scheme = true;
   $thenumber = ereg_replace('[^0-9]+', '', $thenumber_orig);
   
   if($debug)
   {
      print "<hr>Processing ".substr($this_scheme,5)." Scheme.<br>\n";
   }
   //trying to push some info to the CLI
   $astman->command('VERBOSE "Processing '.substr($this_scheme,5).' Scheme." 3');
   
   //determine if this is the correct DID, if this scheme is limited to a DID.
   if(!empty($param[$this_scheme]['DID']))
   {
      $debug_result = "Valid DID.<br>\n";
      if($debug)
      {
         print "DID matching enabled...";
      }
      if(substr($param[$this_scheme]['DID'],0,1) == "_")
      {
         $DID_return = match_pattern(substr($param[$this_scheme]['DID'],1),$DID);
         if($DID != $DID_return)
         {
            $run_this_scheme = false;
            $debug_result = "DID did not match specified patterns.<br>\n";
         }
      }
      else if($DID != $param[$this_scheme]['DID'])
      {
         $run_this_scheme = false;
         $debug_result = "DID did not match.<br>\n";
      }
      
      if($debug)
      {
         print $debug_result;
      }
   }
   
   //determine if the CID matches any patterns defined for this scheme
   if(!empty($param[$this_scheme]['CID_rules']) && $run_this_scheme)
   {
      $debug_result = "No Matching CID Patterns.<br>\n";
      $run_this_scheme = false;
      if($debug)
      {
         print "CID matching enabled...";
      }
      $scheme_rules = split("\n",$param[$this_scheme]['CID_rules']);
      foreach($scheme_rules as $val)
      {
         $thenumber = match_pattern(trim($val),$thenumber_orig);
         if($thenumber !== false)
         {
            $run_this_scheme = true;
            $debug_result = "Valid CID: ".$thenumber.".<br>\n";
            break;
         }
      }
      
      if($debug)
      {
         print $debug_result;
      }
   }
   
   if($run_this_scheme)
   {
      $curl_timeout = $param[$this_scheme]['Curl_Timeout'];
      
      //if a prefix lookup is enabled, look it up, and truncate the result to 10 characters
      if($param[$this_scheme]['Prefix_URL'] != '')
      {
         if($debug)
         {
            $start_time = mctime_float();
         }
         
         $prefix = get_url_contents(str_replace("[thenumber]",$thenumber,$param[$this_scheme]['Prefix_URL']));
         
         if($debug)
         {
            print "Prefix Url defined ...\n";
            if($prefix !='')
            {
               print 'returned: '.$prefix."<br>\n";
            }
            else
            {
               print "result was empty<br>\n";
            }
            print "result <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
         }
      }
      
      //run through the specified sources
      $src_array = explode(',',$param[$this_scheme]['sources']);
      $theoriginalnumber = $thenumber;
      foreach($src_array as $source_name)
      {
         $thenumber = $theoriginalnumber;
         if($debug)
         {
            $start_time = mctime_float();
         }
         $caller_id = '';
         $run_param = $param[substr($this_scheme,5).'_'.$source_name];
         
         eval('include("source-'.$source_name.'.php");');
         $caller_id = _utf8_decode($caller_id);
         if(($first_caller_id == '') && ($caller_id != ''))
         {
            $first_caller_id = $caller_id;
            $winning_source = $source_name;
            if($debug)
            {
               $end_time_whole = mctime_float();
            }
         }
         
         if($debug)
         {
            if($caller_id != '')
            {
               print utf8_encode($caller_id)."<br>\nresult <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
            }
            else
            {
               print "result <img src='images/scrollup.gif'> took ".number_format((mctime_float()-$start_time),4)." seconds.<br>\n<br>\n";
            }
         }
         else if($caller_id != '')
         {
            break;
         }
      }
   
      
      $prefix = ($prefix != '') ? $prefix.':' : '';
      if($spam)
      {
         $first_caller_id = $param[$this_scheme]['SPAM_Text'].':'.$first_caller_id;
      }
   }
   
   if($first_caller_id != '')
   {
      break;
   }
}

//post-processing
if($debug)
{
   print "Post CID retrieval processing.<br>\n<br>\n";
}

//remove unauthorized character in the caller id
if ($first_caller_id !='')
   {
      //$first_caller_id = _utf8_decode($first_caller_id);
      $first_caller_id = strip_tags($first_caller_id );
      $first_caller_id = trim ($first_caller_id);
      if ($charsetIA5)
      {
         $first_caller_id = stripAccents($first_caller_id);
      }      
      $first_caller_id = preg_replace ( "/[\";']/", "", $first_caller_id);
      //limit caller id to the first 60 char
      $first_caller_id = substr($first_caller_id,0,60);
   }

$usage_mode = 'post processing';
foreach($src_array as $source_name)
{   
   $thenumber = $theoriginalnumber;
   $run_param = $param[substr($this_scheme,5).'_'.$source_name];
   eval('include("source-'.$source_name.'.php");');
}

if($debug)
{
   print "<b>Returned Result would be: ";
   $first_caller_id = utf8_encode($first_caller_id);
}
print $prefix.$first_caller_id;

if($debug)
{
   $end_time_whole = ($end_time_whole == 0) ? mctime_float() : $end_time_whole;
   print "<br>\nresult <img src='images/scrollup.gif'> took ".number_format(($end_time_whole-$start_time_whole),4)." seconds.</b>";
}

$astman->disconnect();

/**
Returns the content of a URL.
*/
function get_url_contents($url)
{
   global $debug,$curl_timeout;
   $crl = curl_init();
   $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
   curl_setopt($crl,CURLOPT_USERAGENT,$useragent);
   curl_setopt($crl,CURLOPT_URL,$url);
   curl_setopt($crl,CURLOPT_RETURNTRANSFER,true);
   curl_setopt($crl,CURLOPT_CONNECTTIMEOUT,$curl_timeout);
   curl_setopt($crl,CURLOPT_FAILONERROR,true);
   curl_setopt($crl,CURLOPT_TIMEOUT,$curl_timeout);
   $ret = trim(curl_exec($crl));
   if(curl_error($crl) && $debug)
   {
      print ' '.curl_error($crl).' ';
   }
   
   //if debug is turned on, return the error number if the page fails.
   if($ret === false)
   {
      $ret = '';
   }
   //something in curl is causing a return of "1" if the page being called is valid, but completely empty.
   //to get rid of this, I'm doing a nasty hack of just killing results of "1".
   if($ret == '1')
   {
      $ret = '';
   }
   curl_close($crl);
   return $ret;
}

function mctime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

/**
   Parses Asterisk dial patterns and produces a resulting number if the match is successful or false if there is no match.
*/
function match_pattern($pattern,$number)
{
   $return = false;
   $pattern_error = false;
   $pipe_location = 0;
   $plus_location = 0;
   $required_length = 0;
   $adjustable_length = false;
   $character_array = array();
   $number_split = str_split($number);
   
   //parse through the pattern and build an array for matching
   $split = str_split($pattern);
   $count = 0;
   $bracket_open = false;
   $range_open = false;
   $range_start = 0;
   foreach($split as $key=>$val)
   {
      $skip = false;
      if($val == "]")
      {
         $bracket_open = false;
         $range_open = false;
         $required_length++;
      }
      else if($bracket_open)
      {
         if(is_numeric($val))
         {
            if($range_open)
            {
               for($x = ($range_start + 1); $x <= $val; $x++)
               {
                  $character_array[$count][] = $x;
               }
            }
            else
            {
               $character_array[$count][] = $val;
            }
            $range_start = $val;
            $range_open = false;
         }
         else if($val == "-")
         {
            $range_open = true;
         }
         else
         {
            $pattern_error = true;
            break;
         }
         $skip = true;
      }
      else if($val == "[")
      {
         $bracket_open = true;
         $skip = true;
      }
      else if($val == "+")
      {
         if($plus_location > 0)
         {
            $pattern_error = true;
            break;
         }
         else
         {
            $plus_location = $count;
         }
      }
      else if($val == "|")
      {
         if($pipe_location > 0)
         {
            $pattern_error = true;
            break;
         }
         else
         {
            $pipe_location = $count;
         }
      }
      else if($val == "!")
      {
         if(isset($split[($key + 1)]))
         {
            $pattern_error = true;
            break;
         }
         else
         {
            $adjustable_length = true;
            for($x = $count; $x <= ($count + 30); $x++)
            {
               $character_array[$x] = array(0,1,2,3,4,5,6,7,8,9);
            }
         }
      }
      else if($val == ".")
      {
         if(isset($split[($key + 1)]))
         {
            $pattern_error = true;
            break;
         }
         else
         {
            $adjustable_length = true;
            $required_length++;
            for($x = $count; $x <= ($count + 30); $x++)
            {
               $character_array[$x] = array(0,1,2,3,4,5,6,7,8,9);
            }
         }
      }
      else if($val == "N")
      {
         $character_array[$count] = array(2,3,4,5,6,7,8,9);
         $required_length++;
      }
      else if($val == "X")
      {
         $character_array[$count] = array(0,1,2,3,4,5,6,7,8,9);
         $required_length++;
      }
      else if($val == "Z")
      {
         $character_array[$count] = array(1,2,3,4,5,6,7,8,9);
         $required_length++;
      }
      else if(is_numeric($val))
      {
         $character_array[$count][0] = $val;
         $required_length++;
      }
      else
      {
         $pattern_error = true;
         break;
      }
      
      if(!$skip)
      {
         $count++;
      }
   }
   
   if(!$pattern_error)
   {
      //check for the existence of both the plus and pipe.
      if(($pipe_location > 0) && ($plus_location > 0))
      {
         $good_number = true;
         $new_number = "";
         $prefix = "";
         if($pipe_location > $plus_location)
         {
            $required_length = $required_length - $plus_location;
            if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
            {
               for($x = 0; $x < $plus_location; $x++)
               {
                  if(count($character_array[$x]) > 1)
                  {
                     $pattern_error = true;
                     break;
                  }
                  else
                  {
                     $prefix .= $character_array[$x][0];
                  }
               }
               
               foreach($number_split as $key=>$val)
               {
                  $key = $key + strlen($prefix) + 1;
                  if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
                  {
                     $good_number = false;
                  }
                  else if($key > $pipe_location)
                  {
                     if(!in_array($val,$character_array[$key]))
                     {
                        $good_number = false;
                     }
                     else
                     {
                        $new_number .= $val;
                     }
                  }
               }
               if($good_number)
               {
                  $return = $prefix.$new_number;
               }
            }
         }
         else
         {
            $required_length = $required_length - $plus_location + $pipe_location + 1;
            if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
            {
               for($x = ($pipe_location + 1); $x < $plus_location; $x++)
               {
                  if(count($character_array[$x]) > 1)
                  {
                     $pattern_error = true;
                     break;
                  }
                  else
                  {
                     $prefix .= $character_array[$x][0];
                  }
               }
               
               foreach($number_split as $key=>$val)
               {
                  $key = ($key >= $pipe_location) ? ($key + $plus_location - $pipe_location + 1) : $key;
                  if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
                  {
                     $good_number = false;
                  }
                  else if($key > $pipe_location)
                  {
                     if(!in_array($val,$character_array[$key]))
                     {
                        $good_number = false;
                     }
                     else
                     {
                        $new_number .= $val;
                     }
                  }
               }
               if($good_number)
               {
                  $return = $prefix.$new_number;
               }
            }
         }
      }
      else if(($pipe_location > 0) && (($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number))))
      {
         $good_number = true;
         $new_number = "";
         foreach($number_split as $key=>$val)
         {
            if(($key < $pipe_location) && !in_array($val,$character_array[$key]))
            {
               $good_number = false;
            }
            else if($key >= $pipe_location)
            {
               $key++;
               if(!in_array($val,$character_array[$key]))
               {
                  $good_number = false;
               }
               else
               {
                  $new_number .= $val;
               }
            }
         }
         if($good_number)
         {
            $return = $new_number;
         }
      }
      else if($plus_location > 0)
      {
         $good_number = true;
         $prefix = "";
         $required_length = $required_length - $plus_location;
         if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
         {
            foreach($number_split as $key=>$val)
            {
               if($key < $plus_location)
               {
                  if(count($character_array[$key]) > 1)
                  {
                     $pattern_error = true;
                     $good_number = false;
                     break;
                  }
                  else
                  {
                     $prefix .= $character_array[$key][0];
                  }
               }
               else if(($key > $plus_location) && !in_array($val,$character_array[$key]))
               {
                  $good_number = false;
               }
            }
            if($good_number)
            {
               $return = $prefix.$number;
            }
         }
      }
      else if(($adjustable_length && ($required_length <= strlen($number))) || ($required_length == strlen($number)))
      {
         $good_number = true;
         foreach($number_split as $key=>$val)
         {
            if(!in_array($val,$character_array[$key]))
            {
               $good_number = false;
            }
         }
         if($good_number)
         {
            $return = $number;
         }
      }
   }
   
   
   //split on "+" and check each segment for a match.
   $split = split("+",$pattern);
   $build_number = "";
   $this_match = false;
   foreach($split as $val)
   {
      $this_number = match_pattern($val,$number);
      if(!$this_number)
      {
         $build_number .= $val;
      }
      else
      {
         $build_number .= $this_number;
         $this_match = true;
      }
   }
   
   if($this_match)
   {
      $return = $build_number;
   }
   
   if(!$return)
   {
      //if we don't have a good number to return, continue processing for "|"
      $split = split("+",$pattern);
      $combine = str_replace("|","",$pattern);
   }
   
   return $return;
}

MessaggioInviato: ven giu 04, 2010 9:37 am
da Omega
Di seguito il mio file "source-AsteriDex.php":
Codice: Seleziona tutto
<?php
//this file is designed to be used as an include that is part of a loop.
//If a valid match is found, it should give $caller_id a value
//available variables for use are: $thenumber
//retreive website contents using get_url_contents($url);

//configuration / display parameters
//The description cannot contain "a" tags, but can contain limited HTML. Some HTML (like the a tags) will break the UI.
$source_desc = "Searches an AsteriDex Database - local or remote.";
$source_param['DB_Host']['desc'] = 'Host address of the Asteridex database. (localhost if the database is on the same server as FreePBX)';
$source_param['DB_Host']['type'] = 'text';
$source_param['DB_Host']['default'] = $dsn[hostspec];
$source_param['DB_Name']['desc'] = 'Database name of the Asteridex database';
$source_param['DB_Name']['type'] = 'text';
$source_param['DB_Name']['default'] = 'asteridex';
$source_param['DB_User']['desc'] = 'Username used to connect to the Asteridex database';
$source_param['DB_User']['type'] = 'text';
$source_param['DB_User']['default'] = 'utente';
//$source_param['DB_User']['default'] = $dsn[username];
$source_param['DB_Password']['desc'] = 'Password used to connect to the Asteridex database';
$source_param['DB_Password']['type'] = 'password';
$source_param['DB_Password']['default'] = 'password';
//$source_param['DB_Password']['default'] = $dsn[password];
$source_param['Filter_Length']['desc'] = 'The number of rightmost digits to check for a match';
$source_param['Filter_Length']['type'] = 'number';
$source_param['Filter_Length']['default'] = 10;
//$dbname = "asteridex";

//run this if the script is running in the "get caller id" usage mode.
if($usage_mode == 'get caller id')
{
   if($debug)
   {
      print "Searching AsteriDex ... ";
   }
   
   $value = "";
   $wquery_input = preg_replace("/\D/","",$_REQUEST['thenumber']); // strip non-digits
   if(strlen($wquery_input) == 0) exit; // abandon search if no number is passed
   if (strlen($wquery_input) > $run_param['Filter_Length']) $wquery_input = substr($wquery_input, -$run_param['Filter_Length']); // keep only the filter_length rightmost digits
//include_once("/var/www/html/asteridex4/config.inc.php");
   $link = mysql_connect($run_param['DB_Host'], $run_param['DB_User'], $run_param['DB_Password'])or die("AsteriDex connection failed:". $run_param['DB_Host']);
//   $link = mysql_connect($dsn[hostspec], "utente", "password")or die("AsteriDex connection failed");
   mysql_select_db($run_param['DB_Name']) or die("AsteriDex data base open failed");
//   mysql_select_db($dbname) or die("AsteriDex data base open failed");
   $query = "SELECT * FROM `user1` where RIGHT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(`out`,' ',''),'+',''),'-',''),'(',''),')','')," . $run_param['Filter_Length'] . ") LIKE ".$wquery_input;
//   $query = "SELECT * FROM `user1` where RIGHT(`out`,".$run_param['Filter_Length'] . ") LIKE ".$wquery_input;
   $result = mysql_query($query) or die("AsteriDex query failed: $query");
   if (mysql_num_rows($result)>0)
   {
      $row = mysql_fetch_array($result);
      $value = $row["name"];
   }
   mysql_close($link);
   if(strlen($value) > 0)
   {
      $caller_id = $value;
   }
   else if($debug)
   {
      print "not found<br>\n";
   }
}
?>





Naturalmente ho anche provato a togliere il file ".htaccess" e, altrettanto naturalmente, dove ho scritto "utente" e "password", ci sono rispettivamente nome utente e password di MySQL etc. etc. Per semplificare ho tenuto entrambi i dati sempre gli stessi per tutto (GUI di FreePBX, MySQL, Asteridex etc. etc.). So che non è il massimo in termini di sicurezza, ma volevo essere sicuro, essendo il primo centralino, che i problemi non fossero dettati da errori di questo genere.




Scusate il triplo post, ma come mio solito, ho superato il limite di caratteri consentito.
Chiaccherone.  ;D

Grazie a tutti.

Ciao.

MessaggioInviato: gio giu 10, 2010 5:07 pm
da Omega
Sono tornato e sono il vostro incubo.

Aggiornamento: per raggiungere la tanto agognata/odiata meta, in realtà amo quello che non so fare ;-), ho deciso di cambiare.
Ho avuto poco tempo per fare dei test, ma oggi che la mia testa si è potuta fermare un secondo a pensare, che novità, ha deciso di intraprendere un'altra strada, facendo direttamente la query di MySQL dall'interfaccia del CallerID Lookup Sources. Come avrete capito stiamo sempre parlando di FreePBX e Asterisk 1.4.24 (AsteriskNOW). Sono comunque ben accette soluzioni da "scrivere a manina", che io amo, anche se non sembra, però fattibili per un neofita stu...pendo come me.



Cominciamo.




Interfaccia FreePBX
Codice: Seleziona tutto
Source: CidLookup (id 2)
Edit Source
Source Description:CidLookup    
Source type:MySQL
Cache results:Non marcato   
   
MySQL
Host: localhost    
Database: asteridex   
Query: SELECT name FROM user1 WHERE out LIKE '%[NUMBER]%'    
Username: MySQL Username    
Password: MySQL Password


Ciò comporta la conseguente modifica di "extensions_additional.conf" nella parte del "[cidlookup]":
Codice: Seleziona tutto
[cidlookup]
include => cidlookup-custom
exten => cidlookup_2,1,MYSQL(Connect connid localhost MySQL Username MySQL Password asteridex)
exten => cidlookup_2,n,MYSQL(Query resultid ${connid} SELECT\ name\ FROM\ user1\ WHERE\ out\ LIKE\ \'%${CALLERID(num)}%\')
exten => cidlookup_2,n,MYSQL(Fetch fetchid ${resultid} CALLERID(name))
exten => cidlookup_2,n,MYSQL(Clear ${resultid})
exten => cidlookup_2,n,MYSQL(Disconnect ${connid})
exten => cidlookup_2,n,Return()
exten => cidlookup_return,1,LookupCIDName
exten => cidlookup_return,n,Return()

; end of [cidlookup]



Dopo aver avuto accesso al database "asteridex" su MySQL, da terminale, il seguente comando
Codice: Seleziona tutto
SELECT name FROM `user1` WHERE `out` LIKE '%Numero che c'è dentro al database%';

restituisce il seguente risultato:
Codice: Seleziona tutto
+------+
| name |
+------+
| aaa  |
| bbb  |
+------+
2 rows in set (0.00 sec)

da cui deduco sia tutto ok. Almeno penso.


Nonostante tutto la chiamata non passa, mostrando questo log:
Codice: Seleziona tutto
    -- Executing [Mio "user=" voip@from-zaptel:1] Set("SIP/Mio "user=" voip-09c81ad8", "DID=Mio "user=" voip") in new stack
    -- Executing [Mio "user=" voip@from-zaptel:2] Goto("SIP/Mio "user=" voip-09c81ad8", "s|1") in new stack
    -- Goto (from-zaptel,s,1)
    -- Executing [s@from-zaptel:1] NoOp("SIP/Mio "user=" voip-09c81ad8", "Entering from-zaptel with DID == Mio "user=" voip") in new stack
    -- Executing [s@from-zaptel:2] Ringing("SIP/Mio "user=" voip-09c81ad8", "") in new stack
    -- Executing [s@from-zaptel:3] Set("SIP/Mio "user=" voip-09c81ad8", "DID=Mio "user=" voip") in new stack
    -- Executing [s@from-zaptel:4] NoOp("SIP/Mio "user=" voip-09c81ad8", "DID is now Mio "user=" voip") in new stack
    -- Executing [s@from-zaptel:5] GotoIf("SIP/Mio "user=" voip-09c81ad8", "0?zapok:notzap") in new stack
    -- Goto (from-zaptel,s,6)
    -- Executing [s@from-zaptel:6] Goto("SIP/Mio "user=" voip-09c81ad8", "from-pstn|Mio "user=" voip|1") in new stack
    -- Goto (from-pstn,Mio "user=" voip,1)
    -- Executing [Mio "user=" voip@from-pstn:1] Set("SIP/Mio "user=" voip-09c81ad8", "__FROM_DID=Mio "user=" voip") in new stack
    -- Executing [Mio "user=" voip@from-pstn:2] Gosub("SIP/Mio "user=" voip-09c81ad8", "app-blacklist-check|s|1") in new stack
    -- Executing [s@app-blacklist-check:1] LookupBlacklist("SIP/Mio "user=" voip-09c81ad8", "") in new stack
    -- Executing [s@app-blacklist-check:2] GotoIf("SIP/Mio "user=" voip-09c81ad8", "0?blacklisted") in new stack
    -- Executing [s@app-blacklist-check:3] Set("SIP/Mio "user=" voip-09c81ad8", "CALLED_BLACKLIST=1") in new stack
    -- Executing [s@app-blacklist-check:4] Return("SIP/Mio "user=" voip-09c81ad8", "") in new stack
    -- Executing [Mio "user=" voip@from-pstn:3] Gosub("SIP/Mio "user=" voip-09c81ad8", "cidlookup|cidlookup_2|1") in new stack
  == Spawn extension (cidlookup, cidlookup_2, 1) exited non-zero on 'SIP/Mio "user=" voip-09c81ad8'





Questo è tutto. Idee?


Problema risolto. Che bello.

E' bastato un bel "yum install asterisk-addons", perchè erano proprio quest'ultimi, a mancare.

E infatti nel log, quello completo, appariva questa frase:
Codice:

WARNING[12792] pbx.c: No application 'MYSQL' for extension (cidlookup, cidlookup_2, 1)


Grazie mille e ciao a tutti, per ora. Ghigno

MessaggioInviato: mer giu 30, 2010 5:14 pm
da cape
Finalmente sono riuscito a risolvere il problema del CallerID Superfecta, ecco la soluzione che spero possa essere d'aiuto a tutti.
Per far andare il CID lookup di FreePBX e il CallerID Superfecta bisogna aver installato il pacchetto asterisk-curl che io non avevo, per quello non mi risolveva i numeri in nomi.

Ciao

MessaggioInviato: mer lug 07, 2010 7:32 am
da TheBus
oggi ho trovato questo:
http://eltel.elenchitelefonici.it/home/ ... ero=xxxxxx che dato il numero ritorna il nome

MessaggioInviato: mer lug 21, 2010 8:33 am
da Ste73
cape ha scritto:
Finalmente sono riuscito a risolvere il problema del CallerID Superfecta, ecco la soluzione che spero possa essere d'aiuto a tutti.
Per far andare il CID lookup di FreePBX e il CallerID Superfecta bisogna aver installato il pacchetto asterisk-curl che io non avevo, per quello non mi risolveva i numeri in nomi.

Ciao


Ciao! Io ho Freepbx, in debug il modulo callerid superfecta funziona perfettamente ... ma se lo abbino ad un inbound route ... non va ... e non ho capito dove scrive eventuali log di errore.

Ho verificato e non ho la funzione CURL installata, ma pensavo usasse un semplice wget, no? Ad ogni modo, come la installo? ;)

MessaggioInviato: ven lug 23, 2010 11:39 am
da cape
Io avevo fatto un yum install asterisk-curl, devi avere installati i repository di asterisk.

Ciao

MessaggioInviato: lun set 13, 2010 3:39 pm
da parna
Dove trovo lo script in php cid.php?

MessaggioInviato: gio gen 13, 2011 4:14 pm
da alanb
Volevo segnalare come sono riuscito a far funzionare lo script di babyporch in una configurazione Pbx In A Flash con asterisk 1.4
1. Installare i seguenti pacchetti: perl-AppConfig-1.66-1.el5.rf.noarch.rpm, perl-XML-Simple-2.14-8.0.el5.noarch.rpm
2. Installalare asteridex4
3. copiare lo script ed il file di configurazione di babyporch in /var/www/cgi-bin.
4. In Freepbx definire come suggerito da babyporch facendo attenzione che il path sia /cgi-bin/cnam.pl

Da notare che ho modificato lo script affinche gestisca correttamente le chiamate che entrano tramite tramite voip poiche' esse hanno come numero +39xxxxx

Codice: Seleziona tutto
#!/usr/bin/perl -w

#Ultimate CNAM v1.0
#Date:  12/28/07
#Author: Jonathan Rudenberg <jon335@gmail.com>

#Copyright 2007-2008 Jonathan Rudenberg
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>

#Please note that if you do not have the XML::Simple and AppConfig Perl modules installed, this script will fail!!!
#They are NOT part of a default PBX-in-a-Flash installation.
#Please see the installation instrucations at http://nerdvittles.com/forum/showthread.php?t=65

# Do not edit anything beyond this point unless you know what you are doing!!
####################################################################

use strict;
use warnings;

use DBI;
use AppConfig;
use XML::Simple;
use LWP::UserAgent;
use HTML::TokeParser;

my $xml = new XML::Simple;

my $config = AppConfig->new();

$config->define("configFile",
        {ARGCOUNT => 1, DEFAULT => '/var/www/cgi-bin/cnam.cfg', ALIAS => 'c'});

my $configFile = $config->configFile;

$config->define("Asteridex",   {DEFAULT => 1});
$config->define("Infobel",   {DEFAULT => 1});

$config->define("WCU_name",      {ARGCOUNT => 1});
$config->define("WCU_pass",      {ARGCOUNT => 1});
$config->define("WCU_threshold", {ARGCOUNT => 1});
$config->define("WCU_CNAM",      {ARGCOUNT => 1});

$config->define("debug", {DEFAULT => 0,});

$config->define("number", {ARGCOUNT => 1});

if (-e $configFile) {
        $config->file($configFile);
}
$config->cgi();
$config->args();

my $Asteridex   = $config->Asteridex;
my $Infobel   = $config->Infobel;

my $WCU_name      = $config->WCU_name;
my $WCU_pass      = $config->WCU_pass;
my $WCU_threshold = $config->WCU_threshold;
my $WCU_CNAM      = $config->WCU_CNAM;

my $debug = $config->debug;

my $callerid = $config->number;

if (! $callerid) {
        die "Number undefined\n";
}

print "Content-type: text/html\n\n";

$callerid =~ s/\ //g;


if (substr($callerid, 0, 1) eq '1') {
        $callerid = substr($callerid, 1);
}

if (substr($callerid, 0, 2) eq '+1') {
        $callerid = substr($callerid, 2);
}

if (substr($callerid, 0, 2) eq '39') {
        $callerid = substr($callerid, 2);
}
    my $numero = $callerid;
    my $seconda = substr ($numero, 1, 1);
    my $terza = substr ($numero, 2, 1);

    my $prefisso = "";
    my $num = "";
    my $pre_cell = "";

    if ( substr ($numero, 0, 1) eq '3' ) {
        $pre_cell = 3;
        $prefisso = substr ($numero, 0, 3);
        $num = substr ($numero, 3);
    } else {
        if (($seconda == 2) || ($seconda == 6)) {
            $prefisso = substr ($numero, 0, 2);
            $num = substr ($numero, 2);
        } elsif (($terza == 0) || ($terza == 1) || ($terza == 5) || ($terza == 9)) {
            $prefisso = substr ($numero, 0, 3);
            $num = substr ($numero, 3);
        } elsif (($terza == 2) || ($terza == 3) || ($terza == 4) || ($terza == 6) || ($terza == 7) ||($terza == 8)) {
            $prefisso = substr ($numero, 0, 4);
            $num = substr ($numero, 4);
        } else {
            print "Numero non valido\n";
            exit(0);
        }
    }

my $name;
if ($Asteridex == 1) {
        if ($debug == 1) {print "Ready for AsteriDex lookup...\n";}
        if ($name = &asteridex_lookup($prefisso, $num)) {
                print "$name\n";
                if ($debug == 1) {
                        print "AsteriDex match. New CallerIDName = $name\n";
                }
                exit(0);
        } elsif ($debug == 1) {
                print "Unable to find an AsteriDex match.\n";
        }
} elsif ($debug == 1) {
        print "Asteridex lookup disabled.\n";
}

if (( $Infobel > '0' ) && ( !$pre_cell )) {
        if ($debug == 1) {print "Ready for Infobel lookup...\n";}
        if ( $name = &infobel_lookup ($prefisso, $num) ) {
            print "$name\n";
           if ($debug == 1) {print "InfoBel match. New CallerIDName = $name\n";}
            &asteridex_insert ($prefisso, $num, $name);
         exit(0);
        } else {
           if ($debug == 1) {print "Unable to find an InfoBel lookup.\n";}
}}

exit(0);

sub asteridex_lookup {
        my ($prefisso, $num) = @_;
        my $dbh = DBI->connect("dbi:mysql:asteridex", "root", "passw0rd")
          or die("Connect failed");
        my $sth =
          $dbh->prepare("select * from user1 where `out` = '$prefisso$num'")
          or die("Prepare failed.");
        $sth->execute;
        if ($sth->rows == 0) {
                return '';
        } else {
                my $resptr   = $sth->fetchrow_hashref();
                my $clidname = $resptr->{"name"};
                return $clidname;
        }

        $dbh->disconnect;
        return '';
}

sub infobel_lookup {
    my ($prefisso, $num) = @_;
    my $ua = new LWP::UserAgent;
    $ua->agent("AgentName/0.1 " . $ua->agent);
    my $URL = 'http://www.infobel.com/it/italy/inverse.aspx';
    my $req = new HTTP::Request POST => $URL;
    $req->content_type('application/x-www-form-urlencoded');
    $req->content('qPhone=' . $prefisso . $num . '&SubmitREV=Ricerca&inphCoordType=EPSG');
    my $res = $ua->request($req);
    my $cidname = "";
    if ( $res->is_success() ) {
        if ( $res->content =~ /QName=(.*)&QNum/ ) {
            $cidname = $1;
            $cidname=~ s![-\\|_/]!!g;
            $cidname=~ s/[ ]+/ /gsi;
            $cidname=~ s/\'//g;
        }
        my $newcallerid = "\"$cidname <$prefisso$num>\"";
        return $cidname;
    } else {
        return "";
    }
}

sub asteridex_insert {
    my ($prefisso, $num, $name) = @_;
    my $dbh = DBI->connect("dbi:mysql:asteridex","root","passw0rd") or die("Connect failed");
    my $sth = $dbh->prepare("INSERT INTO user1 VALUES (null, '$name', '*', '$prefisso$num','')");
    $sth->execute;
    $dbh->disconnect;
}


Saluti a tutti.

MessaggioInviato: ven feb 04, 2011 11:06 am
da anna80
Posto un mini-guida per configurare il callerid superfecta 2.0 su elastix:

  • Scaricare Superfecta da questo link: http://projects.colsolgrp.net/projects/list_files/superfecta
  • Aprire FreePBX e selezionare: Admin, Module Admin, Upload Module
  • Selezionare: superfecta-2.x.x.tgz module e click su Upload
  • Cliccare su local module administration. Selezionare CID Superfecta. Click su Install o Upgrade radio button. Click Process, Confirm, Return per installare il nuovo modulo.
  • Per configurare CallerID Superfecta, cliccare Admin, Setup, CID Superfecta in FreePBX
  • Selezionare Default
  • Attivare I servizi Infobel (selezionando IT) e Pagine bianche
  • Nel campo Username digitare admin
  • Nel campo password la password di accesso a Elastix
  • Confermare tutto
  • Nelle Inbound routes nella voce Source selezionare Caller ID Superfecta
  • Aggiungere in /etc/httpd/conf.d/elastix.conf le seguenti righe:

Codice: Seleziona tutto
<Directory "/var/www/html">
    # Redirect administration interface to https
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !(/admin/modules/superfecta/*)
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Directory>


Tutto dovrebbe funzionare a dovere! Ciao Anna

MessaggioInviato: gio nov 03, 2011 7:10 pm
da Raiden
A me lo fa in automatico, ma semplicemente perchè ho la mia rubrica telefonica, sul pc, chiunque mi chiami e sia nella rubrica telefonica compare anche il numero..

MessaggioInviato: gio dic 01, 2011 10:41 am
da GabrieleMaoret
Purtroppo i due provider per l'Italia (cioè Infobel [IT] e Pagine Bianche) sembrano non funzionare più correttamente... Probabilmente è necessario un aggiornamento dei loro moduli.

Qualcuno sa come si può fare per contattare gli sviluppatori o come modificarli "in proprio"(magari poi mandando le modifiche agli autori originali)?

MessaggioInviato: mer gen 04, 2012 5:39 pm
da Tukler
Salve a tutti, ho aggiornato gli script per PagineBianche ed InfoBel IT per utilizzo personale. Oggi ho inviato le patch al responsabile del progetto.
Avendo trovato questo thread su Google ho pensato di aggiungere le patch anche qui.

In ogni caso Infobel non so quanto sia utile, è molto lenta (3-4 secondi) e a quanto ho capito è a sottoscrizione volontaria, quindi credo siano sempre più complete le Pagine Bianche.

Codice: Seleziona tutto
--- source-PagineBianche_IT.original.php        2012-01-04 16:54:23.017475704 +0100
+++ source-PagineBianche_IT.php 2012-01-04 17:23:39.657475697 +0100
@@ -37,12 +37,12 @@
                }       
        }
 
-       $url = "http://www.paginebianche.it/execute.cgi?ver=default&font=default&btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=";
+       $url = "http://www.paginebianche.it/ricerca-da-numero";
       
-       $url = $url . "&qs=" . $thenumber;
+       $url = $url . "?qs=" . $thenumber;
        $sresult =  get_url_contents($url);
       
-       preg_match_all('=<h3.class\=\"org\"[^>]*>(.*)</h3>=siU', $sresult, $sname);
+       preg_match_all('=<h2.class\=\"rgs\"[^>]*><a[^>]*>(.*) </a></h2>=siU', $sresult, $sname);
       
        if (count($sname[1]) > 0)
        {

Codice: Seleziona tutto
--- source-Infobel.original.php 2012-01-04 16:54:09.827475704 +0100
+++ source-Infobel.php  2012-01-04 16:56:13.067475704 +0100
@@ -246,7 +246,8 @@
                        case "LU" :
                        case "DK":
                        case "AU":
-                       case "DE" :
+                       case "DE":
+                       case "IT":
                                preg_match_all('/<span class="fn org">(.*)<\/span><\/a>/U', $sresult, $sname);
                                break;


Ho anche provato ad utilizzare la versione mobile di PagineBianche, pensando che in quanto più leggera fosse anche più veloce, ma a quanto pare in realtà è più lenta (0.66 secondi di media contro 0.44 della desktop). Comunque, se la volete provare, la patch è questa:

Codice: Seleziona tutto
--- source-PagineBianche_IT.original.php        2012-01-04 16:54:23.017475704 +0100
+++ source-PagineBianche_IT.php 2012-01-04 18:27:50.557475679 +0100
@@ -37,13 +37,13 @@
                }       
        }
 
-       $url = "http://www.paginebianche.it/execute.cgi?ver=default&font=default&btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=";
-       
-       $url = $url . "&qs=" . $thenumber;
-       $sresult =  get_url_contents($url);
-       
-       preg_match_all('=<h3.class\=\"org\"[^>]*>(.*)</h3>=siU', $sresult, $sname);
+       $url = "http://smartphone.paginebianche.it/searchtel?emvcc=0";
       
+       $url = $url . "&what=" . $thenumber;
+       $sresult = get_url_contents($url);
+               
+       preg_match_all('=<div.id\=\"line\"[^>]*><div[^>]*><strong[^>]*>[^<]*<a[^>]*>(.*)</a></strong>=siU', $sresult, $sname);
+               
        if (count($sname[1]) > 0)
        {
                $sname = $sname[1][0];

MessaggioInviato: mar gen 10, 2012 8:58 am
da GabrieleMaoret
lun gen 09, 2012 7:34 pm
Grazie Tukler. Domani proverò le tue modifiche!





EDIT1 : mar gen 10, 2012 9:58 am

Una domanda per Tukler: tu usi la versione 2.4 oppure sei passato ad una beta più recente?






EDIT2: mar gen 10, 2012 11:26 am

P.S.: credo di fare qualche errore nell'applicare le patch... non potresti passarci i file già patchati?

Grazie in anticipo...