Improved MAC address formatting

master
Thomas Hooge 1 year ago
parent 02980bbad5
commit 20b54f5b27
  1. 59
      lib/functions.php
  2. 3
      node.php

@ -7,43 +7,44 @@ Copyright (C) 2011-2023 Thomas Hooge
SPDX-License-Identifier: GPL-3.0-or-later
*****************************************************************************/
// strip mac address to 12 char string
function strip_mac($mac) {
function strip_mac($mac, $caps=true) {
// strip mac address to 12 char string
// strip chars we don't need
$mac = preg_replace("|[^a-fA-F0-9]|", "", $mac);
// capitalize (just because it looks better eh)
$mac = strtoupper($mac);
// and return
return ($mac);
$mac = preg_replace('/[^a-fA-F0-9]/', '', $mac);
if ($caps) {
$mac = strtoupper($mac);
} else {
$mac = strtolower($mac);
}
return $mac;
}
// rebuild mac address
function write_mac($mac) {
// check string length
if (strlen($mac)!=12) {
function write_mac($mac, $user_mac='xx:xx:xx:xx:xx:xx') {
// rebuild mac address using user supplied format
if (strlen($mac) != 12) {
// if the MAC is empty, or for whatever reason incorrect, just return
return $mac;
} else {
// count to 12...
for ($i=0; $i<12; $i++) {
// ... and strip mac to pieces
${"mac".$i} = $mac{$i};
}
// get user preference
$user_mac = $_SESSION['suser_mac'];
}
// count to 12 again...
for($i=0; $i<12; $i++) {
// ... and replace user preference with pieces
$user_mac = preg_replace("/x/", ${"mac".$i}, $user_mac, 1);
}
// check format of user mac: count upper or lower char
$chars = count_chars($user_mac, 1);
if (array_key_exists(88, $chars) and $chars[88] == 12) {
$pattern = '/X/';
$mac = strtoupper($mac);
} elseif (array_key_exists(120, $chars) and $chars[120] == 12) {
$pattern = '/x/';
$mac = strtolower($mac);
} else {
// invalid format
return $mac;
}
// and return
return $user_mac;
for($i=0; $i<12; $i++) {
$user_mac = preg_replace($pattern, $mac[$i], $user_mac, 1);
}
return $user_mac;
}
// redirect page

@ -231,7 +231,7 @@ $sth = $dbh->prepare($sql);
$sth->execute([$id]);
$node = $sth->fetch(PDO::FETCH_OBJ);
$node->mac = write_mac($node->mac);
$node->mac = write_mac($node->mac, $_SESSION['suser_mac']);
$smarty->assign("node", $node);
// nat
@ -281,6 +281,7 @@ $sql = "SELECT node_id AS id, node_ip AS ip, node_mac AS mac,
$sth = $dbh->prepare($sql);
$sth->execute([$id]);
$node = $sth->fetch(PDO::FETCH_OBJ);
$node->mac = write_mac($node->mac, $_SESSION['suser_mac']);
$node->flags = explode(',', $node->flags);
$smarty->assign("node", $node);