Optimise aminterface class

Remove duplicate functions
Remove legacy tests from _Construct
Optimise JSON handling (eliminate duplicate parsing of rawMessage)
Optimise Message class _Construct - high load so minimise unnecessary calls
This commit is contained in:
stevenA 2022-01-15 17:00:19 +01:00
parent 9138272a46
commit 519c9a1f3b
7 changed files with 94 additions and 120 deletions

View file

@ -165,7 +165,6 @@ class Sccp_manager extends \FreePBX_Helpers implements \BMO {
// load metainfo from chan-sccp - help information if not in xml. Only load first time as static data. // load metainfo from chan-sccp - help information if not in xml. Only load first time as static data.
if (empty($this->sccpHelpInfo)) { if (empty($this->sccpHelpInfo)) {
$sysConfiguration = $this->aminterface->getSCCPConfigMetaData('general'); $sysConfiguration = $this->aminterface->getSCCPConfigMetaData('general');
foreach ($sysConfiguration['Options'] as $key => $valueArray) { foreach ($sysConfiguration['Options'] as $key => $valueArray) {
foreach ($valueArray['Description'] as $descKey => $descValue) { foreach ($valueArray['Description'] as $descKey => $descValue) {
$this->sccpHelpInfo[$valueArray['Name']] .= $descValue . '<br>'; $this->sccpHelpInfo[$valueArray['Name']] .= $descValue . '<br>';
@ -920,12 +919,10 @@ class Sccp_manager extends \FreePBX_Helpers implements \BMO {
$dev_config['addon_info'][$key] = $hw_data[0]['loadimage']; $dev_config['addon_info'][$key] = $hw_data[0]['loadimage'];
} }
} }
$lang_data = $this->extconfigs->getExtConfig('sccp_lang');
if (!$sccp_native) { if (!$sccp_native) {
return $this->xmlinterface->create_SEP_SIP_XML($this->sccppath["tftp_store_path"], $data_value, $dev_config, $dev_id, $lang_data); return $this->xmlinterface->create_SEP_SIP_XML($this->sccppath["tftp_store_path"], $data_value, $dev_config, $dev_id);
} }
return $this->xmlinterface->create_SEP_XML($this->sccppath["tftp_templates_path"], $data_value, $dev_config, $dev_id, $lang_data); return $this->xmlinterface->create_SEP_XML($this->sccppath["tftp_templates_path"], $data_value, $dev_config, $dev_id);
} }
function deleteSccpDeviceXML($dev_id = '') { function deleteSccpDeviceXML($dev_id = '') {

View file

@ -10,7 +10,6 @@ global $version;
global $aminterface; global $aminterface;
global $extconfigs; global $extconfigs;
global $mobile_hw; global $mobile_hw;
global $useAmiForSoftKeys;
global $settingsFromDb; global $settingsFromDb;
global $thisInstaller; global $thisInstaller;
global $cnf_int; global $cnf_int;
@ -21,7 +20,6 @@ $mobile_hw = '0';
$autoincrement = (($amp_conf["AMPDBENGINE"] == "sqlite") || ($amp_conf["AMPDBENGINE"] == "sqlite3")) ? "AUTOINCREMENT" : "AUTO_INCREMENT"; $autoincrement = (($amp_conf["AMPDBENGINE"] == "sqlite") || ($amp_conf["AMPDBENGINE"] == "sqlite3")) ? "AUTOINCREMENT" : "AUTO_INCREMENT";
$table_req = array('sccpdevice', 'sccpline', 'sccpsettings'); $table_req = array('sccpdevice', 'sccpline', 'sccpsettings');
$sccp_compatible = 0; $sccp_compatible = 0;
$chanSCCPWarning = true;
$db_config = ''; $db_config = '';
$sccp_version = array(); $sccp_version = array();
$cnf_int = \FreePBX::Config(); $cnf_int = \FreePBX::Config();
@ -45,16 +43,14 @@ foreach ($requiredClasses as $className) {
} }
CheckAsteriskVersion(); CheckAsteriskVersion();
$sccp_version = CheckChanSCCPCompatible(); $sccp_compatible = $aminterface->getSCCPVersion['vCode'];
$sccp_compatible = $sccp_version[0];
$chanSCCPWarning = $sccp_version[1] ^= 1;
outn("<li>" . _("Sccp model Compatible code : ") . $sccp_compatible . "</li>"); outn("<li>" . _("Sccp model Compatible code : ") . $sccp_compatible . "</li>");
if ($sccp_compatible == 0) { if ($sccp_compatible == 0) {
outn("<br>"); outn("<br>");
outn("<font color='red'>Chan Sccp not Found. Install it before continuing !</font>"); outn("<font color='red'>chan-sccp not found. Install it before continuing !</font>");
die(); die();
} }
// BackUp Old config // BackUp Old config
createBackUpConfig(); createBackUpConfig();
RenameConfig(); RenameConfig();
@ -68,10 +64,7 @@ InstallDB_createButtonConfigTrigger();
InstallDbCreateViews($sccp_compatible); InstallDbCreateViews($sccp_compatible);
installDbPopulateSccpline(); installDbPopulateSccpline();
InstallDB_updateDBVer($sccp_compatible); InstallDB_updateDBVer($sccp_compatible);
if ($chanSCCPWarning) {
outn("<br>");
outn("<font color='red'>Error: installed version of chan-sccp is not compatible. Please upgrade chan-sccp</font>");
}
Setup_RealTime(); Setup_RealTime();
addDriver($sccp_compatible); addDriver($sccp_compatible);
checkTftpServer(); checkTftpServer();
@ -369,10 +362,8 @@ function CheckAsteriskVersion()
function CheckChanSCCPCompatible() function CheckChanSCCPCompatible()
{ {
global $chanSCCPWarning;
global $aminterface; global $aminterface;
// calling with true returns array with compatibility and RevisionNumber return $aminterface->getSCCPVersion['vCode'];
return $aminterface->get_compatible_sccp(true);
} }
function InstallDB_updateSchema($db_config) function InstallDB_updateSchema($db_config)

View file

@ -71,7 +71,8 @@ abstract class Message
print_r($value); print_r($value);
*/ */
} }
/*
// Duplicate declaration - also declared in Response class where is used.
public function getVariable($key) public function getVariable($key)
{ {
$key = strtolower($key); $key = strtolower($key);
@ -81,17 +82,11 @@ abstract class Message
} }
return $this->variables[$key]; return $this->variables[$key];
} }
*/
protected function setKey($key, $value) protected function setKey($key, $value)
{ {
$key = strtolower((string) $key); $key = strtolower((string) $key);
$this->keys[$key] = (string) $value; $this->keys[$key] = (string) $value;
/*
print_r('<br>----Set Key -------<br>');
print_r($key);
print_r($value);
*
*/
} }
public function getKey($key) public function getKey($key)
@ -126,8 +121,24 @@ abstract class Message
protected function setSanitizedKey($key, $value) protected function setSanitizedKey($key, $value)
{ {
//$key = strtolower((string) $key); // TODO: Need to handle JSON here rather than in getVariable as have
$_string_key = array('actionid', 'descr'); // already broken data into array.
$key = strtolower($key);
switch ($key) {
case 'json':
$this->keys['JSONRAW'] = (string) $value;
break;
case 'actionid':
case 'desc':
$this->keys[$key] = (string) $value;
break;
default:
$this->keys[$key] = $this->sanitizeInput($value);
break;
}
$_string_key = array('actionid', 'descr', 'json');
if (array_search($key, $_string_key) !== false) { if (array_search($key, $_string_key) !== false) {
$this->keys[$key] = (string) $this->sanitizeInput($value, 'string'); $this->keys[$key] = (string) $this->sanitizeInput($value, 'string');
} else { } else {
@ -138,9 +149,11 @@ abstract class Message
protected function sanitizeInput($value, $prefered_type = '') protected function sanitizeInput($value, $prefered_type = '')
{ {
if ($prefered_type == '') { if ($prefered_type == '') {
if (!isset($value) || $value === null || strlen($value) == 0) { // No longer send empty values
return null; //if (!isset($value) || $value === null || strlen($value) == 0) {
} elseif (is_numeric($value)) { //return null;
//} elseif (is_numeric($value)) {
if (is_numeric($value)) {
$prefered_type = 'numeric'; $prefered_type = 'numeric';
} elseif (is_string($value)) { } elseif (is_string($value)) {
$prefered_type = 'string'; $prefered_type = 'string';
@ -148,38 +161,38 @@ abstract class Message
throw new AMIException("Don't know how to convert: '" . $value . "'\n"); throw new AMIException("Don't know how to convert: '" . $value . "'\n");
} }
} }
if ($prefered_type !== '') { //if ($prefered_type !== '') {
switch ($prefered_type) { switch ($prefered_type) {
case 'string': case 'string':
if (!isset($value) || $value === null || strlen($value) == 0) { //if (!isset($value) || $value === null || strlen($value) == 0) {
return ''; //return '';
} //}
if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) { if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
return (boolean) $value; return (boolean) $value;
} elseif (filter_var($value, FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE)) { } elseif (filter_var($value, FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE)) {
return (string) $value; return (string) $value;
} elseif (filter_var($value, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_NULL_ON_FAILURE)) { } elseif (filter_var($value, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_NULL_ON_FAILURE)) {
return (string) htmlspecialchars($value, ENT_QUOTES); return (string) htmlspecialchars($value, ENT_QUOTES);
} else { } else {
throw new AMIException("Incoming String is not sanitary. Skipping: '" . $value . "'\n"); throw new AMIException("Incoming String is not sanitary. Skipping: '" . $value . "'\n");
} }
break; break;
case 'numeric': case 'numeric':
if (!isset($value) || $value === null || strlen($value) == 0) { //if (!isset($value) || $value === null || strlen($value) == 0) {
return 0; //return 0;
} //}
if (filter_var($value, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX | FILTER_FLAG_ALLOW_OCTAL)) { if (filter_var($value, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX | FILTER_FLAG_ALLOW_OCTAL)) {
return intval($value, 0); return intval($value, 0);
} elseif (filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_SCIENTIFIC)) { } elseif (filter_var($value, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_SCIENTIFIC)) {
return (float) $value; return (float) $value;
} else { } else {
return (double) $value; return (double) $value;
} }
default: default:
throw new AMIException("Don't know how to convert: '" . $value . "'\n"); throw new AMIException("Don't know how to convert: '" . $value . "'\n");
break; break;
}
} }
//}
} }
protected function finishMessage($message) protected function finishMessage($message)
@ -257,21 +270,28 @@ abstract class IncomingMessage extends Message
public function __construct($rawContent) public function __construct($rawContent)
{ {
parent::__construct(); parent::__construct();
dbug($rawContent); //dbug($rawContent);
$this->rawContent = $rawContent; $this->rawContent = $rawContent;
$lines = explode(Message::EOL, $rawContent); $lines = explode(Message::EOL, $rawContent);
foreach ($lines as $line) { foreach ($lines as $line) {
$content = explode(':', $line); $content = explode(':', $line);
$name = strtolower(trim($content[0])); //$content = preg_split("/: /",$line);
unset($content[0]); //$name = strtolower(trim($content[0]));
$value = isset($content[1]) ? trim(implode(':', $content)) : ''; // do strtolower in setSanitizedKey
$name = array_shift($content);
//unset($content[0]);
if (!isset($content[0])) {
continue;
}
//$value = isset($content[0]) ? trim(implode(':', $content)) : '';
try { try {
$this->setSanitizedKey($name, $value); $this->setSanitizedKey($name, trim(implode(':', $content)));
} catch (AMIException $e) { } catch (AMIException $e) {
throw new AMIException("Error: '" . $e . "'\n Dump RawContent:\n" . $this->rawContent . "\n"); throw new AMIException("Error: '" . $e . "'\n Dump RawContent:\n" . $this->rawContent . "\n");
} }
dbug($this->keys); //dbug($this->keys);
} }
//dbug($this->keys);
} }
} }
@ -405,9 +425,9 @@ class SCCPDeviceRestartAction extends ActionMessage
{ {
parent::__construct('SCCPDeviceRestart'); parent::__construct('SCCPDeviceRestart');
$this->setResponseHandler("Generic"); $this->setResponseHandler("Generic");
if (empty($Type)) { //if (empty($Type)) {
$Type = "restart"; //$Type = "restart";
} //}
$this->setKey('DeviceName', $DeviceName); $this->setKey('DeviceName', $DeviceName);
if (in_array(strtolower($Type), array('restart', 'full', 'reset'))) { if (in_array(strtolower($Type), array('restart', 'full', 'reset'))) {
$this->setKey('Type', $Type); $this->setKey('Type', $Type);

View file

@ -71,8 +71,10 @@ abstract class Response extends IncomingMessage
$this->setKey('ActionId', $actionId); $this->setKey('ActionId', $actionId);
} }
public function getVariable($_rawContent, $_fields = '') public function getVariable(string $_rawContent, array $_fields)
{ {
dbug($_rawContent);
dbug($_fields);
$lines = explode(Message::EOL, $_rawContent); $lines = explode(Message::EOL, $_rawContent);
foreach ($_fields as $key => $value) { foreach ($_fields as $key => $value) {
foreach ($lines as $data) { foreach ($lines as $data) {
@ -84,9 +86,6 @@ abstract class Response extends IncomingMessage
} }
} }
} }
class GenericResponse extends Response
{
}
//**************************************************************************** //****************************************************************************
// There are two types of Response messages returned by AMI // There are two types of Response messages returned by AMI
@ -106,7 +105,6 @@ class Generic_Response extends Response
$this->_events['ClosingEvent'] = new ResponseComplete_Event($rawContent); $this->_events['ClosingEvent'] = new ResponseComplete_Event($rawContent);
$this->_completed = true; $this->_completed = true;
$this->eventListIsCompleted = true; $this->eventListIsCompleted = true;
} }
} }
@ -157,7 +155,7 @@ class SCCPJSON_Response extends Generic_Response
public function __construct($rawContent) public function __construct($rawContent)
{ {
parent::__construct($rawContent); parent::__construct($rawContent);
$this->getVariable($rawContent, array("DataType" => "DataType:", "JSONRAW" => "JSON:")); //$this->getVariable($rawContent, array("DataType" => "DataType:", "JSONRAW" => "JSON:"));
if (null !== $this->getKey('JSONRAW')) { if (null !== $this->getKey('JSONRAW')) {
$this->setKey('Response', 'Success'); $this->setKey('Response', 'Success');
} }

View file

@ -59,8 +59,7 @@ class aminterface
'pass' => '', 'pass' => '',
'port' => '5038', 'port' => '5038',
'tsoket' => 'tcp://', 'tsoket' => 'tcp://',
'timeout' => 30, 'timeout' => 30
'enabled' => true
); );
$this->_eventListeners = array(); $this->_eventListeners = array();
$this->_incomingMsgObjectList = array(); $this->_incomingMsgObjectList = array();
@ -76,33 +75,14 @@ class aminterface
} }
} }
} }
if ($this->_config['enabled']) { $this->load_subspace();
$this->load_subspace(); $this->open();
}
if ($this->_config['enabled']) {
// Ami is not hard disabled in __construct line 63.
if ($this->open()) {
// Can open a connection. Now check compatibility with chan-sccp.
// will return true if compatible.
if (!$this->get_compatible_sccp(true)[1]) {
// Close the open socket as will not use
$this->close();
}
}
}
} }
public function info() public function info()
{ {
$Ver = '16.0.0.1'; $Ver = '16.0.0.1';
if ($this->_config['enabled']){ return array('Version' => $Ver, 'about' => 'AMI data ver: ' . $Ver);
return array('Version' => $Ver,
'about' => 'AMI data ver: ' . $Ver, 'test' => get_declared_classes());
} else {
return array('Version' => $Ver,
'about' => 'Disabled AMI ver: ' . $Ver);
}
} }
/* /*
@ -509,16 +489,4 @@ class aminterface
} }
return $cmd_res; return $cmd_res;
} }
public function get_compatible_sccp($revNumComp=false) {
// only called with args from installer to get revision and compatibility
$res = $this->getSCCPVersion();
if ($res['RevisionNum'] < 11063) {
$this->useAmiInterface = false;
}
if ($revNumComp) {
return array($res['vCode'], true);
}
return $res['vCode'];
}
} }

View file

@ -126,9 +126,9 @@ class xmlinterface
} else { } else {
$lang = $data_values['devlang']; $lang = $data_values['devlang'];
} }
if (isset($lang_info[$lang])) { if (isset($this->langCodeArray[$lang])) {
$xnode->name = $lang_info[$lang]['locale']; $xnode->name = $lang;
$xnode->langCode = $lang_info[$lang]['code']; $xnode->langCode = $this->langCodeArray[$lang];
} else { } else {
$xnode->name = ''; $xnode->name = '';
$xnode->langCode = ''; $xnode->langCode = '';
@ -156,7 +156,7 @@ class xmlinterface
} }
} }
function create_SEP_XML($store_path, $data_values, $dev_config, $dev_id, $lang_info = array()) function create_SEP_XML($store_path, $data_values, $dev_config, $dev_id)
{ {
// TODO: $data_values are system wide defaults, $dev_config are specific device values. // TODO: $data_values are system wide defaults, $dev_config are specific device values.
// Need to merge the two arrays so that device specific values override system values // Need to merge the two arrays so that device specific values override system values
@ -461,7 +461,7 @@ class xmlinterface
return $res; return $res;
} }
function create_SEP_SIP_XML($store_path = '', $data_values = array(), $dev_config = array(), $dev_id = '', $lang_info = array()) function create_SEP_SIP_XML($store_path = '', $data_values = array(), $dev_config = array(), $dev_id = '')
{ {
$var_xml_general_fields = array('authenticationURL' => 'dev_authenticationURL', 'informationURL' => 'dev_informationURL', 'messagesURL' => 'dev_messagesURL', $var_xml_general_fields = array('authenticationURL' => 'dev_authenticationURL', 'informationURL' => 'dev_informationURL', 'messagesURL' => 'dev_messagesURL',
'servicesURL' => 'dev_servicesURL', 'directoryURL' => 'dev_directoryURL', 'proxyServerURL' => 'dev_proxyServerURL', 'idleTimeout' => 'dev_idleTimeout', 'servicesURL' => 'dev_servicesURL', 'directoryURL' => 'dev_directoryURL', 'proxyServerURL' => 'dev_proxyServerURL', 'idleTimeout' => 'dev_idleTimeout',

View file

@ -27,7 +27,7 @@ foreach ($ast_realtime as $key => $value) {
$conf_realtime = $this->extconfigs->validate_RealTime($ast_realm); $conf_realtime = $this->extconfigs->validate_RealTime($ast_realm);
$db_Schema = $this->dbinterface->validate(); $db_Schema = $this->dbinterface->validate();
$mysql_info = $this->dbinterface->get_db_sysvalues(); $mysql_info = $this->dbinterface->get_db_sysvalues();
$compatible = $this->aminterface->get_compatible_sccp(); $compatible = $core['vCode'];
$info = array(); $info = array();
//$info['srvinterface'] = $this->srvinterface->info(); //$info['srvinterface'] = $this->srvinterface->info();