/**
 * Title
 *
 * Description
 *
 * @access public
 */
 function poll_device($id)
 {
     $rec = SQLSelectOne("SELECT * FROM modbusdevices WHERE ID='" . (int) $id . "'");
     if (!$rec['ID']) {
         return;
     }
     $rec['CHECK_LATEST'] = date('Y-m-d H:i:s');
     $rec['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + (int) $rec['POLLPERIOD']);
     SQLUpdate('modbusdevices', $rec);
     if ($rec['LINKED_OBJECT'] && $rec['LINKED_PROPERTY'] && ($rec['REQUEST_TYPE'] == 'FC5' || $rec['REQUEST_TYPE'] == 'FC6' || $rec['REQUEST_TYPE'] == 'FC15' || $rec['REQUEST_TYPE'] == 'FC16' || $rec['REQUEST_TYPE'] == 'FC23')) {
         $rec['DATA'] = getGlobal($rec['LINKED_OBJECT'] . '.' . $rec['LINKED_PROPERTY']);
     }
     require_once dirname(__FILE__) . '/ModbusMaster.php';
     $modbus = new ModbusMaster($rec['HOST'], $rec['PROTOCOL']);
     if ($rec['PORT']) {
         $modbus->port = $rec['PORT'];
     }
     if ($rec['REQUEST_TYPE'] == 'FC1') {
         //FC1 Read coils
         try {
             $recData = $modbus->readCoils($rec['DEVICE_ID'], $rec['REQUEST_START'], $rec['REQUEST_TOTAL']);
             if (is_array($recData)) {
                 foreach ($recData as $k => $v) {
                     $recData[$k] = (int) $v;
                 }
             }
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC1 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC2') {
         //FC2 Read input discretes
         try {
             $recData = $modbus->readInputDiscretes($rec['DEVICE_ID'], $rec['REQUEST_START'], $rec['REQUEST_TOTAL']);
             if (is_array($recData)) {
                 foreach ($recData as $k => $v) {
                     $recData[$k] = (int) $v;
                 }
             }
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC2 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC3') {
         //FC3 Read holding registers
         try {
             $recData = $modbus->readMultipleRegisters($rec['DEVICE_ID'], $rec['REQUEST_START'], $rec['REQUEST_TOTAL']);
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC3 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC4') {
         //FC4 Read holding input registers
         try {
             $recData = $modbus->readMultipleInputRegisters($rec['DEVICE_ID'], $rec['REQUEST_START'], $rec['REQUEST_TOTAL']);
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC4 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC5') {
         //FC5 Write single coil
         if ((int) $rec['DATA']) {
             $data_set = array(TRUE);
         } else {
             $data_set = array(FALSE);
         }
         try {
             $modbus->writeSingleCoil($rec['DEVICE_ID'], $rec['REQUEST_START'], $data_set);
         } catch (Exception $e) {
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC5 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC6') {
         //FC6 Write single register
         try {
             $data_set = array((int) $rec['DATA']);
             if ($rec['RESPONSE_CONVERT'] == 'r2f') {
                 $dataTypes = array("REAL");
                 $swapregs = false;
             } elseif ($rec['RESPONSE_CONVERT'] == 'r2fs') {
                 $dataTypes = array("REAL");
                 $swapregs = true;
             } elseif ($rec['RESPONSE_CONVERT'] == 'd2i' || $rec['RESPONSE_CONVERT'] == 'dw2i') {
                 $dataTypes = array("DINT");
                 $swapregs = false;
             } elseif ($rec['RESPONSE_CONVERT'] == 'd2is' || $rec['RESPONSE_CONVERT'] == 'dw2is') {
                 $dataTypes = array("DINT");
                 $swapregs = true;
             } else {
                 $dataTypes = array("INT");
                 $swapregs = false;
             }
             $recData = $modbus->writeSingleRegister($rec['DEVICE_ID'], $rec['REQUEST_START'], $data_set, $dataTypes, $swapregs);
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC6 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC15') {
         //FC15 Write multiple coils
         $data_set = explode(',', $rec['DATA']);
         foreach ($data_set as $k => $v) {
             $data_set[$k] = (bool) $v;
         }
         try {
             $modbus->writeMultipleCoils($rec['DEVICE_ID'], $rec['REQUEST_START'], $data_set);
         } catch (Exception $e) {
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC15 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC16') {
         //FC16 Write multiple registers
         try {
             $data_set = explode(',', $rec['DATA']);
             $dataTypes = array();
             foreach ($data_set as $k => $v) {
                 if ($rec['RESPONSE_CONVERT'] == 'r2f') {
                     $dataTypes[] = "REAL";
                     $data_set[$k] = (double) $v;
                     $swapregs = false;
                 } elseif ($rec['RESPONSE_CONVERT'] == 'r2fs') {
                     $dataTypes[] = "REAL";
                     $data_set[$k] = (double) $v;
                     $swapregs = true;
                 } elseif ($rec['RESPONSE_CONVERT'] == 'd2i' || $rec['RESPONSE_CONVERT'] == 'dw2i') {
                     $dataTypes[] = "DINT";
                     $data_set[$k] = (int) $v;
                     $swapregs = false;
                 } elseif ($rec['RESPONSE_CONVERT'] == 'd2is' || $rec['RESPONSE_CONVERT'] == 'dw2is') {
                     $dataTypes[] = "DINT";
                     $data_set[$k] = (int) $v;
                     $swapregs = true;
                 } else {
                     $data_set[$k] = (int) $v;
                     $dataTypes[] = "INT";
                     $swapregs = false;
                 }
             }
             $recData = $modbus->writeMultipleRegister($rec['DEVICE_ID'], $rec['REQUEST_START'], $data_set, $dataTypes, $swapregs);
         } catch (Exception $e) {
             // Print error information if any
             $rec['LOG'] = date('Y-m-d H:i:s') . " FC16 Error: {$modbus} {$e}\n" . $rec['LOG'];
         }
     } elseif ($rec['REQUEST_TYPE'] == 'FC23') {
         //FC23 Read/Write multiple registers
         //TO-DO
     }
     //echo $rec['LOG'];exit;
     if ($rec['REQUEST_TYPE'] == 'FC1' || $rec['REQUEST_TYPE'] == 'FC2' || $rec['REQUEST_TYPE'] == 'FC3' || $rec['REQUEST_TYPE'] == 'FC4' && is_array($recData)) {
         // PROCESS RESPONSE
         if ($rec['RESPONSE_CONVERT'] == 'r2f') {
             //REAL to Float
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 echo $recData[] = PhpType::bytes2float($bytes, false);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'r2fs') {
             //REAL to Float (swap regs)
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 echo $recData[] = PhpType::bytes2float($bytes, true);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'd2i') {
             //DINT to integer
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 echo $recData[] = PhpType::bytes2signedInt($bytes, false);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'd2is') {
             //DINT to integer (swap regs)
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 echo $recData[] = PhpType::bytes2signedInt($bytes, true);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'dw2i') {
             //DWORD to integer
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 $recData[] = PhpType::bytes2unsignedInt($bytes, false);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'dw2is') {
             //DWORD to integer (swap regs)
             $values = array_chunk($recData, 4);
             $recData = array();
             foreach ($values as $bytes) {
                 $recData[] = PhpType::bytes2unsignedInt($bytes, true);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'i2i') {
             //INT to integer
             $values = array_chunk($recData, 2);
             $recData = array();
             foreach ($values as $bytes) {
                 $recData[] = PhpType::bytes2signedInt($bytes, false);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 'w2i') {
             //WORD to integer
             $values = array_chunk($recData, 2);
             $recData = array();
             foreach ($values as $bytes) {
                 $recData[] = PhpType::bytes2unsignedInt($bytes, false);
             }
         } elseif ($rec['RESPONSE_CONVERT'] == 's') {
             //String
             $recData = array(PhpType::bytes2string($recData));
         } else {
             //
         }
         $result = implode(',', $recData);
         if ($result && $result != $rec['DATA']) {
             $rec['LOG'] = date('Y-m-d H:i:s') . " " . $result . "\n" . $rec['LOG'];
         }
         $rec['DATA'] = $result;
         SQLUpdate('modbusdevices', $rec);
         if ($rec['LINKED_OBJECT'] && $rec['LINKED_PROPERTY']) {
             setGlobal($rec['LINKED_OBJECT'] . '.' . $rec['LINKED_PROPERTY'], $rec['DATA'], array($this->name => '0'));
         }
     } else {
         SQLUpdate('modbusdevices', $rec);
     }
 }
 private function cycleAlive()
 {
     if ($this->_latestAlive == time()) {
         return;
     }
     $this->_latestAlive = time();
     global $cycleName;
     global $websockets_script_started;
     if ($cycleName) {
         setGlobal($cycleName, time(), 1);
     }
     global $websockets_script_started;
     if ($websockets_script_started > 0 && time() - $websockets_script_started > 12 * 60 * 60) {
         exit;
         // restart every 12 hours
     }
 }
 public function tick()
 {
     global $config;
     if (time() - $this->last_check > 3) {
         $queue_data = getGlobal('IRCBot1.pushMessage');
         $this->last_check = time();
         if ($queue_data != '') {
             setGlobal('IRCBot1.pushMessage', '');
             $messages = explode("\n", $queue_data);
             $total = count($messages);
             for ($i = 0; $i < $total; $i++) {
                 if ($messages[$i]) {
                     sendMessage($this->socket, $this->config['channel'], iconv('UTF-8', $config['encoding'], $messages[$i]));
                 }
             }
         }
         setGlobal('cycle_app_ircbotRun', time(), 1);
         if (file_exists('./reboot')) {
             global $db;
             $db->Disconnect();
             exit;
         }
     }
 }
Beispiel #4
0
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function upload(&$out)
 {
     set_time_limit(0);
     global $restore;
     global $file;
     global $file_name;
     global $folder;
     if (!$folder) {
         $folder = IsWindowsOS() ? '/.' : '/';
     } else {
         $folder = '/' . $folder;
     }
     if ($restore != '') {
         //$file=ROOT.'saverestore/'.$restore;
         $file = $restore;
     } elseif ($file != '') {
         copy($file, ROOT . 'saverestore/' . $file_name);
         //$file=ROOT.'saverestore/'.$file_name;
         $file = $file_name;
     }
     umask(0);
     @mkdir(ROOT . 'saverestore/temp', 0777);
     if ($file != '') {
         // && mkdir(ROOT.'saverestore/temp', 0777)
         chdir(ROOT . 'saverestore/temp');
         if (IsWindowsOS()) {
             // for windows only
             exec(DOC_ROOT . '/gunzip ../' . $file, $output, $res);
             exec(DOC_ROOT . '/tar xvf ../' . str_replace('.tgz', '.tar', $file), $output, $res);
             //@unlink('../'.str_replace('.tgz', '.tar', $file));
         } else {
             exec('tar xzvf ../' . $file, $output, $res);
         }
         @unlink(ROOT . 'saverestore/temp' . $folder . '/config.php');
         //print_r($output);exit;
         chdir('../../');
         $ignores = SQLSelect("SELECT * FROM ignore_updates ORDER BY NAME");
         $total = count($ignores);
         for ($i = 0; $i < $total; $i++) {
             $name = $ignores[$i]['NAME'];
             if (is_dir(ROOT . 'saverestore/temp/modules/' . $name)) {
                 $this->removeTree(ROOT . 'saverestore/temp/modules/' . $name);
             }
             if (is_dir(ROOT . 'saverestore/temp/templates/' . $name)) {
                 $this->removeTree(ROOT . 'saverestore/temp/templates/' . $name);
             }
         }
         // UPDATING FILES DIRECTLY
         $this->copyTree(ROOT . 'saverestore/temp' . $folder, ROOT, 1);
         // restore all files
         //if (is_dir(ROOT.'saverestore/temp/'.$folder.'modules')) {
         // code restore
         $source = ROOT . 'modules';
         if ($dir = @opendir($source)) {
             while (($file = readdir($dir)) !== false) {
                 if (Is_Dir($source . "/" . $file) && $file != '.' && $file != '..') {
                     // && !file_exists($source."/".$file."/installed")
                     @unlink(ROOT . "modules/" . $file . "/installed");
                 }
             }
         }
         @unlink(ROOT . "modules/control_modules/installed");
         @SaveFile(ROOT . 'reboot', 'updated');
         //}
         if (file_exists(ROOT . 'saverestore/temp' . $folder . '/dump.sql')) {
             // data restore
             $this->restoredatabase(ROOT . 'saverestore/temp' . $folder . '/dump.sql');
         }
         $this->config['LATEST_UPDATED_ID'] = $out['LATEST_ID'];
         setGlobal('UpdateVersion', $this->config['LATEST_UPDATED_ID']);
         $this->saveConfig();
         global $with_extensions;
         $this->redirect("?mode=clear&ok_msg=" . urlencode("Updates Installed!") . "&with_extensions=" . $with_extensions);
     }
     /*
          require 'Tar.php';
          $tar_object = new Archive_Tar($file);
          if ($tar_object->extract(ROOT.'skins/'.$basename)) {
           $out['OK_EXT']=1;
          } else {
           $out['ERR_FORMAT']=1;
          }
     */
 }
Beispiel #5
0
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function processMessage($path, $value)
 {
     if (preg_match('/\\#$/', $path)) {
         return 0;
     }
     $rec = SQLSelectOne("SELECT * FROM mqtt WHERE PATH LIKE '" . DBSafe($path) . "'");
     if (!$rec['ID']) {
         $rec['PATH'] = $path;
         $rec['TITLE'] = $path;
         $rec['ID'] = SQLInsert('mqtt', $rec);
     }
     $rec['VALUE'] = $value;
     $rec['UPDATED'] = date('Y-m-d H:i:s');
     SQLUpdate('mqtt', $rec);
     if ($rec['LINKED_OBJECT'] && $rec['LINKED_PROPERTY']) {
         setGlobal($rec['LINKED_OBJECT'] . '.' . $rec['LINKED_PROPERTY'], $rec['VALUE'], array('mqtt' => '0'));
     }
 }
Beispiel #6
0
 /**
  * Title
  *
  * Description
  *
  * @access public
  */
 function pollDevice($device_id, $data = 0)
 {
     $rec = SQLSelectOne("SELECT * FROM zwave_devices WHERE ID='" . $device_id . "'");
     $properties = array();
     if (!$data) {
         $data = $this->apiCall('/ZWaveAPI/Run/devices[' . $rec['NODE_ID'] . '].instances[' . $rec['INSTANCE_ID'] . ']');
     }
     if (!$data) {
         return 0;
     }
     if ($rec['CLASS_BASIC']) {
         $value = $data->commandClasses->{"32"}->data->value;
         if ($value !== $rec['BASIC']) {
             $rec['BASIC'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Basic'] = $rec['BASIC'];
     }
     if ($rec['CLASS_SENSOR_BINARY']) {
         // ...
         $value = (int) $data->commandClasses->{"48"}->data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Level'] = $rec['LEVEL'];
     }
     if ($rec['CLASS_SENSOR_MULTILEVEL']) {
         // multiple sensor support required!
         //SENSOR_VALUE
         $values = array();
         for ($i = 0; $i < 255; $i++) {
             if (isset($data->commandClasses->{"49"}->data->{"{$i}"})) {
                 $sensor = $data->commandClasses->{"49"}->data->{"{$i}"};
                 $values[] = $sensor->sensorTypeString->value . ': ' . $sensor->val->value . $sensor->scaleString->value;
                 $properties[$sensor->sensorTypeString->value . ', ' . $sensor->scaleString->value] = $sensor->val->value;
             }
         }
         $value = implode('; ', $values);
         if ($value != $rec['SENSOR_VALUE']) {
             $rec['SENSOR_VALUE'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
     }
     if ($rec['CLASS_THERMOSTAT']) {
         $value = $data->commandClasses->{"64"}->data->{$data->commandClasses->{"64"}->data->mode->value}->modeName->value;
         if ($value != $rec['MODE_VALUE']) {
             $rec['MODE_VALUE'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Thermostat mode'] = $rec['MODE_VALUE'];
     }
     if ($rec['CLASS_SWITCH_BINARY']) {
         $value = (int) $data->commandClasses->{"37"}->data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Level'] = $rec['LEVEL'];
     }
     if ($rec['CLASS_SWITCH_MULTILEVEL']) {
         $value = (int) $data->commandClasses->{"38"}->data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Level'] = $rec['LEVEL'];
     }
     if ($rec['CLASS_BATTERY']) {
         $value = (int) $data->commandClasses->{"128"}->data->last->value;
         if ($value != $rec['BATTERY_LEVEL']) {
             $rec['BATTERY_LEVEL'] = $value;
             SQLUpdate('zwave_devices', $rec);
         }
         $properties['Battery'] = $rec['BATTERY_LEVEL'];
     }
     if ($rec['CLASS_METER']) {
         // ...
     }
     foreach ($properties as $k => $v) {
         $prop = SQLSelectOne("SELECT * FROM zwave_properties WHERE DEVICE_ID='" . $rec['ID'] . "' AND UNIQ_ID LIKE '" . DBSafe($k) . "'");
         $prop['DEVICE_ID'] = $rec['ID'];
         $prop['UNIQ_ID'] = $k;
         $prop['TITLE'] = $k;
         $prop['VALUE'] = $v;
         $prop['UPDATED'] = date('Y-m-d H:i:s');
         if ($prop['ID']) {
             SQLUpdate('zwave_properties', $prop);
             if ($prop['LINKED_OBJECT'] && $prop['LINKED_PROPERTY']) {
                 setGlobal($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_PROPERTY'], $prop['VALUE'], array('zwave_properties' => '0'));
             }
         } else {
             $prop['ID'] = SQLInsert('zwave_properties', $prop);
         }
     }
     //print_r($data);exit;
 }
Beispiel #7
0
     }
     if ($_GET['mode'] == "random") {
         $pl = $pl->getSmartPlaylist();
     }
     $pl->play();
 } else {
     if (isset($_GET['type']) && $_GET['type'] == "track") {
         // send file directly if method == direct.
         // otherwise send a playlist.
         // TODO: if method = direct, do things like update playcount.
         // and also validate user (pass username / md5(password) in URL)
         $el =& new jzMediaTrack($_GET['jz_path']);
         $pl =& new jzPlaylist();
         $pl->add($el);
         if (isset($_GET['clip'])) {
             setGlobal("CLIP_MODE", true);
         }
         $pl->play();
     } else {
         // Ok, was this a radio playlist or standard
         if (isset($_GET['mode']) && $_GET['mode'] == "radio") {
             // Let's set the limit
             $lim = isset($_GET['limit']) ? $_GET['limit'] : false;
             // Now let's get the tracks from the primary artist
             $el =& new jzMediaNode($_GET['jz_path']);
             $pl = new jzPlaylist();
             $pl->add($el);
             $pl = $pl->getSmartPlaylist($lim, "radio");
             $pl->play();
         } else {
             $el =& new jzMediaNode($_GET['jz_path']);
Beispiel #8
0
<?php

chdir(dirname(__FILE__) . '/../');
include_once "./config.php";
include_once "./lib/loader.php";
include_once "./lib/threads.php";
set_time_limit(0);
// connecting to database
$db = new mysql(DB_HOST, '', DB_USER, DB_PASSWORD, DB_NAME);
include_once "./load_settings.php";
include_once DIR_MODULES . "control_modules/control_modules.class.php";
$ctl = new control_modules();
if (defined('ONEWIRE_SERVER')) {
    include_once DIR_MODULES . 'onewire/onewire.class.php';
    $onw = new onewire();
} else {
    exit;
}
while (1) {
    echo date("H:i:s") . " running " . basename(__FILE__) . "\n";
    setGlobal(str_replace('.php', '', basename(__FILE__)) . 'Run', time());
    // check all 1wire devices
    $onw->updateDevices();
    $onw->updateDisplays();
    if (file_exists('./reboot') || $_GET['onetime']) {
        $db->Disconnect();
        exit;
    }
    sleep(1);
}
DebMes("Unexpected close of cycle: " . basename(__FILE__));
Beispiel #9
0
    $object_rec['CLASS_ID'] = $class_rec['ID'];
    SQLUpdate('objects', $object_rec);
}
foreach ($known_fields as $k => $v) {
    $prop_rec = SQLSelectOne("SELECT * FROM properties WHERE TITLE LIKE '" . DBSafe($k) . "' AND CLASS_ID = '" . $object_rec['CLASS_ID'] . "'");
    if (!$prop_rec['ID']) {
        $prop_rec['CLASS_ID'] = $object_rec['CLASS_ID'];
        $prop_rec['TITLE'] = $k;
        $prop_rec['KEEP_HISTORY'] = 7;
        $prop_rec['ID'] = SQLInsert('properties', $prop_rec);
    }
}
$res = '';
$updated = array();
foreach ($known_fields as $k => $v) {
    if ($v < 0) {
        continue;
    }
    $res .= $k . ' = ' . $data[(int) $v] . "\n";
    $old_value = getGlobal('ws.' . $k);
    if ($old_value != $data[(int) $v]) {
        $updated[$k] = 1;
        setGlobal('ws.' . $k, $data[(int) $v]);
    }
}
if ($updated['pressure']) {
    setGlobal('ws.pressureRt', round((double) getGlobal('ws.pressure') / 1.33), 1);
}
echo "OK";
$db->Disconnect();
// closing database connection
 function updateDevice($id)
 {
     if (!defined('ONEWIRE_SERVER')) {
         return 0;
     }
     $rec = SQLSelectOne("SELECT * FROM owdevices WHERE ID='" . $id . "'");
     if (!$rec['ID']) {
         return 0;
     }
     $ow = new OWNet(ONEWIRE_SERVER);
     $device = '/' . $rec['UDID'];
     $rec['CHECK_LATEST'] = date('Y-m-d H:i:s');
     $rec['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + (int) $rec['ONLINE_INTERVAL']);
     $old_status = $rec['STATUS'];
     $tmp = $ow->get($device, OWNET_MSG_DIR, false);
     if (!$tmp) {
         $rec['STATUS'] = 0;
     } else {
         $rec['STATUS'] = 1;
     }
     SQLUpdate('owdevices', $rec);
     if ($rec['STATUS'] != $old_status && ($rec['SCRIPT_ID'] || $rec['CODE'])) {
         $params = array();
         $params['DEVICE'] = $device;
         $params['STATUS'] = $rec['STATUS'];
         $params['STATUS_CHANGED'] = 1;
         if ($rec['SCRIPT_ID']) {
             runScript($rec['SCRIPT_ID'], $params);
         } elseif ($rec['CODE']) {
             try {
                 $code = $rec['CODE'];
                 $success = eval($code);
                 if ($success === false) {
                     DebMes("Error in 1-wire action code: " . $code);
                 }
             } catch (Exception $e) {
                 DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
             }
         }
     }
     if (!$rec['STATUS']) {
         return 0;
     }
     $changed_values = array();
     $changed = 0;
     $properties = explode(',', $tmp);
     $totalp = count($properties);
     for ($ip = 0; $ip < $totalp; $ip++) {
         $sysname = str_replace($device . '/', '', $properties[$ip]);
         //echo $properties[$ip]." (".$sysname."): ";
         $prec = SQLSelectOne("SELECT * FROM owproperties WHERE DEVICE_ID='" . $rec['ID'] . "' AND SYSNAME='" . DBSafe($sysname) . "'");
         if (!$prec['ID']) {
             $prec['DEVICE_ID'] = $rec['ID'];
             $prec['SYSNAME'] = $sysname;
             $prec['PATH'] = $properties[$ip];
             $prec['ID'] = SQLInsert('owproperties', $prec);
         }
         $old_value = $prec['VALUE'];
         $value = $ow->get($properties[$ip], OWNET_MSG_READ, false);
         if (is_null($value)) {
             $ow->get("/", OWNET_MSG_DIR, false);
             // hack. for some reason it didn't work correct without it on some devices
             $value = $ow->get($properties[$ip], OWNET_MSG_READ, false);
         }
         if (!is_null($value)) {
             $value = iconv("CP1251", "UTF-8", $value);
             // value updated
             $prec['VALUE'] = $value;
             $prec['UPDATED'] = date('Y-m-d H:i:s');
             $prec['CHECK_LATEST'] = $prec['UPDATED'];
             SQLUpdate('owproperties', $prec);
             //$rec['LOG']=date('Y-m-d H:i:s')." ".$prec['SYSNAME'].": ".$prec['VALUE']."\n".$rec['LOG'];
             //SQLUpdate('owdevices', $rec);
             if ($prec['LINKED_OBJECT'] && $prec['LINKED_PROPERTY']) {
                 setGlobal($prec['LINKED_OBJECT'] . '.' . $prec['LINKED_PROPERTY'], $prec['VALUE'], array($this->name => '0'));
             }
             if ($old_value != $value) {
                 $changed = 1;
                 $changed_values[$prec['SYSNAME']] = array('OLD_VALUE' => $old_value, 'VALUE' => $prec['VALUE']);
             }
         }
     }
     if ($changed) {
         $params = $changed_values;
         $params['DEVICE'] = $device;
         if ($rec['SCRIPT_ID']) {
             runScript($rec['SCRIPT_ID'], $params);
         } elseif ($rec['CODE']) {
             try {
                 $code = $rec['CODE'];
                 $success = eval($code);
                 if ($success === false) {
                     DebMes("Error in code: " . $code);
                 }
             } catch (Exception $e) {
                 DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
             }
         }
     }
 }
Beispiel #11
0
 /**
 * FrontEnd
 *
 * Module frontend
 *
 * @access public
 */
 function usual(&$out)
 {
     /*
     $this->getConfig();
     if ($this->config['ENABLED'] && $_SERVER['REQUEST_URI']=='/') {
      echo "<html><head><title>".SETTINGS_SITE_TITLE."</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><link href=\"/stl.css\" rel=\"stylesheet\" type=\"text/css\"/></head><body>".$this->config['CONTENT']."</body></html>";
      exit;
     }
     */
     global $play;
     global $rnd;
     global $rnd;
     global $session;
     global $play_terminal;
     global $terminal_id;
     if ($this->play) {
         $play = $this->play;
     }
     if ($this->terminal_id) {
         $terminal_id = $this->terminal_id;
     }
     if ($terminal_id) {
         $terminal = SQLSelectOne("SELECT * FROM terminals WHERE ID='" . (int) $terminal_id . "'");
         $session->data['PLAY_TERMINAL'] = $terminal['NAME'];
     }
     if ($session->data['PLAY_TERMINAL'] == '') {
         $session->data['PLAY_TERMINAL'] = $session->data['TERMINAL'];
     }
     if ($play_terminal != '') {
         $session->data['PLAY_TERMINAL'] = $play_terminal;
     }
     if ($session->data['PLAY_TERMINAL'] != '') {
         $terminal = SQLSelectOne("SELECT * FROM terminals WHERE NAME='" . DBSafe($session->data['PLAY_TERMINAL']) . "'");
     }
     if (!$terminal['HOST']) {
         $terminal['HOST'] = 'localhost';
     }
     if (!$play && $session->data['LAST_PLAY']) {
         $play = $session->data['LAST_PLAY'];
     } elseif ($play) {
         $session->data['LAST_PLAY'] = $play;
     }
     if ($play != '') {
         $out['PLAY'] = $play;
     }
     if ($rnd != '') {
         $out['RND'] = $rnd;
     }
     $current_level = getGlobal('ThisComputer.volumeLevel');
     for ($i = 0; $i <= 100; $i += 5) {
         $rec = array('VALUE' => $i);
         if ($i == $current_level) {
             $rec['SELECTED'] = 1;
         }
         $out['VOLUMES'][] = $rec;
     }
     global $ajax;
     if ($ajax != '') {
         global $command;
         if ($command != '') {
             if (!$this->intCall) {
                 echo $command . ' ';
             }
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             if ($terminal['PLAYER_USERNAME'] || $terminal['PLAYER_PASSWORD']) {
                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                 curl_setopt($ch, CURLOPT_USERPWD, $terminal['PLAYER_USERNAME'] . ':' . $terminal['PLAYER_PASSWORD']);
             }
             if (!$terminal['PLAYER_PORT'] && $terminal['PLAYER_TYPE'] == 'foobar') {
                 $terminal['PLAYER_PORT'] = '8888';
             } elseif (!$terminal['PLAYER_PORT'] && $terminal['PLAYER_TYPE'] == 'xbmc') {
                 $terminal['PLAYER_PORT'] = '8080';
             } elseif (!$terminal['PLAYER_PORT']) {
                 $terminal['PLAYER_PORT'] = '80';
             }
             if ($terminal['PLAYER_TYPE'] == 'vlc' || $terminal['PLAYER_TYPE'] == '') {
                 $terminal['PLAYER_PORT'] = '80';
                 if ($command == 'refresh') {
                     $out['PLAY'] = preg_replace('/\\\\$/is', '', $out['PLAY']);
                     $out['PLAY'] = preg_replace('/\\/$/is', '', $out['PLAY']);
                     if (preg_match('/^http/', $out['PLAY'])) {
                         $path = urlencode($out['PLAY']);
                     } else {
                         $path = urlencode('' . str_replace('/', "\\", $out['PLAY']));
                     }
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_play&param=" . $path);
                     //echo $path;exit;
                     $res = curl_exec($ch);
                 }
                 if ($command == 'fullscreen') {
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_fullscreen");
                     $res = curl_exec($ch);
                 }
                 if ($command == 'pause') {
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_pause");
                     $res = curl_exec($ch);
                 }
                 if ($command == 'next') {
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_next");
                     $res = curl_exec($ch);
                 }
                 if ($command == 'prev') {
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_prev");
                     $res = curl_exec($ch);
                 }
                 if ($command == 'close') {
                     curl_setopt($ch, CURLOPT_URL, "http://" . $terminal['HOST'] . ":" . $terminal['PLAYER_PORT'] . "/rc/?command=vlc_close");
                     $res = curl_exec($ch);
                 }
                 if ($command == 'volume') {
                     global $volume;
                     setGlobal('ThisComputer.volumeLevel', $volume);
                     callMethod('ThisComputer.VolumeLevelChanged', array('VALUE' => $volume, 'HOST' => $terminal['HOST']));
                 }
             } elseif ($terminal['PLAYER_TYPE'] == 'xbmc') {
                 include DIR_MODULES . 'app_player/xbmc.php';
             } elseif ($terminal['PLAYER_TYPE'] == 'foobar') {
                 include DIR_MODULES . 'app_player/foobar.php';
             } elseif ($terminal['PLAYER_TYPE'] == 'vlcweb') {
                 include DIR_MODULES . 'app_player/vlcweb.php';
             } elseif ($terminal['PLAYER_TYPE'] == 'mpd') {
                 include DIR_MODULES . 'app_player/mpd.php';
             }
             // close cURL resource, and free up system resources
             curl_close($ch);
         }
         if (!$this->intCall) {
             if ($session->data['PLAY_TERMINAL'] != '') {
                 echo " on " . $session->data['PLAY_TERMINAL'] . ' ';
             }
             echo "OK";
             if ($res) {
                 echo " (" . $res . ")";
             }
             $session->save();
             exit;
         }
     }
     $terminals = SQLSelect("SELECT * FROM terminals WHERE CANPLAY=1 ORDER BY TITLE");
     $total = count($terminals);
     for ($i = 0; $i < $total; $i++) {
         if ($terminals[$i]['NAME'] == $session->data['PLAY_TERMINAL']) {
             $terminals[$i]['SELECTED'] = 1;
             $out['TERMINAL_TITLE'] = $terminals[$i]['TITLE'];
         }
     }
     $out['TERMINALS_TOTAL'] = count($terminals);
     if ($out['TERMINALS_TOTAL'] == 1 || !$session->data['PLAY_TERMINAL']) {
         $terminals[0]['SELECTED'] = 1;
     }
     $out['TERMINALS'] = $terminals;
 }
Beispiel #12
0
/**
 * Summary of processResponse
 * @param mixed $out Out param
 * @return void
 */
function processResponse($out)
{
    global $socket;
    echo date('Y-m-d H:i:s') . ' Incoming: ' . trim($out) . "\n";
    if (preg_match('/REQUEST:(.+)/is', $out, $m)) {
        $url = $m[1];
        if (!preg_match('/^http:/', $url)) {
            $url = 'http://localhost' . $url;
        }
        echo date('Y-m-d H:i:s') . ' Sending request to ' . $url . "\n";
        DebMes('Connect command: ' . $url);
        $content = getURL($url, 0);
    }
    if (preg_match('/PING/is', $out, $m)) {
        $in = "PONG!\n";
        echo date('Y-m-d H:i:s') . ' Sending: ' . $in;
        socket_write($socket, $in, strlen($in));
        echo "OK.\n";
        setGlobal(str_replace('.php', '', basename(__FILE__)) . 'Run', time(), 1);
    }
}
 function processMessage()
 {
     $skip = false;
     $data = $this->telegramBot->getData();
     $this->debug($data);
     $bot_name = $this->config['TLG_BOTNAME'];
     $text = $this->telegramBot->Text();
     $callback = $this->telegramBot->Callback_Data();
     if ($callback) {
         $chat_id = $data["callback_query"]["from"]["id"];
         $username = $data["callback_query"]["message"]["chat"]["username"];
         $fullname = $data["callback_query"]["from"]["first_name"] . ' ' . $data["callback_query"]["from"]["last_name"];
     } else {
         $chat_id = $this->telegramBot->ChatID();
         $username = $this->telegramBot->Username();
         $fullname = $this->telegramBot->FirstName() . ' ' . $this->telegramBot->LastName();
     }
     // поиск в базе пользователя
     $user = SQLSelectOne("SELECT * FROM tlg_user WHERE USER_ID LIKE '" . DBSafe($chat_id) . "';");
     if ($chat_id < 0 && substr($text, 0, strlen('@' . $bot_name)) === '@' . $bot_name) {
         $this->debug("Direct message to bot: " . $bot_name . " ({$text})");
         $text = str_replace('@' . $bot_name, '', $text);
         $source_user = SQLSelectOne("SELECT * FROM tlg_user WHERE TRIM(NAME) LIKE '" . DBSafe(trim($username)) . "'");
         if ($source_user['ID']) {
             $user = $source_user;
             $this->debug("New user check: " . serialize($user));
         } else {
             $this->debug("Cannot find user: "******"Chatid: " . $chat_id . "; Bot-name: " . $bot_name . "; Message: " . $text);
     }
     if ($text == "/start" || $text == "/start@" . $bot_name) {
         // если нет добавляем
         if (!$user['ID']) {
             $user['USER_ID'] = $chat_id;
             $user['CREATED'] = date('Y/m/d H:i:s');
             $user['ID'] = SQLInsert('tlg_user', $user);
             $this->log("Added new user: "******" - " . $chat_id);
         }
         $reply = "Вы зарегистрированы! Обратитесь к администратору для получения доступа к функциям.";
         $content = array('chat_id' => $chat_id, 'text' => $reply);
         $this->sendContent($content);
         $this->updateInfo($user);
         return;
     }
     // пользователь не найден
     if (!$user['ID']) {
         $this->debug("Unknow user: "******"; Message: " . $text);
         return;
     }
     $document = $this->telegramBot->Document();
     $audio = $this->telegramBot->Audio();
     $video = $this->telegramBot->Video();
     $voice = $this->telegramBot->Voice();
     $sticker = $this->telegramBot->Sticker();
     $photo_id = $this->telegramBot->PhotoIdBigSize();
     $location = $this->telegramBot->Location();
     if ($callback) {
         $cbm = $this->telegramBot->Callback_Message();
         $message_id = $cbm["message_id"];
         // get events for callback
         $events = SQLSelect("SELECT * FROM tlg_event WHERE TYPE_EVENT=9 and ENABLE=1;");
         foreach ($events as $event) {
             if ($event['CODE']) {
                 $this->log("Execute code event " . $event['TITLE']);
                 try {
                     eval($event['CODE']);
                 } catch (Exception $e) {
                     registerError('telegram', sprintf('Exception in "%s" method ' . $e->getMessage(), $text));
                 }
             }
             if ($skip) {
                 $this->log("Skip next processing events callback");
                 break;
             }
         }
         return;
     }
     if ($location) {
         $latitude = $location["latitude"];
         $longitude = $location["longitude"];
         $this->log("Get location from " . $chat_id . " - " . $latitude . "," . $longitude);
         if ($user['MEMBER_ID']) {
             $sqlQuery = "SELECT * FROM users WHERE ID = '" . $user['MEMBER_ID'] . "'";
             $userObj = SQLSelectOne($sqlQuery);
             if ($userObj['LINKED_OBJECT']) {
                 $this->log("Update location to user '" . $userObj['LINKED_OBJECT'] . "'");
                 setGlobal($userObj['LINKED_OBJECT'] . '.Coordinates', $latitude . ',' . $longitude);
                 setGlobal($userObj['LINKED_OBJECT'] . '.CoordinatesUpdated', date('H:i'));
                 setGlobal($userObj['LINKED_OBJECT'] . '.CoordinatesUpdatedTimestamp', time());
             }
         }
         // get events for location
         $events = SQLSelect("SELECT * FROM tlg_event WHERE TYPE_EVENT=8 and ENABLE=1;");
         foreach ($events as $event) {
             if ($event['CODE']) {
                 $this->log("Execute code event " . $event['TITLE']);
                 try {
                     eval($event['CODE']);
                 } catch (Exception $e) {
                     registerError('telegram', sprintf('Exception in "%s" method ' . $e->getMessage(), $text));
                 }
             }
             if ($skip) {
                 $this->log("Skip next processing events location");
                 break;
             }
         }
         return;
     }
     //permission download file
     if ($user['DOWNLOAD'] == 1) {
         $type = 0;
         //папку с файлами в настройках
         $storage = $this->config['TLG_STORAGE'] . DIRECTORY_SEPARATOR;
         if ($photo_id) {
             $file = $this->telegramBot->getFile($photo_id);
             $this->log("Get photo from " . $chat_id . " - " . $file["result"]["file_path"]);
             $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . $file["result"]["file_path"];
             $type = 2;
         }
         if ($document) {
             $file = $this->telegramBot->getFile($document["file_id"]);
             $this->log("Get document from " . $chat_id . " - " . $document["file_name"]);
             //print_r($file);
             if (!isset($file['error_code'])) {
                 $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . "document" . DIRECTORY_SEPARATOR . $document["file_name"];
                 if (file_exists($file_path)) {
                     $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . "document" . DIRECTORY_SEPARATOR . $this->telegramBot->UpdateID() . "_" . $document["file_name"];
                 }
             } else {
                 $file_path = "";
                 $this->log($file['description']);
             }
             $type = 6;
         }
         if ($audio) {
             $file = $this->telegramBot->getFile($audio["file_id"]);
             //print_r($file);
             $this->log("Get audio from " . $chat_id . " - " . $file["result"]["file_path"]);
             $path_parts = pathinfo($file["result"]["file_path"]);
             $filename = $path_parts["basename"];
             //use title and performer
             if (isset($audio['title'])) {
                 $filename = $audio['title'] . "." . $path_parts['extension'];
             }
             if (isset($audio['performer'])) {
                 $filename = $audio['performer'] . "-" . $filename;
             }
             $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . "audio" . DIRECTORY_SEPARATOR . $filename;
             $type = 4;
         }
         if ($voice) {
             $file = $this->telegramBot->getFile($voice["file_id"]);
             //print_r($file);
             $this->log("Get voice from " . $chat_id . " - " . $file["result"]["file_path"]);
             $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . $file["result"]["file_path"];
             $type = 3;
         }
         if ($video) {
             $file = $this->telegramBot->getFile($video["file_id"]);
             //print_r($file);
             $this->log("Get video from " . $chat_id . " - " . $file["result"]["file_path"]);
             $file_path = $storage . $chat_id . DIRECTORY_SEPARATOR . $file["result"]["file_path"];
             $type = 5;
         }
         if ($sticker) {
             $file = $this->telegramBot->getFile($sticker["file_id"]);
             $this->log("Get sticker from " . $chat_id . " - " . $sticker["file_id"]);
             $file_path = $storage . 'stickers' . DIRECTORY_SEPARATOR . $file["result"]["file_path"];
             $sticker_id = $sticker["file_id"];
             $type = 7;
         }
         if ($file_path) {
             // качаем файл
             $path_parts = pathinfo($file_path);
             if (!is_dir($path_parts['dirname'])) {
                 mkdir($path_parts['dirname'], 0777, true);
             }
             $this->telegramBot->downloadFile($file["result"]["file_path"], $file_path);
         }
         if ($voice && $user['PLAY'] == 1) {
             //проиграть голосовое сообщение
             $this->log("Play voice from " . $chat_id . " - " . $file_path);
             @touch($file_path);
             playSound($file_path, 1, $level);
         }
         if ($file_path || $sticker_id) {
             // get events
             $events = SQLSelect("SELECT * FROM tlg_event WHERE TYPE_EVENT=" . $type . " and ENABLE=1;");
             foreach ($events as $event) {
                 if ($event['CODE']) {
                     $this->log("Execute code event " . $event['TITLE']);
                     try {
                         eval($event['CODE']);
                     } catch (Exception $e) {
                         registerError('telegram', sprintf('Exception in "%s" method ' . $e->getMessage(), $text));
                     }
                 }
                 if ($skip) {
                     $this->log("Skip next processing events type = " . $type);
                     break;
                 }
             }
         }
         $file_path = "";
     }
     if ($text == "") {
         return;
     }
     $this->log($chat_id . " (" . $username . ", " . $fullname . ")=" . $text);
     // get events for text message
     $events = SQLSelect("SELECT * FROM tlg_event WHERE TYPE_EVENT=1 and ENABLE=1;");
     foreach ($events as $event) {
         if ($event['CODE']) {
             $this->log("Execute code event " . $event['TITLE']);
             try {
                 eval($event['CODE']);
             } catch (Exception $e) {
                 registerError('telegram', sprintf('Exception in "%s" method ' . $e->getMessage(), $text));
             }
         }
         if ($skip) {
             $this->log("Skip next processing events message");
             break;
         }
     }
     // пропуск дальнейшей обработки если с обработчике событий установили $skip
     if ($skip) {
         $this->log("Skip next processing message");
         return;
     }
     if ($user['ID']) {
         //смотрим разрешения на обработку команд
         if ($user['CMD'] == 1) {
             $sql = "SELECT * FROM tlg_cmd where '" . DBSafe($text) . "' LIKE CONCAT(tlg_cmd.TITLE,'%') and (ACCESS=3  OR ((select count(*) from tlg_user_cmd where tlg_user_cmd.USER_ID=" . $user['ID'] . " and tlg_cmd.ID=tlg_user_cmd.CMD_ID)>0 and ACCESS>0))";
             //$this->debug($sql);
             $cmd = SQLSelectOne($sql);
             if ($cmd['ID']) {
                 $this->log("Find command");
                 //нашли команду
                 if ($cmd['CODE']) {
                     $this->log("Execute user`s code command");
                     try {
                         $success = eval($cmd['CODE']);
                         $this->log("Command:" . $text . " Result:" . $success);
                         if ($success == false) {
                             //нет в выполняемом куске кода return
                             //$content = array('chat_id' => $chat_id, 'reply_markup' => $keyb, 'text' => "Ошибка выполнения кода команды ".$text);
                             //$this->telegramBot->sendMessage($content);
                         } else {
                             $keyb = $this->getKeyb($user);
                             $content = array('chat_id' => $chat_id, 'reply_markup' => $keyb, 'text' => $success, 'parse_mode' => 'HTML');
                             $this->sendContent($content);
                             $this->log("Send result to " . $chat_id . ". Command:" . $text . " Result:" . $success);
                         }
                     } catch (Exception $e) {
                         registerError('telegram', sprintf('Exception in "%s" method ' . $e->getMessage(), $text));
                         $keyb = $this->getKeyb($user);
                         $content = array('chat_id' => $chat_id, 'reply_markup' => $keyb, 'text' => "Ошибка выполнения кода команды " . $text);
                         $this->sendContent($content);
                     }
                     return;
                 }
                 // если нет кода, который надо выполнить, то передаем дальше на обработку
             } else {
                 $this->log("Command not found");
             }
         }
         if ($user['PATTERNS'] == 1) {
             say(htmlspecialchars($text), 0, $user['MEMBER_ID'], 'telegram' . $user['ID']);
         }
     }
 }
Beispiel #14
0
 /**
 * BackEnd
 *
 * Module backend
 *
 * @access public
 */
 function admin(&$out)
 {
     if (isset($this->data_source) && !$_GET['data_source'] && !$_POST['data_source']) {
         $out['SET_DATASOURCE'] = 1;
     }
     $this->getConfig();
     $out['MQTT_CLIENT'] = $this->config['MQTT_CLIENT'];
     $out['MQTT_HOST'] = $this->config['MQTT_HOST'];
     $out['MQTT_PORT'] = $this->config['MQTT_PORT'];
     $out['MQTT_QUERY'] = $this->config['MQTT_QUERY'];
     if (!$out['MQTT_HOST']) {
         $out['MQTT_HOST'] = 'localhost';
     }
     if (!$out['MQTT_PORT']) {
         $out['MQTT_PORT'] = '1883';
     }
     if (!$out['MQTT_QUERY']) {
         $out['MQTT_QUERY'] = '/var/now/#';
     }
     $out['MQTT_USERNAME'] = $this->config['MQTT_USERNAME'];
     $out['MQTT_PASSWORD'] = $this->config['MQTT_PASSWORD'];
     $out['MQTT_AUTH'] = $this->config['MQTT_AUTH'];
     if ($this->view_mode == 'update_settings') {
         global $mqtt_client;
         global $mqtt_host;
         global $mqtt_username;
         global $mqtt_password;
         global $mqtt_auth;
         global $mqtt_port;
         global $mqtt_query;
         $this->config['MQTT_CLIENT'] = trim($mqtt_client);
         $this->config['MQTT_HOST'] = trim($mqtt_host);
         $this->config['MQTT_USERNAME'] = trim($mqtt_username);
         $this->config['MQTT_PASSWORD'] = trim($mqtt_password);
         $this->config['MQTT_AUTH'] = (int) $mqtt_auth;
         $this->config['MQTT_PORT'] = (int) $mqtt_port;
         $this->config['MQTT_QUERY'] = trim($mqtt_query);
         $this->saveConfig();
         setGlobal('cycle_mqttControl', 'restart');
         $this->redirect("?");
     }
     if (!$this->config['MQTT_HOST']) {
         $this->config['MQTT_HOST'] = 'localhost';
         $this->saveConfig();
     }
     if (!$this->config['MQTT_PORT']) {
         $this->config['MQTT_PORT'] = '1883';
         $this->saveConfig();
     }
     if (!$this->config['MQTT_QUERY']) {
         $this->config['MQTT_QUERY'] = '/var/now/#';
         $this->saveConfig();
     }
     if ($this->data_source == 'mqtt' || $this->data_source == '') {
         if ($this->view_mode == '' || $this->view_mode == 'search_mqtt') {
             $this->search_mqtt($out);
         }
         if ($this->view_mode == 'edit_mqtt') {
             $this->edit_mqtt($out, $this->id);
         }
         if ($this->view_mode == 'delete_mqtt') {
             $this->delete_mqtt($this->id);
             $this->redirect("?");
         }
     }
 }
Beispiel #15
0
$old_hour = date('h');
if ($_GET['onetime']) {
    $old_minute = -1;
    if (date('i') == '00') {
        $old_hour = -1;
    }
}
$old_date = date('Y-m-d');
$checked_time = 0;
$started_time = time();
echo date("H:i:s") . " running " . basename(__FILE__) . "\n";
while (1) {
    if (time() - $checked_time > 5) {
        $checked_time = time();
        setGlobal(str_replace('.php', '', basename(__FILE__)) . 'Run', time(), 1);
        setGlobal('ThisComputer.uptime', time() - getGlobal('ThisComputer.started_time'));
    }
    $m = date('i');
    $h = date('h');
    $dt = date('Y-m-d');
    if ($m != $old_minute) {
        //echo "new minute\n";
        $sqlQuery = "SELECT ID, TITLE\n                     FROM objects\n                    WHERE {$o_qry}";
        $objects = SQLSelect($sqlQuery);
        $total = count($objects);
        for ($i = 0; $i < $total; $i++) {
            echo date('H:i:s') . ' ' . $objects[$i]['TITLE'] . "->onNewMinute\n";
            getObject($objects[$i]['TITLE'])->setProperty("time", date('Y-m-d H:i:s'));
            getObject($objects[$i]['TITLE'])->raiseEvent("onNewMinute");
        }
        $old_minute = $m;
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function upload(&$out)
 {
     set_time_limit(0);
     global $restore;
     global $file;
     global $file_name;
     global $folder;
     if (!$folder) {
         $folder = IsWindowsOS() ? '/.' : '/';
     } else {
         $folder = '/' . $folder;
     }
     if ($restore != '') {
         //$file=ROOT.'saverestore/'.$restore;
         $file = $restore;
     } elseif ($file != '') {
         copy($file, ROOT . 'saverestore/' . $file_name);
         //$file=ROOT.'saverestore/'.$file_name;
         $file = $file_name;
     }
     umask(0);
     @mkdir(ROOT . 'saverestore/temp', 0777);
     if ($file != '') {
         // && mkdir(ROOT.'saverestore/temp', 0777)
         chdir(ROOT . 'saverestore/temp');
         if (IsWindowsOS()) {
             // for windows only
             exec(DOC_ROOT . '/gunzip ../' . $file, $output, $res);
             exec(DOC_ROOT . '/tar xvf ../' . str_replace('.tgz', '.tar', $file), $output, $res);
             //@unlink('../'.str_replace('.tgz', '.tar', $file));
         } else {
             exec('tar xzvf ../' . $file, $output, $res);
         }
         @unlink(ROOT . 'saverestore/temp' . $folder . '/config.php');
         //print_r($output);exit;
         if (1) {
             chdir('../../');
             if ($this->method == 'direct') {
                 $ignores = SQLSelect("SELECT * FROM ignore_updates ORDER BY NAME");
                 $total = count($ignores);
                 for ($i = 0; $i < $total; $i++) {
                     $name = $ignores[$i]['NAME'];
                     if (is_dir(ROOT . 'saverestore/temp/modules/' . $name)) {
                         $this->removeTree(ROOT . 'saverestore/temp/modules/' . $name);
                     }
                     if (is_dir(ROOT . 'saverestore/temp/templates/' . $name)) {
                         $this->removeTree(ROOT . 'saverestore/temp/templates/' . $name);
                     }
                 }
                 // UPDATING FILES DIRECTLY
                 //$this->copyTree(ROOT.'saverestore/temp'.$folder, ROOT, 1); // restore all files
             } elseif ($this->method == 'ftp') {
                 // UPDATING FILES BY FTP
                 $conn_id = @ftp_connect($this->config['FTP_HOST']);
                 if ($conn_id) {
                     $login_result = @ftp_login($conn_id, $this->config['FTP_USERNAME'], $this->config['FTP_PASSWORD']);
                     if ($login_result) {
                         $systyp = ftp_systype($conn_id);
                         if (@ftp_chdir($conn_id, $this->config['FTP_FOLDER'] . 'saverestore')) {
                             @ftp_chdir($conn_id, $this->config['FTP_FOLDER']);
                             // ok, we're in. updating!
                             $log = '';
                             $files = $this->getLocalFilesTree(ROOT . 'saverestore/temp' . $folder, '.+', 'installed', $log, 0);
                             $total = count($files);
                             $modules_processed = array();
                             for ($i = 0; $i < $total; $i++) {
                                 $file = $files[$i];
                                 $file['REMOTE_FILENAME'] = preg_replace('/^' . preg_quote(ROOT . 'saverestore/temp/' . $folder, '/') . '/is', $this->config['FTP_FOLDER'], $file['FILENAME']);
                                 $file['REMOTE_FILENAME'] = str_replace('//', '/', $file['REMOTE_FILENAME']);
                                 $res_f = $this->ftpput($conn_id, $file['REMOTE_FILENAME'], $file['FILENAME'], FTP_BINARY);
                                 if (preg_match('/\\.class\\.php$/', basename($file['FILENAME'])) && !$modules_processed[dirname($file['REMOTE_FILENAME'])]) {
                                     // if this a module then we should update attributes for folder and remove 'installed' file
                                     $modules_processed[dirname($file['REMOTE_FILENAME'])] = 1;
                                     @ftp_site($conn_id, "CHMOD 0777 " . dirname($file['REMOTE_FILENAME']));
                                     @ftp_delete($conn_id, dirname($file['REMOTE_FILENAME']) . '/installed');
                                 }
                             }
                         } else {
                             $out['FTP_ERR'] = 'Incorrect folder (' . $ftp_folder . ')';
                         }
                     } else {
                         $out['FTP_ERR'] = 'Incorrect username/password';
                     }
                     ftp_close($conn_id);
                 } else {
                     $out['FTP_ERR'] = 'Cannot connect to host (' . $ftp_host . ')';
                     $this->redirect("?err_msg=" . urlencode($out['FTP_ERR']));
                 }
             }
             //if (is_dir(ROOT.'saverestore/temp/'.$folder.'modules')) {
             // code restore
             $source = ROOT . 'modules';
             if ($dir = @opendir($source)) {
                 while (($file = readdir($dir)) !== false) {
                     if (Is_Dir($source . "/" . $file) && $file != '.' && $file != '..') {
                         // && !file_exists($source."/".$file."/installed")
                         @unlink(ROOT . "modules/" . $file . "/installed");
                     }
                 }
             }
             @unlink(ROOT . "modules/control_modules/installed");
             @SaveFile(ROOT . 'reboot', 'updated');
             //}
             if (file_exists(ROOT . 'saverestore/temp' . $folder . '/dump.sql')) {
                 // data restore
                 $this->restoredatabase(ROOT . 'saverestore/temp' . $folder . '/dump.sql');
             }
             $this->config['LATEST_UPDATED_ID'] = $out['LATEST_ID'];
             setGlobal('UpdateVersion', $this->config['LATEST_UPDATED_ID']);
             $this->saveConfig();
             global $with_extensions;
             $this->redirect("?mode=clear&ok_msg=" . urlencode("Updates Installed!") . "&with_extensions=" . $with_extensions);
         }
     }
     /*
          require 'Tar.php';
          $tar_object = new Archive_Tar($file);
          if ($tar_object->extract(ROOT.'skins/'.$basename)) {
           $out['OK_EXT']=1;
          } else {
           $out['ERR_FORMAT']=1;
          }
     */
 }
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function getProperty($id)
 {
     $prop = SQLSelectOne("SELECT * FROM knxproperties WHERE ID='" . $id . "' AND CAN_READ=1");
     if (!$prop['ID']) {
         return false;
     }
     if (!$this->connection) {
         $this->connect(0);
     }
     if ($this->connection) {
         $res = cacheread($this->connection, $prop['ADDRESS'], 0);
         //var_dump($res);
         // $res[0] - addr
         // $res[1] - from
         if (isset($res[2])) {
             $data = array();
             $total = count($res);
             for ($i = 2; $i < $total; $i++) {
                 $data[] = (int) $res[$i];
             }
             $old_value = $prop['DATA_VALUE'];
             if ($prop['DATA_TYPE'] == 'small') {
                 $prop['DATA_VALUE'] = $data[0];
             } elseif ($prop['DATA_TYPE'] == 'p1') {
                 $prop['DATA_VALUE'] = round($data[0] * 100 / 255, 2);
             } elseif ($prop['DATA_TYPE'] == 'f2') {
                 $prop['DATA_VALUE'] = f2_decode($data);
                 // TO-DO: OTHER TYPES!!!
             } elseif ($prop['DATA_TYPE'] == 'b1') {
             } elseif ($prop['DATA_TYPE'] == 'b2') {
             }
             $prop['DATA_RAW'] = implode(',', $data);
             $prop['UPDATED'] = date('Y-m-d H:i:s');
             print_r($prop);
             SQLUpdate('knxproperties', $prop);
             if ($prop['LINKED_OBJECT'] && $prop['LINKED_PROPERTY']) {
                 setGlobal($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_PROPERTY'], $prop['DATA_VALUE'], array($this->name => '0'));
             }
             if ($prop['LINKED_OBJECT'] && $prop['LINKED_METHOD'] && $prop['DATA_VALUE'] != $old_value) {
                 $params = array();
                 $params['VALUE'] = $prop['DATA_VALUE'];
                 callMethod($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_METHOD'], $params);
             }
         }
     }
 }
/**
* Title
*
* Description
*
* @access public
*/
function say($ph, $level = 0, $member_id = 0)
{
    global $commandLine;
    global $voicemode;
    global $noPatternMode;
    global $ignorePushover;
    global $ignorePushbullet;
    global $ignoreGrowl;
    global $ignoreTwitter;
    /*
    if ($commandLine) {
     echo utf2win($ph);
    } else {
     echo $ph;
    }
    */
    $rec = array();
    $rec['MESSAGE'] = $ph;
    $rec['ADDED'] = date('Y-m-d H:i:s');
    $rec['ROOM_ID'] = 0;
    $rec['MEMBER_ID'] = $member_id;
    if ($level > 0) {
        $rec['IMPORTANCE'] = $level;
    }
    $rec['ID'] = SQLInsert('shouts', $rec);
    if ($member_id) {
        //if (!$noPatternMode) {
        include_once DIR_MODULES . 'patterns/patterns.class.php';
        $pt = new patterns();
        $pt->checkAllPatterns($member_id);
        //}
        return;
    }
    if (defined('SETTINGS_HOOK_BEFORE_SAY') && SETTINGS_HOOK_BEFORE_SAY != '') {
        eval(SETTINGS_HOOK_BEFORE_SAY);
    }
    global $ignoreVoice;
    if ($level >= (int) getGlobal('minMsgLevel') && !$ignoreVoice && !$member_id) {
        //$voicemode!='off' &&
        $lang = 'en';
        if (defined('SETTINGS_SITE_LANGUAGE')) {
            $lang = SETTINGS_SITE_LANGUAGE;
        }
        if (defined('SETTINGS_VOICE_LANGUAGE')) {
            $lang = SETTINGS_VOICE_LANGUAGE;
        }
        if (!defined('SETTINGS_TTS_GOOGLE') || SETTINGS_TTS_GOOGLE) {
            $google_file = GoogleTTS($ph, $lang);
        } else {
            $google_file = false;
        }
        if (!defined('SETTINGS_SPEAK_SIGNAL') || SETTINGS_SPEAK_SIGNAL == '1') {
            $passed = time() - (int) getGlobal('lastSayTime');
            if ($passed > 20) {
                // play intro-sound only if more than 20 seconds passed from the last one
                setGlobal('lastSayTime', time());
                playSound('dingdong', 1, $level);
            }
        }
        if ($google_file) {
            @touch($google_file);
            playSound($google_file, 1, $level);
        } else {
            safe_exec('cscript ' . DOC_ROOT . '/rc/sapi.js ' . $ph, 1, $level);
        }
    }
    if (!$noPatternMode) {
        include_once DIR_MODULES . 'patterns/patterns.class.php';
        $pt = new patterns();
        $pt->checkAllPatterns($member_id);
    }
    if (defined('SETTINGS_PUSHOVER_USER_KEY') && SETTINGS_PUSHOVER_USER_KEY && !$ignorePushover) {
        include_once ROOT . 'lib/pushover/pushover.inc.php';
        if (defined('SETTINGS_PUSHOVER_LEVEL')) {
            if ($level >= SETTINGS_PUSHOVER_LEVEL) {
                postToPushover($ph);
            }
        } elseif ($level > 0) {
            postToPushover($ph);
        }
    }
    if (defined('SETTINGS_PUSHBULLET_KEY') && SETTINGS_PUSHBULLET_KEY && !$ignorePushbullet) {
        include_once ROOT . 'lib/pushbullet/pushbullet.inc.php';
        if (defined('SETTINGS_PUSHBULLET_PREFIX') && SETTINGS_PUSHBULLET_PREFIX) {
            $prefix = SETTINGS_PUSHBULLET_PREFIX . ' ';
        } else {
            $prefix = '';
        }
        if (defined('SETTINGS_PUSHBULLET_LEVEL')) {
            if ($level >= SETTINGS_PUSHBULLET_LEVEL) {
                postToPushbullet($prefix . $ph);
            }
        } elseif ($level > 0) {
            postToPushbullet($prefix . $ph);
        }
    }
    if (defined('SETTINGS_GROWL_ENABLE') && SETTINGS_GROWL_ENABLE && $level >= SETTINGS_GROWL_LEVEL && !$ignoreGrowl) {
        include_once ROOT . 'lib/growl/growl.gntp.php';
        $growl = new Growl(SETTINGS_GROWL_HOST, SETTINGS_GROWL_PASSWORD);
        $growl->setApplication('MajorDoMo', 'Notifications');
        //$growl->registerApplication('http://localhost/img/logo.png');
        $growl->notify($ph);
    }
    if (defined('SETTINGS_TWITTER_CKEY') && SETTINGS_TWITTER_CKEY && !$ignoreTwitter) {
        postToTwitter($ph);
    }
    if (defined('SETTINGS_HOOK_AFTER_SAY') && SETTINGS_HOOK_AFTER_SAY != '') {
        eval(SETTINGS_HOOK_AFTER_SAY);
    }
}
Beispiel #19
0
<?php

chdir(dirname(__FILE__) . '/../');
include_once "./config.php";
include_once "./lib/loader.php";
include_once "./lib/threads.php";
set_time_limit(0);
// connecting to database
$db = new mysql(DB_HOST, '', DB_USER, DB_PASSWORD, DB_NAME);
include_once "./load_settings.php";
if (defined('DISABLE_WEBSOCKETS') && DISABLE_WEBSOCKETS == 1) {
    echo "Web-sockets disabled\n";
    exit;
}
include_once DIR_MODULES . "control_modules/control_modules.class.php";
include_once DIR_MODULES . 'scenes/scenes.class.php';
$scenes = new scenes();
include_once DIR_MODULES . 'commands/commands.class.php';
$commands = new commands();
//Define('DEBUG_WEBSOCKETS', 1);
$websockets_script_started = time();
$cycleName = str_replace('.php', '', basename(__FILE__)) . 'Run';
setGlobal($cycleName, time(), 1);
require_once './lib/websockets/server/server.php';
$db->Disconnect();
// closing database connection
Beispiel #20
0
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function checkAllHosts($limit = 1000)
 {
     // ping hosts
     $pings = SQLSelect("SELECT * FROM pinghosts WHERE CHECK_NEXT<=NOW() ORDER BY CHECK_NEXT LIMIT " . $limit);
     $total = count($pings);
     for ($i = 0; $i < $total; $i++) {
         $host = $pings[$i];
         echo "Checking " . $host['HOSTNAME'] . "\n";
         $online_interval = $host['ONLINE_INTERVAL'];
         if (!$online_interval) {
             $online_interval = 60;
         }
         $offline_interval = $host['OFFLINE_INTERVAL'];
         if (!$offline_interval) {
             $offline_interval = $online_interval;
         }
         if ($host['STATUS'] == '1') {
             $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $online_interval);
         } else {
             $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $offline_interval);
         }
         SQLUpdate('pinghosts', $host);
         $online = 0;
         // checking
         if (!$host['TYPE']) {
             //ping host
             $online = ping(processTitle($host['HOSTNAME']));
         } else {
             //web host
             $online = getURL(processTitle($host['HOSTNAME']), 0);
             SaveFile("./cached/host_" . $host['ID'] . '.html', $online);
             if ($host['SEARCH_WORD'] != '' && !is_integer(strpos($online, $host['SEARCH_WORD']))) {
                 $online = 0;
             }
             if ($online) {
                 $online = 1;
             }
         }
         if ($online) {
             $new_status = 1;
         } else {
             $new_status = 2;
         }
         $old_status = $host['STATUS'];
         if ($host['COUNTER_REQUIRED']) {
             $old_status_expected = $host['STATUS_EXPECTED'];
             $host['STATUS_EXPECTED'] = $new_status;
             if ($old_status_expected != $host['STATUS_EXPECTED']) {
                 $host['COUNTER_CURRENT'] = 0;
                 $host['LOG'] = date('Y-m-d H:i:s') . ' tries counter reset (status: ' . $host['STATUS_EXPECTED'] . ')' . "\n" . $host['LOG'];
             } elseif ($host['STATUS'] != $host['STATUS_EXPECTED']) {
                 $host['COUNTER_CURRENT']++;
                 $host['LOG'] = date('Y-m-d H:i:s') . ' tries counter increased to ' . $host['COUNTER_CURRENT'] . ' (status: ' . $host['STATUS_EXPECTED'] . ')' . "\n" . $host['LOG'];
             }
             if ($host['COUNTER_CURRENT'] >= $host['COUNTER_REQUIRED']) {
                 $host['STATUS'] = $host['STATUS_EXPECTED'];
                 $host['COUNTER_CURRENT'] = 0;
             } else {
                 $interval = min($online_interval, $offline_interval, 20);
                 $online_interval = $interval;
                 $offline_interval = $interval;
             }
         } else {
             $host['STATUS'] = $new_status;
             $host['STATUS_EXPECTED'] = $host['STATUS'];
             $host['COUNTER_CURRENT'] = 0;
         }
         $host['CHECK_LATEST'] = date('Y-m-d H:i:s');
         if ($host['LINKED_OBJECT'] != '' && $host['LINKED_PROPERTY'] != '') {
             setGlobal($host['LINKED_OBJECT'] . '.' . $host['LINKED_PROPERTY'], $host['STATUS']);
         }
         if ($host['STATUS'] == '1') {
             $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $online_interval);
         } else {
             $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $offline_interval);
         }
         if ($old_status != $host['STATUS']) {
             if ($host['STATUS'] == 2) {
                 $host['LOG'] .= date('Y-m-d H:i:s') . ' Host is offline' . "\n";
             } elseif ($host['STATUS'] == 1) {
                 $host['LOG'] .= date('Y-m-d H:i:s') . ' Host is online' . "\n";
             }
             $tmp = explode("\n", $host['LOG']);
             $total = count($tmp);
             if ($total > 50) {
                 $tmp = array_slice($tmp, 0, 50);
                 $host['LOG'] = implode("\n", $tmp);
             }
         }
         SQLUpdate('pinghosts', $host);
         if ($old_status != $host['STATUS'] && $old_status != 0) {
             // do some status change actions
             $run_script_id = 0;
             $run_code = '';
             if ($old_status == 2 && $host['STATUS'] == 1) {
                 // got online
                 if ($host['SCRIPT_ID_ONLINE']) {
                     $run_script_id = $host['SCRIPT_ID_ONLINE'];
                 } elseif ($host['CODE_ONLINE']) {
                     $run_code = $host['CODE_ONLINE'];
                 }
             } elseif ($old_status == 1 && $host['STATUS'] == 2) {
                 // got offline
                 if ($host['SCRIPT_ID_OFFLINE']) {
                     $run_script_id = $host['SCRIPT_ID_OFFLINE'];
                 } elseif ($host['CODE_OFFLINE']) {
                     $run_code = $host['CODE_OFFLINE'];
                 }
             }
             if ($run_script_id) {
                 //run script
                 runScript($run_script_id);
             } elseif ($run_code) {
                 //run code
                 try {
                     $code = $run_code;
                     $success = eval($code);
                     if ($success === false) {
                         DebMes("Error in hosts online code: " . $code);
                         registerError('ping_hosts', "Error in hosts online code: " . $code);
                     }
                 } catch (Exception $e) {
                     DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                     registerError('ping_hosts', get_class($e) . ', ' . $e->getMessage());
                 }
             }
         }
     }
 }
 /**
 * Receive Set
 *
 * @access public
 */
 function Internal($arr)
 {
     // Node
     $NId = $arr[0];
     $SubType = $arr[4];
     $val = $arr[5];
     if ($NId == "") {
         return;
     }
     // Skip tester present
     if ($NId == 255) {
         // ($NId == 0) ||
         $node = false;
     } else {
         $node = SQLSelectOne("SELECT * FROM msnodes WHERE NID LIKE '" . DBSafe($NId) . "';");
         if (!$node['ID']) {
             $node['NID'] = $NId;
             $node['TITLE'] = $NId;
             $node['ID'] = SQLInsert('msnodes', $node);
         }
     }
     switch ($SubType) {
         // Battery
         case 0:
             if ($node) {
                 $node['BATTERY'] = $val;
                 SQLUpdate('msnodes', $node);
                 if ($node['BAT_OBJECT'] && $node['BAT_PROPERTY']) {
                     setGlobal($node['BAT_OBJECT'] . '.' . $node['BAT_PROPERTY'], $val, array($this->name => '0'));
                 }
             }
             break;
             // Time
         // Time
         case 1:
             $this->cmd($NId . ";255;3;0;1;" . time());
             break;
             // Version
         // Version
         case 2:
             if ($node) {
                 $node['VER'] = $val;
                 SQLUpdate('msnodes', $node);
             }
             break;
             // ID_REQUEST
         // ID_REQUEST
         case 3:
             $this->getConfig();
             if ($this->config['MS_AUTOID'] == '' || $this->config['MS_AUTOID'] == 1) {
                 $nextid = $this->config['MS_NEXTID'];
                 if ($nextid < 255) {
                     // Send new id
                     $this->cmd("255;255;3;0;4;" . $nextid);
                     echo "Req new ID: {$nextid}\n";
                     $nextid++;
                     $this->config['MS_NEXTID'] = $nextid;
                     $this->saveConfig();
                 } else {
                     echo "Req new ID: out of range\n";
                 }
             } else {
                 echo "Req new ID: rejected\n";
             }
             break;
             // INCLUSION_MODE
         // INCLUSION_MODE
         case 5:
             $this->getConfig();
             $this->config['MS_INCLUSION_MODE'] = $val;
             $this->saveConfig();
             break;
             // CONFIG
         // CONFIG
         case 6:
             if ($node) {
                 $node['PID'] = $val;
                 $node['LASTREBOOT'] = date('Y-m-d H:i:s');
                 SQLUpdate('msnodes', $node);
             }
             // Send ansver - metric
             $this->getConfig();
             $this->cmd($NId . ";255;3;0;6;" . $this->config['MS_MEASURE']);
             break;
             // SKETCH_NAME
         // SKETCH_NAME
         case 11:
             if ($node) {
                 $node['SKETCH'] = $val;
                 SQLUpdate('msnodes', $node);
             }
             break;
             // SKETCH_VERSION
         // SKETCH_VERSION
         case 12:
             if ($node) {
                 $node['VER'] = $val;
                 SQLUpdate('msnodes', $node);
             }
             break;
             // @@@ 7 - FIND_PARENT
             // 9 - LOG_MESSAGE
             // @@@ 14 - GATEWAY_READY
     }
 }
Beispiel #22
0
function sg($varname, $value, $no_linked = 0)
{
    return setGlobal($varname, $value, $no_linked);
}
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function readProperty($p_id)
 {
     $prec = SQLSelectOne("SELECT * FROM snmpproperties WHERE ID='" . $p_id . "'");
     if (!$prec['ID']) {
         return;
     }
     $drec = SQLSelectOne("SELECT * FROM snmpdevices WHERE ID='" . $prec['DEVICE_ID'] . "'");
     if (!$drec['ID']) {
         return 0;
     }
     $snmp_oid = $prec['OID'];
     $snmp_host = $drec['HOST'];
     $snmp_community = $drec['READ_COMMUNITY'];
     @($value = snmpget($snmp_host, $snmp_community, $snmp_oid));
     if ($value === false) {
         return false;
     }
     if (preg_match('/^(\\w+:)/', $value, $m)) {
         $value = trim(str_replace($m[1], '', $value));
     }
     $prec['VALUE'] = $value;
     $prec['UPDATED'] = date('Y-m-d H:i:s');
     if ($prec['ONLINE_INTERVAL']) {
         $prec['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $prec['ONLINE_INTERVAL']);
     }
     SQLUpdate('snmpproperties', $prec);
     if ($prec['LINKED_OBJECT'] && $prec['LINKED_PROPERTY']) {
         setGlobal($prec['LINKED_OBJECT'] . '.' . $prec['LINKED_PROPERTY'], $value, array($this->name => '0'));
     }
     return $value;
 }
 /**
  * Title
  *
  * Description
  *
  * @access public
  */
 function pollDevice($device_id, $data = 0)
 {
     $rec = SQLSelectOne("SELECT * FROM zwave_devices WHERE ID='" . $device_id . "'");
     $rec_updated = 0;
     $comments = array();
     $updatedList = array();
     $properties = array();
     $command_classes = array();
     if (!$data) {
         $data = $this->apiCall('/ZWaveAPI/Run/devices[' . $rec['NODE_ID'] . '].instances[' . $rec['INSTANCE_ID'] . ']');
     }
     if (!$data) {
         return 0;
     }
     if ($_GET['debug']) {
         //echo $data->updateTime;exit;
         var_dump($data);
     }
     $updateTime = 0;
     if (!$rec['RAW_DATA']) {
         $rec_updated = 1;
     }
     $rec['RAW_DATA'] = json_encode($data);
     $rec['SENSOR_VALUE'] = '';
     if ($data->data->updateTime) {
         $updateTime = $data->data->updateTime;
     }
     if ($rec['CLASS_BASIC']) {
         $value = $data->commandClasses->{"32"}->data->value;
         if ($value !== $rec['BASIC']) {
             $rec['BASIC'] = $value;
             $rec_updated = 1;
         }
         $command_classes['Basic'] = 32;
         $properties['Basic'] = $rec['BASIC'];
         $updatedList['Basic'] = $data->commandClasses->{"32"}->data->{"updateTime"};
         if ($data->commandClasses->{"32"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"32"}->data->{"updateTime"};
         }
     }
     if ($rec['CLASS_SENSOR_BINARY']) {
         $sensor_data = $data->commandClasses->{"48"}->data;
         if (isset($data->commandClasses->{"48"}->data->{"1"})) {
             $sensor_data = $data->commandClasses->{"48"}->data->{"1"};
         }
         $value = (int) $sensor_data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             $rec_updated = 1;
         }
         $properties['Level'] = $rec['LEVEL'];
         $command_classes['Level'] = 48;
         $updatedList['Level'] = $sensor_data->{"updateTime"};
         if ($sensor_data->{"updateTime"} > $updateTime) {
             $updateTime = $sensor_data->{"updateTime"};
         }
     }
     if ($rec['CLASS_SENSOR_MULTILEVEL']) {
         // multiple sensor support required!
         //SENSOR_VALUE
         $values = array();
         for ($i = 0; $i < 255; $i++) {
             if (isset($data->commandClasses->{"49"}->data->{"{$i}"})) {
                 $sensor = $data->commandClasses->{"49"}->data->{"{$i}"};
                 $values[] = trim($sensor->sensorTypeString->value) . ': ' . $sensor->val->value . $sensor->scaleString->value;
                 if (trim($sensor->sensorTypeString->value)) {
                     $prop_name = trim($sensor->sensorTypeString->value) . ', ' . $sensor->scaleString->value;
                 } else {
                     $prop_name = "Sensor {$i}";
                 }
                 if ($properties[$prop_name]) {
                     $prop_name .= ' (1)';
                 }
                 $properties[$prop_name] = $sensor->val->value;
                 $command_classes[$prop_name] = 49;
                 $updatedList[$prop_name] = $data->commandClasses->{"49"}->data->{"{$i}"}->{"updateTime"};
                 if ($data->commandClasses->{"49"}->data->{"{$i}"}->{"updateTime"} > $updateTime) {
                     $updateTime = $data->commandClasses->{"49"}->data->{"{$i}"}->{"updateTime"};
                 }
             }
         }
         $value = implode('; ', $values);
         if ($value != $rec['SENSOR_VALUE']) {
             $rec['SENSOR_VALUE'] .= $value . ';';
             $rec_updated = 1;
         }
     }
     if ($rec['CLASS_SWITCH_BINARY']) {
         $value = (int) $data->commandClasses->{"37"}->data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             $rec_updated = 1;
         }
         $properties['Level'] = $rec['LEVEL'];
         $command_classes['Level'] = 37;
         $updatedList['Level'] = $data->commandClasses->{"37"}->data->{"updateTime"};
         if ($data->commandClasses->{"37"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"37"}->data->{"updateTime"};
         }
     }
     if ($rec['CLASS_SWITCH_MULTILEVEL']) {
         $value = (int) $data->commandClasses->{"38"}->data->level->value;
         if ($value !== $rec['LEVEL']) {
             $rec['LEVEL'] = $value;
             $rec_updated = 1;
         }
         $properties['Level'] = $rec['LEVEL'];
         $command_classes['Level'] = 38;
         $updatedList['Level'] = $data->commandClasses->{"38"}->data->{"updateTime"};
         if ($data->commandClasses->{"38"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"38"}->data->{"updateTime"};
         }
         $properties['LevelDuration command (level, duration)'] = '';
     }
     if ($rec['CLASS_BATTERY']) {
         $value = (int) $data->commandClasses->{"128"}->data->last->value;
         if ($value != $rec['BATTERY_LEVEL']) {
             $rec['BATTERY_LEVEL'] = $value;
             $rec_updated = 1;
         }
         $command_classes['Battery'] = 128;
         $properties['Battery'] = $rec['BATTERY_LEVEL'];
         $updatedList['Battery'] = $data->commandClasses->{"128"}->data->{"updateTime"};
         if ($data->commandClasses->{"128"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"128"}->data->{"updateTime"};
         }
     }
     if ($rec['CLASS_METER']) {
         // ... 50
         $values = array();
         for ($i = 0; $i < 255; $i++) {
             if (isset($data->commandClasses->{"50"}->data->{"{$i}"})) {
                 $sensor = $data->commandClasses->{"50"}->data->{"{$i}"};
                 $values[] = trim($sensor->sensorTypeString->value) . ': ' . $sensor->val->value . ' ' . $sensor->scaleString->value;
                 if (trim($sensor->sensorTypeString->value)) {
                     $prop_name = trim($sensor->sensorTypeString->value) . ', ' . $sensor->scaleString->value;
                 } else {
                     $prop_name = "Meter {$i}";
                 }
                 if ($properties[$prop_name]) {
                     $prop_name .= ' (1)';
                 }
                 $command_classes[$prop_name] = 50;
                 $properties[$prop_name] = $sensor->val->value;
                 $updatedList[$prop_name] = $data->commandClasses->{"50"}->data->{"{$i}"}->{"updateTime"};
                 if ($data->commandClasses->{"50"}->data->{"{$i}"}->{"updateTime"} > $updateTime) {
                     $updateTime = $data->commandClasses->{"50"}->data->{"{$i}"}->{"updateTime"};
                 }
             }
         }
         $value = implode('; ', $values);
         if ($value != '') {
             $rec['SENSOR_VALUE'] .= $value . '; ';
             $rec_updated = 1;
         }
     }
     if ($rec['CLASS_SENSOR_ALARM']) {
         // ... $data->commandClasses->{"156"}->data
         if (is_object($data->commandClasses->{"156"}->data->{"0"}->sensorState)) {
             $command_classes['AlarmGeneral'] = 156;
             $properties['AlarmGeneral'] = $data->commandClasses->{"156"}->data->{"0"}->sensorState->value;
             $updatedList['AlarmGeneral'] = $data->commandClasses->{"156"}->data->{"0"}->sensorState->updateTime;
             $value = $properties['AlarmGeneral'];
             if ($value != $rec['LEVEL']) {
                 $rec['LEVEL'] = $value;
                 $rec_updated = 1;
             }
         }
         if (is_object($data->commandClasses->{"156"}->data->{"1"}->sensorState)) {
             $command_classes['AlarmSmoke'] = 156;
             $properties['AlarmSmoke'] = $data->commandClasses->{"156"}->data->{"1"}->sensorState->value;
             $updatedList['AlarmSmoke'] = $data->commandClasses->{"156"}->data->{"1"}->sensorState->updateTime;
         }
         if (is_object($data->commandClasses->{"156"}->data->{"2"}->sensorState)) {
             $command_classes['AlarmCarbonMonoxide'] = 156;
             $properties['AlarmCarbonMonoxide'] = $data->commandClasses->{"156"}->data->{"2"}->sensorState->value;
             $updatedList['AlarmCarbonMonoxide'] = $data->commandClasses->{"156"}->data->{"2"}->sensorState->updateTime;
         }
         if (is_object($data->commandClasses->{"156"}->data->{"3"}->sensorState)) {
             $command_classes['AlarmCarbonDioxide'] = 156;
             $properties['AlarmCarbonDioxide'] = $data->commandClasses->{"156"}->data->{"3"}->sensorState->value;
             $updatedList['AlarmCarbonDioxide'] = $data->commandClasses->{"156"}->data->{"3"}->sensorState->updateTime;
         }
         if (is_object($data->commandClasses->{"156"}->data->{"4"}->sensorState)) {
             $command_classes['AlarmHeat'] = 156;
             $properties['AlarmHeat'] = $data->commandClasses->{"156"}->data->{"4"}->sensorState->value;
             $updatedList['AlarmHeat'] = $data->commandClasses->{"156"}->data->{"4"}->sensorState->updateTime;
         }
         if (is_object($data->commandClasses->{"156"}->data->{"5"}->sensorState)) {
             $command_classes['AlarmFlood'] = 156;
             $properties['AlarmFlood'] = $data->commandClasses->{"156"}->data->{"5"}->sensorState->value;
             $updatedList['AlarmFlood'] = $data->commandClasses->{"156"}->data->{"5"}->sensorState->updateTime;
         }
         if ($data->commandClasses->{"156"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"156"}->data->{"updateTime"};
         }
     }
     if ($rec['CLASS_SCENE_CONTROLLER'] && is_object($data->commandClasses->{"43"}->data->{"currentScene"})) {
         // ... 43
         $properties['CurrentScene'] = $data->commandClasses->{"43"}->data->{"currentScene"}->value;
         if ($data->commandClasses->{"43"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"43"}->data->{"updateTime"};
         }
     } elseif ($rec['CLASS_SCENE_CONTROLLER'] && is_object($data->commandClasses->{"45"}->data->{"currentScene"})) {
         // ... 45
         $properties['CurrentScene'] = $data->commandClasses->{"45"}->data->{"currentScene"}->value;
         if ($data->commandClasses->{"45"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"43"}->data->{"updateTime"};
         }
     }
     if ($rec['CLASS_THERMOSTAT'] && isset($data->commandClasses->{"64"}->data->mode->value)) {
         //$value=$data->commandClasses->{"64"}->data->{$data->commandClasses->{"64"}->data->mode->value}->modeName->value;
         $rec['SENSOR_VALUE'] .= " Mode: " . $data->commandClasses->{"64"}->data->{$data->commandClasses->{"64"}->data->mode->value}->modeName->value . ';';
         $value = $data->commandClasses->{"64"}->data->mode->value;
         if ($value != $rec['MODE_VALUE']) {
             $rec['MODE_VALUE'] = $value;
             $rec_updated = 1;
         }
         $command_classes['Thermostat mode'] = 64;
         $properties['Thermostat mode'] = $rec['MODE_VALUE'];
         $updatedList['Thermostat mode'] = $data->commandClasses->{"64"}->data->{"updateTime"};
         if ($data->commandClasses->{"64"}->data->{"updateTime"} > $updateTime) {
             $updateTime = $data->commandClasses->{"64"}->data->{"updateTime"};
         }
         $comments_str = '';
         for ($i = 0; $i < 255; $i++) {
             if ($data->commandClasses->{"64"}->data->{$i}) {
                 $comments_str .= "{$i} = " . $data->commandClasses->{"64"}->data->{$i}->modeName->value . "; ";
             }
         }
         $comments['Thermostat mode'] = $comments_str;
         if (isset($data->commandClasses->{"67"}->data)) {
             //ThermostatSetPoint
             for ($i = 0; $i < 255; $i++) {
                 if ($data->commandClasses->{"67"}->data->{$i}->val) {
                     $key = 'ThermostatSetPoint ' . $data->commandClasses->{"67"}->data->{$i}->modeName->value;
                     $properties[$key] = $data->commandClasses->{"67"}->data->{$i}->val->value;
                     $command_classes[$key] = 67;
                     if ($data->commandClasses->{"67"}->data->{$i}->scaleString->value) {
                         $comments[$key] = $data->commandClasses->{"67"}->data->{$i}->scaleString->value;
                     }
                 }
             }
         }
         if (isset($data->commandClasses->{"68"}->data->mode->value)) {
             //ThermostatFanMode
             $properties['ThermostatFanOn'] = (int) $data->commandClasses->{"68"}->data->on->value;
             $command_classes['ThermostatFanMode'] = 68;
             $properties['ThermostatFanMode'] = $data->commandClasses->{"68"}->data->mode->value;
             if ($data->commandClasses->{"68"}->data->{"updateTime"} > $updateTime) {
                 $updateTime = $data->commandClasses->{"68"}->data->{"updateTime"};
             }
             $rec['SENSOR_VALUE'] .= " Fan Mode: " . $data->commandClasses->{"68"}->data->{$data->commandClasses->{"68"}->data->mode->value}->modeName->value . ';';
             $comments_str = '';
             for ($i = 0; $i < 255; $i++) {
                 if ($data->commandClasses->{"68"}->data->{$i}) {
                     $comments_str .= "{$i} = " . $data->commandClasses->{"68"}->data->{$i}->modeName->value . "; ";
                 }
             }
             $comments['ThermostatFanMode'] = $comments_str;
         }
     }
     if ($updateTime) {
         $properties['updateTime'] = $updateTime;
         $rec['LATEST_UPDATE'] = date('Y-m-d H:i:s', $properties['updateTime']);
         $rec_updated = 1;
     }
     if ($rec_updated) {
         SQLUpdate('zwave_devices', $rec);
     }
     foreach ($properties as $k => $v) {
         $prop = SQLSelectOne("SELECT * FROM zwave_properties WHERE DEVICE_ID='" . $rec['ID'] . "' AND UNIQ_ID LIKE '" . DBSafe($k) . "'");
         $prop['DEVICE_ID'] = $rec['ID'];
         $prop['UNIQ_ID'] = $k;
         $prop['TITLE'] = $k;
         $prop['COMMAND_CLASS'] = $command_classes[$k];
         if ($prop['VALUE'] != $v) {
             $prop['UPDATED'] = date('Y-m-d H:i:s');
         }
         if ($updatedList[$k]) {
             $prop['UPDATED'] = date('Y-m-d H:i:s', $updatedList[$k]);
         }
         $prop['VALUE'] = $v;
         if ($comments[$k]) {
             $prop['COMMENTS'] = $comments[$k];
         }
         if (is_numeric($prop['VALUE']) && $prop['VALUE'] !== '') {
             $prop['VALUE'] = round($prop['VALUE'], 3);
         }
         if ($prop['ID']) {
             SQLUpdate('zwave_properties', $prop);
             if ($prop['VALUE'] !== '') {
                 $validated = 1;
             } else {
                 $validated = 0;
                 continue;
             }
             if ($prop['LINKED_OBJECT']) {
                 if ($prop['CORRECT_VALUE']) {
                     $prop['VALUE'] += (double) $prop['CORRECT_VALUE'];
                 }
             }
             if ($prop['VALIDATE']) {
                 if ((double) $prop['VALUE'] < (double) $prop['VALID_FROM'] || (double) $prop['VALUE'] > (double) $prop['VALID_TO']) {
                     $validated = 0;
                 }
             }
             if ($prop['LINKED_OBJECT'] && $prop['LINKED_PROPERTY'] && $validated) {
                 $old_value = getGlobal($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_PROPERTY']);
                 if ($prop['VALUE'] != $old_value) {
                     setGlobal($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_PROPERTY'], $prop['VALUE'], array($this->name => '0'));
                 }
             }
             if ($prop['LINKED_OBJECT'] && $prop['LINKED_METHOD'] && $validated && ($prop['VALUE'] != $old_value || !$prop['LINKED_PROPERTY'])) {
                 $params = array();
                 $params['VALUE'] = $prop['VALUE'];
                 callMethod($prop['LINKED_OBJECT'] . '.' . $prop['LINKED_METHOD'], $params);
             }
         } else {
             $prop['ID'] = SQLInsert('zwave_properties', $prop);
         }
     }
     //print_r($data);exit;
 }
Beispiel #25
0
 function run()
 {
     global $session;
     Define('ALTERNATIVE_TEMPLATES', 'templates_alt');
     if ($this->action == 'ajaxgetglobal') {
         header("HTTP/1.0: 200 OK\n");
         header('Content-Type: text/html; charset=utf-8');
         $res['DATA'] = getGlobal($_GET['var']);
         echo json_encode($res);
         global $db;
         $db->Disconnect();
         exit;
     }
     if ($this->action == 'ajaxsetglobal') {
         header("HTTP/1.0: 200 OK\n");
         header('Content-Type: text/html; charset=utf-8');
         setGlobal($_GET['var'], $_GET['value']);
         $res['DATA'] = 'OK';
         echo json_encode($res);
         global $db;
         $db->Disconnect();
         exit;
     }
     if ($this->action == 'getlatestnote') {
         header("HTTP/1.0: 200 OK\n");
         header('Content-Type: text/html; charset=utf-8');
         $msg = SQLSelectOne("SELECT * FROM shouts WHERE MEMBER_ID=0 ORDER BY ID DESC LIMIT 1");
         $res = array();
         $res['DATA'] = $msg['MESSAGE'];
         echo json_encode($res);
         global $db;
         $db->Disconnect();
         exit;
     }
     if ($this->action == 'getlatestmp3') {
         header("HTTP/1.0: 200 OK\n");
         header('Content-Type: text/html; charset=utf-8');
         if ($dir = @opendir(ROOT . "cached/voice")) {
             while (($file = readdir($dir)) !== false) {
                 if (preg_match('/\\.mp3$/', $file)) {
                     $mtime = filemtime(ROOT . "cached/voice" . $file);
                     if (time() - $mtime > 60 * 60 * 24 && $mtime > 0) {
                         //old file, delete?
                         unlink(ROOT . "cached/voice" . $file);
                     } else {
                         $files[] = array('FILENAME' => $file, 'MTIME' => filemtime(ROOT . "cached/voice" . $file));
                     }
                 }
                 if (preg_match('/\\.wav$/', $file)) {
                     $mtime = filemtime(ROOT . "cached/voice" . $file);
                     if (time() - $mtime > 60 * 60 * 24 && $mtime > 0) {
                         //old file, delete?
                         unlink(ROOT . "cached/voice" . $file);
                     }
                 }
             }
             closedir($dir);
         }
         if (is_array($files)) {
             function sortFiles($a, $b)
             {
                 if ($a['MTIME'] == $b['MTIME']) {
                     return 0;
                 }
                 return $a['MTIME'] > $b['MTIME'] ? -1 : 1;
             }
             usort($files, 'sortFiles');
             echo '/cached/voice/' . $files[0]['FILENAME'];
         }
         global $db;
         $db->Disconnect();
         exit;
     }
     if (!defined('SETTINGS_SITE_LANGUAGE') || !defined('SETTINGS_SITE_TIMEZONE') || !defined('SETTINGS_TTS_GOOGLE') || !defined('SETTINGS_GROWL_ENABLE') || !defined('SETTINGS_HOOK_BEFORE_SAY')) {
         $this->action = 'first_start';
     }
     if ($this->action == 'first_start') {
         include DIR_MODULES . 'first_start.php';
     }
     $out["ACTION"] = $this->action;
     $out["TODAY"] = date('l, F d, Y');
     $out["DOC_NAME"] = $this->doc_name;
     global $username;
     if ($username) {
         $user = SQLSelectOne("SELECT * FROM users WHERE USERNAME LIKE '" . DBSafe($username) . "'");
         if (!$user['PASSWORD']) {
             $session->data['SITE_USERNAME'] = $user['USERNAME'];
             $session->data['SITE_USER_ID'] = $user['ID'];
         } else {
             if (!isset($_SERVER['PHP_AUTH_USER'])) {
                 header('WWW-Authenticate: Basic realm="MajorDoMo"');
                 header('HTTP/1.0 401 Unauthorized');
                 echo 'Password required!';
                 exit;
             } else {
                 if ($_SERVER['PHP_AUTH_USER'] == $user['USERNAME'] && $_SERVER['PHP_AUTH_PW'] == $user['PASSWORD']) {
                     $session->data['SITE_USERNAME'] = $user['USERNAME'];
                     $session->data['SITE_USER_ID'] = $user['ID'];
                 } else {
                     header('WWW-Authenticate: Basic realm="MajorDoMo"');
                     header('HTTP/1.0 401 Unauthorized');
                     echo 'Incorrect username/password!';
                     exit;
                 }
             }
         }
     }
     global $terminal;
     if ($terminal) {
         $session->data['TERMINAL'] = $terminal;
     }
     if (preg_match('/^app_\\w+$/is', $this->action) || $this->action == 'xray') {
         $out['APP_ACTION'] = 1;
     }
     if ($this->app_action) {
         $out['APP_ACTION'] = 1;
     }
     $terminals = SQLSelect("SELECT * FROM terminals ORDER BY TITLE");
     $total = count($terminals);
     for ($i = 0; $i < $total; $i++) {
         //!$session->data['TERMINAL'] &&
         if ($terminals[$i]['HOST'] != '' && $_SERVER['REMOTE_ADDR'] == $terminals[$i]['HOST']) {
             $session->data['TERMINAL'] = $terminals[$i]['NAME'];
         }
         if ($terminals[$i]['NAME'] == $session->data['TERMINAL']) {
             $terminals[$i]['SELECTED'] = 1;
             $out['TERMINAL_TITLE'] = $terminals[$i]['TITLE'];
         }
     }
     $out['TERMINALS'] = $terminals;
     if ($total == 1) {
         $out['HIDE_TERMINALS'] = 1;
         $session->data['TERMINAL'] = $terminals[0]['NAME'];
     }
     $users = SQLSelect("SELECT * FROM users ORDER BY NAME");
     $total = count($users);
     for ($i = 0; $i < $total; $i++) {
         if ($users[$i]['USERNAME'] == $session->data['SITE_USERNAME']) {
             $users[$i]['SELECTED'] = 1;
             $out['USER_TITLE'] = $users[$i]['NAME'];
             $out['USER_AVATAR'] = $users[$i]['AVATAR'];
         } elseif (!$session->data['SITE_USERNAME'] && $users[$i]['HOST'] && $users[$i]['HOST'] == $_SERVER['REMOTE_ADDR']) {
             $session->data['SITE_USERNAME'] = $users[$i]['USERNAME'];
             $session->data['SITE_USER_ID'] = $users[$i]['ID'];
             $out['USER_TITLE'] = $users[$i]['NAME'];
             $out['USER_AVATAR'] = $users[$i]['AVATAR'];
         }
         if ($users[$i]['IS_DEFAULT'] == 1) {
             $out['DEFAULT_USERNAME'] = $users[$i]['USERNAME'];
             $out['DEFAULT_USER_ID'] = $users[$i]['ID'];
         }
     }
     $out['USERS'] = $users;
     if ($total == 1) {
         $out['HIDE_USERS'] = 1;
         $session->data['SITE_USERNAME'] = $users[0]['USERNAME'];
         $session->data['SITE_USER_ID'] = $users[0]['ID'];
     }
     if (!$session->data['SITE_USERNAME'] && $out['DEFAULT_USERNAME']) {
         $session->data['SITE_USERNAME'] = $out['DEFAULT_USERNAME'];
         $session->data['SITE_USER_ID'] = $out['DEFAULT_USER_ID'];
         for ($i = 0; $i < $total; $i++) {
             if ($users[$i]['USERNAME'] == $session->data['USERNAME']) {
                 $users[$i]['SELECTED'] = 1;
                 $out['USER_TITLE'] = $users[$i]['NAME'];
                 $out['USER_AVATAR'] = $users[$i]['AVATAR'];
             }
         }
     }
     if ($out['USER_TITLE']) {
         Define('USER_TITLE', $out['USER_TITLE']);
         Define('USER_AVATAR', $out['USER_AVATAR']);
     } else {
         Define('USER_TITLE', '');
         Define('USER_AVATAR', '');
     }
     if ($out["DOC_NAME"]) {
         $doc = SQLSelectOne("SELECT ID FROM cms_docs WHERE NAME LIKE '" . DBSafe($out['DOC_NAME']) . "'");
         if ($doc['ID']) {
             $this->doc = $doc['ID'];
         }
     }
     if ($session->data["AUTHORIZED"]) {
         $out['AUTHORIZED_ADMIN'] = 1;
     }
     if ($this->action == '') {
         $res = SQLSelect("SELECT * FROM layouts ORDER BY PRIORITY DESC, TITLE");
         if ($this->action != 'admin') {
             $total = count($res);
             $res2 = array();
             for ($i = 0; $i < $total; $i++) {
                 if (checkAccess('layout', $res[$i]['ID'])) {
                     $res2[] = $res[$i];
                 }
             }
             $res = $res2;
             unset($res2);
         }
         $out['LAYOUTS'] = $res;
         $total = count($out['LAYOUTS']);
         for ($i = 0; $i < $total; $i++) {
             $out['LAYOUTS'][$i]['NUM'] = $i;
         }
         $out['TOTAL_LAYOUTS'] = count($out['LAYOUTS']);
     }
     if ($this->doc) {
         $this->doc_id = $this->doc;
     }
     $out["DOC_ID"] = $this->doc_id;
     if ($session->data['MY_MEMBER']) {
         $out['MY_MEMBER'] = $session->data['MY_MEMBER'];
         $tmp = SQLSelectOne("SELECT ID FROM users WHERE ID='" . (int) $out['MY_MEMBER'] . "' AND ACTIVE_CONTEXT_ID!=0 AND TIMESTAMPDIFF(SECOND, ACTIVE_CONTEXT_UPDATED, NOW())>600");
         if ($tmp['ID']) {
             SQLExec("UPDAE users SET ACTIVE_CONTEXT_ID=0, ACTIVE_CONTEXT_EXTERNAL=0 WHERE ID='" . $tmp['ID'] . "'");
         }
     }
     $out['AJAX'] = $this->ajax;
     $out['POPUP'] = $this->popup;
     $days = array('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
     $out['TODAY'] = $days[date('w')] . ', ' . date('d.m.Y');
     Define(TODAY, $out['TODAY']);
     global $ajt;
     if ($ajt == '') {
         $template_file = DIR_TEMPLATES . $this->name . ".html";
     } else {
         $template_file = ROOT . 'templates_ajax/' . $this->name . "_" . $ajt . ".html";
     }
     if ($this->action == 'menu') {
         $template_file = DIR_TEMPLATES . "menu.html";
     }
     $this->data = $out;
     $p = new parser($template_file, $this->data, $this);
     return $p->result;
 }
 function processSubscription($event, $details = '')
 {
     //to-do
     if ($event == 'SAY') {
         $level = $details['level'];
         $message = $details['message'];
         $current_queue = getGlobal('IRCBot1.pushMessage');
         $queue = explode("\n", $current_queue);
         $queue[] = $message;
         if (count($queue) >= 25) {
             $queue = array_slice($queue, -25);
         }
         setGlobal('IRCBot1.pushMessage', implode("\n", $queue));
     }
 }
Beispiel #27
0
            @unlink(ROOT."modules/".$file."/installed");
           }
          }
         }
*/
echo "Checking modules.\n";
// continue startup
include_once DIR_MODULES . "control_modules/control_modules.class.php";
$ctl = new control_modules();
//removing cached data
echo "Clearing the cache.\n";
SQLExec("TRUNCATE TABLE `cached_values`");
$run_from_start = 1;
include "./scripts/startup_maintenance.php";
$run_from_start = 0;
setGlobal('ThisComputer.started_time', time());
getObject('ThisComputer')->raiseEvent("StartUp");
// 1 second sleep
sleep(1);
// getting list of /scripts/cycle_*.php files to run each in separate thread
$cycles = array();
if (is_dir("./scripts")) {
    if ($lib_dir = opendir("./scripts")) {
        while (($lib_file = readdir($lib_dir)) !== false) {
            if (preg_match("/^cycle_.+?\\.php\$/", $lib_file)) {
                $cycles[] = './scripts/' . $lib_file;
            }
        }
        closedir($lib_dir);
    }
}
Beispiel #28
0
                            $code = $gpsaction['CODE'];
                            $success = eval($code);
                            if ($success === false) {
                                DebMes("Error in GPS action code: " . $code);
                            }
                        } catch (Exception $e) {
                            DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                        }
                    }
                }
            }
        }
    }
}
if ($user['LINKED_OBJECT'] && !$location_found) {
    setGlobal($user['LINKED_OBJECT'] . '.seenAt', '');
}
$sqlQuery = "SELECT *, DATE_FORMAT(ADDED, '%H:%i') as DAT\n               FROM shouts\n              ORDER BY ADDED DESC\n              LIMIT 1";
$tmp = SQLSelectOne($sqlQuery);
if (!headers_sent()) {
    header("HTTP/1.0: 200 OK\n");
    header('Content-Type: text/html; charset=utf-8');
}
if (defined('BTRACED')) {
    echo "OK";
} elseif ($tmp['MESSAGE'] != '') {
    echo ' ' . $tmp['DAT'] . ' ' . transliterate($tmp['MESSAGE']);
}
// closing database connection
$db->Disconnect();
endMeasure('TOTAL');
 function pollDevice($id, $states_data = '')
 {
     $dev_rec = SQLSelectOne("SELECT * FROM veradevices WHERE ID='" . $id . "'");
     if (!is_array($states_data)) {
         $data = $this->api_request('status', 'DeviceNum=' . $dev_rec['DEVICE_NUM']);
         $json = json_decode($data, true);
         $states_data = $json['Device_Num_' . $dev_rec['DEVICE_NUM']]['states'];
         if (!is_array($states_data)) {
             return 0;
         }
     }
     /*
     $data=$this->api_request('invoke', 'DeviceNum='.$dev_rec['DEVICE_NUM']);
     echo $data;exit;
     $json=json_decode($data, true);
     print_r($json);exit;
     */
     $totals = count($states_data);
     for ($is = 0; $is < $totals; $is++) {
         $state_id = $states_data[$is]['id'];
         $property = SQLSelectOne("SELECT * FROM veraproperties WHERE DEVICE_ID='" . $dev_rec['ID'] . "' AND VARIABLE LIKE '" . DBSafe($states_data[$is]['variable']) . "'");
         $old_value = $property['VALUE'];
         if (!$property['ID']) {
             $property = array();
             $property['DEVICE_ID'] = $dev_rec['ID'];
             $property['STATE_ID'] = (int) $state_id;
             $property['VARIABLE'] = $states_data[$is]['variable'];
             $property['ID'] = SQLInsert('veraproperties', $property);
         }
         $property['SERVICE'] = $states_data[$is]['service'];
         $property['VALUE'] = $states_data[$is]['value'];
         $property['UPDATED'] = date('Y-m-d H:i:s');
         SQLUpdate('veraproperties', $property);
         $validated = true;
         if ($property['LINKED_OBJECT'] && $property['LINKED_PROPERTY'] && $validated) {
             $old_value = getGlobal($property['LINKED_OBJECT'] . '.' . $property['LINKED_PROPERTY']);
             if ($property['VALUE'] != $old_value) {
                 setGlobal($property['LINKED_OBJECT'] . '.' . $property['LINKED_PROPERTY'], $property['VALUE'], array($this->name => '0'));
             }
         }
         if ($property['LINKED_OBJECT'] && $property['LINKED_METHOD'] && $validated && ($property['VALUE'] != $old_value || !$property['LINKED_PROPERTY'])) {
             $params = array();
             $params['VALUE'] = $property['VALUE'];
             callMethod($property['LINKED_OBJECT'] . '.' . $property['LINKED_METHOD'], $params);
         }
     }
 }