root/modules/branches/2.6/sipstation/sipstation.html.php

Revision 8417, 7.2 kB (checked in by p_lindheimer, 4 years ago)

new sipstation module to auto-configure and monitor FreePBX.com SIP trunks and service

Line 
1 <?php
2 /* $Id:$ */
3
4 // Original Release by Philippe Lindheimer
5 // Copyright Philippe Lindheimer (2009)
6 // Copyright Bandwidth.com (2009)
7 /*
8    TODO: Get proper licensing.
9          This is free to use and distribute for use. The licensing is NOT GPL or other open source and derivative work is not allowed.
10 */
11
12 // TODO: set this in production
13 error_reporting(0);
14
15 include_once('sipstation.utility.php');
16
17 if (! @include_once("common/json.inc.php")) {
18   include_once("/var/www/html/admin/common/json.inc.php");
19   include_once("/var/www/html/admin/functions.inc.php");
20
21   $amp_conf = parse_amportal_conf("/etc/amportal.conf");
22     require_once('/var/www/html/admin/common/php-asmanager.php');
23     $astman        = new AGI_AsteriskManager();
24     if (!isset($amp_conf["ASTMANAGERPROXYPORT"]) || !$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPROXYPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off')) {
25         if (!$res = $astman->connect("127.0.0.1:".$amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"], 'off')) {
26             unset( $astman );
27         }
28     }
29   include_once("/var/www/html/admin/common/db_connect.php");
30   include_once("/var/www/html/admin/modules/core/functions.inc.php");
31   if (!isset($active_modules)) {
32     $active_modules = array();
33   }
34 }
35 global $db;
36 global $sipstation_xml_version;
37 /* For testing:
38 *//*
39 include_once("common/json.inc.php");
40 */
41
42
43 //TODO: mockup, would need to do error checking
44 //
45
46 $json_array = sipstation_get_config( sipstation_get_key() );
47
48 /* Check if we have trunks configured with the same credentials
49    and if so, skip the trunk creation mode
50
51    Note: there are some ugly queries below. We don't like to do that
52          but the APIs are not ideal and very heavy. This turns out
53          to be much more efficient to detect these trunks.
54  */
55 $trunk_conflict = array();
56 if ($json_array['query_status'] == 'SUCCESS') {
57   $sip_user = $json_array['sip_username'];
58   $gateways = implode("','",$json_array['gateways']);
59
60   $sql = "
61    SELECT `id` FROM `sip` WHERE `keyword` = 'username'
62    AND `data` = '$sip_user' AND `id` IN (
63      SELECT `id` FROM `sip` WHERE `keyword` = 'host'
64      AND `data` IN ('$gateways')
65    )";
66   $results = $db->getCol($sql);
67   if(DB::IsError($results)) {
68       $results = array();
69   }
70  
71   $sql = "SELECT `id` FROM `sip` WHERE `keyword` = 'register' AND (";
72   foreach ($json_array['gateways'] as $gw) {
73     $sql .= "(`data` LIKE '$sip_user:%@$gw%') OR ";
74   }
75   $sql = rtrim($sql,' OR').")";
76   $results2 = $db->getCol($sql);
77   if(DB::IsError($results)) {
78       $results2 = array();
79   }
80   $results2 = array_merge($results, $results2);
81
82   /* Now we have to find the trunk, looking at the pre-2.6 and post
83      2.6 account id formats
84    */
85   $existing_trunks = array();
86   $existing_trunk_hash = array();
87   foreach ($results2 as $tr) {
88     if (preg_match('/^9999([\d]{1,2})$|^99999([\d]{1,2})$|^9999999([\d]{1,2})$|^tr-peer-([\d]+)$|^tr-user-([\d]+)$|^tr-reg-([\d]+)$/',$tr,$match)) {
89       $existing_trunks[$match[count($match)-1]][] = $tr;
90       $existing_trunk_hash[$tr] = $match[count($match)-1];
91     }
92   }
93   $sql = "SELECT `data` name, `id` FROM `sip` WHERE `keyword` = 'account' AND `id` IN ('".implode("','",array_keys($existing_trunk_hash))."')";
94   $results = $db->getAll($sql,DB_FETCHMODE_ASSOC);
95   if(DB::IsError($results)) {
96       $results = array();
97   }
98
99   foreach ($results as $trunk_name) {
100     if ($trunk_name['name'] != "fpbx-1-$sip_user" && $trunk_name['name'] != "fpbx-2-$sip_user") {
101       $tname core_trunks_getTrunkTrunkName($existing_trunk_hash[$trunk_name['id']]);
102       if ($tname != $trunk_name['name']) {
103         $tname .= " ({$trunk_name['name']})";
104       }
105       $trunk_conflict[] = array('name' => $tname, 'href' => 'OUT_'.$existing_trunk_hash[$trunk_name['id']]);
106     }
107   }
108 }
109
110 /* If we detected trunk conflicts then we don't bother with the Trunk and Routing
111    section, just report and be done.
112  */
113 if (!empty($trunk_conflict)) {
114   unset($json_array['query_status_message']);
115   unset($json_array['query_status']);
116   $json_array['trunk_conflict'] = $trunk_conflict;
117
118 } elseif ($json_array['query_status'] == 'SUCCESS' && $json_array['xml_version'] == $sipstation_xml_version) { // TODO: This needs to be checking that there was no failure
119   $need_reload = sipstation_get_or_create_trunks($json_array,$globalvar1,$trunknum1,$globalvar2,$trunknum2);
120   if ($need_reload) {
121     needreload();
122     if ($_POST['send_reload'] == 'yes') {
123       ob_start();
124       if (!@include ('views/freepbx_reloadbar.php')) {
125         @include ('../../views/freepbx_reloadbar.php'); //TODO for debugging
126       }
127       $json_array['reload_bar'] = ob_get_clean();
128       ob_start();
129       if (!@include ('views/freepbx_reload.php')) {
130         @include ('../../views/freepbx_reload.php'); //TODO for debugging
131       }
132       $json_array['reload_header'] = ob_get_clean();
133     }
134     $json_array['show_reload'] = 'yes';
135   } else {
136     $json_array['show_reload'] = 'no';
137   }
138
139   // Check trunknum1 for a prefix and use it since it is the primary trunk
140   // hopefully they will be the same
141   //
142   $json_array['areacode'] = "";
143   if ($temp = core_trunks_getDialRules($trunknum1)) {
144     foreach ($temp as $key=>$val) {
145       // extract all ruleXX keys
146       if (preg_match("/^rule\d+$/",$key)) {
147         if (preg_match("/^1([\d]{3})\+NXXXXXX$/",$val,$matches)) {
148           $json_array['areacode'] = $matches[1];
149           break;
150         }
151       }
152     }
153   }
154   $settings = sipstation_get_sip_settings();
155   $json_array['asterisk_registerattempts'] = $settings['Outbound reg. attempts'];
156
157   // Get the Asterisk Registration Status, retry once if bumping into Auth. Sent.
158   //
159   $try_again = false;
160   $cnt = 0;
161   do {
162     if ($try_again) {
163       sleep(1);
164     }
165     $cnt++;
166     $trunk_status = sipstation_get_registration_status($json_array['sip_username']);
167     foreach ($json_array['gateways'] as $gw => $trunk) {
168       if (isset($trunk_status[$trunk])) {
169         $json_array['asterisk_registry'][$gw] = $trunk_status[$trunk];
170         $try_again = $trunk_status[$trunk] == 'Auth. Sent' ? true : $try_again;
171       } else {
172         $json_array['asterisk_registry'][$gw] = _("Not Registered");
173       }
174     }
175   } while ($try_again && $cnt < 2);
176
177   $routes = core_routing_getroutenames();
178
179   foreach($routes as $route) {
180     $route_name = substr($route[0],4);
181     $trunks = core_routing_getroutetrunks($route[0]);
182
183     $gw1 = array_search($globalvar1,$trunks);
184     $gw1 = ($gw1 === false ? 0 : $gw1+1);
185
186     $gw2 = array_search($globalvar2,$trunks);
187     $gw2 = ($gw2 === false ? 0 : $gw2+1);
188     $json_array['routes'][$route_name] = array('gw1' => $gw1, 'gw2' => $gw2);
189   }
190 } elseif ($json_array['query_status'] == 'SUCCESS' && $json_array['xml_version'] != $sipstation_xml_version) {
191     $json_array['status'] = sprintf(_("Your module version is not compatible with the current API requirements and needs to be updated. Expecting XML version %s and received version %s."),$sipstation_xml_version, $json_array['xml_version']);
192   unset($json_array['query_status_message']);
193   unset($json_array['query_status']);
194 } else {
195     $json_array['status'] = $json_array['query_status_message'];
196   unset($json_array['query_status_message']);
197   unset($json_array['query_status']);
198 }
199
200 $json = new Services_JSON();
201 header("Content-type: application/json");
202 echo $json->encode($json_array);
203
Note: See TracBrowser for help on using the browser.