root/modules/branches/2.10/dahdiconfig/functions.inc.php

Revision 11758, 42.3 kB (checked in by p_lindheimer, 2 years ago)

fix undefined index re #4937 but should not have anything to do with that bug

Line 
1 <?php
2
3 /**
4  * FreePBX DAHDi Config Module
5  *
6  * Copyright (c) 2009, Digium, Inc.
7  *
8  * Author: Ryan Brindley <ryan@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License Version 2.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Affero General Public License for more details.
17  *
18  * You should have received a copy of the GNU Affero General Public License
19  * along with this program. If not, see <http://www.gnu.org/licenses/>.
20  *
21  */
22
23 global $db;
24
25 /**
26  * DAHDI CONF
27  *
28  * This class contains all the functions to configure asterisk via freepbx
29  */
30  class dahdiconfig_conf {
31     var $cards;
32
33      public function dahdiconfig_conf() {
34         $this->cards = new dahdi_cards();
35
36         $this->cards->dahdi_cfg();
37         $this->cards->write_modprobe();
38     }
39
40     public function get_filename() {
41         return array('chan_dahdi_general.conf', 'chan_dahdi_groups.conf');
42     }
43
44     public function generateConf($file) {
45         switch($file) {
46         case 'chan_dahdi_general.conf':
47             $output = array();
48         
49             if ( ! $this->cards->get_advanced('mwi_checkbox')) {
50                 return '';   
51             }
52
53             if ($this->cards->get_advanced('mwi') == 'fsk') {
54                 $output[] = "mwimonitor=fsk";
55                 $output[] = "mwilevel=512";
56                 $output[] = "mwimonitornotify=__builtin__";
57             } else if ($this->cards->get_advanced('mwi') == 'neon') {
58                 $output[] = "mwimonitor=neon";
59                 $output[] = "mwimonitornotify=__builtin__";
60             }
61
62             return implode("\n", $output);
63         case 'chan_dahdi_groups.conf':
64             $output = array();
65
66             foreach ($this->cards->get_spans() as $key=>$span) {
67                 if ($span['signalling'] == '') {
68                     continue;
69                 }
70
71                 $output[] = "";
72                 $output[] = "; [span_{$key}]";   
73                 $output[] = "signalling={$span['signalling']}";
74                 $output[] = "switchtype={$span['switchtype']}";
75                 $output[] = "pridialplan={$span['pridialplan']}";
76                 $output[] = "prilocaldialplan={$span['prilocaldialplan']}";
77                 $output[] = "group={$span['group']}";
78                 $output[] = "context={$span['context']}";
79                 $output[] = "channel=".$this->cards->calc_bchan_fxx($key);
80             }
81
82             foreach ($this->cards->get_analog_ports() as $num=>$port) {
83                 if ($port['type'] == '') {
84                     continue;
85                 }
86
87                 $output[] = "";
88                 $output[] = "signalling=".(($port['type']=='fxo')?'fxs':'fxo')."_{$port['signalling']}";
89                 $output[] = "context={$port['context']}";
90                 if (isset($port['group']) && $port['group'] != 0) {
91                     $output[] = "group={$port['group']}";
92                 }
93                 $output[] = "channel=>{$num}";
94             }
95
96             return implode("\n", $output);
97         default:
98             return '';
99         }
100     }
101
102  }
103
104 /**
105  * DAHDI CARDS
106  *
107  * This class contains all the functions necessary to manage DAHDi hardware.
108  */
109 class dahdi_cards {
110     private $analog_ports = array();    // stores all analog port info
111     private $advanced = array(        // advanced array of values
112         'module_name'=>'wctdm24xxp',
113         'tone_region'=>'us',
114         'opermode_checkbox'=>0,
115         'opermode'=>'USA',
116         'alawoverride_checkbox'=>0,
117         'alawoverride'=>0,
118         'fxs_honor_mode_checkbox'=>0,
119         'fxs_honor_mode'=>0,
120         'boostringer_checkbox'=>0,
121         'boostringer'=>0,
122         'fastringer_checkbox'=>0,
123         'fastringer'=>0,
124         'lowpower_checkbox'=>0,
125         'lowpower'=>0,
126         'ringdetect_checkbox'=>0,
127         'ringdetect'=>0,
128         'mwi_checkbox'=>0,
129         'mwi'=>'none',
130         'neon_voltage'=>'',
131         'neon_offlimit'=>'',
132         'echocan_nlp_type'=>0,
133         'echocan_nlp_threshold'=>'',
134         'echocan_nlp_max_supp'=>'' );
135     private $configured_hdwr = array();     // The hardware already configured
136     private $channels = array();       
137     private $chan_dahdi_conf;        // /etc/asterisk/chan_dahdi_additional.conf
138     private $dahdi_scan;            // The output of a DAHDi scan
139     private $detected_hdwr = array();    // Existing hardware on the sys
140     private $drivers_list = array(        // List of available drivers
141         'tor2',
142         'wcb4xxp',
143         'wcfxo',
144         'wct1xxp',
145         'wct4xxp',
146         'wctc4xxp',
147         'wctdm24xxp',
148         'wctdm',
149         'wcte11xp',
150         'wcte12xp',
151         'wcusb',
152         'xpp_usb' );
153     private $echocans = array(        // List of possible echo cancellers
154         'mg2'=>0,
155         'kb1'=>1,
156         'sec'=>2,
157         'sec2'=>3,
158         'hpec'=>4 );
159     private $error_msg = '';        // The latest error message
160     private $fxo_ports = array();
161     private $fxs_ports = array();
162     private $groups = array();        // DAHDi Groups
163     private $hardware = array();       
164     private $has_analog_hdwr = FALSE;    // If the sys has analog hardware
165     private $has_vpm = FALSE;        // If the sys has echo can
166     private $has_digital_hdwr = FALSE;    // If the sys has digital hardware
167     private $hdwr_changes = FALSE;        // If hardware has changed since last configure
168     private $module_name = 'wctdm24xxp';    // The module used
169     private $ports_signalling = array(    // The ports signalling
170         'ls' => array(),
171         'ks' => array() );
172     private $spancount = array();        // Per location
173     private $spans = array();        // The current spans
174     private $system_conf;            // /etc/dahdi/system.conf
175
176     /**
177      * Constructor
178      */
179     public function dahdi_cards () {
180         if (!is_file('/etc/dahdi/system.conf')) {
181             $this->dahdi_genconf();
182         }
183
184         $this->load();
185     }
186
187     /**
188      * Calc Bchan Fxx
189      *
190      * Calculates the bchan and fxx strings for a given span
191      */
192      public function calc_bchan_fxx($num) {
193          $span = $this->spans[$num];
194         $y = $span['min_ch'];
195         
196         if ($span['totchans'] == 3) {
197             return "$y-".($y+1);
198         }
199
200         $z = $span['definedchans'];
201         if ($z === 1) {
202             return $y;
203         }
204
205         if (isset($span['signalling']) && $span['signalling'] != "" && (substr($span['signalling'],0,3) !== 'pri')) {
206             return "$y-".($y+$z);
207         }
208
209         if ($span['totchans'] <= 24) {
210             return "$y-".($y+$z-1);
211         }
212
213         if ($z == 16) {
214             return "$y-".($y+14).",".($y+16);
215         } else if ($z < 16) {
216             return "$y-".($y+$z-1);
217         } else {
218             return "$y-".($y+14).",".($y+16)."-".($y+$z-1);
219         }
220      }
221
222     /**
223      * DAHDi Gen Conf
224      *
225      * Run dahdi_genconf to generate system.conf
226      */
227      public function dahdi_genconf() {
228         return `/usr/sbin/dahdi_genconf`;
229      }
230
231      /**
232       * DAHDi Config
233       *
234       * Run dahdi_cfg
235       */
236       public function dahdi_cfg() {
237         return `/usr/sbin/dahdi_cfg`;
238       }
239
240     /**
241      * Detect Hardware Changes
242      *
243      * Compare the known hardware with the current sys hardware and report
244      * if there are any changes
245      *
246      * @access public
247      * @return bool
248      */
249     public function detect_hdwr_changes() {
250         if ( count($this->detected_hdwr) != count($this->configured_hdwr)) {
251             return TRUE;
252         }
253
254         foreach ($this->detected_hdwr as $location=>$detected) {
255             if ( ! isset($this->configured_hdwr[$location])) {
256                 return TRUE;
257             }
258
259             $configured = $this->configured_hdwr[$location];
260
261             $fields = array('device', 'basechan', 'type');
262             foreach ($fields as $fld) {
263                 if ($configured[$fld] == $detected[$fld]) {
264                     continue;
265                 }
266
267                 if ($fld == 'analog' && $detected[$fld] == 'analog') {
268                     if (gettype($configured[$fld]) != gettype($detected[$fld])) {
269                         return TRUE;
270                     } else if (count($configured[$fld]) != count($detected[$fld])) {
271                         return TRUE;
272                     }
273
274                     
275                     for($i=0; $i<count($detected['port']); $i++) {
276                         if ($configured['port'][$i] == $detected['port'][$i]) {
277                             continue;
278                         }
279
280                         return TRUE;
281                     }
282
283                     continue;
284                 }
285
286                 return TRUE;
287             }
288         }
289
290         return FALSE;
291     }
292
293     /**
294      * Get Advanced
295      *
296      * Get an advanced parameter
297      */
298      public function get_advanced($param) {
299         return $this->advanced[$param];
300      }
301
302     /**
303      * Get All Advanced
304      *
305      * Get all advanced parameters
306      */
307      public function get_all_advanced() {
308         return $this->advanced;
309      }
310
311     /**
312      * Get Analog Ports
313      *
314      * Get all analog port info
315      */
316      public function get_analog_ports() {
317         return $this->analog_ports;
318      }
319
320     /**
321      * Get Channels
322      *
323      * Get the channels array
324      *
325      * @access public
326      * @return array
327      */
328     public function get_channels() {
329         return $this->channels;
330     }
331
332     /**
333      * Get Hardware
334      *
335      * Get the hardware array
336      *
337      * @access public
338      * @return array
339      */
340     public function get_hardware() {
341         return $this->hardware;
342     }
343
344     /**
345      * Get FXO Ports
346      *
347      * Get the FXO ports
348      *
349      * @access public
350      * @return array
351      */
352     public function get_fxo_ports() {
353         return $this->fxo_ports;
354     }
355
356     /**
357      * Get FXS Ports
358      *
359      * Get the FXS ports
360      *
361      * @access public
362      * @return array
363      */
364     public function get_fxs_ports() {
365         return $this->fxs_ports;
366     }
367
368     /**
369      * Get FX(O|S)LS ports
370      *
371      * Get all the FXO and FXS ports with loop start signalling
372      *
373      * @access public
374      * @return array
375      */
376     public function get_ls_ports() {
377         return $this->ports_signalling['ls'];
378     }
379
380     /**
381      * Get Port
382      *
383      * Get the Analog Port assoc array that is associated
384      * with the given port number
385      */
386     public function get_port($num) {
387         return $this->analog_ports[$num];
388     }
389
390     /**
391      * Get Span Count
392      *
393      * Get the span count per location
394      *
395      * @access public
396      * @return array
397      */
398     public function get_span_count($loc) {
399         return $this->spancount[$loc];
400     }
401
402     /**
403      * Get Spans
404      *
405      * Get the digital spans
406      *
407      * @access public
408      * @return array
409      */
410     public function get_spans() {
411         return $this->spans;
412     }
413
414     /**
415      * Get Span
416      *
417      * Get a digital span and all its info
418      */
419     public function get_span($num) {
420         return $this->spans[$num];
421     }
422
423     /**
424      * Has VPM
425      *
426      * Return if the cards have a vpm module
427      */
428     public function has_vpm() {
429         return $this->has_vpm;
430     }
431
432     /**
433      * Hardware Changes
434      *
435      * Return if hdwr has changed or not
436      *
437      * @access public
438      * @return bool
439      */
440     public function hdwr_changes() {
441         return $this->hdwr_changes;
442     }
443
444     /**
445      * Load
446      *
447      * Load all the information the various locations (database, system.conf, chan_dahdi.conf)
448      */
449     public function load() {
450         global $db;
451
452         $this->read_configured_hdwr();
453         $this->read_dahdi_scan();
454
455         $this->hdwr_changes = $this->detect_hdwr_changes();
456         if ($this->hdwr_changes) {
457             $this->dahdi_genconf();
458             $this->dahdi_cfg();
459             $this->read_dahdi_scan();
460             $this->write_detected();
461             $this->write_spans();
462             $this->write_analog_signalling();
463         }
464
465         $this->read_system_conf();
466         $this->read_chan_dahdi_conf();
467         $this->read_dahdi_advanced();
468         $this->read_dahdi_analog();
469         $this->read_dahdi_spans();
470     }
471
472     /**
473      * Read Configured Hardware
474      *
475      * Go check out the database and read in the configured hardware
476      */
477      public function read_configured_hdwr() {
478         global $db;
479
480         $sql = "SELECT * FROM dahdi_configured_locations ORDER BY basechan";
481
482         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
483         if (DB::IsError($results)) {
484             die_freepbx($results->getDebugInfo());
485             return false;
486         }
487
488         foreach ($results as $row) {
489             if ( ! isset($this->configured_hdwr[$row['location']])) {
490                 $this->configured_hdwr[$row['location']] = array();
491             }
492
493             $this->configured_hdwr[$row['location']]['device'] = $row['device'];
494             $this->configured_hdwr[$row['location']]['basechan'] = $row['basechan'];
495             $this->configured_hdwr[$row['location']]['type'] = $row['type'];
496         }
497      }
498
499     /**
500      * Read DAHDi Advanced
501      *
502      * Load all the configuration information in /etc/dahdi/system.conf
503      */
504     public function read_dahdi_advanced() {
505         global $db;
506
507         $sql = 'SELECT * FROM dahdi_advanced';
508
509         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
510         if (DB::IsError($results)) {
511             die_freepbx($results->getDebugInfo());
512             return false;
513         }
514
515         foreach($results as $result) {
516             $this->advanced[$result['keyword']] = ($result['val']) ? $result['val'] : $result['default_val'];
517         }
518     }
519
520     /**
521      *
522      *
523      */
524     public function read_dahdi_analog() {
525         global $db;
526
527         $sql = 'SELECT * FROM dahdi_analog';
528
529         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
530         if (DB::IsError($results)) {
531             die_freepbx($results->getDebugInfo());
532             return false;
533         }
534
535         foreach($results as $res) {
536             $this->analog_ports[$res['port']] = $res;
537             if ($res['signalling'] == 'ls') {
538                 $this->ports_signalling['ls'][] = $res['port'];
539             } else {
540                 $this->ports_signalling['ks'][] = $res['port'];
541             }
542         }
543     }
544
545     /**
546      * Read DAHDi Spans
547      *
548      * Read in all the dahdi_spans info from the database
549      */
550     public function read_dahdi_spans() {
551         global $db;
552
553         $sql = 'SELECT * FROM dahdi_spans';
554
555         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
556         if (DB::IsError($results)) {
557             die_freepbx($results->getDebugInfo());
558             return false;
559         }
560
561         foreach ($results as $span) {
562             foreach ($span as $key=>$val) {
563                 if ($val == '') {
564                     continue;
565                 }
566
567                 $this->spans[$span['span']][$key] = $val;
568             }
569         }
570     }
571
572     /**
573      * Read System Conf
574      *
575      * Load all the configuration information in /etc/dahdi/system.conf
576      */
577     public function read_system_conf() {
578         
579         $nomore = false;
580         $ctr = 0;
581         do {
582             $this->system_conf = file_get_contents('/etc/dahdi/system.conf');
583             if (! $this->system_conf) {
584                 return FALSE;
585             }
586
587             $lines = explode("\n", $this->system_conf);
588
589             $hasaline = false;
590       foreach ($lines as $line) {
591                 // its a comment, like this line
592                 if (substr($line,0,1) == '#' || trim($line) == '') {
593                     continue;
594                 }
595                 $hasaline = true;
596         break;
597             }
598
599             if ( ! $hasaline) {
600                 $this->dahdi_genconf();
601             }
602
603             $ctr++;
604             if ($ctr > 2) {
605                 $nomore = true;
606             }
607         } while ( !$hasaline || $nomore);
608
609         if ( ! $hasaline) {
610             return false;
611         }
612
613         for($i=0;$i<count($lines);$i++) {
614
615             $line = $lines[$i];
616             if ($line == '' || (strpos($line, '#') === 0)) {
617                 continue;
618             }
619
620             $begin = substr($line, 0, 5);
621             switch($begin) {
622             case 'fxoks':
623             case 'fxsks':
624                 $ks_ports = explode('=',$line);
625                 $ks_ports = $ks_ports[1];
626                 $this->ports_signalling['ks'] = array_merge($this->ports_signalling['ks'], dahdi_chans2array($ks_ports));
627                 break;
628             case 'fxols':
629             case 'fxsls':
630                 $ls_ports = explode('=',$line);
631                 $ls_ports = $ls_ports[1];
632                 $this->ports_signalling['ls'] = array_merge($this->ports_signalling['ls'], dahdi_chans2array($ls_ports));
633                 break;
634             case 'echoc': //echocanceller
635                 $this->has_echo_can = true;
636                 break;
637             case 'span=':
638                 $info = explode('=', $line);
639                 list($num, $timing, $lbo, $framing, $coding, $yellow) = explode(',', $info[1]);
640                 $this->spans[$num]['timing'] = $timing;
641                 $this->spans[$num]['lbo'] = $lbo;
642                 $this->spans[$num]['framing'] = $framing;
643                 $this->spans[$num]['coding'] = $coding.(($yellow)?"/$yellow":"");
644                 break;
645             default:
646             }
647         }
648
649         // write echo can if it doesn't exist, for ABE only ???
650     }
651
652     /**
653      * Read Chan Dahdi Conf
654      *
655      * Read from chan_dahdi_additional.conf and get any useful information
656      */
657      public function read_chan_dahdi_conf() {
658          global $db;
659
660         $sql = 'SELECT * FROM dahdi WHERE id = -1 AND keyword != "account" AND flags != 1';
661         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
662         if (DB::IsError($results)) {
663             return($results->getMessage());
664         }
665
666         $additional = array();
667         foreach ($results as $result) {
668             $additional[$result['keyword']] = $result['data'];
669         }
670
671         unset($results);
672         unset($result);
673
674         $sql = 'SELECT * FROM dahdi WHERE keyword != "account" and flags != 1';
675         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
676         if (DB::IsError($results)) {
677             return($results->getMessage());
678         }
679
680         $accounts = array();
681         foreach ($results as $result) {
682             if ( ! isset($accounts[$result['id']])) {
683                 $accounts[$result['id']] = array();
684             }
685
686             switch($result['keyword']) {
687             case 'record_in':
688             case 'record_out':
689             case 'dial':
690                 break;
691             default:
692                 $accounts[$result['id']][$result['keyword']] = $result['data'];
693             }
694         }
695
696         unset($results);
697         unset($result);
698         unset($sql);
699
700         foreach ($accounts as $account) {
701             $account = array_merge($account, $additional);
702             $this->channels[$account['channel']] = $account;
703         }
704
705         $sql = 'SELECT * FROM dahdi_spans';
706         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
707         if (DB::IsError($results)) {
708             die_freepbx($results->getDebugInfo());
709         }
710
711         $flds = array('framing', 'signalling', 'coding', 'definedchans', 'switchtype', 'syncsrc', 'lbo', 'pridialplan', 'prilocaldialplan');
712         foreach ($results as $span) {
713             foreach ($flds as $fld) {
714                 if ( ! $span[$fld]) {
715                     continue;
716                 }
717
718                 $this->spans[$span['span']][$fld] = $span[$fld];
719             }
720         }
721
722         return true;
723      }
724
725     /**
726      * Read DAHDi Scan
727      *
728      * Read all the information given in the DAHDi Scan script
729      */
730     public function read_dahdi_scan() {
731         $this->dahdi_scan = `/usr/sbin/dahdi_scan`;
732         unset($this->fxo_ports);
733         unset($this->fxs_ports);
734         $this->fxo_ports = array();
735         $this->fxs_ports = array();
736
737         $lines = explode("\n", $this->dahdi_scan);
738         foreach ($lines as $line) {
739             if ($line == '') {
740                 continue;
741             } else if (preg_match('/^\[([-a-zA-Z0-9_][-a-zA-Z0-9_]*)\]/', $line, $matches)) {
742                         $cxt = $matches[1];
743                         $cxts[$cxt] = array();
744                         continue;
745             }
746
747             list($var, $val) = explode('=', $line);
748
749             if ($var == 'port' && strpos($val, 'FXO')) {
750                 $num = explode(',',$val);
751                 $num = $num[0];
752                 $this->fxo_ports[] = $num;
753             } else if ($var == 'port' && strpos($val, 'FXS')) {
754                 $num = explode(',',$val);
755                 $num = $num[0];
756                 $this->fxs_ports[] = $num;
757             }
758
759             if ($var == 'type' && strpos($val,'analog')) {
760                 $this->has_analog_hdwr = TRUE;
761             } else if ($var == 'type' && strpos($val, 'digital')) {
762                 $this->has_digital_hdwr = TRUE;
763             }
764         }
765
766         /* If there is a DAHDI_Dummy then there is no hardware to parse */
767         if (isset($cxts)) foreach ($cxts as $cxt) {
768             if (strpos($cxt['description'],'DAHDI_DUMMY') === false) {
769                 continue;
770             }
771
772             return;
773         }
774
775         $spans = dahdi_config2array($this->dahdi_scan);
776
777         if (count($spans) == 0) {
778             $this->has_digital_hdwr = FALSE;
779             $this->has_analog_hdwr = FALSE;
780             return;
781         }
782
783         foreach ($spans as $key=>$span) {
784             if (strpos($span['devicetype'], 'VPMADT032') !== FALSE) {
785                 $this->has_vpm = true;
786             }
787
788             if ($span['type'] == 'analog') {
789                 $this->hardware[$span['location']] = array();
790                 $this->hardware[$span['location']]['device'] = $span['devicetype'];
791                 $this->hardware[$span['location']]['basechan'] = $span['basechan'];
792                 $this->hardware[$span['location']]['type'] = $span['type'];
793
794                 $this->detected_hdwr[$span['location']] = $this->hardware[$span['location']];
795                 continue;
796             }
797
798             if (strpos($span['description'], 'ztdummy') !== false) {
799                 continue;
800             }
801
802             $this->spans[$key] = array();
803             foreach ($span as $attr=>$val) {
804                 $this->spans[$key][$attr] = $span[$attr];
805
806                 switch($attr) {
807                 case 'location':
808                     if ( ! isset($this->spancount[$val]) ) {
809                         $this->spancount[$val] = 0;
810                     }
811
812                     $this->spancount[$val]++;
813                 
814                     if (!isset($this->hardware[$val]) ) {
815                         $this->hardware[$val] = array();
816                         $this->hardware[$val]['device'] = $span['devicetype'];
817                         $this->hardware[$val]['basechan'] = $span['basechan'];
818                         $this->hardware[$val]['type'] = $span['type'];
819                         $this->detected_hdwr[$span['location']] = $this->hardware[$span['location']];
820                     }
821                     break;
822                 case 'totchans':
823                     list($dummy, $this->spans[$key]['spantype']) = explode('-',$span['type']);
824                     $this->spans[$key]['min_ch'] = $span['basechan'];
825                     $this->spans[$key]['max_ch'] = $span['basechan'] + $span['totchans'] - 1;
826
827                     switch ($span['totchans']) {
828                     case 3:
829                         $this->spans[$key]['definedchans'] = 2;
830                         $this->spans[$key]['reserved_ch'] = $span['basechan'] + 2;
831                         break;
832                     case 24:
833                         $this->spans[$key]['definedchans'] = 23;
834                         $this->spans[$key]['reserved_ch'] = $span['basechan'] + 23;
835                         break;
836                     case 31:
837                         $this->spans[$key]['definedchans'] = 31;
838                         $this->spans[$key]['reserved_ch'] = $span['basechan'] + 15;
839                         break;
840                     default:
841                         $this->spans[$key]['definedchans'] = 0;
842                         break;
843                     }
844                     break;
845                 case 'lbo':
846                     switch($val){
847                     case '0 db (CSU)/0-133 feet (DSX-1)':
848                         $this->spans[$key]['lbo'] = 0;
849                         break;
850                     case '133-266 feet (DSX-1)':
851                         $this->spans[$key]['lbo'] = 1;
852                         break;
853                     case '266-399 feet (DSX-1)':
854                         $this->spans[$key]['lbo'] = 2;
855                         break;
856                     case '399-533 feet (DSX-1)':
857                         $this->spans[$key]['lbo'] = 3;
858                         break;
859                     case '533-655 feet (DSX-1)':
860                         $this->spans[$key]['lbo'] = 4;
861                         break;
862                     case '-7.5db (CSU)':
863                         $this->spans[$key]['lbo'] = 5;
864                         break;
865                     case '-15db (CSU)':
866                         $this->spans[$key]['lbo'] = 6;
867                         break;
868                     case '-22.5db (CSU)':
869                         $this->spans[$key]['lbo'] = 7;
870                         break;
871                     default:
872                         $this->spans[$key]['lbo'] = 0;
873                         break;
874                     }
875                     break;
876                 default:
877                     break;
878                 }
879             }
880         }
881     }
882     
883     /**
884      * Set Analog Signalling
885      *
886      * Take the port number and signalling (ls/ks) and update the
887      * ports_signalling array
888      */
889     public function set_analog_signalling($num, $port) {
890         $opp = ($port['signalling'] == 'ks') ? 'ls' : 'ks';
891         $key = array_search($num, $this->ports_signalling[$opp]);
892         if ($key) {
893             unset($this->ports_signalling[$opp][$key]);
894         }
895
896         if ( ! in_array($num, $this->ports_signalling[$port['signalling']])) {
897             $this->ports_signalling[$port['signalling']][] = $num;
898         }
899
900         $this->analog_ports[$num]['group'] = $port['group'];
901         $this->analog_ports[$num]['context'] = $port['context'];
902
903         needreload();
904     }
905
906     /**
907      * Update DAHDi Advanced
908      *
909      * Update the database for dahdi advanced and then update the proper files
910      *
911      * @access public
912      * @param array $params An array of parameters
913      * @return bool
914      */
915     public function update_dahdi_advanced($params) {
916          global $db;
917
918         foreach ($params as $keyword=>$val) {
919             if ($val === null) {
920                 $sql = "UPDATE dahdi_advanced SET val=null WHERE keyword=\"{$keyword}\"";
921                 $this->advanced[$keyword] = null;
922             } else {
923                 $sql = "UPDATE dahdi_advanced SET val=\"{$val}\" WHERE keyword=\"{$keyword}\"";
924                 $this->advanced[$keyword] = $val;
925             }
926             $result = $db->query($sql);
927             if (DB::IsError($result)) {
928                 echo $result->getDebugInfo();
929                 return false;
930             }
931             unset($result);
932         }
933
934         needreload();
935     }
936
937     /**
938      * Update Span
939      *
940      * Update the span info and write it to the appropriate files
941      */
942     public function update_span($editspan) {
943         $num = $editspan['span'];
944
945         if ($editspan['fac'] == 'CCS/HDB3/CRC4') {
946             $this->spans[$num]['framing'] = 'CCS/HDB3';
947             $this->spans[$num]['coding'] = 'CRC4';
948         } else {
949             list($framing, $coding) = explode('/',$editspan['fac']);
950             $this->spans[$num]['framing'] = $framing;
951             $this->spans[$num]['coding'] = $coding;
952         }
953
954         $this->spans[$num]['fac'] = $editspan['fac'];
955         $this->spans[$num]['signalling'] = $editspan['signalling'];
956         $this->spans[$num]['syncsrc'] = $editspan['syncsrc'];
957         $this->spans[$num]['channels'] = $editspan['channels'];
958         $this->spans[$num]['switchtype'] = $editspan['switchtype'];
959         $this->spans[$num]['lbo'] = $editspan['lbo'];
960         $this->spans[$num]['pridialplan'] = $editspan['pridialplan'];
961         $this->spans[$num]['prilocaldialplan'] = $editspan['prilocaldialplan'];
962         $this->spans[$num]['group'] = $editspan['group'];
963         $this->spans[$num]['context'] = $editspan['context'];
964         $this->spans[$num]['definedchans'] = $editspan['definedchans'];
965
966         $this->write_spans();
967         $this->write_system_conf();
968
969         needreload();
970     }
971
972     /**
973      * Write Analog Signalling
974      *
975      * Take the analog ports and write them to the dahdi_analog table
976      */
977     public function write_analog_signalling() {
978         global $db;
979
980         $sql = 'TRUNCATE dahdi_analog';
981
982         $result = $db->query($sql);
983         if (DB::IsError($result)) {
984             die_freepbx($result->getDebugInfo());
985         }
986         unset($result);
987
988         $ports = array();
989         foreach ($this->fxo_ports as $fxo) {
990             if (in_array($fxo, $this->ports_signalling['ls'])) {
991                 $sig = 'ls';
992             } else {
993                 $sig = 'ks';
994             }
995
996             $group = (isset($this->analog_ports[$fxo]['group']))?$this->analog_ports[$fxo]['group']:0;
997             $context = (isset($this->analog_ports[$fxo]['context']))?$this->analog_ports[$fxo]['context']:'from-analog';
998
999             $ports[] = "($fxo, 'fxo', '$sig', $group, '$context')";
1000         }
1001
1002         foreach ($this->fxs_ports as $fxs) {
1003             if (in_array($fxs, $this->ports_signalling['ls'])) {
1004                 $sig = 'ls';
1005             } else {
1006                 $sig = 'ks';
1007             }
1008
1009             $group = (isset($this->analog_ports[$fxs]['group']))?$this->analog_ports[$fxs]['group']:0;
1010             $context = (isset($this->analog_ports[$fxs]['context']))?$this->analog_ports[$fxs]['context']:'from-analog';
1011
1012             $ports[] = "($fxs, 'fxs', '$sig', $group, '$context')";
1013         }
1014
1015         if (sizeof($ports) <= 0) {
1016             return true;
1017         }
1018
1019         $sql = 'INSERT INTO dahdi_analog (port, type, signalling, `group`, context) VALUES '.implode(', ',$ports);
1020
1021         $result = $db->query($sql);
1022         if (DB::IsError($result)) {
1023             die_freepbx($result->getDebugInfo());
1024         }
1025
1026         $this->write_system_conf();
1027
1028         return true;
1029     }
1030
1031     /**
1032      * Write Detected
1033      *
1034      * Write the detected hardware to the dahdi_configured_locations table
1035      */
1036     public function write_detected() {
1037         global $db;
1038
1039         $sql = "TRUNCATE TABLE dahdi_configured_locations";
1040         $result = $db->query($sql);
1041         if (DB::IsError($result)) {
1042             die_freepbx($result->getDebugInfo());
1043         }
1044         unset($result);
1045
1046         $flds = array('location', 'device', 'basechan', 'type');
1047         $inserts = array();
1048         foreach ($this->detected_hdwr as $loc=>$hdwr) {
1049             $insert = array();
1050             foreach ($flds as $fld) {
1051                 if ($fld == 'location') {
1052                     $insert[] = "'$loc'";
1053                 } else {
1054                     $insert[] = "'{$hdwr[$fld]}'";
1055                 }
1056             }
1057
1058             $inserts[] = '('.implode(', ',$insert).')';
1059         }
1060         $sql = 'INSERT INTO dahdi_configured_locations ('.implode(', ',$flds).') VALUES '.implode(', ',$inserts);
1061
1062         $result = $db->query($sql);
1063         if (DB::IsError($result)) {
1064             die_freepbx($result->getDebugInfo());
1065         }
1066
1067         return true;
1068     }
1069
1070     /**
1071      * Write Spans
1072      *
1073      * Write the current spans to the database
1074      */
1075     public function write_spans() {
1076         global $db;
1077
1078         $sql = "TRUNCATE dahdi_spans";
1079         $result = $db->query($sql);
1080         if (DB::IsError($result)) {
1081             die_freepbx($result);
1082         }
1083         unset($result);
1084
1085         $flds = array('span', 'framing', 'definedchans', 'coding', 'signalling', 'switchtype', 'syncsrc', 'lbo', 'pridialplan', 'prilocaldialplan', 'group', 'context');
1086
1087         $sql = 'INSERT INTO dahdi_spans (`'.implode('`, `',$flds).'`) VALUES ';
1088         $inserts = array();
1089         foreach ($this->spans as $key=>$span) {
1090             $values = array();
1091
1092             foreach ($flds as $fld) {
1093                 if ($fld == 'span') {
1094                     $values[] = "'$key'";
1095                 } else {
1096                     $values[] = "'{$span[$fld]}'";
1097                 }
1098             }
1099
1100             $inserts[] = '('.implode(', ',$values).')';
1101             unset($values);
1102         }
1103         $sql .= implode(', ', $inserts);
1104
1105         $result = $db->query($sql);
1106         if (DB::IsError($result)) {
1107             die_freepbx($result->getDebugInfo());
1108         }
1109         unset($result);
1110     }
1111
1112     /**
1113      * Write System Conf
1114      *
1115      * Take all the information received and write a new /etc/dahdi/system.conf
1116      */
1117     public function write_system_conf() {
1118           $fxx = array();
1119            $output = array();
1120         $bchan = '';
1121         $dchan = '';
1122         $hardhdlc = '';
1123
1124         foreach ($this->spans as $num=>$span) {
1125             if ( ! $span['signalling']) {
1126                 continue;
1127             }
1128
1129             $span['fac'] = str_replace('/',',',$span['framing']).','.$span['coding'];
1130             $span['lbo'] = ($span['lbo']) ? $span['lbo'] : 0;
1131             $span['syncsrc'] = (isset($span['syncsrc'])) ? $span['syncsrc'] : 1;
1132
1133             $spanline = "{$num},{$span['syncsrc']},{$span['lbo']},{$span['fac']}";
1134
1135             $output[] = "span={$spanline}";
1136
1137             $chan = $this->calc_bchan_fxx($num);
1138
1139             if ( substr($span['signalling'],0,3) != 'pri' && substr($span['signalling'],0,3) != 'bri') {
1140                 if (substr($span['signalling'],0,2) == 'fx') {
1141                     $fx = str_replace('_','',$span['signalling']);
1142                 } else {
1143                     $fx = 'e&m';
1144                 }
1145
1146                 if ($fxx[$fx]) {
1147                     $fxx[$fx] .= ",{$chan}";
1148                 } else {
1149                     $fxx[$fx] = $chan;
1150                 }
1151             } else if (substr($span['signalling'],0,3) == 'pri') {
1152                 $bchan .= ($bchan) ? ",$chan" : "$chan";
1153                 $dchan .= ($dchan) ? ",{$span['reserved_ch']}" : "{$span['reserved_ch']}";
1154             } else {
1155                 $bchan .= ($bchan) ? ",$chan" : "$chan";
1156                 $hardhdlc .= ($hardhdlc) ? ",{$span['reserved_ch']}" : "{$span['reserved_ch']}";
1157             }
1158
1159             $this->spans[$num]['dahdichanstring'] = $chan;
1160         }
1161
1162         foreach ($fxx as $e=>$val) {
1163             $output[]  = "$e={$val}";
1164         }
1165
1166         if ($bchan) {
1167             $output[] = "bchan={$bchan}";
1168         }
1169
1170         if ($dchan) {
1171             $output[] = "dchan={$dchan}";
1172         }
1173
1174         if ($hardhdlc) {
1175             $output[]  = "hardhdlc={$hardhdlc}";
1176         }
1177
1178         $fxols = array();
1179         $fxoks = array();
1180         $fxsls = array();
1181         $fxsks = array();
1182
1183         foreach ($this->fxo_ports as $fxo) {
1184             if (in_array($fxo, $this->ports_signalling['ls'])) {
1185                 $fxols[] = $fxo;
1186             } else {
1187                 $fxoks[] = $fxo;
1188             }
1189         }
1190
1191         foreach ($this->fxs_ports as $fxs) {
1192             if (in_array($fxs, $this->ports_signalling['ls'])) {
1193                 $fxsls[] = $fxs;
1194             } else {
1195                 $fxsks[] = $fxs;
1196             }
1197         }
1198
1199         if ($fxols) {
1200             $output[] = "fxsls=".dahdi_array2chans($fxols);
1201         }
1202         if ($fxoks) {
1203             $output[] = "fxsks=".dahdi_array2chans($fxoks);
1204         }
1205         if ($fxsls) {
1206             $output[] = "fxols=".dahdi_array2chans($fxsls);
1207         }
1208         if ($fxsks) {
1209             $output[] = "fxoks=".dahdi_array2chans($fxsks);
1210         }
1211
1212         $output[] = "loadzone={$this->advanced['tone_region']}";
1213         $output[] = "defaultzone={$this->advanced['tone_region']}";
1214
1215         $fh = fopen('/etc/dahdi/system.conf', 'w');
1216         $output = implode("\n", $output);
1217         fwrite($fh, $output);
1218         fclose();
1219     }
1220
1221     /**
1222      * Write Modprobe
1223      *
1224      * Write all the modprob options to modprobe.conf
1225      */
1226     public function write_modprobe() {
1227         $file = "/etc/modprobe.d/dahdi.conf";
1228
1229         if ( ! is_writable($file)) {
1230             echo "not writable";
1231         }
1232
1233         $fh = fopen($file, 'w');
1234
1235         fwrite($fh, "#******************************************#\n");
1236         fwrite($fh, "#* Auto-generated by FreePBX, do not edit *#\n");
1237         fwrite($fh, "#******************************************#\n");
1238
1239         $options = "options {$this->advanced['module_name']}";
1240
1241         $opts = array('opermode'=>'opermode', 'alawoverride'=>'alawoverride', 'boostringer'=>'boostringer', 'lowpower'=>'lowpower', 'fastringer'=>'fastringer', 'ringdetect'=>'fwringdetect', 'fxs_honor_mode'=>'fxshonormode');
1242         foreach ($opts as $opt=>$name) {
1243             if ( ! $this->advanced["{$opt}_checkbox"]) {
1244                 continue;   
1245             }
1246
1247             $options .= " {$name}={$this->advanced[$opt]}";
1248         }
1249
1250         if ($this->advanced["mwi_checkbox"]) {
1251             if ($this->advanced['mwi'] == 'neon') {
1252                 $options .= " neonmwi_monitor=1";
1253                 if ($this->advanced['neon_voltage']) {
1254                     $options .= " neonmwi_level={$this->advanced['neon_voltage']}";
1255                 }
1256                 if ($this->advanced['neon_offlimit']) {
1257                     $options .= " neonmwi_offlimit={$this->advanced['neon_offlimit']}";
1258                 }
1259             } else {
1260                 $options .= " neonmwi_monitor=0";
1261             }
1262         }
1263
1264         $opts = array('echocan_nlp_type'=>'vpmnlptype', 'echocan_nlp_threshold'=>'vpmnlpthresh', 'echocan_nlp_max_supp'=>'vpmnlpmaxsupp');
1265         foreach ($opts as $adv=>$opt) {
1266             if ( ! $this->advanced[$adv]) {
1267                 continue;
1268             }
1269
1270             $options .= " {$opt}={$this->advanced[$adv]}";
1271         }
1272
1273         fwrite($fh,$options);
1274         fclose($fh);
1275     }
1276 }
1277
1278 function dahdi_config2array ($config) {
1279     if (! is_array($config)) {
1280         $config = explode("\n", $config);   
1281     }
1282
1283     $cxts = array();
1284     $cxt = '';
1285
1286     unset($config[count($config)-1]);
1287     
1288     for($i=0;$i<count($config);$i++) {
1289         unset($matches);
1290         if ($config[$i] == '') {
1291             continue;
1292         } else if (preg_match('/^\[([-a-zA-Z0-9_][-a-zA-Z0-9_]*)\]/', $config[$i], $matches)) {
1293             $cxt = $matches[1];
1294             $cxts[$cxt] = array();
1295             continue;
1296         }
1297
1298         if ($cxt == '') {
1299             continue;
1300         }
1301
1302         list($var, $val) = explode('=',$config[$i]);
1303         
1304         if (isset($cxts[$cxt][$var])) {
1305             if (gettype($cxts[$cxt][$var]) !== 'array') {
1306                 $cxts[$cxt][$var] = array($cxts[$cxt][$var]);
1307             }
1308
1309             $cxts[$cxt][$var][] = $val;
1310         } else {
1311             $cxts[$cxt][$var] = $val;
1312         }
1313     }
1314
1315     return $cxts;
1316 }
1317
1318 function dahdi_chans2array($chans=null) {
1319     if (!$chans || $chans = '') {
1320         return array();
1321     }
1322
1323     $chanarray = array();
1324     
1325     if (strpos($chans,',') && strpos($chans,'-')) {
1326         $segs = explode(',',$chans);
1327         foreach ($segs as $seg) {
1328             if (strpos($chans,'-')) {
1329                 list($start, $end) = explode('-',$chans);
1330                 for($i=$start;$i<=$end;$i++) {
1331                     $chanarray[] = $i;
1332                 }
1333                 continue;
1334             }
1335
1336             $chanarray[] = $seg;
1337         }
1338     } else if (strpos($chans,',')) {
1339         $chanarray = explode(',',$chans);   
1340     } else if (strpos($chans,'-')) {
1341         list($start,$end) = explode('-',$chans);
1342         for($i=$start; $i<=$end; $i++) {
1343             $chanarray[] = $i;
1344         }
1345     } else {
1346         $chanarray = array($chans);
1347     }
1348
1349     return $chanarray;
1350 }
1351
1352 function dahdi_array2chans($arr) {
1353     $chans = array();;
1354     $seq = 0;
1355     for($i=0;$i<count($arr);$i++) {
1356         $last_write = false;
1357         if ( $i != 0 && $arr[$i] - $arr[$i-1] == 1) {
1358             $seq++;
1359             if ($i+1 == count($arr)) {
1360                 $chans[] = "{$arr[$i-$seq]}-{$arr[$i]}";
1361                 $last_write = true;
1362             }
1363         } else if ($seq > 0) {
1364             $chans[] = "{$arr[$i-1-$seq]}-{$arr[$i-1]}";
1365             $seq = 0;
1366         } else if ($i != 0) {
1367             $chans[] = "$arr[$i]";
1368         }
1369         
1370         if ( !$last_write && $i+1 == count($arr)) {
1371             $chans[] = "$arr[$i]";
1372         }
1373     }
1374
1375     return implode(',',$chans);
1376 }
1377
1378 // list unused DAHDI fxs channels that can be configured for extensions
1379 //
1380 function dahdiconfig_get_unused_fxs_channels($current_device='') {
1381   $all_channels = sql('SELECT * FROM dahdi_analog WHERE type = "fxs"','getAll',DB_FETCHMODE_ASSOC);
1382   $used_channels = sql('SELECT id device, data port FROM dahdi WHERE keyword = "channel"','getAll',DB_FETCHMODE_ASSOC);
1383   $used_channels_hash = array();
1384   foreach ($used_channels as $chan) {
1385     $used_channels_hash[$chan['port']] = $chan['device'];
1386   }
1387
1388   $avail_channels = array();
1389   foreach ($all_channels as $chan) {
1390     if (isset($used_channels_hash[$chan['port']])) {
1391       if ($current_device == $used_channels_hash[$chan['port']]) {
1392         $selected = true;
1393       } else {
1394         continue;
1395       }
1396     } else {
1397       $selected = false;
1398     }
1399     $avail_channels[] = array('channel' => $chan['port'], 'signalling' => 'fxo_'.$chan['signalling'], 'selected' => $selected);
1400   }
1401   return $avail_channels;
1402 }
1403
1404 function _dahdiconfig_gsort($a, $b) {
1405   $gn_a = substr($a,1);
1406   $gn_b = substr($b,1);
1407   if ($gn_a == $gn_b) {
1408     return ($b > $a);
1409   } else {
1410     return ($gn_a > $gn_b);
1411   }
1412 }
1413
1414 function dahdiconfig_get_unused_trunk_options($current_identifier='') {
1415   global $amp_conf;
1416   $avail_group = array();
1417   $analog_chan = array();
1418   $digital_chan = array();
1419
1420   $dahdi_cards = new dahdi_cards();
1421   $analog_ports = $dahdi_cards->get_fxo_ports();
1422
1423   // Get Analog Groups and Channels for FXO
1424   //
1425   foreach ($analog_ports as $port) {
1426     $port_details = $dahdi_cards->get_port($port);
1427     $grp = $port_details['group'];
1428     $chan = (string) $port_details['port'];
1429     $avail_group["g$grp"] = array('identifier' => "g$grp",'name' => "Group $grp Ascending",'alarms' => '','selected'  => ($current_identifier == "g$grp"));
1430     $avail_group["G$grp"] = array('identifier' => "G$grp",'name' => "Group $grp Descending",'alarms' => '','selected' => ($current_identifier == "G$grp"));
1431     $analog_chan[$chan] = array('identifier' => $chan, 'name' => "Analog Channel $chan",'alarms' => '','selected' => ($current_identifier == $chan));
1432   }
1433   // Get Digital Groups and Channels. Channels are not that useful
1434   // but can be helpful when testing bad channels
1435   //
1436   $digital_spans = $dahdi_cards->get_spans();
1437   foreach ($digital_spans as $span) {
1438     if (!$span['active']) {
1439       continue;
1440     }
1441     $grp = $span['group'];
1442     $alarms = $span['alarms'];
1443     if (!isset($avail_group["g$grp"])) {
1444       $avail_group["g$grp"] = array('identifier' => "g$grp",'name' => "Group $grp Ascending",'alarms' => $alarms,'selected'  => ($current_identifier == "g$grp"));
1445       $avail_group["G$grp"] = array('identifier' => "G$grp",'name' => "Group $grp Descending",'alarms' => $alarms,'selected' => ($current_identifier == "G$grp"));
1446     } else {
1447       //TODO: figure out the possible alarms and the create proper hiearchy of what to report
1448       //
1449       if ($alarms == 'RED' || $avail_group["g$grp"]['alarms'] == '') {
1450         $avail_group["g$grp"]['alarms'] = $alarms;
1451         $avail_group["G$grp"]['alarms'] = $alarms;
1452       }
1453     }
1454     if ($amp_conf['DAHDISHOWDIGITALCHANS']) {
1455       $basechan = $span['basechan'];
1456       $definedchans = $span['definedchans'];
1457       $topchan = $basechan + $definedchans;
1458       for ($port = $basechan; $port < $topchan; $port++) {
1459         $digital_chan["$port"] = array('identifier' => "$port", 'name' => "Digital Channel $port",'alarms' => $alarms,'selected' => ($current_identifier == "$port"));
1460       }
1461     }
1462   }
1463   uksort($avail_group,'_dahdiconfig_gsort');
1464   ksort($analog_chan);
1465   if ($amp_conf['DAHDISHOWDIGITALCHANS']) {
1466     ksort($digital_chan);
1467     $avail_identifiers = $avail_group + $analog_chan + $digital_chan;
1468   } else {
1469     $avail_identifiers = $avail_group + $analog_chan;
1470   }
1471   $trunk_list = core_trunks_listbyid();
1472   foreach ($trunk_list as $trunk) {
1473     if ($trunk['tech'] != 'dahdi' || $trunk['channelid'] == $current_identifier) {
1474       continue;
1475     }
1476     unset($avail_identifiers[$trunk['channelid']]);
1477   }
1478   return ($avail_identifiers);
1479 }
1480
1481 function dahdiconfig_configpageinit($dispnum) {
1482 global $currentcomponent;
1483 switch ($dispnum) {
1484   case 'devices':
1485   case 'extensions':
1486     // if tech_hardware set, this is an initial extension/device creation
1487     // otherwise, determine if the target extension/device is DAHDI
1488     //
1489     if (isset($_REQUEST['tech_hardware']) && $_REQUEST['tech_hardware'] == 'dahdi_generic') {
1490       $extdisplay = '';
1491     } else {
1492       if (!isset($_REQUEST['extdisplay']) || $_REQUEST['extdisplay'] == '') {
1493         return true;
1494       }
1495       $extdisplay = $_REQUEST['extdisplay'];
1496       $device_info = core_devices_get($extdisplay);
1497       if (empty($device_info) || $device_info['tech'] != 'dahdi') {
1498         return true;
1499       }
1500     }
1501  
1502       $channel_select  = dahdiconfig_get_unused_fxs_channels($extdisplay);
1503     $currentcomponent->addoptlistitem('dahdi_channel_select', '', _('==Choose=='));
1504       foreach ($channel_select as $val) {
1505           $currentcomponent->addoptlistitem('dahdi_channel_select', $val['channel'].':'.$val['signalling'], $val['channel']);
1506       }
1507       $currentcomponent->setoptlistopts('dahdi_channel_select', 'sort', false);
1508   break;
1509   case 'trunks':
1510     if (isset($_REQUEST['tech']) && strtolower($_REQUEST['tech']) == 'dahdi') {
1511       $extdisplay = '';
1512       $_REQUEST['dahdi_current_channel'] = '';
1513     } else {
1514       if (!isset($_REQUEST['extdisplay']) || $_REQUEST['extdisplay'] == '') {
1515         return true;
1516       }
1517       $extdisplay = $_REQUEST['extdisplay'];
1518       $trunknum = ltrim($extdisplay,'OUT_');
1519       $trunk_details = core_trunks_getDetails($trunknum);
1520       $tech = $trunk_details['tech'];
1521       if ($tech != 'dahdi') {
1522         return true;
1523       }
1524       $_REQUEST['dahdi_current_channel'] = $trunk_details['channelid'];
1525     }
1526     // dahdiconfig_hook_core will see this and create the needed selelect structure
1527     //
1528     $_REQUEST['display_dahdi_select'] = 'true';
1529   break;
1530   default;
1531     return true;
1532   break;
1533   }
1534   $currentcomponent->addguifunc("dahdiconfig_{$dispnum}_configpageload");
1535 }
1536
1537 function dahdiconfig_hook_core($viewing_itemid, $target_menuid) {
1538   global $tabindex;
1539   $html = '';
1540   if ($target_menuid == 'trunks' && isset($_REQUEST['display_dahdi_select']) && $_REQUEST['display_dahdi_select'] == 'true') {
1541
1542     // TODO: If list is exhausted, write message that no options left
1543     //
1544     $avail_trunks = dahdiconfig_get_unused_trunk_options($_REQUEST['dahdi_current_channel']);
1545     if (!empty($avail_trunks)) {
1546       $html = '
1547                 <tr>
1548                     <td>
1549                         <a href=# class="info">' . _("DAHDI Trunks") . '<span>' . _("Available DAHDI Groups and Channels configued in the DAHDI Configuration Module") . '</span></a>:
1550           </td>
1551           <td>
1552             <select name="dahdi_trunks" id="dahdi_trunks" tabindex="' . ++$tabindex . '">
1553       ';
1554       foreach ($avail_trunks as $ident) {
1555         $selected = $ident['selected'] ? ' SELECTED' : '';
1556         $html .= "
1557             <option value='{$ident['identifier']}'$selected>{$ident['name']}
1558         ";
1559       }
1560       $html .= "
1561             </select>
1562                     </td>
1563         </tr>
1564       ";
1565     } else {
1566       $html .= '
1567                 <tr>
1568                     <td colspan="2">
1569                         <a href=# class="info">' . _("No Available Groups or Channels") . '<span>' . _("There are no DAHDI Groups or Channels available to be configured. Check the DAHDI module (linked below) to configure any un-used cards") . '</span></a>
1570           </td>
1571                 </tr>
1572       ';
1573     }
1574
1575       $URL = $_SERVER['PHP_SELF'].'?'.'display=dahdi';
1576     $html .= '
1577                 <tr><td colspan="2"><input type="hidden" id="dahdi_trunks" value=""></td></tr>
1578                 <tr>
1579                     <td colspan="2">
1580                         <a href="'.$URL.'" class="info">' . _("Configure/Edit DAHDI Cards") . '<span>' . _("Configure/Edit DAHDI Card settings in DAHDi Module") . '</span></a>
1581           </td>
1582                 </tr>
1583     ';
1584   }
1585   return $html;
1586 }
1587
1588 //hook gui function
1589 //
1590 function dahdiconfig_devices_configpageload() {
1591   dahdiconfig_configpageload('device');
1592 }
1593 function dahdiconfig_extensions_configpageload() {
1594   dahdiconfig_configpageload('extension');
1595 }
1596 function dahdiconfig_configpageload($mode) {
1597   global $currentcomponent;
1598
1599     $extdisplay = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null;
1600
1601   $dahdi_channel_select = $currentcomponent->getoptlist('dahdi_channel_select');
1602   if (!empty($dahdi_channel_select)) {
1603     // Generate Channel Select, on submit populuate device channel, dial and signalling fields
1604     $currentcomponent->addguielem('Device Options', new gui_selectbox(
1605       'dahdi_channel',
1606       $dahdi_channel_select,
1607       '',
1608       _('Channel'),
1609       sprintf(_('Choose the FXS channel for this %s'),$mode),
1610     false,
1611       "javascript:if (document.frm_{$mode}s.dahdi_channel.value) {parts = document.frm_{$mode}s.dahdi_channel.value.split(':');document.frm_{$mode}s.devinfo_channel.value = parts[0];document.frm_{$mode}s.devinfo_dial.value = 'DAHDI/'+parts[0];document.frm_{$mode}s.devinfo_signalling.value = parts[1]; } else { document.frm_{$mode}s.devinfo_channel.value = ''}"
1612     ));
1613
1614     // On pageload hide channel, signalling and dial fields and select dahdi_channel based on channel field's contents
1615     $js = '<script type="text/javascript">
1616       $(document).ready(function(){
1617         $("#dahdi_channel").val($("#devinfo_channel").val()+":"+$("#devinfo_signalling").val());
1618         if ($("#dahdi_channel").val() == null) {
1619           $("#dahdi_channel").val("");
1620         }
1621         $("#devinfo_channel").parent().parent().hide();
1622         $("#devinfo_signalling").parent().parent().hide();
1623         $("#devinfo_dial").parent().parent().hide();
1624       });
1625     </script>';
1626     $currentcomponent->addguielem('Device Options', new guielement('dahdi-chan-html', $js, ''));
1627   } else {
1628     // No available channels so display that and hide channel, signalling and dial fields
1629       $currentcomponent->addguielem('Device Options', new gui_label('no_dahdi_channel', _('No Unused DAHDi Channels Available')));
1630     $js = '<script type="text/javascript">
1631       $(document).ready(function(){
1632         $("#devinfo_channel").parent().parent().hide();
1633         $("#devinfo_signalling").parent().parent().hide();
1634         $("#devinfo_dial").parent().parent().hide();
1635       });
1636     </script>';
1637     $currentcomponent->addguielem('Device Options', new guielement('dahdi-chan-html', $js, ''));
1638   }
1639 }
1640
1641 function dahdiconfig_trunks_configpageload() {
1642   global $currentcomponent;
1643     $extdisplay = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null;
1644
1645   $js = '
1646   <script type="text/javascript">
1647     $(document).ready(function(){
1648       $("input[name=\'channelid\']").attr("id","channelid").val($("#dahdi_trunks").val()).parent().parent().hide();
1649       $("#dahdi_trunks").change(function(){
1650         $("#channelid").val(this.value);
1651       });
1652     });
1653   </script>';
1654   $currentcomponent->addguielem('_top', new guielement('dahdi-chan-html', $js, ''));
1655 }
1656 // End of File
1657
Note: See TracBrowser for help on using the browser.