public function initialize()
 {
     $this->_action = 'menuitem_add';
     $name = new Text('name');
     $name->setFilters(array('striptags', 'string'));
     $name->setAttributes(array('class' => 'form-control', 'autocomplete' => 'off', 'id' => 'menuitem_name'));
     $name->setLabel('Name');
     $url = new Text('url');
     $url->setFilters(array('striptags', 'string'));
     $url->setAttributes(array('class' => 'form-control', 'autocomplete' => 'off'));
     $url->setLabel('URL');
     $icon = new Text('icon');
     $icon->setFilters(array('striptags', 'string'));
     $icon->setAttributes(array('class' => 'form-control', 'autocomplete' => 'off'));
     $icon->setLabel('Icon');
     $device = new Select('device_id', Devices::find(), array('using' => array('id', 'name'), 'useEmpty' => true, 'emptyText' => 'None', 'emptyValue' => 0));
     $device->setLabel('Device');
     $menuId = new Hidden('menu_id');
     $menuId->setDefault(1);
     $this->add($name);
     $this->add($url);
     $this->add($icon);
     $this->add($device);
     $this->add($menuId);
 }
예제 #2
1
 /**
  * Shows the dashboard view
  */
 public function indexAction()
 {
     $this->view->menu = Menus::findFirst(array('conditions' => 'id = ?1', 'order' => 'name', 'bind' => array(1 => 1)));
     $this->view->devices = Devices::find(array('order' => 'name ASC'));
     $this->view->movies = KodiMovies::getLatestMovies();
     $this->view->albums = KodiMusic::getLatestAlbums();
     $this->view->episodes = KodiTVShowEpisodes::getLatestEpisodes();
     $this->executionTime = -microtime(true);
     $this->view->phpsysinfoData = PHPSysInfo::getData($this->config);
     $this->view->PHPSysinfoExecutionTime = round($this->executionTime + microtime(true), 2) . 's';
 }
 public function IsValid($data = null, $entity = null)
 {
     $devices = array();
     foreach ($data['devices'] as $id => $device) {
         $newDevice = new Devices();
         $newDevice->id = $id;
         foreach ($device as $key => $value) {
             $newDevice->{$key} = $value;
         }
         $newDevice->validate();
         $devices[] = $newDevice;
     }
     return $devices;
 }
 public function initialize($menuitems)
 {
     $this->_action = 'menu';
     foreach ($menuitems as $menuItem) {
         $name = new Text('menuitem[' . $menuItem->id . '][name]');
         $name->setFilters(array('striptags', 'string'));
         $name->setAttributes(array('class' => 'form-control'));
         $name->setDefault($menuItem->name);
         $url = new Text('menuitem[' . $menuItem->id . '][url]');
         $url->setFilters(array('striptags', 'string'));
         $url->setAttributes(array('class' => 'form-control'));
         $url->setDefault($menuItem->url);
         $icon = new Text('menuitem[' . $menuItem->id . '][icon]');
         $icon->setFilters(array('striptags', 'string'));
         $icon->setAttributes(array('class' => 'form-control'));
         $icon->setDefault($menuItem->icon);
         $device = new Select('menuitem[' . $menuItem->id . '][device]', Devices::find(), array('using' => array('id', 'name'), 'useEmpty' => true, 'emptyText' => 'None', 'emptyValue' => 0));
         $device->setDefault($menuItem->device_id);
         $id = new Hidden('menuitem[' . $menuItem->id . '][id]');
         $id->setDefault($menuItem->id);
         $this->add($name);
         $this->add($url);
         $this->add($icon);
         $this->add($device);
         $this->add($id);
     }
 }
예제 #5
0
 public function actionCommand($id)
 {
     //get Scene Devices by Scene ID
     $sceneDevices = SceneDevices::model()->findAll('tbl_scene_idtbl_scene=:sceneID', array(':sceneID' => $id));
     foreach ($sceneDevices as $node) {
         //get node details and get device type
         $device = Devices::model()->find('idtbl_device=:deviceID', array(':deviceID' => $node["tbl_devices_idtbl_device"]));
         if ($_GET['state'] == "100") {
             $nodeLevel = $node["tbl_scene_device_level"];
         } else {
             $nodeLevel = 0;
         }
         $nodeID = $device["tbl_device_nodeid"];
         $nodeType = $device["tbl_device_type"];
         $url = Yii::app()->params['serverurl'] . "/server.php?command=control&node=" . $nodeID . "&type=" . urlencode($nodeType) . "&level=" . $nodeLevel;
         echo $url;
         // create a new cURL resource
         $ch = curl_init();
         // set URL and other appropriate options
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         // grab URL and pass it to the browser
         curl_exec($ch);
         // close cURL resource, and free up system resources
         curl_close($ch);
     }
     $this->redirect(array('index'));
 }
 public function actionGetdevices()
 {
     $data = Devices::model()->findAll('tbl_rooms_idtbl_room=:room_id', array(':room_id' => (int) $_POST['room_id']));
     $data = CHtml::listData($data, 'idtbl_device', 'tbl_device_name');
     foreach ($data as $value => $name) {
         echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
     }
 }
 public static function fromArray($data)
 {
     $vd = new ValidatedDevices();
     foreach ($data as $key => $value) {
         if ($key == "devices") {
             $vd->{$key} = Devices::fromArray($value);
         } else {
             $vd->{$key} = $value;
         }
     }
     return $vd;
 }
예제 #8
0
 /**
  * API function for register device.
  *
  * @return Response
  */
 public function postRegisterDevice()
 {
     $data = post();
     // Validator for post params
     $valids = Validator::make($data, ['device_id' => 'required']);
     // Check is valid
     if ($valids->fails()) {
         return EXRHelper::getErrorMsg($valids->messages());
     }
     $result = Devices::addDevice($data['device_id']);
     return EXRHelper::getSuccess($result);
 }
 private function generateCronJob($min, $hr, $day, $month, $dayOfWeek, $devices, $state)
 {
     $jobs = array();
     $count = 0;
     //get all devices for this particualr scene
     foreach ($devices as $device) {
         //get device details
         $node = Devices::model()->find("idtbl_device=" . $device->tbl_devices_idtbl_device);
         if ($node) {
             if ($state == 'off') {
                 $level = 0;
             } else {
                 $level = $device->tbl_scene_device_level;
             }
             //build cron job string
             $jobs[$count] = $min . ' ' . $hr . ' ' . $day . ' ' . $month . ' ' . $dayOfWeek . ' curl "' . "http://localhost" . Yii::app()->createUrl("control/command", array("node" => $node->tbl_device_nodeid, "type" => $node->tbl_device_type, "level" => $level)) . '"';
             $count++;
         }
     }
     return $jobs;
 }
예제 #10
0
 static function getInstance()
 {
     if (empty(self::$instance)) {
         switch (_RELEASE) {
             case "fermi":
                 if (!file_exists(_ABSPATH . '/lib/DevicesFermi.php')) {
                     die("Fermi Devices class does not exist");
                 }
                 require_once _ABSPATH . '/lib/DevicesFermi.php';
                 self::$instance = new DevicesFermi();
                 break;
             case "general":
             default:
                 if (!file_exists(_ABSPATH . '/lib/DevicesGeneral.php')) {
                     die("General Devices class does not exist");
                 }
                 require_once _ABSPATH . '/lib/DevicesGeneral.php';
                 self::$instance = new DevicesGeneral();
                 break;
         }
     }
     return self::$instance;
 }
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = Devices::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
예제 #12
0
* You should have received a copy of the GNU General Public License
* along with this package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA  02110-1301  USA
*
*
* On Debian GNU/Linux systems, the complete text of the GNU General
* Public License can be found in `/usr/share/common-licenses/GPL-2'.
*
* Otherwise you can read it here: http://www.gnu.org/licenses/gpl-2.0.txt
*
*/
require_once 'av_init.php';
$db = new ossim_db();
$conn = $db->connect();
$device_obj = new Devices($conn);
$devices = $device_obj->get_devices();
$db->close();
?>


/****************************************************
 **************** Device functions ******************
 ****************************************************/
 

var device_types = new Array();
var device_subtypes = new Array();
            
<?php 
foreach ($devices as $dt_id => $dt_data) {
예제 #13
0
 /**
  * Check is device already registered
  * @param string $deviceId
  * @return boolean
  */
 public function checkIsDeviceRegistered($deviceId)
 {
     return Devices::where('device_identifier', '=', $deviceId)->exists();
 }
예제 #14
0
    <div class="row">	
    <?php 
if (isset($_GET["sceneId"])) {
    $model->tbl_scene_idtbl_scene = $_GET["sceneId"];
}
echo $form->hiddenField($model, 'tbl_scene_idtbl_scene');
?>
    </div>

    <div class="row">
       <?php 
echo $form->labelEx($model, 'tbl_devices_idtbl_device');
?>
        <?php 
if (isset($_GET['id'])) {
    echo $form->dropDownList($model, 'tbl_devices_idtbl_device', CHtml::listData(Devices::model()->findAll(), 'idtbl_device', 'tbl_device_name'));
} else {
    echo $form->dropDownList($model, 'tbl_devices_idtbl_device', array());
}
?>
        <?php 
echo $form->error($model, 'tbl_devices_idtbl_device');
?>
    </div>

    <div class="row">
<?php 
echo $form->labelEx($model, 'tbl_scene_device_level');
echo $form->textField($model, 'tbl_scene_device_level');
?>
        <?php 
function devices_controller()
{
    //return array('content'=>"ok");
    global $mysqli, $redis, $user, $session, $route, $feed_settings;
    // There are no actions in the input module that can be performed with less than write privileges
    if (!$session['write']) {
        return array('content' => false);
    }
    global $feed, $timestore_adminkey;
    $result = false;
    include "Modules/feed/feed_model.php";
    $feed = new Feed($mysqli, $redis, $feed_settings);
    require "Modules/input/input_model.php";
    // 295
    $input = new Input($mysqli, $redis, $feed);
    require "Modules/input/process_model.php";
    // 886
    $process = new Process($mysqli, $input, $feed);
    include "Modules/devices/devices_model.php";
    $devices = new Devices($mysqli, $redis, $input, $feed, $process);
    function getArray($string)
    {
        $json = preg_replace('/[^\\w\\s-.:,]/', '', $string);
        $data = explode(',', $json);
        $return = array();
        foreach ($data as $d) {
            $return[] = trim($d);
        }
        return array_unique($return);
    }
    if ($route->format == 'html') {
        if ($route->action == 'api') {
            $result = view("Modules/devices/Views/devices_api.php", array());
        }
        if ($route->action == 'devices') {
            $result = view("Modules/devices/Views/devices.php", array());
        }
        if ($route->action == 'configure') {
            $result = view("Modules/driver/Views/configure.php", array('driverid' => intval(get('driverid'))));
        }
        if ($route->action == 'startstop') {
            $result = view("Modules/driver/Views/startstop.php", array('driverid' => intval(get('driverid'))));
        }
    }
    if ($route->format == 'json') {
        if ($route->action == "template") {
            if ($route->subaction == "add") {
                $result = $devices->add_template($session['userid'], $_GET['productname'], $_GET['producttype'], $_GET['operatingtype'], getArray(get('requirednodetypes')), getArray(get('modes')));
            }
            if ($route->subaction == "remove") {
                $result = $devices->remove_template($session['userid'], get('templateid'));
            }
            if ($route->subaction == "list") {
                $result = $devices->list_templates($session['userid']);
            }
        }
        if ($route->action == "registernode") {
            $result = $devices->register_node($session['userid'], $_GET['driverid'], $_GET['address'], getArray(get('type')));
        }
        if ($route->action == "node") {
            if ($route->subaction == "register") {
                $result = $devices->register_node($session['userid'], $_GET['driverid'], $_GET['address'], getArray(get('type')));
            }
            if ($route->subaction == "unregister") {
                $result = $devices->unregister_node($session['userid'], get('nodeid'));
            }
            if ($route->subaction == "getunassigned") {
                $result = $devices->get_unassigned_nodes($session['userid'], get('type') ? getArray(get('type')) : false);
            }
            if ($route->subaction == "get" and get('driverid') != null and get('address') != null) {
                $result = $devices->get_nodeid($session['userid'], get('driverid'), get('address'));
            }
        }
        if ($route->action == "getunassignednodes") {
            $result = $devices->get_unassigned_nodes($session['userid'], get('type') ? getArray(get('type')) : false);
        }
        if ($route->action == "device") {
            if ($route->subaction == "add") {
                $result = $devices->add_device($session['userid'], get('name'), get('templateid'), getArray(get('nodes')));
            }
            if ($route->subaction == "remove") {
                $result = $devices->remove_device($session['userid'], get('deviceid'));
            }
            if ($route->subaction == "list") {
                $result = $devices->list_devices($session['userid']);
            }
            if ($route->subaction == "status") {
                $result = $devices->set_device_status($session['userid'], get('deviceid'), get('status'));
            }
            if ($route->subaction == "get" and get('nodeid') != null) {
                $result = $devices->get_device_by_nodeid($session['userid'], get('nodeid'));
            }
        }
        if ($route->action == "post") {
            $result = $devices->post_value($session['userid'], get('driverid'), get('address'), get('type'), get('value'), get('time') != null ? get('time') : time());
        }
        if ($route->action == "reserve") {
            if (isset($_GET['driverID'])) {
                $result = $driver->reserve($session['userid'], $_GET['driverID']);
            } else {
                $result = -1;
            }
        }
        //get parameters of a driver
        if ($route->action == "parameters") {
            if (isset($_GET['driverid'])) {
                $result = $driver->get_parameters($_GET['driverid']);
            }
        }
        if ($route->action == "startstop") {
            if (isset($_GET['driverid'])) {
                $result = $driver->startstop($_GET['driverid']);
            }
        }
        /*
            if ($route->action == "getinputs") $result = $input->get_inputs($session['userid']);
        */
        /*if (isset($_GET['driverid']) && $driver->belongs_to_user($session['userid'],get("driverid")))
            {
              if ($route->action == "delete") $result = $driver->delete($session['userid'],get("driverid"));
        
              if ($route->action == 'set') $result = $driver->set_fields(get('driverid'),get('fields'));
              if ($route->action == 'setparameters') $result = $driver->set_parameters(get('driverid'),get('fields'));*/
        /*
              if ($route->action == "process")
              { 
                if ($route->subaction == "add") $result = $input->add_process($process,$session['userid'], get('inputid'), get('processid'), get('arg'), get('newfeedname'), get('newfeedinterval'));
                if ($route->subaction == "list") $result = $input->get_processlist_desc($process, get("inputid"));
                if ($route->subaction == "delete") $result = $input->delete_process(get("inputid"),get('processid'));
                if ($route->subaction == "move") $result = $input->move_process(get("inputid"),get('processid'),get('moveby'));
                if ($route->subaction == "reset") $result = $input->reset_process(get("inputid"));
              }
              * */
        //}
        if (isset($_GET['parameterid'])) {
            if ($route->action == 'set') {
                $result = $driver->set_parameter(get('parameterid'), get('fields'));
            }
        }
    }
    return array('content' => $result);
}
예제 #16
0
 public function getInfo()
 {
     /* Items allocated*/
     $commodity['consumable'] = Consumable::model()->findAll();
     $commodity['monitor'] = Monitor::model()->findAll();
     $commodity['printers'] = Printers::model()->findAll();
     $commodity['devices'] = Devices::model()->findAll();
     $dup = $commodity;
     /* Items available on Loan*/
     $availableOnLoan = 0;
     $thresholdItems = 0;
     $content = '';
     foreach ($commodity as $key => $commo) {
         foreach ($commo as $item) {
             if ($item['available_on_loan'] == 1 || $item['available_on_loan'] == 'Yes') {
                 ++$availableOnLoan;
             }
             if ($key == 'consumable') {
                 $commodity = Commodity::model()->findByAttributes(array('name' => $key));
                 $allocates = Allocate::model()->findAllByAttributes(array('commodity_id' => $commodity['id'], 'cons_id' => $item['id']));
                 if (count($allocates) < $item['threshold']) {
                     ++$thresholdItems;
                 }
             }
         }
     }
     /** Allocated and unallocated **/
     $countAllocated = 0;
     $countUnAllocated = 0;
     $commodity = $dup;
     $unAllocated = Allocate::model()->findAllByAttributes(array('date_out' => NULL));
     $allocated = Allocate::model()->findAll('date_out IS NOT NULL');
     $countAllocated += count($allocated);
     $countUnAllocated += count($unAllocated);
     $content .= '<b style="color:red">' . $availableOnLoan . '</b> item available on loan<br/>';
     $content .= '<b style="color:red">' . $thresholdItems . '</b> item below threshold<br/>';
     $content .= '<b style="color:red">' . $countAllocated . '</b> item allocated<br/>';
     $content .= '<b style="color:red">' . $countUnAllocated . '</b> item unallocated<br/>';
     /* Items below threshold*/
     return $content;
 }
예제 #17
0
                 $display = $stmt3->result(0);
             } else {
                 $display = $row['plugin'];
             }
         }
         $plugins[] = array('id' => $count, 'name' => $plugin_name, 'type' => $plugin_type, 'disp' => $display, 'val' => $plugin_name);
         $count++;
     }
     $tpl->assign('plugins', $plugins);
     $tpl->display('settings_specific_scan_plugins.tpl');
     break;
 case "x_do_get_specific_scan_devices":
     require_once _ABSPATH . '/lib/Clusters.php';
     require_once _ABSPATH . '/lib/Devices.php';
     $_clu = Clusters::getInstance();
     $_dev = Devices::getInstance();
     $profile_id = import_var('profile_id', 'P');
     $count = 1;
     $devices = array();
     $sql = array('devices' => "SELECT * FROM profile_machine_list WHERE profile_id=':1';");
     $stmt1 = $db->prepare($sql['devices']);
     $stmt1->execute($profile_id);
     while ($row = $stmt1->fetch_assoc()) {
         $type = '';
         $device = '';
         // determine the device type here; cluster,registered,etc
         $type = $_dev->determine_device_type($row['machine']);
         // strip off the device type to only get back the device name
         // aka the cluster name, whitelist entry, vhost, etc
         $device = $_dev->strip_device_type($row['machine']);
         /**
$sql = "SELECT distinct HEX(h.id) as id, h.hostname, MAX(ac.day) as log\n                FROM alienvault.host_net_reference hn, alienvault.host h\n                LEFT JOIN alienvault_siem.ac_acid_event ac ON ac.src_host = h.id\n                WHERE h.id=hn.host_id AND hn.net_id=UNHEX(?) AND h.id NOT IN (Select host_id from host_types)\n                GROUP BY h.id\n                ";
$params = array($id);
$asset_list = array();
if ($rs = $conn->Execute($sql, $params)) {
    while (!$rs->EOF) {
        try {
            $ips = Asset_host_ips::get_ips_to_string($conn, $rs->fields['id']);
        } catch (Exception $e) {
            $ips = '';
        }
        $asset_list[] = array('id' => $rs->fields['id'], 'name' => $rs->fields["hostname"], 'ip' => $ips, 'log' => $rs->fields["log"]);
        $rs->MoveNext();
    }
}
try {
    $devices = new Devices($conn);
    $dev_list = $devices->get_devices();
} catch (Exception $e) {
    $dev_list = array();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title> <?php 
echo _("OSSIM Framework");
?>
 </title>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <meta http-equiv="Pragma" content="no-cache"/>
예제 #19
0
 /**
  * Deletes a device if $_GET['id'] is present.
  * Redirects back to index.
  */
 public function devices_deleteAction()
 {
     if (isset($_GET['id'])) {
         Devices::findFirst(array('conditions' => 'id = ?1', 'bind' => array(1 => intval($_GET['id']))))->delete();
     }
     return (new Response())->redirect('settings/index#devices');
 }
예제 #20
0
<?php

/**
 */
if (session_id() == '') {
    require_once LIB_PATH . "session_php.class.php";
    $session = new PbSessions();
}
$wap_theme_name = "";
require APP_ROOT . 'languages' . DS . $app_lang . DS . 'template.room.inc.php';
require CACHE_PATH . "cache_membergroup.php";
require APP_ROOT . './libraries/device.class.php';
$smarty->template_dir = "template/";
$smarty->setCompileDir("wap" . DS);
$smarty->flash_layout = "flash";
$device = new Devices();
$device_id = $device->getHandsetId();
setvar("Device", $device->getHandsetFullname());
if (isset($_GET['msisdn'])) {
    $_SESSION['msisdn'] = $_GET['msisdn'];
}
if (!isset($_SESSION['msisdn'])) {
    pheader("location:" . URL . "wap/msisdn.php?forward=" . urlencode(pb_get_host() . $_SERVER['REQUEST_URI']));
    //echo urlencode(pb_get_host().$_SERVER['REQUEST_URI'] ); exit;
}
if (!empty($_SESSION['msisdn'])) {
    setvar("msisdn", "Xin chào: " . $_SESSION['msisdn']);
} else {
    setvar("msisdn", "Chưa nhận diện được số điện thoại!");
}
$today_start = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
예제 #21
0
function import_assets_from_csv($filename, $iic, $ctx, $import_type)
{
    //Process status
    $summary = array('general' => array('status' => '', 'data' => '', 'statistics' => array('total' => 0, 'warnings' => 0, 'errors' => 0, 'saved' => 0)), 'by_hosts' => array());
    $db = new ossim_db();
    $conn = $db->connect();
    $str_data = file_get_contents($filename);
    if ($str_data === FALSE) {
        $summary['general']['status'] = 'error';
        $summary['general']['data']['errors'] = _('Failed to read data from CSV file');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    $array_data = preg_split('/\\n|\\r/', $str_data);
    foreach ($array_data as $k => $v) {
        if (trim($v) != '') {
            $data[] = explode('";"', trim($v));
        }
    }
    /*************************************************************************************************************************************
     * From asset section:
     *  - Version 4.x.x or higher: "IP (IP1,IP2,...)";"Hostname";"FQDNs(FQDN1,FQDN2,...)";"Description";"Asset value";"Operating System";
     *                   "Latitude";"Longitude";"Host ID";"External Asset";"Device Types(Type1,Type2,...)"
     *
     *  - Version 3.x.x: "IP"*;"Hostname";"FQDNs(FQDN1,FQDN2,...)";"Description";"Asset value";"Sensors(Sensor1,Sensor2,...)";
     *                   "Operating System";"Latitude";"Longitude"
     *
     * From welcome wizard:
     *  - Version 4.x.x or higher: "IP (IP1,IP2,...)";"Hostname";"Description";"Operating System";"Device Type(Type1,Type2,...)"
     *
     **************************************************************************************************************************************/
    //Check file size
    if (count($data) <= 0 || count($data) == 1 && preg_match('/IP/', $data[0][0])) {
        $summary['general']['status'] = 'error';
        $summary['general']['data'] = _('CSV file is empty');
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    //Check importation type and headers
    $csv_headers = array();
    if ($import_type == 'hosts') {
        if (preg_match('/Operating System/', $data[0][5]) || preg_match('/Sensors/', $data[0][5])) {
            $csv_headers = array_shift($data);
        } else {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Headers not found');
            $summary['general']['statistics']['errors'] = 1;
            return $summary;
        }
    }
    //Setting total hosts to import
    $summary['general']['statistics']['total'] = count($data);
    //Getting all Operating System
    $all_os = Properties::get_all_os();
    //Getting devices types
    $all_devices = array();
    $aux_all_devices = Devices::get_all_for_filter($conn);
    $_all_devices = $aux_all_devices[0];
    foreach ($_all_devices as $d_data) {
        $d_key = $d_data['type_name'];
        $d_key .= $d_data['subtype_id'] != 0 ? ':' . $d_data['subtype_name'] : '';
        $all_devices[$d_key] = $d_data['type_id'] . ':' . $d_data['subtype_id'];
    }
    //Allowed sensors
    $filters = array('where' => "acl_sensors.entity_id = UNHEX('{$ctx}')");
    $a_sensors = Av_sensor::get_basic_list($conn, $filters);
    $sensor_ids = array_keys($a_sensors);
    if (count($sensor_ids) == 0) {
        $summary['general']['status'] = 'error';
        $s_error_msg = Session::is_pro() ? _('There is no sensors for this context') : _('There is no sensors for this IP address');
        $summary['general']['data'] = $s_error_msg;
        $summary['general']['statistics']['errors'] = 1;
        return $summary;
    }
    Util::disable_perm_triggers($conn, TRUE);
    foreach ($data as $k => $v) {
        //Clean previous errors
        ossim_clean_error();
        $num_line = $k + 1;
        //Set default status
        $summary['by_hosts'][$num_line]['status'] = 'error';
        //Check file format
        $cnd_1 = $import_type == 'hosts' && count($v) < 9;
        $cnd_2 = $import_type == 'welcome_wizard_hosts' && count($v) < 5;
        if ($cnd_1 || $cnd_2) {
            $summary['by_hosts'][$num_line]['errors']['Format'] = _('Number of fields is incorrect');
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Clean values
        $param = array();
        $index = 0;
        $max_index = count($v) - 1;
        foreach ($v as $field) {
            $parameter = trim($field);
            if ($index == 0) {
                $pattern = '/^\\"|^\'/';
                $param[] = preg_replace($pattern, '', $parameter);
            } else {
                if ($index == $max_index) {
                    $pattern = '/\\"$|\'$/';
                    $param[] = preg_replace($pattern, '', $parameter);
                } else {
                    $param[] = $parameter;
                }
            }
            $index++;
        }
        //Values
        $is_in_db = FALSE;
        $host_id = '';
        $sensors = $sensor_ids;
        $csv_ips = preg_replace("/\\s+/", '', $param[0]);
        if (!empty($param[1])) {
            $name = $param[1];
        } else {
            $aux_name = str_replace(' ', '', $csv_ips);
            $aux_name = str_replace(',', '-', $aux_name);
            $name = Asset_host::get_autodetected_name($aux_name);
        }
        if ($import_type == 'hosts') {
            $fqdns = $param[2];
            $descr = $param[3];
            $asset_value = !empty($param[4]) ? $param[4] : 2;
            if (preg_match('/Host ID/', $csv_headers[8])) {
                $os = $param[5];
                $latitude = floatval($param[6]);
                $longitude = floatval($param[7]);
                $external = empty($param[9]) ? 0 : intval($param[9]);
                $csv_devices = $param[10];
            } else {
                $os = $param[6];
                $latitude = floatval($param[7]);
                $longitude = floatval($param[8]);
                $external = 0;
                $csv_devices = '';
            }
        } else {
            $descr = $param[2];
            $os = $param[3];
            $latitude = 0;
            $longitude = 0;
            $asset_value = 2;
            $external = 0;
            $csv_devices = $param[4];
        }
        //Permissions
        $can_i_create_assets = Session::can_i_create_assets();
        $can_i_modify_ips = TRUE;
        //IPs
        if (!ossim_valid($csv_ips, OSS_IP_ADDR, 'illegal:' . _('IP'))) {
            $summary['by_hosts'][$num_line]['errors']['IP'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        }
        //Check Host ID: Is there a host registered in the System?
        $host_ids = Asset_host::get_id_by_ips($conn, $csv_ips, $ctx);
        $host_id = key($host_ids);
        if (!empty($host_id)) {
            $is_in_db = TRUE;
        } else {
            $host_id = Util::uuid();
        }
        // Special case: Forced Host ID [Version 4.x.x or higher]
        if ($import_type == 'hosts' && preg_match('/Host ID/', $csv_headers[8]) && valid_hex32($param[8])) {
            $csv_hosts_id = strtoupper($param[8]);
            if ($is_in_db == TRUE && $csv_hosts_id != $host_id) {
                $id_error_msg = _('Host is already registered in the System with another Host ID');
                $summary['by_hosts'][$num_line]['errors']['Host'] = $id_error_msg;
                $summary['general']['statistics']['errors']++;
                continue;
            } else {
                if ($is_in_db == FALSE) {
                    $host_id = $csv_hosts_id;
                    // Save host ID to insert it
                }
            }
        }
        //Hostname
        if (!empty($iic)) {
            $name = clean_iic($name);
        }
        if (!ossim_valid($name, OSS_HOST_NAME, 'illegal:' . _('Hostname'))) {
            ossim_clean_error();
            $name = Asset_host::create_valid_name($name);
            $warning_msg = _('Hostname does not match with RFC 1123 specifications') . '<br/>' . _('Hostname will be replaced by') . ": <strong>{$name}</strong>";
            $summary['by_hosts'][$num_line]['warnings']['Hostname'] = $warning_msg;
            $summary['by_hosts'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            if (!ossim_valid($name, OSS_HOST_NAME, 'illegal:' . _('Hostname'))) {
                unset($summary['by_hosts'][$num_line]['warnings']);
                $summary['general']['statistics']['warnings']--;
                $summary['by_hosts'][$num_line]['status'] = 'error';
                $summary['by_hosts'][$num_line]['errors']['Hostname'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
        }
        //Description
        if (!ossim_valid($descr, OSS_NULLABLE, OSS_ALL, 'illegal:' . _('Description'))) {
            $summary['by_hosts'][$num_line]['errors']['Description'] = ossim_get_error_clean();
            $summary['general']['statistics']['errors']++;
            continue;
        } else {
            if (mb_detect_encoding($descr . ' ', 'UTF-8,ISO-8859-1') == 'UTF-8') {
                $descr = mb_convert_encoding($descr, 'HTML-ENTITIES', 'UTF-8');
            }
        }
        //Operating System
        $os_pattern = '/' . preg_quote(implode('|', $all_os), '/') . '/';
        $os_pattern = str_replace('\\|', '|', $os_pattern);
        if (!empty($os) && !preg_match($os_pattern, $os)) {
            $warning_msg = _('Operating System unknown');
            $summary['by_hosts'][$num_line]['warnings']['Operating System'] = $warning_msg;
            $summary['by_hosts'][$num_line]['status'] = 'warning';
            $summary['general']['statistics']['warnings']++;
            $os = 'Unknown';
        }
        //Devices Types
        $devices = array();
        $unallowed_devices = array();
        if (!empty($csv_devices)) {
            $aux_devices = explode(',', $csv_devices);
            if (is_array($aux_devices) && !empty($aux_devices)) {
                foreach ($aux_devices as $d_name) {
                    $d_name = trim($d_name);
                    if (array_key_exists($d_name, $all_devices)) {
                        $devices[] = $all_devices[$d_name];
                    } else {
                        $unallowed_devices[] = $d_name;
                    }
                }
                if (!empty($unallowed_devices)) {
                    $warning_msg = _('Some devices could not be added (Type and/or subtype unknown)') . ': ' . implode(',', $unallowed_devices);
                    $summary['by_hosts'][$num_line]['warnings']['Devices'] = $warning_msg;
                    $summary['by_hosts'][$num_line]['status'] = 'warning';
                    $summary['general']['statistics']['warnings']++;
                }
            }
        }
        //Sensor
        if ($is_in_db == FALSE) {
            //Only update host sensors with unregistered hosts
            if ($import_type == 'hosts' && preg_match('/Sensors/', $csv_headers[5])) {
                //Special case: Sensors in CSV file //[Version 3.x.x]
                $sensors = array();
                $_sensors = explode(',', $param[4]);
                if (is_array($_sensors) && !empty($_sensors)) {
                    $_sensors = array_flip($_sensors);
                    if (is_array($a_sensors) && !empty($a_sensors)) {
                        foreach ($a_sensors as $s_id => $s_data) {
                            if (array_key_exists($s_data['ip'], $_sensors)) {
                                $sensors[] = $s_id;
                            }
                        }
                    }
                }
                if (!is_array($sensors) || empty($sensors)) {
                    $s_error_msg = Session::is_pro() ? _('There is no sensors for this context') : _('There is no sensors for this IP address');
                    $summary['by_hosts'][$num_line]['errors']['Sensors'] = $s_error_msg;
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        /***********************************************************
         ********** Only for importation from host section **********
         ***********************************************************/
        if ($import_type == 'hosts') {
            //FQDNs
            if (!ossim_valid($fqdns, OSS_FQDNS, OSS_NULLABLE, 'illegal:' . _('FQDN/Aliases'))) {
                $summary['by_hosts'][$num_line]['errors']['FQDN/Aliases'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
            //Asset
            if (!ossim_valid($asset_value, OSS_DIGIT, 'illegal:' . _('Asset value'))) {
                $summary['by_hosts'][$num_line]['errors']['Asset value'] = ossim_get_error_clean();
                $summary['general']['statistics']['errors']++;
                continue;
            }
            //Latitude
            if (!empty($latitude)) {
                if (!ossim_valid(trim($latitude), OSS_NULLABLE, OSS_DIGIT, OSS_DOT, '\\-', 'illegal:' . _('Latitude'))) {
                    $summary['by_hosts'][$num_line]['errors']['Latitude'] = ossim_get_error_clean();
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
            //Longitude
            if (!empty($longitude)) {
                if (!ossim_valid(trim($longitude), OSS_NULLABLE, OSS_DIGIT, OSS_DOT, '\\-', 'illegal:' . _('Longitude'))) {
                    $summary['by_hosts'][$num_line]['errors']['Longitude'] = ossim_get_error_clean();
                    $summary['general']['statistics']['errors']++;
                    continue;
                }
            }
        }
        //Insert/Update host in database
        if (count($summary['by_hosts'][$num_line]['errors']) == 0) {
            try {
                $host = new Asset_host($conn, $host_id);
                if ($is_in_db == TRUE) {
                    $host->load_from_db($conn, $host_id);
                    $can_i_modify_ips = Asset_host::can_i_modify_ips($conn, $host_id);
                } else {
                    if ($can_i_create_assets == FALSE) {
                        $n_error_msg = _('Host') . ' ' . $name . ' ' . _("not allowed. You don't have permissions to import this host");
                        $summary['by_hosts'][$num_line]['errors']['Net'] = $n_error_msg;
                        $summary['general']['statistics']['errors']++;
                        continue;
                    }
                }
                //Check IPs
                if ($can_i_modify_ips == TRUE) {
                    $aux_ips = explode(',', $csv_ips);
                    foreach ($aux_ips as $ip) {
                        $host_ids = Asset_host::get_id_by_ips($conn, $ip, $ctx);
                        unset($host_ids[$host_id]);
                        if (!empty($host_ids)) {
                            $c_error_msg = _('IP') . ' ' . $csv_ips . ' ' . _("not allowed. IP {$ip} already exists for this entity");
                            $summary['by_hosts'][$num_line]['errors']['IP'] = $c_error_msg;
                            $summary['general']['statistics']['errors']++;
                            break;
                        } else {
                            $cnd_1 = Session::get_net_where() != '' && !Session::only_ff_net();
                            $cnd_2 = Asset_host::is_ip_in_cache_cidr($conn, $ip, $ctx, TRUE);
                            if ($cnd_1 && !$cnd_2) {
                                $c_error_msg = sprintf(_("Error! The IP %s is not allowed. Please check with your account admin for more information"), $csv_ips);
                                $summary['by_hosts'][$num_line]['errors']['IP'] = $c_error_msg;
                                $summary['general']['statistics']['errors']++;
                                break;
                            }
                        }
                    }
                } else {
                    $c_error_msg = _('Host') . ' ' . $name . ': ' . _("IP address not allowed. IP address cannot be modified");
                    $summary['by_hosts'][$num_line]['status'] = 'warning';
                    $summary['general']['warnings']['errors']++;
                    $summary['by_hosts'][$num_line]['warnings']['IP'] = $c_error_msg;
                }
                //Setting new values
                if (count($summary['by_hosts'][$num_line]['errors']) == 0) {
                    $host->set_ctx($ctx);
                    $host->set_name($name);
                    $host->set_descr($descr);
                    if ($is_in_db == FALSE) {
                        if ($can_i_modify_ips == TRUE) {
                            if (is_array($aux_ips) && !empty($aux_ips)) {
                                $ips = array();
                                foreach ($aux_ips as $ip) {
                                    $ips[$ip] = array('ip' => $ip, 'mac' => NULL);
                                }
                                $host->set_ips($ips);
                            }
                        }
                        $host->set_sensors($sensors);
                    }
                    if (!empty($fqdns)) {
                        $host->set_fqdns($fqdns);
                    }
                    $host->set_external($external);
                    $host->set_location($latitude, $longitude);
                    $host->set_asset_value($asset_value);
                    $host->set_devices($devices);
                    $host->save_in_db($conn, FALSE);
                    //Save Operating System
                    if (!empty($os)) {
                        Asset_host_properties::save_property_in_db($conn, $host_id, 3, $os, 2);
                    }
                    $summary['general']['statistics']['saved']++;
                    $summary['by_hosts'][$num_line]['data'] = $is_in_db == TRUE ? _('Asset updated') : _('New asset inserted');
                    //Keep warnings
                    if ($summary['by_hosts'][$num_line]['status'] != 'warning') {
                        $summary['by_hosts'][$num_line]['status'] = 'success';
                    }
                }
            } catch (Exception $e) {
                $summary['by_hosts'][$num_line]['errors']['Database error'] = $e->getMessage();
                $summary['general']['statistics']['errors']++;
            }
        }
    }
    if ($summary['general']['statistics']['saved'] > 0) {
        if ($summary['general']['statistics']['errors'] == 0) {
            $summary['general']['status'] = 'success';
            $summary['general']['data'] = _('All assets have been successfully imported ');
        } else {
            $summary['general']['status'] = 'warning';
            $summary['general']['data'] = _('Some assets cannot be imported');
        }
        Util::disable_perm_triggers($conn, FALSE);
        try {
            Asset_host::report_changes($conn, 'hosts');
        } catch (Exception $e) {
            Av_exception::write_log(Av_exception::USER_ERROR, $e->getMessage());
        }
    } else {
        $summary['general']['statistics']['errors'] = count($data);
        //CSV file is not empty, but all lines are wrong
        if (empty($summary['general']['status'])) {
            $summary['general']['status'] = 'error';
            $summary['general']['data'] = _('Assets cannot be imported');
        }
    }
    @$conn->Execute("REPLACE INTO alienvault.host_net_reference SELECT host.id,net_id FROM alienvault.host, alienvault.host_ip, alienvault.net_cidrs WHERE host.id = host_ip.host_id AND host_ip.ip >= net_cidrs.begin AND host_ip.ip <= net_cidrs.end");
    $db->close();
    return $summary;
}
예제 #22
0
function device_type_list($conn, $page, $search)
{
    $filters = array();
    $filters['limit'] = get_query_limits($page);
    if ($search != '') {
        $search = utf8_decode($search);
        $search = escape_sql($search, $conn);
        $filters['where'] = " (type_name LIKE '%{$search}%' OR subtype_name LIKE '%{$search}%') ";
    }
    try {
        $filters['where'] .= $filters['where'] != '' ? ' AND q.type_id = host_types.type AND q.subtype_id = host_types.subtype' : 'q.type_id = host_types.type AND q.subtype_id = host_types.subtype';
        list($devices, $total) = Devices::get_all_for_filter($conn, ', host_types', $filters, TRUE);
    } catch (Exception $e) {
        $return['error'] = TRUE;
        $return['msg'] = $e->getMessage();
        return $return;
    }
    if ($total > 0) {
        $selected = get_selected_values(8);
    }
    $list = array();
    //Going through the list to format the elements properly:
    foreach ($devices as $device) {
        $_dev = array();
        $sname = $device['subtype_name'] != '' ? '/' . $device['subtype_name'] : '';
        $id = $device['type_id'] . ';' . $device['subtype_id'];
        $name = $device['type_name'] . $sname;
        $md5 = md5($id);
        $_chk = $selected[$md5] != '' ? TRUE : FALSE;
        $_dev = array('id' => $id, 'name' => Util::utf8_encode2($name), 'checked' => $_chk);
        $list[$md5] = $_dev;
    }
    $data['total'] = intval($total);
    $data['list'] = $list;
    $return['error'] = FALSE;
    $return['data'] = $data;
    return $return;
}
예제 #23
0
 /**
  * Create list of machines to scan
  *
  * This function will query the database for the list
  * of all the machines that were specified when the
  * scan was created
  *
  * @param string $profile_id ID of the profile to get machines of
  * @return array Return array of machines listed in profile
  */
 public function getMachines($profile_id)
 {
     require_once _ABSPATH . '/lib/Devices.php';
     require_once _ABSPATH . '/lib/Clusters.php';
     $db = nessquikDB::getInstance();
     $_dev = Devices::getInstance();
     $_clu = Clusters::getInstance();
     $result = array();
     $sql = array('select' => "SELECT machine FROM profile_machine_list WHERE profile_id=':1';");
     $stmt = $db->prepare($sql['select']);
     $stmt->execute($profile_id);
     while ($row = $stmt->fetch_assoc()) {
         $machine = $row['machine'];
         $type = $_dev->determine_device_type($machine);
         /**
          * Clusters are special cases because they conflict with
          * hostnames by not having any special defining characters
          * in them. That's one of the reasons I do the cluster
          * processing here.
          *
          * Another is because in the settings for a specific scan
          * you can add and remove devices. Well, clusters are one
          * of those things you can remove and to distinctly know
          * which device is a cluster, I need to retain the :clu:
          * prefix on the cluster name.
          */
         if ($type == "cluster") {
             $machine_list = array();
             foreach ($cluster as $key => $cluster_id) {
                 $output = array();
                 $output = $_clu->get_cluster($cluster_id);
                 foreach ($output as $key2 => $val2) {
                     // Index 1 is the hostname as pulled from miscomp
                     $hostname = $val2[1];
                     $tmp = array();
                     $tmp = $_dev->get_mac_from_system($hostname);
                     // The first index will hold the IP address
                     array_push($machine_list, $tmp[0]);
                 }
             }
             $result = array_merge($result, $machine_list);
         } else {
             $item = $_dev->strip_device_type($machine);
             if (is_ip($item)) {
                 $result[] = $item;
             } else {
                 if (is_cidr($item)) {
                     $result[] = $item;
                 } else {
                     if (is_vhost($item)) {
                         $result[] = $item;
                     } else {
                         $item = gethostbyname($item);
                         if ($item != '') {
                             $result[] = $item;
                         }
                     }
                 }
             }
         }
     }
     return $result;
 }
 public function actionGeneratePdf()
 {
     $this->layout = 'pdf';
     $model = new Devices('search');
     if (isset($_GET['Devices'])) {
         $model->attributes = $_GET['Devices'];
     }
     // to execute the filters (if is the case)
     $dataProvider = $model->search();
     $dataProvider->pagination = false;
     $mPDF1 = Yii::app()->ePdf->mpdf();
     # You can easily override default constructor's params
     $mPDF1 = Yii::app()->ePdf->mpdf('', 'A5');
     # renderPartial (only 'view' of current controller)
     $mPDF1->WriteHTML($this->renderPartial('admin', array('model' => $model), true));
     # Outputs ready PDF
     $mPDF1->Output();
 }
예제 #25
0
 /**
  * Shows the webtemp image exports for all devices configured.
  * 
  * @return  The webtemp view
  */
 public function webtempAction()
 {
     $this->view->setMainView('layouts/empty');
     $this->view->device = Devices::findFirst(array('conditions' => 'id = ?1', 'order' => 'name', 'bind' => array(1 => intval($_GET['id']))));
 }