code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function getItems($url) { $this->root->toggleSelected($url); $menu = $this->root->getChildren(); return $menu; }
return full menu system including selected items @param string $url current location @return array
getItems
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Base/Menu/MenuSystem.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Base/Menu/MenuSystem.php
BSD-2-Clause
public function getBreadcrumbs() { $nodes = $this->root->getChildren(); $breadcrumbs = array(); while ($nodes != null) { $next = null; foreach ($nodes as $node) { if ($node->Selected) { /* ignore client-side anchor in breadcrumb */ if (!empty($node->Url) && strpos($node->Url, '#') !== false) { $next = null; break; } $breadcrumbs[] = array('name' => $node->VisibleName); /* only go as far as the first reachable URL */ $next = empty($node->Url) ? $node->Children : null; break; } } $nodes = $next; } return $breadcrumbs; }
return the currently selected page's breadcrumbs @return array
getBreadcrumbs
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Base/Menu/MenuSystem.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Base/Menu/MenuSystem.php
BSD-2-Clause
public function setValue($value) { $value = (string)$value; $parent = $this->getParentNode(); if (Util::isIpAddress($value)) { $parent->ipaddr = $value; $parent->if = ''; } else { $parent->if = $value; $parent->ipaddr = ''; } }
Reflect interface or address choice into their appropriate fields.
setValue
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Interfaces/FieldTypes/LinkAddressField.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Interfaces/FieldTypes/LinkAddressField.php
BSD-2-Clause
public function run($model) { if (!$model instanceof IPsec) { return; } $cnf = Config::getInstance()->object(); if (!isset($cnf->system)) { return; } if (isset($cnf->system->disablevpnrules) && !empty((string)$cnf->system->disablevpnrules)) { $model->general->disablevpnrules = '1'; unset($cnf->system->disablevpnrules); } }
Migrate the previously missing advanced setting that was stored under "system" section
run
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/IPsec/Migrations/M1_0_3.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/IPsec/Migrations/M1_0_3.php
BSD-2-Clause
public function post($model) { if (!$model instanceof IPsec) { return; } $cnf = Config::getInstance()->object(); if (isset($cnf->ipsec->phase1) && isset($cnf->ipsec->phase2)) { $reqids = []; $last_seq = 1; foreach ($cnf->ipsec->phase1 as $phase1) { $p2sequence = 0; foreach ($cnf->ipsec->phase2 as $phase2) { if ((string)$phase1->ikeid != (string)$phase2->ikeid) { continue; } if (empty($phase2->reqid)) { if ((string)$phase2->mode == "route-based") { // persist previous logic for route-based entries $phase2->reqid = (int)$phase1->ikeid * 1000 + $p2sequence; } else { // allocate next sequence in the list $phase2->reqid = (int)$last_seq; } $reqids[] = $last_seq; while (in_array($last_seq, $reqids)) { $last_seq++; } } $p2sequence++; } } } }
setup initial reqid's in phase2 entries
post
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/IPsec/Migrations/M1_0_0.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/IPsec/Migrations/M1_0_0.php
BSD-2-Clause
public function add() { $result = [ 'key' => base64_encode(random_bytes(60)), 'secret' => base64_encode(random_bytes(60)) ]; $new_items = array_merge( array_filter(explode("\n", $this->getCurrentValue())), [sprintf("%s|%s", $result['key'], crypt($result['secret'], '$6$'))] ); $this->internalValue = implode("\n", $new_items); return $result; }
generate a new key and return it @return array generated key+secret
add
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Auth/FieldTypes/ApiKeyField.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Auth/FieldTypes/ApiKeyField.php
BSD-2-Clause
private function generateNewId($startAt, $allIds) { $newId = $startAt; for ($i = 0; $i < count($allIds); ++$i) { if ($allIds[$i] > $newId && isset($allIds[$i + 1])) { if ($allIds[$i + 1] - $allIds[$i] > 1) { // gap found $newId = $allIds[$i] + 1; break; } } elseif ($allIds[$i] >= $newId) { // last item is higher than target $newId = $allIds[$i] + 1; } } return $newId; }
generate new Id by filling a gap or add 1 to the last @param int $startAt start search at number @param array $allIds all reserved id's @return int next number
generateNewId
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
BSD-2-Clause
public function getMaxRuleSequence() { $seq = 0; foreach ($this->rules->rule->iterateItems() as $rule) { if ((string)$rule->sequence > $seq) { $seq = (string)$rule->sequence; } } return $seq; }
retrieve last generated rule sequence number
getMaxRuleSequence
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
BSD-2-Clause
public function isEnabled() { foreach ($this->pipes->pipe->iterateItems() as $item) { if ((string)$item->enabled == '1') { return true; } } return false; }
return whether the shaper is currently in use
isEnabled
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/TrafficShaper/TrafficShaper.php
BSD-2-Clause
public function serializeToConfig($validateFullModel = false, $disable_validation = false) { @touch("/tmp/monit.dirty"); return parent::serializeToConfig($validateFullModel, $disable_validation); }
mark configuration as changed when data is pushed back to the config
serializeToConfig
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
BSD-2-Clause
public function configClean() { return @unlink("/tmp/monit.dirty"); }
mark configuration as consistent with the running config @return bool
configClean
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
BSD-2-Clause
public function isTestServiceRelated($testUUID = null) { $serviceNodes = $this->service->getNodes(); foreach ($this->service->iterateItems() as $serviceNode) { if (in_array($testUUID, explode(',', (string)$serviceNode->tests))) { return true; } } return false; }
determine if services have links to this test node @param string $testUUID uuid of the test node @return bool
isTestServiceRelated
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
BSD-2-Clause
public function getTestType($condition) { $condition = preg_replace('/\s\s+/', ' ', $condition); $keyLength = 0; $foundOperand = ''; $foundTestType = 'Custom'; foreach ($this->conditionPatterns as $testType => $operandList) { // find the operand for this condition using the longest match foreach ($operandList as $operand) { $operandLength = strlen($operand); if ( !strncmp($condition, $operand, $operandLength) && $operandLength > $keyLength ) { $keyLength = $operandLength; $foundOperand = $operand; $foundTestType = $testType; } } } // 'memory usage' can be ambiguous but 'percent' unit makes it clear if (strcmp('memory usage', $foundOperand) == 0) { if (preg_match('/^.*\spercent|%\s*$/', $condition)) { $foundTestType = 'SystemResource'; } else { $foundTestType = 'ProcessResource'; } } return $foundTestType; }
get test type from condition string @param string $condition condition string @return string
getTestType
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Monit/Monit.php
BSD-2-Clause
public function usedVPNIds() { $result = []; $cfg = Config::getInstance()->object(); foreach (['openvpn-server', 'openvpn-client'] as $ref) { if (isset($cfg->openvpn) && isset($cfg->openvpn->$ref)) { foreach ($cfg->openvpn->$ref as $item) { if (isset($item->vpnid)) { $result[] = (string)$item->vpnid; } } } } foreach ($this->Instances->Instance->iterateItems() as $node_uuid => $node) { if ((string)$node->vpnid != '') { $result[$node_uuid] = (string)$node->vpnid; } } return $result; }
The VPNid sequence is used for device creation, in which case we can't use uuid's due to their size @return list of vpn id's used by legacy or mvc instances
usedVPNIds
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/OpenVPN/OpenVPN.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/OpenVPN/OpenVPN.php
BSD-2-Clause
public function getServer($vpnid) { foreach ($this->servers->server->iterateItems() as $uuid => $server) { if ((string)$server->vpnid == (string)$vpnid) { return $server; } } $server = $this->servers->server->add(); $server->vpnid = (string)$vpnid; return $server; }
get or create server to store defaults @param string $vpnid openvpn unique reference (number) @return mixed server object
getServer
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/OpenVPN/Export.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/OpenVPN/Export.php
BSD-2-Clause
private function valid_net($val) { return Util::isIpAddress($val) || Util::isSubnet($val); }
is valid network or ip address
valid_net
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/OpenVPN/Migrations/M1_0_0.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/OpenVPN/Migrations/M1_0_0.php
BSD-2-Clause
protected function actionPostLoadingEvent() { if (empty(self::$internalLegacyVPNids)) { self::$internalLegacyVPNids = $this->getParentModel()->usedVPNIds(); } }
fetch (legacy) vpn id's as these are reserved
actionPostLoadingEvent
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/OpenVPN/FieldTypes/VPNIdField.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/OpenVPN/FieldTypes/VPNIdField.php
BSD-2-Clause
public function setNodes($data) { $ifconfig = json_decode((new Backend())->configdRun('interface list ifconfig'), true) ?? []; foreach ($this->subnets->subnet4->iterateItems() as $subnet) { if (!empty((string)$subnet->option_data_autocollect)) { // find first possible candidate to use as a gateway. $host_ip = null; foreach ($ifconfig as $if => $details) { foreach ($details['ipv4'] as $net) { if (Util::isIPInCIDR($net['ipaddr'], (string)$subnet->subnet)) { $host_ip = $net['ipaddr']; break 2; } } } if (!empty($host_ip)) { $subnet->option_data->routers = $host_ip; $subnet->option_data->domain_name_servers = $host_ip; $subnet->option_data->ntp_servers = $host_ip; } } } return parent::setNodes($data); }
Before persisting data into the model, update option_data fields for selected subnets. setNodes() is used in most cases (at least from our base controller), which should make this a relatvily save entrypoint to enforce some data.
setNodes
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Kea/KeaDhcpv4.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Kea/KeaDhcpv4.php
BSD-2-Clause
public function fwrulesEnabled() { return (string)$this->general->enabled == '1' && (string)$this->general->fwrules == '1' && !empty((string)(string)$this->general->interfaces); }
should filter rules be enabled @return bool
fwrulesEnabled
php
opnsense/core
src/opnsense/mvc/app/models/OPNsense/Kea/KeaDhcpv4.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/models/OPNsense/Kea/KeaDhcpv4.php
BSD-2-Clause
protected function convertReplyTo(&$rule) { if (!empty($rule['reply-to'])) { // reply-to gateway set, when found map to reply attribute, otherwise skip keyword if (!empty($this->gatewayMapping[$rule['reply-to']])) { $if = $this->gatewayMapping[$rule['reply-to']]['interface']; if (!empty($this->gatewayMapping[$rule['reply-to']]['gateway'])) { $gw = $this->gatewayMapping[$rule['reply-to']]['gateway']; $rule['reply'] = "reply-to ( {$if} {$gw} ) "; } else { $rule['reply'] = "reply-to {$if} "; } } } elseif (!isset($rule['disablereplyto']) && ($rule['direction'] ?? "") != 'any') { $proto = $rule['ipprotocol']; if (!empty($this->interfaceMapping[$rule['interface']]['if']) && empty($rule['gateway'])) { $if = $this->interfaceMapping[$rule['interface']]['if']; switch ($proto) { case "inet6": if ( !empty($this->interfaceMapping[$rule['interface']]['gatewayv6']) && Util::isIpAddress($this->interfaceMapping[$rule['interface']]['gatewayv6']) ) { $gw = $this->interfaceMapping[$rule['interface']]['gatewayv6']; $rule['reply'] = "reply-to ( {$if} {$gw} ) "; } break; default: if ( !empty($this->interfaceMapping[$rule['interface']]['gateway']) && Util::isIpAddress($this->interfaceMapping[$rule['interface']]['gateway']) ) { $gw = $this->interfaceMapping[$rule['interface']]['gateway']; $rule['reply'] = "reply-to ( {$if} {$gw} ) "; } break; } } } }
add reply-to tag when applicable @param array $rule rule
convertReplyTo
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/FilterRule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/FilterRule.php
BSD-2-Clause
private function reflectionInterfaces($interface) { $result = []; foreach ($this->interfaceMapping as $intfk => $intf) { if ( empty($intf['gateway']) && empty($intf['gatewayv6']) && $interface != $intfk && !in_array($intf['if'], $result) && $intfk != 'loopback' ) { $result[] = $intfk; } } return $result; }
search interfaces without a gateway other then the one provided @param $interface @return array list of interfaces
reflectionInterfaces
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/NptRule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/NptRule.php
BSD-2-Clause
private function parseNptRules() { foreach ($this->reader('npt') as $rule) { if (empty($rule['to'])) { /* auto-detect expands from dynamic interface address on interface */ $toif = !empty($rule['trackif']) ? $rule['trackif'] : $rule['interface']; /* can be empty on /128 due to legacy pconfig_to_address() behaviour */ $frommask = explode('/', $rule['from'])[1] ?? '128'; $rule['to'] = $this->parseInterface($toif, '(', ':0)/' . $frommask); } yield $rule; } }
preprocess internal rule data to detail level of actual ruleset handles shortcuts, like inet46 and multiple interfaces @return array
parseNptRules
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/NptRule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/NptRule.php
BSD-2-Clause
public static function isIpAddress($address) { return !empty(filter_var($address, FILTER_VALIDATE_IP)); }
is provided address an ip address. @param string $address network address @return boolean
isIpAddress
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isLinkLocal($address) { return !!preg_match('/^fe[89ab][0-9a-f]:/i', $address); }
is provided address an link-locak IPv6 address. @param string $address network address @return boolean
isLinkLocal
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isMACAddress($address) { return !empty(filter_var($address, FILTER_VALIDATE_MAC)); }
is provided address a mac address. @param string $address network address @return boolean
isMACAddress
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isSubnetStrict($network) { if (self::isSubnet($network)) { list($net, $mask) = explode('/', $network); $ip_net = inet_pton($net); $bits = (strpos($net, ":") !== false && $mask <= 128) ? 128 : 32; $ip_mask = ""; $significant_bits = $mask; for ($i = 0; $i < $bits / 8; $i++) { if ($significant_bits >= 8) { $ip_mask .= chr(0xFF); $significant_bits -= 8; } else { $ip_mask .= chr(~(0xFF >> $significant_bits)); $significant_bits = 0; } } return $ip_net == ($ip_net & $ip_mask); } return false; }
is provided network strict (host bits not set) @param string $network network @return boolean
isSubnetStrict
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isWildcard($network) { $tmp = explode('/', $network); if (count($tmp) == 2) { if (self::isIpAddress($tmp[0]) && self::isIpAddress($tmp[1])) { if (strpos($tmp[0], ':') !== false && strpos($tmp[1], ':') !== false) { return true; } elseif (strpos($tmp[0], ':') === false && strpos($tmp[1], ':') === false) { return true; } } } return false; }
is provided network a valid wildcard (https://en.wikipedia.org/wiki/Wildcard_mask) @param string $network network @return boolean
isWildcard
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function attachAliasObject($alias) { self::$aliasObject = $alias; if ($alias != null) { $alias->flushCache(); } }
use provided alias object instead of creating one. When modifying multiple aliases referencing each other we need to use the same object for validations. @param Alias $alias object to link
attachAliasObject
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isAlias($name, $valid = false) { if (self::$aliasObject == null) { // Cache the alias object to avoid object creation overhead. self::$aliasObject = new Alias(); self::$aliasObject->flushCache(); } if (!empty($name)) { $alias = self::$aliasObject->getByName($name); if ($alias != null) { if ($valid) { // check validity for port type aliases if (preg_match("/port/i", (string)$alias->type) && empty((string)$alias->content)) { return false; } } return true; } } return false; }
check if name exists in alias config section @param string $name name @param boolean $valid check if the alias can safely be used @return boolean @throws \OPNsense\Base\ModelException
isAlias
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function getservbyname($service) { if (empty(self::$servbynames)) { foreach (explode("\n", file_get_contents('/etc/services')) as $line) { if (strlen($line) > 1 && $line[0] != '#') { foreach (preg_split('/\s+/', $line) as $idx => $tmp) { if ($tmp[0] == '#') { break; } elseif ($idx != 1) { self::$servbynames[$tmp] = true; } } } } } return isset(self::$servbynames[$service]); }
cached version of getservbyname() existence check @param string $service service name @return boolean
getservbyname
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function isDomain($domain) { $pattern = '/^(?:(?:[a-z\pL0-9]|[a-z\pL0-9][a-z\pL0-9\-]*[a-z\pL0-9])\.)*(?:[a-z\pL0-9]|[a-z\pL0-9][a-z\pL0-9\-]*[a-z\pL0-9])$/iu'; $parts = explode(".", $domain); if (ctype_digit($parts[0]) && ctype_digit($parts[count($parts) - 1])) { // according to rfc1123 2.1 // a valid host name can never have the dotted-decimal form #.#.#.#, since at least the highest-level // component label will be alphabetic. return false; } elseif (preg_match($pattern, $domain)) { return true; } return false; }
Check if provided string is a valid domain name @param string $domain @return false|int
isDomain
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function CIDRToMask($bits) { return long2ip(0xFFFFFFFF << (32 - $bits)); }
convert ipv4 cidr to netmask e.g. 24 --> 255.255.255.0 @param int $bits ipv4 bits @return string netmask
CIDRToMask
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
public static function cidrToRange($cidr) { if (!self::isSubnet($cidr)) { return false; } list ($ipaddr, $bits) = explode('/', $cidr); $inet_ip = inet_pton($ipaddr); if (str_contains($ipaddr, ':')) { /* IPv6 */ $size = 128 - (int)$bits; $mask = [ 1 => (0xffffffff << max($size - 96, 0)) & 0xffffffff, 2 => (0xffffffff << max($size - 64, 0)) & 0xffffffff, 3 => (0xffffffff << max($size - 32, 0)) & 0xffffffff, 4 => (0xffffffff << $size) & 0xffffffff, ]; $netmask_parts = []; for ($pos = 1; $pos <= 4; $pos += 1) { $netmask_parts = array_merge($netmask_parts, str_split(sprintf('%08x', $mask[$pos]), 4)); } $inet_mask = inet_pton(implode(':', $netmask_parts)); } else { /* IPv4 */ $size = 32 - (int)$bits; $inet_mask = inet_pton(long2ip((0xffffffff << $size) & 0xffffffff)); } $inet_start = $inet_ip & $inet_mask; $inet_end = $inet_ip | ~$inet_mask; return [inet_ntop($inet_start), inet_ntop($inet_end)]; }
convert cidr to array containing a start and end address @param array $cidr ipv4/6 cidr range definition @return array|bool address range or false when not a valid cidr
cidrToRange
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Util.php
BSD-2-Clause
protected function parseBool($value, $valueTrue, $valueFalse = "") { if (!empty($value)) { return !empty($valueTrue) ? $valueTrue . " " : ""; } else { return !empty($valueFalse) ? $valueFalse . " " : ""; } }
parse boolean, return text from $valueTrue / $valueFalse @param string $value field value @param $valueTrue @param string $valueFalse @return string
parseBool
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
BSD-2-Clause
protected function legacyMoveAddressFields(&$rule) { $fields = []; $fields['source'] = 'from'; $fields['destination'] = 'to'; $interfaces = $this->interfaceMapping; foreach ($fields as $tag => $target) { if (!empty($rule[$tag])) { if (isset($rule[$tag]['any'])) { $rule[$target] = 'any'; } elseif (!empty($rule[$tag]['network'])) { $rule[$target] = $rule[$tag]['network']; } elseif (!empty($rule[$tag]['address'])) { $rule[$target] = $rule[$tag]['address']; } $rule[$target . '_not'] = isset($rule[$tag]['not']); /* to be used in mapAddressInfo() */ if ( isset($rule['protocol']) && in_array(strtolower($rule['protocol']), ["tcp", "udp", "tcp/udp"]) && !empty($rule[$tag]['port']) ) { $rule[$target . "_port"] = $rule[$tag]['port']; } if (!isset($rule[$target])) { // couldn't convert address, disable rule // dump all tag contents in target (from/to) for reference $rule['disabled'] = true; $this->log("Unable to convert address, see {$target} for details"); $rule[$target] = json_encode($rule[$tag]); } } } }
convert source/destination structures as used by the gui into simple flat structures. @param array $rule rule
legacyMoveAddressFields
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
BSD-2-Clause
protected function parseInterface($value, $prefix = "on ", $suffix = "") { if (!empty($this->rule['interfacenot'])) { $prefix = "{$prefix} ! "; } if (empty($value)) { return ""; } elseif (empty($this->interfaceMapping[$value]['if'])) { return "{$prefix}##{$value}##{$suffix} "; } else { return "{$prefix}" . $this->interfaceMapping[$value]['if'] . "{$suffix} "; } }
parse interface (name to interface) @param string|array $value field value @param string $prefix prefix interface tag @param string $suffix suffix interface tag @return string
parseInterface
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
BSD-2-Clause
protected function isIpV4($rule) { if (!empty($rule['ipprotocol'])) { return $rule['ipprotocol'] == 'inet'; } else { // check fields which are known to contain addresses and search for an ipv4 address foreach (array('from', 'to', 'external', 'target') as $fieldname) { if ( (Util::isIpAddress($rule[$fieldname]) || Util::isSubnet($rule[$fieldname])) && strpos($rule[$fieldname], ":") === false ) { return true; } } return false; } }
Validate if the provided rule looks like an ipv4 address. This method isn't bulletproof (if only aliases are used and we don't know the protocol, this might fail to tell the truth) @param array $rule parsed rule info @return bool
isIpV4
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Rule.php
BSD-2-Clause
public function setGateways(\OPNsense\Routing\Gateways $gateways) { $this->gateways = $gateways; foreach ($gateways->gatewaysIndexedByName(false, true) as $key => $gw) { if (!empty($gw['gateway_interface']) || Util::isIpAddress($gw['gateway'] ?? null)) { $this->gatewayMapping[$key] = [ "interface" => $gw['if'], "proto" => $gw['ipprotocol'], "type" => "gateway" ]; if (!empty($gw['gateway']) && Util::isIpAddress($gw['gateway'])) { $this->gatewayMapping[$key]['logic'] = "route-to ( {$gw['if']} {$gw['gateway']} )"; $this->gatewayMapping[$key]['gateway'] = $gw['gateway']; } else { $this->gatewayMapping[$key]['logic'] = "route-to {$gw['if']}"; } } } }
set defined gateways (route-to) @param \OPNsense\Routing\Gateways $gateways object
setGateways
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function setGatewayGroups($groups) { if (is_array($groups)) { foreach ($groups as $key => $gwgr) { $routeto = []; $proto = 'inet'; foreach ($gwgr as $gw) { if (Util::isIpAddress($gw['gwip']) && !empty($gw['int'])) { $gwweight = empty($gw['weight']) ? 1 : $gw['weight']; $routeto[] = str_repeat("( {$gw['int']} {$gw['gwip']} )", $gwweight); if (strstr($gw['gwip'], ':')) { $proto = 'inet6'; } } } if (count($routeto) > 0) { $routetologic = "route-to {" . implode(' ', $routeto) . "}"; if (!empty($gwgr[0]['poolopts'])) { // Since Gateways->getGroups() returns detail items, we have no other choice than // to copy top level attributes into the details if they matter (poolopts) $routetologic .= " {$gwgr[0]['poolopts']} "; } elseif (count($routeto) > 1) { $routetologic .= " round-robin "; if (!empty(Config::getInstance()->object()->system->lb_use_sticky)) { $routetologic .= " sticky-address "; } } $this->gatewayMapping[$key] = array("logic" => $routetologic, "proto" => $proto, "type" => "group"); } } } }
set defined gateway groups (route-to) @param array $groups named array
setGatewayGroups
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function anchorToText($types = "fw", $placement = "tail") { $result = ""; foreach (explode(',', $types) as $type) { foreach ($this->anchors as $anchorKey => $anchor) { if (strpos($anchorKey, "{$type}.{$placement}") === 0) { $result .= ($type == "fw" || $type == "ether") ? "" : "{$type}-"; $prefix = $type == "ether" ? "ether " : ""; $result .= "{$prefix}anchor \"{$anchor['name']}\""; if ($anchor['quick']) { $result .= " quick"; } if (!empty($anchor['ifs'])) { $ifs = array_filter(array_map(function ($if) { return $this->interfaceMapping[$if]['if'] ?? null; }, explode(',', $anchor['ifs']))); if (!empty($ifs)) { $result .= " on {" . implode(', ', $ifs) . "}"; } } $result .= "\n"; } } } return $result; }
fetch anchors as text (pf ruleset part) @param string $types anchor types (fw for filter, other options are nat,rdr,binat. comma-separated) @param string $placement placement head,tail @return string
anchorToText
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function registerDNatRule($prio, $conf) { if (!empty($this->systemDefaults['nat'])) { $conf = array_merge($this->systemDefaults['nat'], $conf); } $rule = new DNatRule($this->interfaceMapping, $conf); if (empty($this->natRules[$prio])) { $this->natRules[$prio] = []; } $this->natRules[$prio][] = $rule; }
register a destination Nat rule @param int $prio priority @param array $conf configuration
registerDNatRule
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function iterateFilterRules() { ksort($this->filterRules); /* sort rules by priority */ foreach ($this->filterRules as $prio => $ruleset) { foreach ($ruleset as $rule) { yield $prio => $rule; } } }
iterate through registered rules @return Iterator
iterateFilterRules
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function tablesToText() { $result = ""; foreach ($this->tables as $table) { $result .= "table <{$table['name']}>"; if ($table['persist']) { $result .= " persist"; } if (!empty($table['file'])) { $result .= " file \"{$table['file']}\""; } $result .= "\n"; } return $result; }
fetch tables as text (pf tables part) @return string
tablesToText
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Firewall/Plugin.php
BSD-2-Clause
public function base64Safe($len = 16) { return rtrim(strtr(base64_encode(random_bytes($len)), "+/", "-_"), '='); }
Generate a random URL-safe base64 string. Usable base64 characters according to https://www.ietf.org/rfc/rfc3548.txt
base64Safe
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Mvc/Security.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Mvc/Security.php
BSD-2-Clause
public function getActionName() { return substr($this->action, 0, strlen($this->action) - 6); }
XXX: rename to getMethodName when phalcon is removed and return plain $this->action, next cleanup ApiControllerBase. @return string action name
getActionName
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Mvc/Dispatcher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Mvc/Dispatcher.php
BSD-2-Clause
protected function init() { }
by default there must be an inherited init method so an extended class could simply specify its own init
init
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Singleton.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Singleton.php
BSD-2-Clause
public function isValid() { return $this->statusIsValid; }
return last known status of this configuration (valid or not) @return bool return (last known) status of this configuration
isValid
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
private function isArraySequential(&$arrayData) { return is_array($arrayData) && ctype_digit(implode('', array_keys($arrayData))); }
check if array is a sequential type. @param &array $arrayData array structure to check @return bool
isArraySequential
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function toArrayFromFile($filename, $forceList = null) { $fp = fopen($filename, "r"); $xml = $this->loadFromStream($fp); fclose($fp); return $this->toArray($forceList, $xml); }
convert an arbitrary config xml file to an array @param $filename config xml filename to parse @param null $forceList items to treat as list @return array interpretation of config file @throws ConfigException when config could not be parsed
toArrayFromFile
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
private function checkvalid() { if (!$this->statusIsValid) { throw new ConfigException('no valid config loaded'); } }
check if there's a valid config loaded, throws an error if config isn't valid. @throws ConfigException when config could not be parsed
checkvalid
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function xpath($query) { $this->checkvalid(); $configxml = dom_import_simplexml($this->simplexml); $dom = new \DOMDocument('1.0'); $dom_sxe = $dom->importNode($configxml, true); $dom->appendChild($dom_sxe); $xpath = new \DOMXPath($dom); return $xpath->query($query); }
Execute a xpath expression on config.xml (full DOM implementation) @param string $query xpath expression @return \DOMNodeList nodes @throws ConfigException when config could not be parsed
xpath
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function object() { $this->checkvalid(); return $this->simplexml; }
object representation of xml document via simplexml, references the same underlying model @return SimpleXML configuration object @throws ConfigException when config could not be parsed
object
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
protected function init() { $this->statusIsLocked = false; $this->config_file = (new AppConfig())->globals->config_path . "config.xml"; try { $this->load(); } catch (\Exception $e) { $this->simplexml = null; // there was an issue with loading the config, try to restore the last backup $backups = $this->getBackups(); $logger = new Syslog('audit', null, LOG_LOCAL5); if (count($backups) > 0) { // load last backup $logger->error(gettext('No valid config.xml found, attempting last known config restore.')); foreach ($backups as $backup) { try { $this->restoreBackup($backup); $logger->error("restored " . $backup); return; } catch (ConfigException $e) { $logger->error("failed restoring " . $backup); } } } // in case there are no backups, restore defaults. $logger->error(gettext('No valid config.xml found, attempting to restore factory config.')); $this->restoreBackup('/usr/local/etc/config.xml'); } }
init new config object, try to load current configuration (executed via Singleton)
init
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function forceReload() { if ($this->config_file_handle !== null) { fclose($this->config_file_handle); $this->config_file_handle = null; } $this->init(); }
force a re-init of the object and reload the object
forceReload
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
private function auditLogChange($backup_filename, $revision) { openlog("audit", LOG_ODELAY, LOG_AUTH); syslog(LOG_NOTICE, sprintf( "user %s%s changed configuration to %s in %s %s", $revision['username'], !empty($revision['impersonated_by']) ? sprintf(" (%s)", $revision['impersonated_by']) : '', $backup_filename, !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME'], $revision['description'] ?? '' )); }
send config change to audit log including the context we currently know of. @param string $backup_filename new backup filename @param array $revision revision adata used
auditLogChange
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
private function overwrite($filename) { $fhandle = fopen($this->config_file, "a+e"); if (flock($fhandle, LOCK_EX)) { fseek($fhandle, 0); chmod($this->config_file, 0640); ftruncate($fhandle, 0); fwrite($fhandle, file_get_contents($filename)); fclose($fhandle); } }
Overwrite current config with contents of new file @param $filename
overwrite
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function restoreBackup($filename) { if ($this->isValid()) { // if current config is valid, $simplexml = $this->simplexml; $config_file_handle = $this->config_file_handle; try { // try to restore config $this->overwrite($filename); $this->load(); return true; } catch (ConfigException $e) { // copy / load failed, restore previous version $this->simplexml = $simplexml; $this->config_file_handle = $config_file_handle; $this->statusIsValid = true; $this->save(null, true); return false; } } else { // we don't have a valid config loaded, just copy and load the requested one $this->overwrite($filename); $this->load(); return true; } }
restore and load backup config @param $filename @return bool restored, valid config loaded @throws ConfigException no config loaded
restoreBackup
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public function getBackupFilename($revision) { $tmp = preg_replace("/[^0-9.]/", "", $revision); $bckfilename = dirname($this->config_file) . "/backup/config-{$tmp}.xml"; if (is_file($bckfilename)) { return $bckfilename; } else { return false; } }
return backup file path if revision exists @param $revision revision timestamp (e.g. 1583766095.9337) @return bool|string filename when available or false when not found
getBackupFilename
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Config.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Config.php
BSD-2-Clause
public static function file_put_contents(string $filename, mixed $data, int $permissions = 0640, int $flags = 0) { @touch($filename); @chmod($filename, $permissions); return file_put_contents($filename, $data, $flags); }
file_put_contents wrapper which sets permissions before writing data. @param string $filename Path to the file where to write the data. @param mixed $data The data to write. @param int $permissions permissions to set, see chmod for usage @param int $flags flags to pass to file_put_contents() @return int|false
file_put_contents
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/File.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/File.php
BSD-2-Clause
public function getLastRestart() { if (file_exists($this->configdSocket)) { return filemtime($this->configdSocket); } else { return 0; } }
check configd socket for last restart, return 0 socket not present. @return int last restart timestamp
getLastRestart
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Core/Backend.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Core/Backend.php
BSD-2-Clause
public function _authenticate($username, $password) { // reset auth properties $this->lastAuthProperties = []; // search local user in database $userinfo = (new User())->getApiKeySecret($username); if ($userinfo != null) { if (!empty($userinfo['disabled'])) { // disabled user return false; } if ( !empty($userinfo['expires']) && strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($userinfo['expires']))) ) { // expired user return false; } if (password_verify($password, $userinfo['secret'])) { // password ok, return successfully authentication $this->lastAuthProperties['username'] = $userinfo['name']; return true; } } return false; }
authenticate user against local database (in config.xml) @param string $username username to authenticate @param string $password user password @return bool authentication status
_authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/API.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/API.php
BSD-2-Clause
public function createKey($username) { Config::getInstance()->lock(); $mdl = new \OPNsense\Auth\User(); $user = $mdl->getUserByName($username); if ($user) { $tmp = $user->apikeys->add(); if (!empty($tmp)) { $mdl->serializeToConfig(false, true); Config::getInstance()->save(); return $tmp; } } Config::getInstance()->unlock(); return false; }
generate a new api key for an existing user, backwards compatibility stub @param $username username @return array|null apikey/secret pair
createKey
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/API.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/API.php
BSD-2-Clause
public function dropKey($username, $apikey) { Config::getInstance()->lock(); $mdl = new \OPNsense\Auth\User(); $user = $mdl->getUserByName($username); if ($user) { if ($user->apikeys->del($apikey)) { $mdl->serializeToConfig(false, true); Config::getInstance()->save(); return true; } } Config::getInstance()->unlock(); return false; }
remove user api key, backwards compatibility stub @param string $username username @param string $apikey api key @return bool key found
dropKey
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/API.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/API.php
BSD-2-Clause
public function getDescription() { return gettext("LDAP + Timebased One Time Password"); }
user friendly description of this authenticator @return string
getDescription
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAPTOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAPTOTP.php
BSD-2-Clause
public function getConfigurationOptions() { $options = array_merge($this->getTOTPConfigurationOptions(), parent::getConfigurationOptions()); return $options; }
retrieve configuration options @return array
getConfigurationOptions
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAPTOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAPTOTP.php
BSD-2-Clause
private function addSearchAttribute($attrName) { if (!array_key_exists($attrName, $this->ldapSearchAttr)) { $this->ldapSearchAttr[] = $attrName; } }
add additional query result attributes @param $attrName string attribute to append to result list
addSearchAttribute
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
BSD-2-Clause
private function logLdapError($message) { $error_string = ""; if ($this->ldapHandle !== false) { ldap_get_option($this->ldapHandle, LDAP_OPT_ERROR_STRING, $error_string); $error_string = str_replace(array("\n","\r","\t"), ' ', $error_string); syslog(LOG_ERR, sprintf($message . " [%s; %s]", $error_string, ldap_error($this->ldapHandle))); if (!empty($error_string)) { $this->lastAuthErrors['error'] = $error_string; } $this->lastAuthErrors['ldap_error'] = ldap_error($this->ldapHandle); } else { syslog(LOG_ERR, $message); } }
log ldap errors, append ldap error output when available @param string message
logLdapError
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
BSD-2-Clause
public function __destruct() { $this->closeLDAPHandle(); }
close ldap handle on destruction
__destruct
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
BSD-2-Clause
public function searchUsers($username, $userNameAttribute, $extendedQuery = null) { if ($this->ldapHandle !== false) { // on Active Directory sAMAccountName is returned as samaccountname $userNameAttribute = strtolower($userNameAttribute); // add $userNameAttribute to search results $this->addSearchAttribute($userNameAttribute); $result = array(); if (empty($extendedQuery)) { $searchResults = $this->search("({$userNameAttribute}={$username})"); } else { // add additional search phrases $searchResults = $this->search("(&({$userNameAttribute}={$username})({$extendedQuery}))"); } if ($searchResults !== false) { for ($i = 0; $i < $searchResults["count"]; $i++) { // fetch distinguished name and most likely username (try the search field first) foreach (array($userNameAttribute, "name") as $ldapAttr) { if (isset($searchResults[$i][$ldapAttr]) && $searchResults[$i][$ldapAttr]['count'] > 0) { $user = array( 'name' => $searchResults[$i][$ldapAttr][0], 'dn' => $searchResults[$i]['dn'] ); if (!empty($searchResults[$i]['displayname'][0])) { $user['fullname'] = $searchResults[$i]['displayname'][0]; } elseif (!empty($searchResults[$i]['cn'][0])) { $user['fullname'] = $searchResults[$i]['cn'][0]; } elseif (!empty($searchResults[$i]['name'][0])) { $user['fullname'] = $searchResults[$i]['name'][0]; } else { $user['fullname'] = ''; } if (!empty($searchResults[$i]['mail'][0])) { $user['email'] = $searchResults[$i]['mail'][0]; } else { $user['email'] = ''; } $result[] = $user; break; } } } return $result; } } return false; }
search user by name or expression @param string $username username(s) to search @param string $userNameAttribute ldap attribute to use for the search @param string|null $extendedQuery additional search criteria (narrow down search) @return array|bool
searchUsers
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
BSD-2-Clause
public function authenticate($username, $password) { return $this->_authenticate($username, $password); }
authenticate user against ldap server without Base's timer @param string $username username to authenticate @param string $password user password @return bool authentication status
authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/LDAP.php
BSD-2-Clause
public function checkPolicy($username, $old_password, $new_password) { return []; }
check if password meets policy constraints, needs implementation if it applies. @param string $username username to check @param string $old_password current password @param string $new_password password to check @return array of unmet policy constraints
checkPolicy
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
public function shouldChangePassword($username, $password = null) { return false; }
check if the user should change his or her password, needs implementation if it applies. @param string $username username to check @param string $password password to check @return boolean
shouldChangePassword
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
protected function getUser($username) { // search local user in database $configObj = Config::getInstance()->object(); $userObject = null; foreach ($configObj->system->children() as $key => $value) { if ($key == 'user' && !empty($value->name)) { // depending on caseInSensitiveUsernames setting match exact or case-insensitive if ( (string)$value->name == $username || ($this->caseInSensitiveUsernames && strtolower((string)$value->name) == strtolower($username)) ) { // user found, stop search $userObject = $value; break; } } } return $userObject; }
find user settings in local database @param string $username username to find @return SimpleXMLElement|null user settings (xml section)
getUser
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
public function getUserName($username) { if ($this->caseInSensitiveUsernames) { $user = $this->getUser($username); if ($user) { return (string)$user->name; } } else { return $username; } }
return actual username. This is more or less a temporary function to support case insensitive names in sessions @param string $username username @return string
getUserName
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
protected function _authenticate($username, $password) { return false; }
authenticate user, implementation when using this base classes authenticate() @param string $username username to authenticate @param string $password user password @return bool
_authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
public function authenticate($username, $password) { $tstart = microtime(true); $expected_time = 2000000; /* failed login, aim at 2 seconds total time */ $result = $this->_authenticate($username, $password); $timeleft = $expected_time - ((microtime(true) - $tstart) * 1000000); if (!$result && $timeleft > 0) { usleep((int)$timeleft); } return $result; }
authenticate user, when failed, make sure we always spend the same time for the sequence. This also adds a penalty for failed attempts. @param string $username username to authenticate @param string $password user password @return bool
authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Base.php
BSD-2-Clause
private function userNameExists($username) { $stmt = $this->dbHandle->prepare('select count(*) cnt from vouchers where username = :username'); $stmt->bindParam(':username', $username); $result = $stmt->execute(); $row = $result->fetchArray(); if ($row['cnt'] == 0) { return false; } else { return true; } }
check if username does already exist @param string $username username @return bool
userNameExists
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
BSD-2-Clause
public function generateVouchers($vouchergroup, $count, $validity, $expirytime, $starttime = null) { $response = array(); if ($this->dbHandle != null) { $characterMap = '!#$%()*+,-./0123456789:;=?@ABCDEFGHIJKLMNPQRSTUVWXYZ[\]_abcdefghijkmnopqrstuvwxyz'; if ($this->simplePasswords) { // a map of easy to read characters $characterMap = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'; } // generate new vouchers $vouchersGenerated = 0; $expirytime = $expirytime == 0 ? 0 : $expirytime + time(); while ($vouchersGenerated < $count) { $generatedUsername = ''; for ($j = 0; $j < max($this->usernameLength, 1); $j++) { $generatedUsername .= $characterMap[random_int(0, strlen($characterMap) - 1)]; } $generatedPassword = ''; if (!empty($this->passwordLength)) { for ($j = 0; $j < $this->passwordLength; $j++) { $generatedPassword .= $characterMap[random_int(0, strlen($characterMap) - 1)]; } } if (!$this->userNameExists($generatedUsername)) { $vouchersGenerated++; // save user, hash password first $generatedPasswordHash = crypt($generatedPassword, '$6$'); $stmt = $this->dbHandle->prepare(' insert into vouchers(username, password, vouchergroup, validity, expirytime, starttime) values (:username, :password, :vouchergroup, :validity, :expirytime, :starttime) '); $stmt->bindParam(':username', $generatedUsername); $stmt->bindParam(':password', $generatedPasswordHash); $stmt->bindParam(':vouchergroup', $vouchergroup); $stmt->bindParam(':validity', $validity); $stmt->bindParam(':expirytime', $expirytime); $stmt->bindParam(':starttime', $starttime); $stmt->execute(); $row = array('username' => $generatedUsername, 'password' => $generatedPassword, 'vouchergroup' => $vouchergroup, 'validity' => $validity, 'expirytime' => $expirytime, 'starttime' => $starttime ); $response[] = $row; } } } return $response; }
generate new vouchers and store in voucher database @param string $vouchergroup voucher groupname @param int $count number of vouchers to generate @param int $validity time (in seconds) @param int $starttime valid from @param int $expirytime valid until ('0' means no expiry time) @return array list of generated vouchers
generateVouchers
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
BSD-2-Clause
public function dropVoucherGroup($vouchergroup) { $stmt = $this->dbHandle->prepare(' delete from vouchers where vouchergroup = :vouchergroup '); $stmt->bindParam(':vouchergroup', $vouchergroup); $stmt->execute(); }
drop all vouchers from voucher a voucher group @param string $vouchergroup group name
dropVoucherGroup
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
BSD-2-Clause
public function dropExpired($vouchergroup) { $stmt = $this->dbHandle->prepare(' delete from vouchers where vouchergroup = :vouchergroup and ( (starttime is not null and starttime + validity < :endtime) or (expirytime > 0 and expirytime < :endtime) )'); $stmt->bindParam(':vouchergroup', $vouchergroup); $endtime = time(); $stmt->bindParam(':endtime', $endtime, SQLITE3_INTEGER); $stmt->execute(); return $this->dbHandle->changes(); }
drop expired vouchers in group @param $vouchergroup voucher group name @return int number of deleted vouchers
dropExpired
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
BSD-2-Clause
protected function _authenticate($username, $password) { $stmt = $this->dbHandle->prepare(' select username, password, validity, expirytime, starttime from vouchers where username = :username '); $stmt->bindParam(':username', $username); $result = $stmt->execute(); $row = $result->fetchArray(); if ($row != null) { if (password_verify($password, (string)$row['password'])) { // correct password, check validity if ($row['starttime'] == null) { // initial login, set starttime for counter $row['starttime'] = time(); $this->setStartTime($username, $row['starttime']); } $is_never_expire = $row['expirytime'] === 0; $is_not_expired = $row['expirytime'] > 0 && $row['expirytime'] > time(); $is_valid = time() - $row['starttime'] < $row['validity']; if (($is_never_expire || $is_not_expired) && $is_valid) { $this->lastAuthProperties['session_timeout'] = min( // use PHP_INT_MAX as "never expire" for session_timeout $row['validity'] - (time() - $row['starttime']), $row['expirytime'] > 0 ? $row['expirytime'] - time() : PHP_INT_MAX ); return true; } } } return false; }
authenticate user against voucher database @param string $username username to authenticate @param string $password user password @return bool authentication status
_authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
BSD-2-Clause
public function shouldChangePassword($username, $password = null) { $configObj = Config::getInstance()->object(); if (!empty($configObj->system->webgui->enable_password_policy_constraints)) { $userObject = $this->getUser($username); if ($userObject != null) { if (!empty($configObj->system->webgui->password_policy_duration)) { $now = microtime(true); $pwdChangedAt = empty($userObject->pwd_changed_at) ? 0 : $userObject->pwd_changed_at; if (abs($now - $pwdChangedAt) / 60 / 60 / 24 >= $configObj->system->webgui->password_policy_duration) { return true; } } if (!empty($configObj->system->webgui->password_policy_compliance)) { /* if compliance is required make sure the user has a SHA-512 hash as password */ if (strpos((string)$userObject->password, '$6$') !== 0) { return true; } } } } if ($password != null) { /* not optimal, modify "old_password" to avoid equal check */ if (count($this->checkPolicy($username, '~' . $password, $password))) { return true; } } return false; }
check if the user should change his or her password, calculated by the time difference of the last pwd change and other criteria through checkPolicy() if password was given @param string $username username to check @param string $password password to check @return boolean
shouldChangePassword
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Local.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Local.php
BSD-2-Clause
protected function _authenticate($username, $password) { $userObject = $this->getUser($username); if ($userObject != null) { if (!empty((string)$userObject->disabled)) { // disabled user return false; } if ( !empty($userObject->expires) && strtotime("-1 day") > strtotime(date("m/d/Y", strtotime((string)$userObject->expires))) ) { // expired user return false; } if (password_verify($password, (string)$userObject->password)) { // password ok, return successfully authentication return true; } } return false; }
authenticate user against local database (in config.xml) @param string|SimpleXMLElement $username username (or xml object) to authenticate @param string $password user password @return bool authentication status
_authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Local.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Local.php
BSD-2-Clause
private function timesToCheck() { $result = array(); if ($this->graceperiod > $this->timeWindow) { $step = $this->timeWindow; $start = -1 * floor($this->graceperiod / $this->timeWindow) * $this->timeWindow; } else { $step = $this->graceperiod; $start = -1 * $this->graceperiod; } $now = time(); for ($count = $start; $count <= $this->graceperiod; $count += $step) { $result[] = $now + $count; if ($this->graceperiod == 0) { // special case, we expect the clocks to match 100%, so step and target are both 0 break; } } return $result; }
use graceperiod and timeWindow to calculate which moments in time we should check @return array timestamps
timesToCheck
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
BSD-2-Clause
protected function _authenticate($username, $password) { $userObject = $this->getUser($username); if ($userObject != null && !empty($userObject->otp_seed)) { if (strlen($password) > $this->otpLength) { // split otp token code and userpassword $pwLength = strlen($password) - $this->otpLength; $pwStart = $this->otpLength; $otpStart = 0; if ($this->passwordFirst) { $otpStart = $pwLength; $pwStart = 0; } $userPassword = substr($password, $pwStart, $pwLength); $code = substr($password, $otpStart, $this->otpLength); $otp_seed = \Base32\Base32::decode($userObject->otp_seed); if ($this->authTOTP($otp_seed, $code)) { // token valid, do parents auth return parent::_authenticate($username, $userPassword); } } } return false; }
authenticate user against otp key stored in local database @param string $username username to authenticate @param string $password user password @return bool authentication status
_authenticate
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
BSD-2-Clause
public function shouldChangePassword($username, $password = null) { if ($password != null && strlen($password) > $this->otpLength) { /* deconstruct password according to settings */ $pwLength = strlen($password) - $this->otpLength; $pwStart = $this->passwordFirst ? 0 : $this->otpLength; $password = substr($password, $pwStart, $pwLength); } return parent::shouldChangePassword($username, $password); }
check if the user should change his or her password @param string $username username to check @param string $password password to check @return boolean
shouldChangePassword
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
BSD-2-Clause
public function setTOTPProperties($config) { if (!empty($config['timeWindow'])) { $this->timeWindow = $config['timeWindow']; } if (!empty($config['otpLength'])) { $this->otpLength = $config['otpLength']; } if (!empty($config['graceperiod'])) { $this->graceperiod = $config['graceperiod']; } if (!empty($config['passwordFirst'])) { $this->passwordFirst = true; } }
set TOTP specific connector properties @param array $config connection properties
setTOTPProperties
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
BSD-2-Clause
private function getTOTPConfigurationOptions() { $fields = array(); $fields["otpLength"] = array(); $fields["otpLength"]["name"] = gettext("Token length"); $fields["otpLength"]["type"] = "dropdown"; $fields["otpLength"]["default"] = 6; $fields["otpLength"]["options"] = array(); $fields["otpLength"]["options"]["6"] = "6"; $fields["otpLength"]["options"]["8"] = "8"; $fields["otpLength"]["help"] = gettext("Token length to use"); $fields["otpLength"]["validate"] = function ($value) { if (!in_array($value, array(6,8))) { return array(gettext("Only token lengths of 6 or 8 characters are supported")); } else { return array(); } }; $fields["timeWindow"] = array(); $fields["timeWindow"]["name"] = gettext("Time window"); $fields["timeWindow"]["type"] = "text"; $fields["timeWindow"]["default"] = null; $fields["timeWindow"]["help"] = gettext("The time period in which the token will be valid," . " default is 30 seconds."); $fields["timeWindow"]["validate"] = function ($value) { if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) { return array(gettext("Please enter a valid time window in seconds")); } else { return array(); } }; $fields["graceperiod"] = array(); $fields["graceperiod"]["name"] = gettext("Grace period"); $fields["graceperiod"]["type"] = "text"; $fields["graceperiod"]["default"] = null; $fields["graceperiod"]["help"] = gettext("Time in seconds in which this server and the token may differ," . " default is 10 seconds. Set higher for a less secure easier match."); $fields["graceperiod"]["validate"] = function ($value) { if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) { return array(gettext("Please enter a valid grace period in seconds")); } else { return array(); } }; $fields["passwordFirst"] = array(); $fields["passwordFirst"]["name"] = gettext("Reverse token order"); $fields["passwordFirst"]["help"] = gettext("Checking this box requires the token after the password. Default requires the token before the password."); $fields["passwordFirst"]["type"] = "checkbox"; $fields["passwordFirst"]["validate"] = function ($value) { return array(); }; return $fields; }
retrieve TOTP specific configuration options @return array
getTOTPConfigurationOptions
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
BSD-2-Clause
public function preauth($config) { if (!empty($config['calling_station_id'])) { $this->callingStationId = $config['calling_station_id']; } return parent::preauth($config); }
set known per-session radius access request attributes @param array $config @return IAuthConnector
preauth
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/Radius.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/Radius.php
BSD-2-Clause
public function listConfigOptions() { $result = array(); foreach ($this->listConnectors() as $connector) { if ($connector['classHandle']->hasMethod('getDescription')) { $obj = $connector['classHandle']->newInstance(); $authItem = $connector; $authItem['description'] = $obj->getDescription(); if ($connector['classHandle']->hasMethod('getConfigurationOptions')) { $authItem['additionalFields'] = $obj->getConfigurationOptions(); } else { $authItem['additionalFields'] = array(); } $result[$obj->getType()] = $authItem; } } return $result; }
list configuration options for pluggable auth modules @return array
listConfigOptions
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/AuthenticationFactory.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/AuthenticationFactory.php
BSD-2-Clause
public function getLastAuthProperties() { if ($this->lastUsedAuth != null) { return $this->lastUsedAuth->getLastAuthProperties(); } else { return []; } }
return authenticator properties from last authentication @return array mixed named list of authentication properties
getLastAuthProperties
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Auth/AuthenticationFactory.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Auth/AuthenticationFactory.php
BSD-2-Clause
public function getProvider($className) { $providers = $this->listProviders(); if (!empty($providers[$className])) { return $providers[$className]; } else { return null; } }
return a specific provider by class name (without namespace) @param string $className without namespace @return mixed|null
getProvider
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Backup/BackupFactory.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Backup/BackupFactory.php
BSD-2-Clause
public static function signCert( $keylen_curve, $lifetime, $csr, $digest_alg, $caref, $x509_extensions = 'usr_cert', $extns = [] ) { $old_err_level = error_reporting(0); /* prevent openssl error from going to stderr/stdout */ $args = self::_createSSLOptions($keylen_curve, $digest_alg, $x509_extensions, $extns); $result = self::_signCert($csr, $caref, $lifetime, $args); self::_addSSLErrors($result); // remove tempfile (template) @unlink($args['filename']); error_reporting($old_err_level); return $result; }
Sign a certificate, when signed by a CA, make sure to serialize the config after doing so, it's the callers responsibility to update the serial number administration of the supplied CA. A call to \OPNsense\Core\Config::getInstance()->save(); would persist the new serial. @param string $keylen_curve rsa key length or elliptic curve name to use @param int $lifetime in number of days @param string $csr certificate signing request @param string $digest_alg digest algorithm @param string $caref key to certificate authority @param string $x509_extensions openssl section to use @param array $extns template fragments to replace in openssl.cnf @return array containing generated certificate or returned errors
signCert
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
BSD-2-Clause
public static function reIssueCert( $keylen_curve, $lifetime, $dn, $prv, $digest_alg, $caref, $x509_extensions = 'usr_cert', $extns = [] ) { $old_err_level = error_reporting(0); /* prevent openssl error from going to stderr/stdout */ $args = self::_createSSLOptions($keylen_curve, $digest_alg, $x509_extensions, $extns); $csr = openssl_csr_new($dn, $prv, $args); if ($csr !== false) { $result = self::_signCert($csr, $caref, $lifetime, $args); } else { $result = []; } self::_addSSLErrors($result); // remove tempfile (template) @unlink($args['filename']); error_reporting($old_err_level); return $result; }
re-issue a certificate, when signed by a CA, make sure to serialize the config after doing so, it's the callers responsibility to update the serial number administration of the supplied CA. A call to \OPNsense\Core\Config::getInstance()->save(); would persist the new serial. @param string $keylen_curve rsa key length or elliptic curve name to use @param int $lifetime in number of days @param array $dn subject to use @param string $prv private key @param string $digest_alg digest algorithm @param string $caref key to certificate authority @param string $x509_extensions openssl section to use @param array $extns template fragments to replace in openssl.cnf @return array containing generated certificate or returned errors
reIssueCert
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
BSD-2-Clause
public static function verify($cert) { return static::proc_open('/usr/local/bin/openssl verify', $cert); }
verify offered cert agains local trust store @param string $cert certificate @return array [stdout|stderr|exit_status]
verify
php
opnsense/core
src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/library/OPNsense/Trust/Store.php
BSD-2-Clause
function view_fetch_themed_filename($url, $theme) { $search_pattern = array( "/themes/{$theme}/build/", "/" ); foreach ($search_pattern as $pattern) { $filename = __DIR__ . "{$pattern}{$url}"; if (file_exists($filename)) { return str_replace("//", "/", "/ui{$pattern}{$url}"); } } return $url; // not found, return source }
search for a themed filename or return distribution standard @param string $url relative url @param array $theme theme name @return string
view_fetch_themed_filename
php
opnsense/core
src/opnsense/www/index.php
https://github.com/opnsense/core/blob/master/src/opnsense/www/index.php
BSD-2-Clause
function view_file_exists($filename) { return file_exists($filename); }
check if file exists, wrapper around file_exists() so services.php can define other implementation for local testing @param string $filename to check @return boolean
view_file_exists
php
opnsense/core
src/opnsense/www/index.php
https://github.com/opnsense/core/blob/master/src/opnsense/www/index.php
BSD-2-Clause
function view_cache_safe($url) { $info = stat('/usr/local/opnsense/www/index.php'); if (!empty($info['mtime'])) { return "{$url}?v=" . substr(md5($info['mtime']), 0, 16); } return $url; }
return appended version string with a hash for proper caching for currently installed version @param string $url to make cache-safe @return string
view_cache_safe
php
opnsense/core
src/opnsense/www/index.php
https://github.com/opnsense/core/blob/master/src/opnsense/www/index.php
BSD-2-Clause
function view_html_safe($text) { /* gettext() embedded in JavaScript can cause syntax errors */ return str_replace("\n", '&#10;', htmlspecialchars($text ?? '', ENT_QUOTES | ENT_HTML401)); }
return safe HTML encoded version of input string @param string $text to make HTML safe @return string
view_html_safe
php
opnsense/core
src/opnsense/www/index.php
https://github.com/opnsense/core/blob/master/src/opnsense/www/index.php
BSD-2-Clause
public function isStruct($array) { $expected = 0; foreach ($array as $key => $value) { if ((string)$key != (string)$expected) { return true; } $expected++; } return false; }
Checks whether or not the supplied array is a struct or not @param unknown_type $array @return boolean
isStruct
php
opnsense/core
contrib/IXR/IXR_Library.php
https://github.com/opnsense/core/blob/master/contrib/IXR/IXR_Library.php
BSD-2-Clause