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.
if (empty($this->sccpHelpInfo)) {
$sysConfiguration = $this->aminterface->getSCCPConfigMetaData('general');
foreach ($sysConfiguration['Options'] as $key => $valueArray) {
foreach ($valueArray['Description'] as $descKey => $descValue) {
$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'];
}
}
$lang_data = $this->extconfigs->getExtConfig('sccp_lang');
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 = '') {

View file

@ -10,7 +10,6 @@ global $version;
global $aminterface;
global $extconfigs;
global $mobile_hw;
global $useAmiForSoftKeys;
global $settingsFromDb;
global $thisInstaller;
global $cnf_int;
@ -21,7 +20,6 @@ $mobile_hw = '0';
$autoincrement = (($amp_conf["AMPDBENGINE"] == "sqlite") || ($amp_conf["AMPDBENGINE"] == "sqlite3")) ? "AUTOINCREMENT" : "AUTO_INCREMENT";
$table_req = array('sccpdevice', 'sccpline', 'sccpsettings');
$sccp_compatible = 0;
$chanSCCPWarning = true;
$db_config = '';
$sccp_version = array();
$cnf_int = \FreePBX::Config();
@ -45,16 +43,14 @@ foreach ($requiredClasses as $className) {
}
CheckAsteriskVersion();
$sccp_version = CheckChanSCCPCompatible();
$sccp_compatible = $sccp_version[0];
$chanSCCPWarning = $sccp_version[1] ^= 1;
$sccp_compatible = $aminterface->getSCCPVersion['vCode'];
outn("<li>" . _("Sccp model Compatible code : ") . $sccp_compatible . "</li>");
if ($sccp_compatible == 0) {
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();
}
// BackUp Old config
createBackUpConfig();
RenameConfig();
@ -68,10 +64,7 @@ InstallDB_createButtonConfigTrigger();
InstallDbCreateViews($sccp_compatible);
installDbPopulateSccpline();
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();
addDriver($sccp_compatible);
checkTftpServer();
@ -369,10 +362,8 @@ function CheckAsteriskVersion()
function CheckChanSCCPCompatible()
{
global $chanSCCPWarning;
global $aminterface;
// calling with true returns array with compatibility and RevisionNumber
return $aminterface->get_compatible_sccp(true);
return $aminterface->getSCCPVersion['vCode'];
}
function InstallDB_updateSchema($db_config)

View file

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

View file

@ -71,8 +71,10 @@ abstract class Response extends IncomingMessage
$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);
foreach ($_fields as $key => $value) {
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
@ -106,7 +105,6 @@ class Generic_Response extends Response
$this->_events['ClosingEvent'] = new ResponseComplete_Event($rawContent);
$this->_completed = true;
$this->eventListIsCompleted = true;
}
}
@ -157,7 +155,7 @@ class SCCPJSON_Response extends Generic_Response
public function __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')) {
$this->setKey('Response', 'Success');
}

View file

@ -59,8 +59,7 @@ class aminterface
'pass' => '',
'port' => '5038',
'tsoket' => 'tcp://',
'timeout' => 30,
'enabled' => true
'timeout' => 30
);
$this->_eventListeners = array();
$this->_incomingMsgObjectList = array();
@ -76,33 +75,14 @@ class aminterface
}
}
}
if ($this->_config['enabled']) {
$this->load_subspace();
}
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();
}
}
}
$this->load_subspace();
$this->open();
}
public function info()
{
$Ver = '16.0.0.1';
if ($this->_config['enabled']){
return array('Version' => $Ver,
'about' => 'AMI data ver: ' . $Ver, 'test' => get_declared_classes());
} else {
return array('Version' => $Ver,
'about' => 'Disabled AMI ver: ' . $Ver);
}
return array('Version' => $Ver, 'about' => 'AMI data ver: ' . $Ver);
}
/*
@ -509,16 +489,4 @@ class aminterface
}
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 {
$lang = $data_values['devlang'];
}
if (isset($lang_info[$lang])) {
$xnode->name = $lang_info[$lang]['locale'];
$xnode->langCode = $lang_info[$lang]['code'];
if (isset($this->langCodeArray[$lang])) {
$xnode->name = $lang;
$xnode->langCode = $this->langCodeArray[$lang];
} else {
$xnode->name = '';
$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.
// Need to merge the two arrays so that device specific values override system values
@ -461,7 +461,7 @@ class xmlinterface
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',
'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);
$db_Schema = $this->dbinterface->validate();
$mysql_info = $this->dbinterface->get_db_sysvalues();
$compatible = $this->aminterface->get_compatible_sccp();
$compatible = $core['vCode'];
$info = array();
//$info['srvinterface'] = $this->srvinterface->info();