Newer
Older
ubFramework / Provisioning / docroot / Old_Prov / ultrative / getData.php
@Christopher W. Olsen Christopher W. Olsen on 10 Dec 2017 28 KB iSinc
<?php
exit();

/*
 * *****************************************************************************************
 * Copyright (c) 2013, 2014 Christopher W. Olsen <cwolsen@ubixtechnologies.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions, the following disclaimer and the list of authors. Redistributions in binary
 * form must reproduce the above copyright notice, this list of conditions, the following
 * disclaimer and the list of authors in the documentation and/or other materials provided
 * with the distribution. Neither the name of the uBix Cube Project nor the names of its
 * contributors may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: getData.php 1715 2014-07-16 04:58:08Z reddawg $
 *
 * ***************************************************************************************
 */

/* Main include info */
ini_set ( 'include_path', $_SERVER ['DOCUMENT_ROOT'] . "/include/" );
include ("config.php");

/* Initialize Our Device Global */
$cDev = new VoIP_Device ();

/* Main defines */
$data ['tpl']->define ( array (
  "conf_file" => "error.tpl" 
) );

/*
 * this is expired.
 *
 * $regEx = "/((?:[a-zA-Z][a-zA-Z]+)) ((?:[a-zA-Z][a-zA-Z]+))-((?:[a-zA-Z][a-zA-Z]+))_(\d+)-((?:[a-zA-Z][a-zA-Z]+))\/((?:[\w\.\-]+)+) ((?:[a-zA-Z][a-zA-Z]+))\/((?:[a-zA-Z][a-zA-Z]+))/";
 * $regEx2 = "/((?:[a-zA-Z][a-zA-Z]+)) ((?:[a-zA-Z][a-zA-Z]+))-((?:[a-zA-Z][a-zA-Z]+))_(\d+)-((?:[a-zA-Z][a-zA-Z]+))\/((?:[\w\.\-]+)+) \(((?:[a-zA-Z][a-zA-Z]+)):((?:[\w\.\-]+)+)\) ((?:[a-zA-Z][a-zA-Z]+))\/((?:[a-zA-Z][a-zA-Z]+))/";
 * $regEx3 = "/((?:[a-zA-Z][a-zA-Z]+)) ((?:[a-zA-Z][a-zA-Z]+))-((?:[a-zA-Z][a-zA-Z]+))_(\d+)-((?:[a-zA-Z][a-zA-Z]+))\/((?:[\w\.\-]+)+)/";
 *
 * $pM = preg_match ( $regEx, $_SERVER ['HTTP_USER_AGENT'], $dI );
 *
 * if ($pM == 0)
 * $pM = preg_match ( $regEx2, $_SERVER ['HTTP_USER_AGENT'], $dI );
 *
 * if ($pM == 0)
 * $pM = preg_match ( $regEx3, $_SERVER ['HTTP_USER_AGENT'], $dI );
 *
 * system ( "echo 'PM: " . $pM . " - " . json_encode ( $dI ) . "' >> /tmp/AGENT.log" );
 */

/* Here we need to determine what type of device is querying the provisioning system */
$devAgent = explode ( ' ', $_SERVER ['HTTP_USER_AGENT'] );

switch ($devAgent [0]) {
  case 'FileTransport' :
    $eC = count ( $devAgent );
    
    system ( "echo 'Polycom Device: " . $eC . "' >> /tmp/AGENT.log" );
    
    /* By Default Will Consider It A Cold Boot Unless We Determine Non Boot Loader Requested Information */
    $cDev->bootStatus = 'Cold';
    
    /* The Secnd Part Of The Agent Is Uniform Through All Polycom UC Firmware */
    preg_match ( "/((?:[a-zA-Z][a-zA-Z]+))-((?:[a-zA-Z][a-zA-Z]+))_(\d+)-((?:[a-zA-Z][a-zA-Z]+))\/((?:[\w\.\-]+)+)/", $devAgent [1], $dI );
    
    $cDev->deviceFamily = $dI [1];
    $cDev->model = $dI [2];
    $cDev->modelNo = $dI [3];
    // $cDev [$dI [4]] = $dI [5];
    $cDev->userAgent = $dI [5];
    
    if ($eC == 4) {
      system ( "echo 'Device Information Contains SN' >> /tmp/AGENT.log" );
      
      /* Get Devices Serial Number AKA MAC */
      preg_match ( "/\(((?:[a-zA-Z][a-zA-Z]+)):((?:[\w\.\-]+)+)\)/", $devAgent [2], $dI );
      // $cDev [$dI [1]] = $dI [2];
      $cDev->deviceSerial = $dI [2];
      
      /* Get Loader Type Boot/App */
      preg_match ( "/((?:[a-zA-Z][a-zA-Z]+))\/((?:[a-zA-Z][a-zA-Z]+))/", $devAgent [3], $dI );
      if ($dI [1] == 'Application')
        $cDev->bootStatus = 'Warm';
      
      $cDev->appType = $dI [2];
      // $cDev [$dI [1]] = $dI [2];
    }
    else if ($eC == 3) {
      // MrOlsen (2015-12-09) - I'm not happy with this and want to change how I detect
      
      /* Get Devices Serial Number AKA MAC */
      if ($devAgent [2] [0] == '(') {
        system ( "echo 'Device Information Contains SN With No Type' >> /tmp/AGENT.log" );
        preg_match ( "/\(((?:[a-zA-Z][a-zA-Z]+)):((?:[\w\.\-]+)+)\)/", $devAgent [2], $dI );
        // $cDev [$dI [1]] = $dI [2];
        $cDev->deviceSerial = $dI [2];
        $cDev->appType = 'Unknown'; //Updater';
      }
      else {
        /* Get Loader Type Boot/App */
        system ( "echo 'Device Information Does Not Contain SN' >> /tmp/AGENT.log" );
        preg_match ( "/((?:[a-zA-Z][a-zA-Z]+))\/((?:[a-zA-Z][a-zA-Z]+))/", $devAgent [2], $dI );
        if ($dI [1] == 'Application')
          $cDev->bootStatus = 'Warm';
        
        $cDev->appType = $dI [2];
      }
    }
    else if ($eC == 2) {
      $cDev->appType = 'Updater';
    }
    else {
      $cDev->bootStatus = 'Invalid';
      
      system ( "echo 'Invalid Device Information' >> /tmp/AGENT.log" );
      unset ( $cDev );
    }
    break;
  default :
    system ( "echo 'Unsupported Device' >> /tmp/AGENT.log" );
    break;
}

system ( "echo 'cDev[" . $data ['mode'] . "]: " . json_encode ( $cDev ) . "' >> /tmp/AGENT.log" );

/* Break The Request File Into Parts */
$cFile = explode ( "-", $data ['file'] );

switch ($data ['type']) {
  case 'xml' :
    switch ($cFile [1]) {
      case 'directory' :
        Polycom_Device::loadDirectory ( $data, $cFile[0] );
        exit ();
        break;
      default :
        script404 ();
    }
    break;
  case 'ug' :
    if (($cDev->appType == "Application" && $cDev->userAgent [0] == '3') || ($cDev->appType == "Updater" && $cDev->userAgent [0] == '4')) {
      system ( "echo 'UG: " . $data ['mode'] . "-" . $cDev->userAgent . "' >> /tmp/AGENT.log" );
      if ($cFile [0] == "000000000000") {
        print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"firmware/Polycom/4.0.9/sip.ld\" CONFIG_FILES=\"\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
        exit ();
      }
      else
        script404 ();
    }
    else {
      print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"firmware/Polycom/4.0.9/sip.ld\" CONFIG_FILES=\"http://prov.spherepbx.com/ns/completed.cfg, http://prov.spherepbx.com/" . $cFile[0] . ".cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
      exit;
    }
    break;
  case 'dg' :
    if (($cDev->appType == "Application" && $cDev->userAgent [0] == '4') || ($cDev->appType == "Updater" && $cDev->userAgent [0] == '5')) {
      system ( "echo 'DG: " . $data ['mode'] . "-" . $cDev->userAgent . "' >> /tmp/AGENT.log" );
      if ($cFile [0] == "000000000000") {
        print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"sip.ld\" CONFIG_FILES=\"\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
        exit ();
      }
      else
        script404 ();
    }
    else {
        print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"sip.ld\" CONFIG_FILES=\"http://prov.spherepbx.com/ns/completed.cfg, http://prov.spherepbx.com/" . $cFile[0] . ".cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
        exit ();
    }
    break;
  case 'cfg' :
    $cFile = explode ( "-", $data ['file'] );
    
    if (count ( $cFile ) == 1)
      $cFile [1] = "mac";

     if ($cFile[0] == "00000000000000")
       script404();
    
    $query = "UPDATE voip_devices SET last_config = " . time () . ", last_ip = '" . $_SERVER ['REMOTE_ADDR'] . "' WHERE mac = '" . $cFile [0] . "'";
    $data ['ubix_db']->query ( $query );
    $query = "SELECT * FROM voip_devices vd LEFT JOIN voip_device_types vdt ON vd.vdtid=vdt.vdtid WHERE mac = '" . $cFile [0] . "'";
    $result = $data ['ubix_db']->query ( $query );
    if ($result === false)
      script404 ();
    else
      $qData = $result->fetch_assoc ();

//MrOlsen (2015-12-10) NOTICE: Temp
$frm = $qData['firmware'];
    
    $result->free ();
    
    /* Make Sure We're Running The Expected Firmware Before Continuing */
    if (strstr ( $qData ['firmware'], "_4" )) {
      if (($cDev->appType == 'Updater' && $cDev->userAgent [0] != '5') || ($cDev->appType == "Application" && $cDev->userAgent [0] != '4') || ($cDev->appType == "Unknown" && $cDev->userAgent[0] == '3')) {
        system ( "echo 'Test for UG: " . $qData ['firmware'] . "' >> /tmp/AGENT.log" );
        print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"http://prov.spherepbx.com/firmware/Polycom/sip_333/sip.ld\" CONFIG_FILES=\"http://prov.spherepbx.com/ns/upgrade.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
        exit ();
      }
    }
    else if (strstr ( $qData ['firmware'], "_3" )) {
      if (($cDev->appType == 'Updater' && $cDev->userAgent [0] != '4') || ($cDev->appType == "Application" && $cDev->userAgent [0] != '3')) {
        system ( "echo 'Test for DG: " . $qData ['firmware'] . "' >> /tmp/AGENT.log" );
        print ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n<APPLICATION APP_FILE_PATH=\"http://prov.spherepbx.com/firmware/Polycom/4.0.9/sip.ld\" CONFIG_FILES=\"http://prov.spherepbx.com/ns/downgrade.cfg\" MISC_FILES=\"\" LOG_FILE_DIRECTORY=\"http://prov.spherepbx.com/logs/\" OVERRIDES_DIRECTORY=\"\" CONTACTS_DIRECTORY=\"\" LICENSE_DIRECTORY=\"\" />") ;
        exit ();
      }
    }
    
    switch ($cFile [1]) {
      case 'reg' :
      case 'sip' :
system ("echo 'MrOlsen - Start' >> /tmp/AGENT.log");
        $data ['tpl']->define ( array (
          "conf_file" => $qData ['firmware'] . "/000000000000-" . $cFile [1] . ".tpl" 
        ) );
        
        $query = "SELECT extensions, server_primary, server_port_primary, transport_primary, server_backup, server_port_backup, transport_backup, dialplan, dialplan_timeout FROM voip_devices WHERE mac = '" . $cFile [0] . "'";

system('echo "TPL: ' . $qData['firmware'] . ', Query:[' . $data['ubix_db']->real_escape_string($query) . '"] >> /tmp/AGENT.log');

        $result = $data ['ubix_db']->query ( $query );
        $qData = $result->fetch_assoc ();
        $result->free ();

        
        $extensions = json_decode ( $qData ['extensions'], true );
        
        $data ['tpl']->assign ( "SERVER_PRIMARY", $qData ['server_primary'] );
        $data ['tpl']->assign ( "TRANSPORT_PRIMARY", $qData ['transport_primary'] );
        $data ['tpl']->assign ( "SERVER_BACKUP", $qData ['server_backup'] );
        $data ['tpl']->assign ( "TRANSPORT_BACKUP", $qData ['transport_backup'] );
        
        $ext = "";
        $i = 1;
        $reg = "";
        $mwi = "";
        
        foreach ( $extensions as $key => $val ) {
//system('echo "Kev: ' . $key . ', Val: ' . $val . '" >> /tmp/AGENT.log');
          if ($val ['extension'] != "") {
            
            // MrOlsen Temp 04-30-2015
            if (isset ( $val ['primary_server'] ))
              $val ['server_primary'] = $val ['primary_server'];
            if (isset ( $val ['primary_port'] ))
              $val ['server_port_primary'] = $val ['primary_port'];
            if (isset ( $val ['primary_transport'] ))
              $val ['transport_primary'] = $val ['primary_transport'];
            
            if (isset ( $val ['backup_server'] ))
              $val ['server_backup'] = $val ['backup_server'];
            if (isset ( $val ['backup_port'] ))
              $val ['server_port_backup'] = $val ['backup_port'];
            if (isset ( $val ['backup_transport'] ))
              $val ['transport_backup'] = $val ['backup_transport'];

            if ($val['extension'] != '9999') {
            if (strstr($_SERVER['REMOTE_ADDR'], "10.0.0"))
              $query = "UPDATE sippeers SET permit = '69.126.26.10', deny = '0.0.0.0' WHERE name = '" . $val['extension'] . "'";
            else {
              $query = "UPDATE sippeers SET permit = '" . $_SERVER['REMOTE_ADDR'] . "', deny = '0.0.0.0' WHERE name = '" . $val['extension'] . "'";
            }
            $data['voip_db']->query($query);
            }
            
            $query = "SELECT name, secret, accountcode, callerid FROM sippeers WHERE name = '" . $val ['extension'] . "'";
            $result = $data ['voip_db']->query ( $query );
            
            if ($val ['line_keys'] == "") {
              $LKS = "";
              $CPK = "";
            }
            else if ($val ['line_keys'] == 1) {
              $LKS = 1;
              $CPK = 4;
            }
            else {
              $LKS = $val ['line_keys'];
              $CPK = 1;
            }
            
            if ($result->num_rows > 0) {
              $eRow = $result->fetch_row ();
              
              $ext = substr ( $eRow [0], strlen ( $eRow [2] ) );
              $user = $eRow [0];
              $pass = $eRow [1];
              
              $callerid = explode ( "<", $eRow [3] );
              
              $dN = $callerid [0];
              
              if ($val ['label'] != '')
                $label = $val ['label'];
              else
                $label = strtoupper ( $eRow [2] ) . " " . substr ( $callerid [1], 0, - 1 );
              
              $dN = $label;
              
              $result->free ();
            }
            else if (isset ( $val ['secret'] )) {
              $ext = $val ['extension'];
              $user = $val ['extension'];
              $pass = $val ['secret'];
              
              if ($val ['label'] != '') {
                $label = $val ['label'];
                $dN = $val ['label'];
              }
              else {
                $label = $val ['extension'];
                $dN = $val ['extension'];
              }
            }
            else {
              $ext = "9999";
              $user = "9999";
              $dN = "9999";
              $label = "9999";
              $pass = "1981";
            }
            
            if (! isset ( $val ['server_port_primary'] ))
              $val ['server_port_primary'] = "5060";
            
            if (! isset ( $val ['server_port_backup'] ))
              $val ['server_port_backup'] = "5060";
            
            if (! isset ( $val ['primary_transport'] ))
              $val ['primary_transport'] = "UDPonly";
            
            if (! isset ( $val ['backup_transport'] ))
              $val ['backup_transport'] = "UDPOnly";
            
            $rG = "1";
          }
          else {
            $ext = "";
            $user = "";
            $dN = "";
            $label = "";
            $pass = "";
            $val ['server_port_primary'] = "5060";
            $val ['server_port_backup'] = "5060";
            $val ['transport_primary'] = "UDPOnly";
            $val ['transport_backup'] = "UDPOnly";
            $val ['server_primary'] = "";
            $val ['server_backup'] = "";
            $rG = "";
          }
          
          if ($user != "" && $pass != "") {

//MrOlsen(2015-12-20) NOTE: Forced Backup
//$val['server_backup'] = "Failover.SpherePBX.com";
            
            // if (isset ( $polyMatrix [$dI [3]] [$dI [4]] ['reg'] )) {
        system ( "echo 'FW: " . $frm . "' >> /tmp/AGENT.log" );
            if ($frm == 'sip_409') {

             $rI = new Polycom_Firmware_409();
        //system ( "echo 'PWND: " . $cDev->model . " - " . $cDev->modelNo . "<" . json_encode($rI->regInfo) . ">' >> /tmp/AGENT.log" );
              
             // $rI->regInfo = $polyMatrix [$dI [3]] [$dI [4]] ['reg'];
              $rI->regInfo ['displayName'] = $dN;
              $rI->regInfo ['address'] = $user;
              $rI->regInfo ['label'] = $label;
              $rI->regInfo ['auth.userId'] = $user;
              $rI->regInfo ['auth.password'] = $pass;
              $rI->regInfo ['lineKeys'] = $LKS;
              $rI->regInfo ['callsPerLineKey'] = $CPK;
              $rI->regInfo ['server.1.address'] = $val ['server_primary'];
              $rI->regInfo ['server.1.port'] = $val ['server_port_primary'];
              $rI->regInfo ['server.1.transport'] = $val ['primary_transport'];
              $rI->regInfo ['server.2.address'] = $val ['server_backup'];
              $rI->regInfo ['server.1.register'] = $rG;
              $rI->regInfo ['server.2.register'] = "1"; //MrOlsen (2015-12-10) TEMP $rG;
              $rI->regInfo ['server.2.port'] = $val ['server_port_backup'];
              $rI->regInfo ['server.2.transport'] = $val ['backup_transport'];
              
              foreach ( $rI->regInfo as $rKey => $rVal ) {
                $reg .= 'reg.' . $i . '.' . $rKey . '="' . $rVal . '" ';
              }
        system ( "echo 'PWND.2: " . $cDev->model . " - " . $cDev->modelNo . "<" . json_encode($rI->regInfo) . ">" . $reg . "' >> /tmp/AGENT.log" );
            }
            else {
              $reg .= "reg.$i.displayName=\"" . $dN . "\" reg.$i.address=\"" . $user . "\" reg.$i.label=\"" . $label . "\" reg.$i.auth.userId=\"" . $user . "\" reg.$i.auth.password=\"" . $pass . "\" reg.$i.lineKeys=\"$LKS\" reg.$i.callsPerLineKey=\"$CPK\" reg.$i.server.1.address=\"" . $val ['server_primary'] . "\" reg.$i.server.1.port=\"" . $val ['server_port_primary'] . "\" reg.$i.server.1.transport=\"" . $val ['transport_primary'] . "\" reg.$i.server.2.address=\"" . $val ['server_backup'] . "\" reg.$i.server.1.register=\"" . $rG . "\" reg.$i.server.1.expires=\"60\" reg.$i.server.2.register=\"$rG\" reg.$i.server.2.expires=\"60\" reg.$i.server.2.port=\"" . $val ['server_port_backup'] . "\" reg.$i.server.2.transport=\"" . $val ['transport_backup'] . "\" reg.$i.auth.domain=\"\" reg.$i.outboundProxy.address=\"\" ";
            }
            
            // $mwi .= "msg.mwi.$i.callBackMode=\"contact\" msg.mwi.$i.subscribe=\"" . $val ['server_primary'] . "\" msg.mwi.$i.callBack=\"*98\" ";
            $mwi .= "msg.mwi.$i.callBackMode=\"contact\" msg.mwi.$i.subscribe=\"" . $user . "\" msg.mwi.$i.callBack=\"*98\" ";
          }
          
          $i ++;
        }
        
        $data ['tpl']->assign ( "DIALPLAN", $qData ['dialplan'] );
        $data ['tpl']->assign ( "DIALPLAN_TIMEOUT", $qData ['dialplan_timeout'] );
        
        $data ['tpl']->assign ( "REG", $reg );

system("echo 'Reg: " . $data['ubix_db']->real_escape_string($reg)  . "' >> /tmp/AGENT.log");
        $data ['tpl']->assign ( "MWI", $mwi );
system("echo 'MWI: " . $data['ubix_db']->real_escape_string($mwi)  . "' >> /tmp/AGENT.log");
system ("echo 'MrOlsen - END' >> /tmp/AGENT.log");

        
        break;
      case 'mac' :
        $data ['tpl']->define ( array (
          "conf_file" => "000000000000.tpl" 
        ) );
        system ( "echo 'PMM: " . $cDev->model . " - " . $cDev->modelNo . "' >> /tmp/AGENT.log" );
        
        //if (isset ( $polyMatrix [$cDev->model] [$cDev->model_no] ['firmware'] ) && strstr ( $qData ['firmware'], "_4" )) {
        if (strstr ( $qData ['firmware'], "_409" )) {
          //$data ['tpl']->assign ( "FIRMWARE", "http://prov.spherepbx.com/firmware/" . $qData ['manufacturer'] . "/" . $polyMatrix [$dI [3]] [$dI [4]] ['firmware'] . "/sip.ld" );
          $data ['tpl']->assign ( "FIRMWARE", "http://prov.spherepbx.com/firmware/" . $qData ['manufacturer'] . "/4.0.9/sip.ld" );
          //$defDir = "http://prov.spherepbx.com/defaults/" . $qData ['manufacturer'] . "/" . $polyMatrix [$cDev ['model']] [$cDev ['model_no']] ['firmware'];
          $defDir = "http://prov.spherepbx.com/defaults/" . $qData ['manufacturer'] . "/4.0.9";
          $data ['tpl']->assign ( "CONFIG_FILES", $defDir . "/applications.cfg, " . $defDir . "/device.cfg, " . $defDir . "/features.cfg, " . $defDir . "/sip.cfg, /" . $cFile [0] . "-reg.cfg" );
        }
        else {
          $data ['tpl']->assign ( "FIRMWARE", "http://prov.spherepbx.com/firmware/" . $qData ['manufacturer'] . "/" . $qData ['firmware'] . "/sip.ld" );
          $data ['tpl']->assign ( "CONFIG_FILES", "http://prov.spherepbx.com/defaults/" . $qData ['firmware'] . "/device-ubix.cfg, " . $cFile [0] . "-sip.cfg, http://prov.spherepbx.com/defaults/" . $qData ['firmware'] . "/features-ubix.cfg" );
        }
        $data ['tpl']->assign ( "MISC_FILES", "" ); // "/firmware" . $qData['manufacturer'] . "/" . $qData['firmware'] . "/misc/");
        break;
      case 'web' :
        $query = "SELECT cfg FROM voip_device_configs WHERE mac = '" . $cFile [0] . "' AND cfg_type = 'web'";
        $res = $data ['ubix_db']->query ( $query );
        $wD = $res->fetch_row ();
        if ($res->num_rows == 0) {
          script404 ();
          
          print ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<WEB_CONFIG>\n<OVERRIDES />\n</WEB_CONFIG>\n") ;
        }
        else {
          $res->free ();
          print ($wD [0]) ;
        }
        exit ();
        break;
      case 'phone' :
        $query = "SELECT cfg FROM voip_device_configs WHERE mac = '" . $cFile [0] . "' AND cfg_type = 'phone'";
        $res = $data ['ubix_db']->query ( $query );
        $wD = $res->fetch_row ();
        if ($res->num_rows == 0) {
          print ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<PHONE_CONFIG>\n<OVERRIDES />\n</PHONE_CONFIG>\n") ;
          script404 ();
        }
        else {
          $res->free ();
          print ($wD [0]) ;
        }
        exit ();
        break;
      case 'license' :
        $query = "SELECT cfg FROM voip_device_configs WHERE mac = '" . $cFile [0] . "' AND cfg_type = 'license'";
        $res = $data ['ubix_db']->query ( $query );
        $wD = $res->fetch_row ();
        if ($res->num_rows == 0)
          script404 ();
        else {
          $res->free ();
          print ($wD [0]) ;
        }
        exit ();
        break;
      default :
        script404 ();
        break;
    } /*
       * END * *
       * switch
       */
    
    break;
  default :
    script404 ();
} /* END switch */

/*
 * Parse
 * and * print
 */
$data ['tpl']->parse ( "CONF_FILE", array (
  "conf_file" 
) );
$data ['tpl']->FastPrint ( "CONF_FILE" );

system('echo "TPL: ' . $qData['firmware'] . ', Query:[' . $data['ubix_db']->real_escape_string($data['tpl']->fetch("CONF_FILE")) . '"] >> /tmp/CONF_FILE.log');

function script404($message = '404 Not Found') {

  header ( $_SERVER ["SERVER_PROTOCOL"] . " " . $message );
  exit ( 0 );

}

class Polycom_Device {

  /* Firmware Matchup */
  public $polyMatrix = Array ();

  /*
   * 'SPIP' => Array (
   * // '301' => '3.1.8',
   * // '320' => '3.3.5',
   * // '330' => '3.3.5',
   * '321' => Array (
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * '331' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * '335' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * // '430' => '3.2.7',
   * '450' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * // '501' => '3.1.8',
   * '550' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * '560' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * // '600' => '3.1.8',
   * // '601' => '3.1.8',
   * '650' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * ),
   * '670' => Array (
   * 'firmware' => '4.0.9',
   * 'reg' => '',
   * 'boot_major' => Array (
   * '4' => '3.3.3',
   * '5' => '4.0.9'
   * )
   * )
   * )
   * );
   */
  
  /*
   * public function __construct() {
   *
   * foreach ( Polycom_Firmware_409::devices as $key => $val ) {
   * foreach ( $val as $sval )
   * $this->polyMatrix [$key] = $sval;
   * }
   *
   * }
   */
  public function loadDirectory($data,$mac) {
    $query = "SELECT directory FROM voip_device_directories WHERE mac = '" . $mac . "'";
    $query = "SELECT cfg FROM voip_device_configs WHERE mac = '" . $mac . "' AND cfg_type = 'directory'";
    $res = $data ['ubix_db']->query ( $query );
    if ($res->num_rows == 0)
      script404 ();
    else {
      $dD = $res->fetch_row ();
      print $dD [0];
      $res->free ();
    }
  
  }

}

class Polycom_Firmware_409 {

  /* Default Regstation Info */
  public $regInfo = array (
    'acd-agent-available' => "0",
    'acd-login-logout' => "0",
    'auth.domain' => "",
    'auth.optimizedInFailover' => "0",
    'auth.useLoginCredentials' => "0",
    'bargeInEnabled' => "0",
    'csta' => "0",
    'fwd.busy.contact' => "",
    'fwd.busy.status' => "0",
    'fwd.noanswer.contact' => "",
    'fwd.noanswer.ringCount' => "9",
    'fwd.noanswer.status' => "0",
    'lcs' => "0",
    'musicOnHold.uri' => "",
    'outboundProxy.failOver.failBack.timeout' => "3600",
    'outboundProxy.failOver.failRegistrationOn' => "1",
    'outboundProxy.failOver.onlySignalWithRegistered' => "1",
    'outboundProxy.failOver.reRegisterOn' => "0",
    'outboundProxy.port' => "0",
    'outboundProxy.transport' => "DNSnaptr",
    'outboundProxy.address' => "",
    'protocol' => "",
    'ringType' => "default",
    'serverFeatureControl.activateCodeSequence.cf.always' => "",
    'serverFeatureControl.activateCodeSequence.cf.busy' => "",
    'serverFeatureControl.activateCodeSequence.cf.noanswer' => "",
    'serverFeatureControl.activateCodeSequence.dnd' => "",
    'serverFeatureControl.cf' => "0",
    'serverFeatureControl.deActivateCodeSequence.cf.always' => "",
    'serverFeatureControl.deActivateCodeSequence.cf.busy' => "",
    'serverFeatureControl.deActivateCodeSequence.cf.noanswer' => "",
    'serverFeatureControl.deActivateCodeSequence.dnd' => "",
    'serverFeatureControl.dnd' => "0",
    'serverFeatureControl.signalingMethod' => "subscribeAsFeatureEvent",
    'serverFeatureControl.subscribeToUri' => "",
    'telephony' => "1",
    'teluri' => "0",
    'thirdPartyName' => "",
    'type' => "private",
    'useCompleteUriForRetrieve' => "1",
    'useLocalTargetUriForLegacyPickup' => "0",
    'server.1.expires' => "300",
    'server.1.expires.lineSeize' => "30",
    'server.1.expires.overlap' => "60",
    'server.1.lcs' => "0",
    'server.1.retryMaxCount' => "3",
    'server.1.retryTimeOut' => "0",
    'server.1.specialInterop' => "standard",
    'server.2.expires' => "300",
    'server.2.expires.lineSeize' => "30",
    'server.2.expires.overlap' => "60",
    'server.2.lcs' => "0",
    'server.2.retryMaxCount' => "3",
    'server.2.retryTimeOut' => "0",
    'server.2.specialInterop' => "standard",
    'displayName' => "",
    'address' => "",
    'label' => "",
    'auth.userId' => "",
    'auth.password' => "",
    'lineKeys' => "1",
    'callsPerLineKey' => "1",
    'server.1.address' => "",
    'server.1.port' => "5060",
    'server.1.transport' => "DNSnaptr",
    'server.2.address' => "",
    'server.1.register' => "0",
    'server.2.register' => "0",
    'server.2.port' => "5060",
    'server.2.transport' => "DNSnaptr",
  );

  public static $version = '4.0.9';

  public static $boot_major = '5';

  public static $devices = Array (
    'SPIP' => Array (
      '321',
      '331',
      '335',
      '450',
      '550',
      '560',
      '650',
      '670' 
    ) 
  );

  public function reg() {
    return($this->regInfo);
  }

}

class VoIP_Device {

  public $deviceFamily;

  public $model;

  public $modelNo;

  public $bootStatus;

  public $userAgent;

  public $deviceSerial;

  public $appType;

}

?>