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 hasTokenMatch($token)
{
return $token['content'] === 'ObjectManager';
} | Check if the content related to direct ObjectManager usage.
@param $token
@return bool | hasTokenMatch | php | magento-ecg/coding-standard | EcgM2/Sniffs/Performance/ObjectManagerUsageSniff.php | https://github.com/magento-ecg/coding-standard/blob/master/EcgM2/Sniffs/Performance/ObjectManagerUsageSniff.php | MIT |
function is_schedule_inuse($schedule)
{
global $config;
if ($schedule == '') {
return false;
}
/* loop through firewall rules looking for schedule in use */
if (isset($config['filter']['rule'])) {
foreach ($config['filter']['rule'] as $rule) {
if ($rule['sched'] == $schedule) {
return true;
}
}
}
return false;
} | *f* legacy/is_schedule_inuse
NAME
checks to see if a schedule is currently in use by a rule
INPUTS
RESULT
true or false
NOTES | is_schedule_inuse | php | opnsense/core | src/www/firewall_schedule_edit.php | https://github.com/opnsense/core/blob/master/src/www/firewall_schedule_edit.php | BSD-2-Clause |
function delete_id($id, &$array)
{
// Index to delete
$delete_index = NULL;
if (!isset($array)) {
return false;
}
// Search for the item in the array
foreach ($array as $key => $item){
// If this item is the one we want to delete
if(isset($item['associated-rule-id']) && $item['associated-rule-id']==$id ){
$delete_index = $key;
break;
}
}
// If we found the item, unset it
if( $delete_index!==NULL ){
unset($array[$delete_index]);
return true;
} else {
return false;
}
} | *f* itemid/delete_id (duplicate to remove itemid.inc)
NAME
delete_id - delete an item with ['id'] = $id from $array
INPUTS
$id - int: The ID to delete
$array - array to delete the item from
RESULT
boolean - true if item was found and deleted | delete_id | php | opnsense/core | src/www/firewall_nat.php | https://github.com/opnsense/core/blob/master/src/www/firewall_nat.php | BSD-2-Clause |
function http_basic_auth($http_auth_header)
{
$tags = explode(' ', $http_auth_header);
if (count($tags) >= 2) {
$userinfo= explode(':', base64_decode($tags[1]), 2);
if (count($userinfo) == 2) {
$username = authenticate_user($userinfo[0], $userinfo[1]);
if ($username !== false) {
$aclObj = new \OPNsense\Core\ACL();
return $aclObj->isPageAccessible($username, '/xmlrpc.php');
}
}
}
/* not authenticated */
return false;
} | do a basic authentication, uses $_SERVER['HTTP_AUTHORIZATION'] to validate user.
@param string $http_auth_header content of the Authorization HTTP header
@return bool | http_basic_auth | php | opnsense/core | src/www/xmlrpc.php | https://github.com/opnsense/core/blob/master/src/www/xmlrpc.php | BSD-2-Clause |
function idinfo_to_pconfig($prefix, $idinfo, & $pconfig)
{
switch ($idinfo['type']) {
case "address":
$pconfig[$prefix."id_type"] = $idinfo['type'];
$pconfig[$prefix."id_address"] = $idinfo['address'];
break;
case "network":
$pconfig[$prefix."id_type"] = $idinfo['type'];
$pconfig[$prefix."id_address"] = $idinfo['address'];
$pconfig[$prefix."id_netbits"] = $idinfo['netbits'];
break;
default:
$pconfig[$prefix."id_type"] = $idinfo['type'];
break;
}
} | reverse pconfig_to_idinfo from $idinfo array to $pconfig | idinfo_to_pconfig | php | opnsense/core | src/www/vpn_ipsec_phase2.php | https://github.com/opnsense/core/blob/master/src/www/vpn_ipsec_phase2.php | BSD-2-Clause |
function getIndexByUniqueId($uniqid)
{
global $config;
$p2index = null;
if ($uniqid != null) {
foreach ($config['ipsec']['phase2'] as $idx => $ph2) {
if ($ph2['uniqid'] == $uniqid) {
$p2index = $idx;
break;
}
}
}
return $p2index;
} | search phase 2 entries for record with uniqid | getIndexByUniqueId | php | opnsense/core | src/www/vpn_ipsec_phase2.php | https://github.com/opnsense/core/blob/master/src/www/vpn_ipsec_phase2.php | BSD-2-Clause |
function FormSetAdvancedOptions(&$item) {
foreach (array("max", "max-src-nodes", "max-src-conn", "max-src-states","nopfsync", "statetimeout", "adaptivestart"
, "adaptiveend", "max-src-conn-rate","max-src-conn-rates", "tag", "tagged", "allowopts", "reply-to","tcpflags1"
,"tcpflags2", "tos", "state-policy") as $fieldname) {
if (strlen($item[$fieldname]) > 0) {
return true;
}
}
// check these fields for anything being set except a blank string
foreach (array('set-prio', 'set-prio-low', 'prio') as $fieldname) {
if (isset($item[$fieldname]) && $item[$fieldname] !== '') {
return true;
}
}
if (!empty($item["statetype"]) && $item["statetype"] != 'keep state') {
return true;
}
return false;
} | check if advanced options are set on selected element | FormSetAdvancedOptions | php | opnsense/core | src/www/firewall_rules_edit.php | https://github.com/opnsense/core/blob/master/src/www/firewall_rules_edit.php | BSD-2-Clause |
function formNetworks()
{
$networks = array();
$networks["any"] = gettext("any");
// foreach (get_configured_interface_with_descr() as $ifent => $ifdesc) {
// $networks[$ifent] = htmlspecialchars($ifdesc) . " " . gettext("net");
// $networks[$ifent."ip"] = htmlspecialchars($ifdesc). " ". gettext("address");
// }
return $networks;
} | fetch list of selectable networks to use in form | formNetworks | php | opnsense/core | src/www/firewall_scrub_edit.php | https://github.com/opnsense/core/blob/master/src/www/firewall_scrub_edit.php | BSD-2-Clause |
function wg_stop($server)
{
if (does_interface_exist($server->interface)) {
legacy_interface_destroy($server->interface);
}
syslog(LOG_NOTICE, "wireguard instance {$server->name} ({$server->interface}) stopped");
} | stop wireguard tunnel, kill the device, the routes should drop automatically. | wg_stop | php | opnsense/core | src/opnsense/scripts/Wireguard/wg-service-control.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/Wireguard/wg-service-control.php | BSD-2-Clause |
function wg_reconfigure_hash($server)
{
if (empty((string)$server->disableroutes)) {
return md5(uniqid('', true)); // random hash, should always reconfigure
}
return md5(
sprintf(
'%s|%s|%s',
$server->tunneladdress,
$server->mtu,
$server->gateway
)
);
} | Calculate a hash which determines if we are able to reconfigure without a restart of the tunnel.
We currently assume if something changed on the interface or peer routes are being pushed, it's safer to
restart then reload. | wg_reconfigure_hash | php | opnsense/core | src/opnsense/scripts/Wireguard/wg-service-control.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/Wireguard/wg-service-control.php | BSD-2-Clause |
function get_stat_hash($fhandle)
{
fseek($fhandle, 0);
$payload = stream_get_contents($fhandle) ?? '';
$parts = explode('|', $payload);
return [
'file' => $parts[0] ?? '',
'interface' => $parts[1] ?? ''
];
} | The stat hash file answers two questions, [1] has anything changed, which is answered using an md5 hash of the
configuration file. The second question, if something has changed, is it safe to only reload the configuration.
This is answered by wg_reconfigure_hash() for the instance in question. | get_stat_hash | php | opnsense/core | src/opnsense/scripts/Wireguard/wg-service-control.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/Wireguard/wg-service-control.php | BSD-2-Clause |
function parse_auth_properties($props)
{
$result = [];
if (!empty($props['Framed-IP-Address']) && !empty($props['Framed-IP-Netmask'])) {
$cidrmask = 32 - log((ip2long($props['Framed-IP-Netmask']) ^ ip2long('255.255.255.255')) + 1, 2);
$result['tunnel_network'] = $props['Framed-IP-Address'] . "/" . $cidrmask;
}
if (!empty($props['Framed-Route']) && is_array($props['Framed-Route'])) {
$result['local_network'] = implode(",", $props['Framed-Route']);
}
return $result;
} | Parse provisioning properties supplied by the authenticator
@param array $props key value store containing addresses and routes
@return array formatted like openvpn_csc_conf_write() expects | parse_auth_properties | php | opnsense/core | src/opnsense/scripts/openvpn/user_pass_verify.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/openvpn/user_pass_verify.php | BSD-2-Clause |
public function getData(string $name)
{
return isset($this->stats[$name]) ? $this->stats[$name]['data'] : [];
} | get gathered statistics for a specific collector
@param string $name name of the collector, e.g. Mbuf
@return array | getData | php | opnsense/core | src/opnsense/scripts/health/library/OPNsense/RRD/Factory.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/health/library/OPNsense/RRD/Factory.php | BSD-2-Clause |
protected function jsonShellCmd($cmd)
{
exec($cmd . ' 2>&1', $payload, $returncode);
if ($returncode == 0 && !empty($payload[0])) {
return json_decode($payload[0], true) ?? [];
}
return null;
} | run simple shell command, expected to return json output | jsonShellCmd | php | opnsense/core | src/opnsense/scripts/health/library/OPNsense/RRD/Stats/Base.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/health/library/OPNsense/RRD/Stats/Base.php | BSD-2-Clause |
public static function wantsStats()
{
return 'Interfaces';
} | Traffic is a subcollection of Interfaces | wantsStats | php | opnsense/core | src/opnsense/scripts/health/library/OPNsense/RRD/Types/Traffic.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/health/library/OPNsense/RRD/Types/Traffic.php | BSD-2-Clause |
public static function payloadSplitter(array $payload)
{
if (!empty(static::$stdfilename)) {
yield static::$basedir . static::$stdfilename => $payload;
}
} | Maps datasets (stats) to input a new type object requires
@param array collected stats for the type
@return \Iterator<string, array> | payloadSplitter | php | opnsense/core | src/opnsense/scripts/health/library/OPNsense/RRD/Types/Base.php | https://github.com/opnsense/core/blob/master/src/opnsense/scripts/health/library/OPNsense/RRD/Types/Base.php | BSD-2-Clause |
public function __construct($new_data = null)
{
if ($new_data != null) {
self::$data = $new_data;
// simple conversion from array to StdClass container, current representation of self::$data.
self::$obj = json_decode(json_encode(self::$data));
}
} | construct new application config object, keep $data when not offered. | __construct | php | opnsense/core | src/opnsense/mvc/app/config/AppConfig.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/config/AppConfig.php | BSD-2-Clause |
public function update($path, $value)
{
$tmp = &self::$data;
foreach (explode('.', $path) as $key) {
if (isset($tmp[$key])) {
$tmp = &$tmp[$key];
} else {
return false;
}
}
$tmp = $value;
self::$obj = json_decode(json_encode(self::$data));
return true;
} | update a property inside the container
@param string $path in dot notation a.b.c
@param mixed $value
@return bool true when found and updated | update | php | opnsense/core | src/opnsense/mvc/app/config/AppConfig.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/config/AppConfig.php | BSD-2-Clause |
protected function getAdvancedIds($form)
{
$advancedFieldIds = [];
foreach ($form as $field) {
if (!empty($field['advanced']) && $field['advanced'] == "true") {
if (!empty($field['id'])) {
$tmp = explode('.', $field['id']);
$advancedFieldIds[] = $tmp[count($tmp) - 1];
}
}
}
return implode(',', $advancedFieldIds);
} | Get an array of field IDs that have the advanced flag set to "true".
@param array $form An array of field definitions
@return string list of fieldnames, comma separated for easy template usage | getAdvancedIds | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/FilterController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/FilterController.php | BSD-2-Clause |
public function setItemAction($uuid)
{
if ($this->request->isPost() && $this->request->hasPost("alias")) {
Config::getInstance()->lock();
$node = $this->getModel()->getNodeByReference('aliases.alias.' . $uuid);
$old_name = $node != null ? (string)$node->name : null;
if ($old_name !== null && !empty($this->request->getPost("alias")['name'])) {
$new_name = $this->request->getPost("alias")['name'];
if ($new_name != $old_name) {
// replace aliases, setBase() will synchronise the changes to disk
$this->getModel()->refactor($old_name, $new_name);
}
}
}
return $this->setBase("alias", "aliases.alias", $uuid);
} | Update alias with given properties
@param string $uuid internal id
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | setItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | BSD-2-Clause |
public function addItemAction()
{
return $this->addBase("alias", "aliases.alias");
} | Add new alias and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | addItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | BSD-2-Clause |
public function getTableSizeAction()
{
return json_decode((new Backend())->configdRun('filter diag table_size'), true);
} | get aliases load stats and table-entries limit | getTableSizeAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | BSD-2-Clause |
private function getRawNodes($parent_node)
{
$result = array();
foreach ($parent_node->iterateItems() as $key => $node) {
if ($node->isContainer()) {
$result[$key] = $this->getRawNodes($node);
} else {
$result[$key] = (string)$node;
}
}
return $result;
} | variant on model.getNodes() returning actual field values
@param $parent_node BaseField node to reverse | getRawNodes | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasController.php | BSD-2-Clause |
public function findReferencesAction()
{
if ($this->request->isPost() && $this->request->hasPost('ip')) {
$ip = $this->request->getPost('ip');
if (preg_match("/[^0-9a-f\:\.\/_]/", $ip)) {
return ['status' => 'Not an IP address!'];
}
$backend = new Backend();
return json_decode($backend->configdpRun('filter find_table_references', [$ip]), true);
} else {
return ['status' => 'IP parameter not specified!'];
}
} | API handler to look up in which rules an IP is used (either explicitly or included in a range).
@return array Array with indexes 'status' (whether the call succeeded) and 'matches' (which rules match this IP,
only present if the call was successful.)
@throws \Exception | findReferencesAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasUtilController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/AliasUtilController.php | BSD-2-Clause |
public function setItemAction($uuid)
{
$refactored = false;
$node = $this->getModel()->getNodeByReference('ifgroupentry.' . $uuid);
$old_name = $node != null ? (string)$node->ifname : null;
if ($old_name !== null && $this->request->isPost() && $this->request->hasPost("group")) {
$new_name = $this->request->getPost("group")['ifname'];
if ($new_name != $old_name) {
// replace groups, setBase() will synchronise the changes to disk
$refactored = $this->getModel()->refactor($old_name, $new_name);
}
}
$result = $this->setBase("group", "ifgroupentry", $uuid);
if ($refactored) {
// interface renamed
(new Backend())->configdRun('interface invoke registration');
}
return $result;
} | Update group with given properties
@param string $uuid internal id
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | setItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | BSD-2-Clause |
public function addItemAction()
{
return $this->addBase("group", "ifgroupentry");
} | Add new group and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | addItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | BSD-2-Clause |
public function getItemAction($uuid = null)
{
return $this->getBase("group", "ifgroupentry", $uuid);
} | Retrieve group settings or return defaults for new one
@param $uuid item unique id
@return array group content
@throws \ReflectionException when not bound to model | getItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/GroupController.php | BSD-2-Clause |
public function setItemAction($uuid)
{
$node = $this->getModel()->getNodeByReference('categories.category.' . $uuid);
$old_name = $node != null ? (string)$node->name : null;
if ($old_name !== null && $this->request->isPost() && $this->request->hasPost("category")) {
$new_name = $this->request->getPost("category")['name'];
if ($new_name != $old_name) {
// replace categories, setBase() will synchronise the changes to disk
$this->getModel()->refactor($old_name, $new_name);
}
}
return $this->setBase("category", "categories.category", $uuid);
} | Update category with given properties
@param string $uuid internal id
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | setItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | BSD-2-Clause |
public function addItemAction()
{
return $this->addBase("category", "categories.category");
} | Add new category and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | addItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | BSD-2-Clause |
public function getItemAction($uuid = null)
{
return $this->getBase("category", "categories.category", $uuid);
} | Retrieve category settings or return defaults for new one
@param $uuid item unique id
@return array category content
@throws \ReflectionException when not bound to model | getItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | BSD-2-Clause |
public function delItemAction($uuid)
{
Config::getInstance()->lock();
$node = $this->getModel()->getNodeByReference('categories.category.' . $uuid);
$node_name = $node != null ? (string)$node->name : null;
if ($node_name != null && $this->getModel()->isUsed($node_name)) {
$message = gettext("Cannot delete a category which is still in use.");
throw new \OPNsense\Base\UserException($message, gettext("Category in use"));
}
return $this->delBase("categories.category", $uuid);
} | Delete alias by uuid, save contents to tmp for removal on apply
@param string $uuid internal id
@return array save status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model
@throws \OPNsense\Base\UserException when unable to delete | delItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Firewall/Api/CategoryController.php | BSD-2-Clause |
public function getDestinationAction($uuid = null)
{
return $this->getBase("destination", "destinations.destination", $uuid);
} | Retrieve destination settings or return defaults for a new one
@param $uuid item unique id
@return array destination content
@throws \ReflectionException when not bound to model | getDestinationAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | BSD-2-Clause |
public function setDestinationAction($uuid)
{
return $this->setBase("destination", "destinations.destination", $uuid);
} | Update destination with given properties
@param string $uuid internal id
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | setDestinationAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | BSD-2-Clause |
public function addDestinationAction()
{
return $this->addBase('destination', 'destinations.destination');
} | Add new destination and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail | addDestinationAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | BSD-2-Clause |
public function toggleDestinationAction($uuid, $enabled = null)
{
return $this->toggleBase("destinations.destination", $uuid, $enabled);
} | Toggle destination defined by uuid (enable/disable)
@param $uuid user defined rule internal id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array save result
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | toggleDestinationAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Syslog/Api/SettingsController.php | BSD-2-Clause |
public function reloadRulesAction()
{
$status = "failed";
if ($this->request->isPost()) {
$backend = new Backend();
// flush rule configuration
$bckresult = trim($backend->configdRun('template reload OPNsense/IDS'));
if ($bckresult == "OK") {
$status = $backend->configdRun("ids reload");
} else {
$status = "template error";
}
}
return array("status" => $status);
} | Flush rule configuration to config and reload suricata ruleset (graceful restart)
@return array
@throws \Exception when configd action fails | reloadRulesAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/ServiceController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/ServiceController.php | BSD-2-Clause |
public function listRulesetsAction()
{
$result = array();
$result['rows'] = $this->listInstallableRules();
// sort by description
usort($result['rows'], function ($item1, $item2) {
return strcmp(strtolower($item1['description']), strtolower($item2['description']));
});
$result['rowCount'] = empty($result['rows']) ? 0 : count($result['rows']);
$result['total'] = empty($result['rows']) ? 0 : count($result['rows']);
$result['current'] = 1;
return $result;
} | List all installable rules including current status
@return array|mixed list of items when $id is null otherwise the selected item is returned
@throws \Exception | listRulesetsAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function toggleRulesetAction($filenames, $enabled = null)
{
$update_count = 0;
$result = array("status" => "none");
if ($this->request->isPost()) {
$backend = new Backend();
$response = $backend->configdRun("ids list installablerulesets");
$data = json_decode($response, true);
foreach (explode(",", $filenames) as $filename) {
if ($data != null && array_key_exists("items", $data) && array_key_exists($filename, $data['items'])) {
$node = $this->getModel()->getFileNode($filename);
if ($enabled == "0" || $enabled == "1") {
$node->enabled = (string)$enabled;
} elseif ((string)$node->enabled == "1") {
$node->enabled = "0";
} else {
$node->enabled = "1";
}
// only update result state if all items until now are ok
if ($result['status'] != 'error') {
$result['status'] = (string)$node->enabled;
}
$update_count++;
} else {
$result['status'] = "error";
}
}
if ($update_count > 0) {
$this->save();
}
}
return $result;
} | Toggle usage of rule file or set enabled / disabled depending on parameters
@param $filenames (target) rule file name, or list of filenames separated by a comma
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array status 0/1 or error
@throws \Exception
@throws \OPNsense\Base\ValidationException | toggleRulesetAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function getUserRuleAction($uuid = null)
{
return $this->getBase("rule", "userDefinedRules.rule", $uuid);
} | Get properties of user defined rule
@param null|string $uuid user rule internal id
@return array user defined properties
@throws \ReflectionException when not bound to model | getUserRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function toggleUserRuleAction($uuid, $enabled = null)
{
return $this->toggleBase("userDefinedRules.rule", $uuid, $enabled);
} | Toggle user defined rule by uuid (enable/disable)
@param $uuid user defined rule internal id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array save result
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | toggleUserRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function togglePolicyAction($uuid, $enabled = null)
{
return $this->toggleBase("policies.policy", $uuid, $enabled);
} | Toggle policy by uuid (enable/disable)
@param $uuid user defined rule internal id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array save result
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | togglePolicyAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function addPolicyRuleAction()
{
return $this->addBase("rule", "rules.rule");
} | Add new policy rule adjustment
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | addPolicyRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function getPolicyRuleAction($uuid = null)
{
return $this->getBase("rule", "rules.rule", $uuid);
} | Get properties of a policy rule adjustment
@param null|string $uuid internal id
@return array user defined properties
@throws \ReflectionException when not bound to model | getPolicyRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function delPolicyRuleAction($uuid)
{
return $this->delBase("rules.rule", $uuid);
} | Delete policy rule adjustment item
@param string $uuid internal id
@return array save status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | delPolicyRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function togglePolicyRuleAction($uuid, $enabled = null)
{
return $this->toggleBase("rules.rule", $uuid, $enabled);
} | Toggle policy rule adjustment by uuid (enable/disable)
@param $uuid user internal id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array save result
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | togglePolicyRuleAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/IDS/Api/SettingsController.php | BSD-2-Clause |
public function indexAction()
{
$this->view->pick('OPNsense/Core/firmware');
} | return to / for non existent actions | indexAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/FirmwareController.php | BSD-2-Clause |
public function licenseAction($package)
{
$backend = new Backend();
$response = array();
if ($this->request->isPost()) {
// sanitize package name
$package = (new SanitizeFilter())->sanitize($package, 'pkgname');
$text = trim($backend->configdRun(sprintf('firmware license %s', $package)));
if (!empty($text)) {
$response['license'] = $text;
}
}
return $response;
} | Retrieve specific license for package in text format
@param string $package package to retrieve
@return array with all possible licenses
@throws \Exception | licenseAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | BSD-2-Clause |
public function syncPluginsAction()
{
$backend = new Backend();
$response = array();
if ($this->request->isPost()) {
$this->getLogger('audit')->notice(sprintf("[Firmware] User %s executed a plugins sync", $this->getUserName()));
$response['status'] = strtolower(trim($backend->configdRun('firmware sync')));
} else {
$response['status'] = 'failure';
}
return $response;
} | install missing configured plugins
@return array status
@throws \Exception | syncPluginsAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | BSD-2-Clause |
public function resyncPluginsAction()
{
$backend = new Backend();
$response = array();
if ($this->request->isPost()) {
$response['status'] = strtolower(trim($backend->configdRun('firmware resync')));
} else {
$response['status'] = 'failure';
}
return $response;
} | reset missing configured plugins
@return array status
@throws \Exception | resyncPluginsAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | BSD-2-Clause |
public function upgradestatusAction()
{
$backend = new Backend();
$result = array('status' => 'running');
$cmd_result = trim($backend->configdRun('firmware status') ?? '');
$result['log'] = $cmd_result;
if ($cmd_result == null) {
$result['status'] = 'error';
} elseif (strpos($cmd_result, '***DONE***') !== false) {
$result['status'] = 'done';
} elseif (strpos($cmd_result, '***REBOOT***') !== false) {
$result['status'] = 'reboot';
}
return $result;
} | retrieve upgrade status (and log file of current process) | upgradestatusAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | BSD-2-Clause |
public function getOptionsAction()
{
return $this->getModel()->getRepositoryOptions();
} | list firmware mirror and flavour options
@return array | getOptionsAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/FirmwareController.php | BSD-2-Clause |
private function isValidName($name)
{
return !preg_match('/\s/', $name);
} | allow all but whitespaces for now
@param string $name snapshot name | isValidName | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/SnapshotsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/SnapshotsController.php | BSD-2-Clause |
private function throwReadOnly()
{
if ((new ACL())->hasPrivilege($this->getUserName(), 'user-config-readonly')) {
throw new UserException(
sprintf("User %s denied for write access (user-config-readonly set)", $this->getUserName())
);
}
} | when the user-config-readonly privilege is set, raise an error | throwReadOnly | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/BackupController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/BackupController.php | BSD-2-Clause |
public function downloadAction($host, $backup = null)
{
$providers = $this->providers();
if (!empty($providers[$host])) {
foreach (array_reverse(glob($providers[$host]['dirname'] . "/config-*.xml")) as $filename) {
if (empty($backup) || $backup == basename($filename)) {
$payload = @simplexml_load_file($filename);
$hostname = '';
if ($payload !== false && isset($payload->system) && isset($payload->system->hostname)) {
$hostname = $payload->system->hostname . "." . $payload->system->domain;
}
$target_filename = urlencode('config-' . $hostname . '-' . explode('/config-', $filename, 2)[1]);
$this->response->setContentType('application/octet-stream');
$this->response->setRawHeader("Content-Disposition: attachment; filename=" . $target_filename);
$this->response->setRawHeader("Content-length: " . filesize($filename));
$this->response->setRawHeader("Pragma: no-cache");
$this->response->setRawHeader("Expires: 0");
$this->response->setContent(fopen($filename, 'r'));
break;
}
}
}
} | download specified backup, when left empty the latest is offered | downloadAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/BackupController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/BackupController.php | BSD-2-Clause |
private function applyACL(&$menuItems, &$acl)
{
foreach ($menuItems as &$menuItem) {
$menuItem->isVisible = false;
if (count($menuItem->Children) > 0) {
$this->applyACL($menuItem->Children, $acl);
foreach ($menuItem->Children as $subMenuItem) {
if ($subMenuItem->isVisible) {
$menuItem->isVisible = true;
break;
}
}
} else {
if (!$acl->isPageAccessible($this->getUserName(), $menuItem->Url)) {
$menuItem->isVisible = false;
} else {
$menuItem->isVisible = true;
}
}
}
} | traverse menu items and mark user visibility (isVisible true/false)
@param array $menuItems menuitems from menu->getItems()
@param ACL $acl acl object reference | applyACL | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | BSD-2-Clause |
private function getMenu($selected_uri)
{
// construct menu and acl and merge collected info
$menu = new Menu\MenuSystem();
$acl = new ACL();
// fetch menu items and apply acl
$menu_items = $menu->getItems($selected_uri);
$this->applyACL($menu_items, $acl);
return $menu_items;
} | request user context sensitive menu (items)
@param string $selected_uri selected uri
@return array menu items | getMenu | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | BSD-2-Clause |
private function menuToArray($menu_items)
{
$result = array();
foreach ($menu_items as $menu_item) {
if ($menu_item->isVisible) {
$new_item = (array) $menu_item;
$new_item['Children'] = array();
if (count($menu_item->Children) > 0) {
$new_item['Children'] = $this->menuToArray($menu_item->Children);
}
$result[] = $new_item;
}
}
return $result;
} | flatten menu structure, only returning visible entries
@param $menu_items array containing stdClass objects
@return array tree containing simple types | menuToArray | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | BSD-2-Clause |
public function treeAction()
{
$selected_uri = $this->request->get("uri", null, null);
$menu_items = $this->getMenu($selected_uri);
return $this->menuToArray($menu_items);
} | return menu items for this user
@return array | treeAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Core/Api/MenuController.php | BSD-2-Clause |
public function reconfigureGeneralAction()
{
$backend = new Backend();
$backend->configdRun('dns reload');
$result = $this->reconfigureAction();
$backend->configdRun('dhcpd restart');
return $result;
} | Only used on the general page to account for resolver_configure and dhcp hooks
since these check if unbound is enabled. | reconfigureGeneralAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Unbound/Api/ServiceController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Unbound/Api/ServiceController.php | BSD-2-Clause |
public function dumpcacheAction()
{
$ret['status'] = "failed";
$backend = new Backend();
$result = json_decode(trim($backend->configdRun("unbound dumpcache")), true);
if ($result !== null) {
$ret['data'] = $result;
$ret['status'] = 'ok';
}
return $ret;
} | return the entries of the cache | dumpcacheAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Unbound/Api/DiagnosticsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Unbound/Api/DiagnosticsController.php | BSD-2-Clause |
public function setrouteAction($uuid)
{
$node = $this->getBase("route", "route", $uuid);
// delete previous route when changed (one shot, apply should only delete the last known situation)
if (
!empty($node['route']['network']) && $_POST['route']['network'] != $node['route']['network']
&& !file_exists("/tmp/delete_route_{$uuid}.todo")
) {
file_put_contents("/tmp/delete_route_{$uuid}.todo", $node['route']['network']);
}
return $this->setBase("route", "route", $uuid);
} | Update route with given properties
@param string $uuid internal id
@return array save result + validation output
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | setrouteAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | BSD-2-Clause |
public function addrouteAction()
{
return $this->addBase("route", "route");
} | Add new route and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException | addrouteAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | BSD-2-Clause |
public function getrouteAction($uuid = null)
{
return $this->getBase("route", "route", $uuid);
} | Retrieve route settings or return defaults for new one
@param $uuid item unique id
@return array route content
@throws \ReflectionException when not bound to model | getrouteAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | BSD-2-Clause |
public function delrouteAction($uuid)
{
$node = (new Route())->getNodeByReference('route.' . $uuid);
$response = $this->delBase("route", $uuid);
if (!empty($response['result']) && $response['result'] == 'deleted') {
// we don't know for sure if this route was already removed, flush to disk to remove on apply
file_put_contents("/tmp/delete_route_{$uuid}.todo", (string)$node->network);
}
return $response;
} | Delete route by uuid, save contents to tmp for removal on apply
@param string $uuid internal id
@return array save status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model
@throws \OPNsense\Base\ModelException when not bound to model | delrouteAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | BSD-2-Clause |
public function togglerouteAction($uuid, $disabled = null)
{
$result = array("result" => "failed");
if ($this->request->isPost() && $uuid != null) {
$node = $this->getModel()->getNodeByReference('route.' . $uuid);
if ($node != null) {
if ($disabled == '0' || $disabled == '1') {
$node->disabled = (string)$disabled;
} elseif ((string)$node->disabled == '1') {
$node->disabled = '0';
} else {
$node->disabled = '1';
}
$result['result'] = (string)$node->disabled == '1' ? 'Disabled' : 'Enabled';
$this->save();
}
}
return $result;
} | toggle, we can not use our default action here since enabled/disabled are swapped
@param string $uuid id to toggled
@param string|null $disabled set disabled by default
@return array status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model
@throws \OPNsense\Base\ModelException when not bound to model | togglerouteAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Routes/Api/RoutesController.php | BSD-2-Clause |
public function openAction($uuid = null)
{
$this->view->selected_uuid = htmlspecialchars($uuid, ENT_QUOTES | ENT_HTML401);
// include dialog form definitions
$this->view->formDialogEdit = $this->getForm("dialogEdit");
$this->view->pick('OPNsense/Cron/index');
} | open cron form with selected item
@param null $uuid cron item to open
@throws \Exception | openAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Cron/ItemController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Cron/ItemController.php | BSD-2-Clause |
public function getJobAction($uuid = null)
{
return $this->getBase("job", "jobs.job", $uuid);
} | retrieve job settings or return defaults
@param $uuid item unique id
@return array job contents
@throws \ReflectionException when not bound to model | getJobAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | BSD-2-Clause |
public function addJobAction()
{
return $this->addBase("job", "jobs.job");
} | add new job and set with attributes from post
@return array save result + validation output
@throws \OPNsense\Base\ModelException when not bound to model
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException | addJobAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | BSD-2-Clause |
public function delJobAction($uuid)
{
if ($uuid != null) {
$node = (new Cron())->getNodeByReference('jobs.job.' . $uuid);
if ($node->origin == "cron") {
return $this->delBase("jobs.job", $uuid);
}
}
return array("result" => "failed");
} | delete job by uuid ( only if origin is cron)
@param string $uuid item unique id
@return array status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model
@throws \OPNsense\Base\ModelException when not bound to model | delJobAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | BSD-2-Clause |
public function toggleJobAction($uuid, $enabled = null)
{
return $this->toggleBase("jobs.job", $uuid, $enabled);
} | toggle job by uuid (enable/disable)
@param $uuid item unique id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array status
@throws \OPNsense\Base\ValidationException when field validations fail
@throws \ReflectionException when not bound to model | toggleJobAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Cron/Api/SettingsController.php | BSD-2-Clause |
public function listProvidersAction()
{
$result = array();
$authFactory = new AuthenticationFactory();
foreach ($authFactory->listServers() as $authName => $authProps) {
if ($authProps['type'] == 'voucher') {
$result[] = $authName;
}
}
return $result;
} | list voucher providers (authenticators of type "voucher")
@return array list of auth providers | listProvidersAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/VoucherController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/VoucherController.php | BSD-2-Clause |
public function getZoneAction($uuid = null)
{
return $this->getBase("zone", "zones.zone", $uuid);
} | retrieve zone settings or return defaults
@param $uuid item unique id
@return array | getZoneAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | BSD-2-Clause |
public function setZoneAction($uuid)
{
return $this->setBase("zone", "zones.zone", $uuid);
} | update zone with given properties
@param $uuid item unique id
@return array | setZoneAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | BSD-2-Clause |
public function addZoneAction()
{
return $this->addBase("zone", "zones.zone");
} | add new zone and set with attributes from post
@return array | addZoneAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | BSD-2-Clause |
public function toggleZoneAction($uuid, $enabled = null)
{
return $this->toggleBase("zones.zone", $uuid, $enabled);
} | toggle zone by uuid (enable/disable)
@param $uuid item unique id
@param $enabled desired state enabled(1)/disabled(1), leave empty for toggle
@return array status | toggleZoneAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/CaptivePortal/Api/SettingsController.php | BSD-2-Clause |
private function parseJsonBodyData()
{
switch (strtolower(str_replace(' ', '', $this->request->getHeader('CONTENT_TYPE')))) {
case 'application/json':
case 'application/json;charset=utf-8':
$jsonRawBody = $this->request->getJsonRawBody();
if (empty($this->request->getRawBody()) && empty($jsonRawBody)) {
return "Invalid JSON syntax";
}
$_POST = is_array($jsonRawBody) ? $jsonRawBody : [];
foreach ($_POST as $key => $value) {
$_REQUEST[$key] = $value;
}
break;
case 'application/x-www-form-urlencoded':
case 'application/x-www-form-urlencoded;charset=utf-8':
// valid non parseable content
break;
default:
if (!empty($this->request->getRawBody())) {
$this->getLogger()->warning('unparsable Content-Type:' . $this->request->getHeader('CONTENT_TYPE') . ' received');
}
break;
}
return null;
} | parse raw json type content to POST data depending on content type
(only for api calls)
@return string | parseJsonBodyData | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiControllerBase.php | BSD-2-Clause |
protected function isExternalClient()
{
return !empty($this->request->getHeader('Authorization'));
} | is external client (other then session authenticated)
@return bool | isExternalClient | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiControllerBase.php | BSD-2-Clause |
protected function reconfigureForceRestart()
{
return 1;
} | reconfigure force restart check, return zero and define 'reload' backend action for soft-reload | reconfigureForceRestart | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | BSD-2-Clause |
protected function invokeInterfaceRegistration()
{
return false;
} | invoke interface registration check, return true to invoke configd action | invokeInterfaceRegistration | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | BSD-2-Clause |
protected function serviceEnabled()
{
if (empty(static::$internalServiceEnabled)) {
throw new \Exception('cannot check if service is enabled without internalServiceEnabled defined.');
}
return (string)($this->getModel())->getNodeByReference(static::$internalServiceEnabled) == '1';
} | check if service is enabled according to model | serviceEnabled | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | BSD-2-Clause |
public function reconfigureAction()
{
if ($this->request->isPost()) {
$restart = $this->reconfigureForceRestart();
$enabled = $this->serviceEnabled();
$backend = new Backend();
if ($restart || !$enabled) {
$backend->configdRun(escapeshellarg(static::$internalServiceName) . ' stop');
}
if ($this->invokeInterfaceRegistration()) {
$backend->configdRun('interface invoke registration');
}
if (!empty(static::$internalServiceTemplate)) {
$result = trim($backend->configdpRun('template reload', [static::$internalServiceTemplate]) ?? '');
if ($result !== 'OK') {
throw new UserException(sprintf(
gettext('Template generation failed for internal service "%s". See backend log for details.'),
static::$internalServiceName
), gettext('Configuration exception'));
}
}
if ($enabled) {
if ($restart || $this->statusAction()['status'] != 'running') {
$backend->configdRun(escapeshellarg(static::$internalServiceName) . ' start');
} else {
$backend->configdRun(escapeshellarg(static::$internalServiceName) . ' reload');
}
}
return ['status' => 'ok'];
}
return ['status' => 'failed'];
} | reconfigure with optional stop, generate config and start / reload
@return array response message
@throws \Exception when configd action fails
@throws \ReflectionException when model can't be instantiated | reconfigureAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableServiceControllerBase.php | BSD-2-Clause |
protected function sessionClose()
{
return;
} | XXX: remove in a future version, sessions are handled via session class
Wrap close session, for long running operations. | sessionClose | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerRoot.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerRoot.php | BSD-2-Clause |
protected function setLang()
{
$config = Config::getInstance()->object();
$lang = $this->langcode;
foreach ($config->system->children() as $key => $node) {
if ($key == 'language' && !empty((string)$node)) {
$lang = (string)$node;
break;
}
}
if ($this->session->has('Username')) {
$username = $this->session->get('Username');
foreach ($config->system->user as $user) {
if ($username == (string)$user->name && !empty((string)$user->language)) {
$lang = (string)$user->language;
break;
}
}
}
$locale = $lang . '.UTF-8';
$interpolator = new InterpolatorFactory();
$this->translator = new ViewTranslator($interpolator, [
'directory' => '/usr/local/share/locale',
'defaultDomain' => 'OPNsense',
'locale' => [$locale],
]);
/* somehow this is not done by Phalcon */
bind_textdomain_codeset('OPNsense', $locale);
putenv('LANG=' . $locale);
$this->langcode = $lang;
} | set system language according to configuration | setLang | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerRoot.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerRoot.php | BSD-2-Clause |
private function parseFormNode($xmlNode)
{
$result = [];
foreach ($xmlNode as $key => $node) {
switch ($key) {
case "tab":
if (!array_key_exists("tabs", $result)) {
$result['tabs'] = [];
}
$tab = [];
$tab[] = (string)$node->attributes()->id;
$tab[] = gettext((string)$node->attributes()->description);
if (isset($node->subtab)) {
$tab["subtabs"] = $this->parseFormNode($node);
} else {
$tab[] = $this->parseFormNode($node);
}
$result['tabs'][] = $tab;
break;
case "subtab":
$subtab = [];
$subtab[] = $node->attributes()->id;
$subtab[] = gettext((string)$node->attributes()->description);
$subtab[] = $this->parseFormNode($node);
$result[] = $subtab;
break;
case "field":
// field type, containing attributes
$result[] = $this->parseFormNode($node);
break;
case "help":
case "hint":
case "label":
$result[$key] = gettext((string)$node);
break;
default:
// default behavior, copy in value as key/value data
$result[$key] = (string)$node;
break;
}
}
return $result;
} | convert xml form definition to simple data structure to use in our Volt templates
@param $xmlNode
@return array | parseFormNode | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | BSD-2-Clause |
public function getFormGrid($formname, $grid_id = null, $edit_alert_id = null)
{
/* collect all fields, sort by sequence */
$all_data = [];
$idx = 0;
foreach ($this->getFormXML($formname) as $rootkey => $rootnode) {
if ($rootkey == 'field' && !empty((string)$rootnode->id)) {
$record = [
'column-id' => '',
'label' => '',
'visible' => 'true',
'sortable' => 'true',
'identifier' => 'false',
'type' => 'string' /* XXX: convert to type + formatter using source type? */
];
foreach ($rootnode as $key => $item) {
switch ($key) {
case 'label':
$record['label'] = gettext((string)$item);
break;
case 'id':
$tmp = explode('.', (string)$item);
$record['column-id'] = end($tmp);
break;
}
}
/* iterate field->grid_view items */
$this_sequence = '9999999';
if (isset($rootnode->grid_view)) {
foreach ($rootnode->grid_view->children() as $key => $item) {
if ($key == 'ignore' && $item != 'false') {
/* ignore field as requested */
continue 2;
} elseif ($key == 'sequence') {
$this_sequence = (string)$item;
} else {
$record[$key] = (string)$item;
}
}
}
$all_data[sprintf("%010d.%03d", $this_sequence, $idx++)] = $record;
}
}
/* prepend identifier */
$all_data[sprintf("%010d.%03d", 0, 0)] = [
'column-id' => 'uuid',
'label' => gettext('ID'),
'type' => 'string',
'identifier' => 'true',
'visible' => 'false'
];
ksort($all_data);
$basename = $grid_id ?? $formname;
return [
'table_id' => $basename,
'edit_dialog_id' => 'dialog_' . $basename,
'edit_alert_id' => $edit_alert_id == null ? 'change_message_base_form' : $edit_alert_id,
'fields' => array_values($all_data)
];
} | Extract grid fields from form definition
@return array | getFormGrid | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | BSD-2-Clause |
public function initialize()
{
// set base template
$this->view->setTemplateBefore('default');
$this->view->session = $this->session;
} | Default action. Set the standard layout. | initialize | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ControllerBase.php | BSD-2-Clause |
protected function setSaveAuditMessage($msg)
{
$this->internalAuditMessage = $msg;
} | Message to use on save of this model | setSaveAuditMessage | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
private function checkAndThrowSafeDelete($uuid)
{
if (static::$internalModelUseSafeDelete) {
$this->checkAndThrowValueInUse($uuid);
}
} | Check if item can be safely deleted if $internalModelUseSafeDelete is enabled.
Throws a user exception when the $uuid seems to be used in some other config section.
@param $uuid string uuid to check
@throws UserException containing additional information | checkAndThrowSafeDelete | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
protected function getModelNodes()
{
return $this->getModel()->getNodes();
} | Override this to customize what part of the model gets exposed
@return array
@throws \ReflectionException | getModelNodes | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
protected function validateAndSave($node = null, $prefix = null)
{
$result = $this->validate($node, $prefix);
if (empty($result['result'])) {
$result = $this->save();
if ($node !== null) {
$attrs = $node->getAttributes();
if (!empty($attrs['uuid'])) {
$result['uuid'] = $attrs['uuid'];
}
}
}
return $result;
} | Validate and save model after update or insertion.
Use the reference node and tag to rename validation output for a specific node to a new offset, which makes
it easier to reference specific uuids without having to use them in the frontend descriptions.
@param string $node reference node, to use as relative offset
@param string $prefix prefix to use when $node is provided (defaults to static::$internalModelName)
@return array result / validation output
@throws \OPNsense\Base\ValidationException on validation issues
@throws \ReflectionException when binding to the model class fails
@throws UserException when denied write access | validateAndSave | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
protected function save($validateFullModel = false, $disable_validation = false)
{
if (!(new ACL())->hasPrivilege($this->getUserName(), 'user-config-readonly')) {
if ($this->getModel()->serializeToConfig($validateFullModel, $disable_validation)) {
if ($this->internalAuditMessage) {
Config::getInstance()->save(['description' => $this->internalAuditMessage]);
} else {
/* default "endpoint made changes" message */
Config::getInstance()->save();
}
}
return array("result" => "saved");
} else {
// XXX remove user-config-readonly in some future release
throw new UserException(
sprintf("User %s denied for write access (user-config-readonly set)", $this->getUserName())
);
}
} | Save model after update or insertion, validate() first to avoid raising exceptions
@param bool $validateFullModel by default we only validate the fields we have changed
@param bool $disable_validation skip validation, be careful to use this!
@return array result / validation output
@throws \OPNsense\Base\ValidationException on validation issues
@throws \ReflectionException when binding to the model class fails
@throws \OPNsense\Base\UserException when denied write access | save | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
protected function setActionHook()
{
} | Hook to be overridden if the controller is to take an action when
setAction is called. This hook is called after a model has been
constructed and validated but before it serialized to the configuration
and written to disk
@return string error message on error, or null/void on success | setActionHook | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
protected function setBaseHook($node)
{
} | Hook to be overridden if the controller is to take an action when
setBase/addBase is called. This hook is called after a model has been
constructed and validated but before it serialized to the configuration
and written to disk
@throws UserException when action is not possible (and save should be aborted) | setBaseHook | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
public function getBase($key_name, $path, $uuid = null)
{
$mdl = $this->getModel();
if ($uuid != null) {
$node = $mdl->getNodeByReference($path . '.' . $uuid);
if ($node != null) {
// return node
return array($key_name => $node->getNodes());
}
} else {
foreach (explode('.', $path) as $step) {
$mdl = $mdl->{$step};
}
$node = $mdl->Add();
return array($key_name => $node->getNodes());
}
return [];
} | Model get wrapper, fetches an array item and returns it's contents
@param string $key_name result root key
@param string $path path to fetch, relative to our model
@param null|string $uuid node key
@return array
@throws \ReflectionException when binding to the model class fails | getBase | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Base/ApiMutableModelControllerBase.php | BSD-2-Clause |
private function stashUpdate($gifif)
{
file_put_contents("/tmp/.gif.todo", "{$gifif}\n", FILE_APPEND | LOCK_EX);
chmod("/tmp/.gif.todo", 0750);
} | write updated or removed gif to temp | stashUpdate | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | BSD-2-Clause |
public function setItemAction($uuid)
{
$node = $this->getModel()->getNodeByReference('gif.' . $uuid);
$overlay = null;
if (!empty($node)) {
// not allowed to change gif interface name
$overlay['gifif'] = (string)$node->gifif;
}
$result = $this->setBase("gif", "gif", $uuid, $overlay);
if ($result['result'] != 'failed') {
$this->stashUpdate($overlay !== null ? $overlay['gifif'] : $this->request->get('gif')['gifif']);
}
return $result;
} | Update gif with given properties
@param string $uuid internal id
@return array save result + validation output | setItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | BSD-2-Clause |
public function getItemAction($uuid = null)
{
return $this->getBase("gif", "gif", $uuid);
} | Retrieve gif settings or return defaults for new one
@param $uuid item unique id
@return array gif content | getItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/GifSettingsController.php | BSD-2-Clause |
public function setItemAction($uuid)
{
Config::getInstance()->lock();
$node = $this->getModel()->getNodeByReference('bridged.' . $uuid);
$overlay = null;
if (!empty($node)) {
// not allowed to change bridge interface name
$overlay['bridgeif'] = (string)$node->bridgeif;
}
return $this->setBase("bridge", "bridged", $uuid, $overlay);
} | Update bridge with given properties
@param string $uuid internal id
@return array save result + validation output | setItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/BridgeSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/BridgeSettingsController.php | BSD-2-Clause |
public function getItemAction($uuid = null)
{
return $this->getBase("bridge", "bridged", $uuid);
} | Retrieve bridge settings or return defaults for new one
@param $uuid item unique id
@return array bridge content | getItemAction | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/BridgeSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/BridgeSettingsController.php | BSD-2-Clause |
private function stashUpdate($laggif)
{
file_put_contents("/tmp/.lagg.todo", "{$laggif}\n", FILE_APPEND | LOCK_EX);
chmod("/tmp/.lagg.todo", 0750);
} | write updated or removed laggif to temp | stashUpdate | php | opnsense/core | src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/LaggSettingsController.php | https://github.com/opnsense/core/blob/master/src/opnsense/mvc/app/controllers/OPNsense/Interfaces/Api/LaggSettingsController.php | BSD-2-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.