コード例 #1
0
ファイル: threads.php プロジェクト: vasvlad/majordomo
 public function iteration()
 {
     $result = '';
     if (!count($this->streams)) {
         return false;
     }
     $read = $this->streams;
     $write = null;
     $except = null;
     if (false === ($number_of_streams = stream_select($read, $write, $except, $this->timeout))) {
         DebMes("No active streams");
         return 0;
     }
     /* 
     $stream = next($read);
     if (!$stream) {
      reset($read);
      $stream=current($read);
     }
     */
     foreach ($read as $stream) {
         $id = array_search($stream, $this->streams);
         //stream_set_blocking($stream, FALSE);
         stream_set_timeout($stream, $this->timeout);
         //echo date('H:i:s')." Reading thread: ".$this->commandLines[$id]."\n";
         //$result = stream_get_contents($this->pipes[$id][1]);
         if (feof($stream) || ($contents = fread($stream, 255)) == false) {
             //)
             echo date('H:i:s') . " Closing thread: " . $this->commandLines[$id] . "\n";
             DebMes("Closing thread: " . $this->commandLines[$id]);
             $result .= "THREAD CLOSED: [" . $this->commandLines[$id] . "]\n";
             fclose($this->pipes[$id][0]);
             fclose($this->pipes[$id][1]);
             proc_close($this->handles[$id]);
             unset($this->handles[$id]);
             unset($this->streams[$id]);
             unset($this->pipes[$id]);
             unset($this->commandLines[$id]);
         } else {
             echo $contents;
             $result .= $contents;
         }
     }
     return $result;
 }
コード例 #2
0
/**
* Object constructor
*
* @access public
* @param string $description error description
* @param int $stop 0 - stop script execution, 1 - show warning and continue script execution
*/
  function error($description, $stop=0, $short=0) {
   $script='http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
   $dat=date("M d, Y H:i:s");
   $description=$dat." ".$script."\nError:\n".$description;
   DebMes($description);
   if (Defined("DEBUG_MODE")) {
    if (!$short) {
     $this->alert(nl2br($description));
    } else {
     echo (nl2br($description));
    }
   } else {
    if (!$short) {
     $this->alert("");
    } else {
     echo "Warning...<br>";
    }
   }
   sendmail("errors@".PROJECT_DOMAIN, PROJECT_BUGTRACK, "Error reporting: $script", $description);
   if ($stop) exit;
  }
コード例 #3
0
ファイル: cycle_connect.php プロジェクト: cdkisa/majordomo
/**
 * 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);
    }
}
コード例 #4
0
ファイル: gps.php プロジェクト: cdkisa/majordomo
                $gpsaction = SQLSelectOne($sqlQuery);
                if ($gpsaction['ID']) {
                    $gpsaction['EXECUTED'] = date('Y-m-d H:i:s');
                    $gpsaction['LOG'] = $gpsaction['EXECUTED'] . " Executed\n" . $gpsaction['LOG'];
                    SQLUpdate('gpsactions', $gpsaction);
                    if ($gpsaction['SCRIPT_ID']) {
                        runScript($gpsaction['SCRIPT_ID']);
                    } elseif ($gpsaction['CODE']) {
                        try {
                            $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');
コード例 #5
0
ファイル: cycle_onewire.php プロジェクト: vasvlad/majordomo
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__));
コード例 #6
0
ファイル: write_error.php プロジェクト: novozhenets/majordomo
<?
/**
* Write Error script
*
* @package MajorDoMo
* @author Serge Dzheigalo <*****@*****.**> http://smartliving.ru/
* @version 1.1
*/


 include_once("./config.php");
 include_once("./lib/loader.php");

 if ($error) {
  echo $error;
  DebMes("JAVASCRIPT Error: ".$error);
 }

?>
コード例 #7
0
 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() . '.');
             }
         }
     }
 }
コード例 #8
0
ファイル: scenes.class.php プロジェクト: NioFBI/majordomo
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function checkState($id)
 {
     $rec = SQLSelectOne("SELECT * FROM elm_states WHERE ID='" . $id . "'");
     if (!checkAccess('scene_elements', $rec['ELEMENT_ID'])) {
         $status = 0;
         return $status;
     }
     startMeasure('state_dynamic' . $rec['IS_DYNAMIC']);
     if (!$rec['IS_DYNAMIC']) {
         $status = 1;
     } elseif ($rec['IS_DYNAMIC'] == 1) {
         if ($rec['LINKED_OBJECT'] != '' && $rec['LINKED_PROPERTY'] != '') {
             $value = gg(trim($rec['LINKED_OBJECT']) . '.' . trim($rec['LINKED_PROPERTY']));
         } elseif ($rec['LINKED_PROPERTY'] != '') {
             $value = gg($rec['LINKED_PROPERTY']);
         } else {
             $value = -1;
         }
         if (($rec['CONDITION'] == 2 || $rec['CONDITION'] == 3) && $rec['CONDITION_VALUE'] != '' && !is_numeric($rec['CONDITION_VALUE']) && !preg_match('/^%/', $rec['CONDITION_VALUE'])) {
             $rec['CONDITION_VALUE'] = '%' . $rec['CONDITION_VALUE'] . '%';
         }
         if (is_integer(strpos($rec['CONDITION_VALUE'], "%"))) {
             $rec['CONDITION_VALUE'] = processTitle($rec['CONDITION_VALUE']);
         }
         if ($rec['CONDITION'] == 1 && $value == $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 2 && (double) $value > (double) $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 3 && (double) $value < (double) $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 4 && $value != $rec['CONDITION_VALUE']) {
             $status = 1;
         } else {
             $status = 0;
         }
     } elseif ($rec['IS_DYNAMIC'] == 2) {
         $display = 0;
         if (is_integer(strpos($rec['CONDITION_ADVANCED'], "%"))) {
             $rec['CONDITION_ADVANCED'] = processTitle($rec['CONDITION_ADVANCED']);
         }
         try {
             $code = $rec['CONDITION_ADVANCED'];
             $success = eval($code);
             if ($success === false) {
                 DebMes("Error in scene code: " . $code);
                 registerError('scenes', "Error in scene code: " . $code);
             }
         } catch (Exception $e) {
             DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
             registerError('scenes', get_class($e) . ', ' . $e->getMessage());
         }
         $status = $display;
     }
     endMeasure('state_dynamic' . $rec['IS_DYNAMIC']);
     if ($rec['CURRENT_STATE'] != $status) {
         startMeasure('stateUpdate');
         $rec['CURRENT_STATE'] = $status;
         SQLExec('UPDATE elm_states SET CURRENT_STATE=' . $rec['CURRENT_STATE'] . ' WHERE ID=' . (int) $rec['ID']);
         endMeasure('stateUpdate');
     }
     return $status;
 }
コード例 #9
0
ファイル: cycle.php プロジェクト: vasvlad/majordomo
    while (($lib_file = readdir($lib_dir)) !== false) {
        if (preg_match("/^cycle_.+?\\.php\$/", $lib_file)) {
            $cycles[] = './scripts/' . $lib_file;
        }
    }
    closedir($lib_dir);
}
$threads = new Threads();
if (substr(php_uname(), 0, 7) == "Windows") {
    $threads->phpPath = '..\\server\\php\\php.exe';
} else {
    $threads->phpPath = 'php';
}
foreach ($cycles as $path) {
    if (file_exists($path)) {
        DebMes("Starting " . $path . " ... ");
        echo "Starting " . $path . " ... ";
        if (preg_match("/_X/", $path)) {
            //для начала убедимся, что мы в Линуксе. Иначе удаленный запуск этих скриптов не делаем
            if (substr(php_uname(), 0, 5) == "Linux") {
                $display = '101';
                //Попробуем получить номер Дисплея из имени файла
                if (preg_match("/_X(.+)_/", $path, $displays)) {
                    if (count($displays) > 1) {
                        $display = $displays[1];
                    }
                }
                //запускаем Линуксовый поцесс на дисплее, номер которого в имени файла после _X
                $pipe_id = $threads->newXThread($path, $display);
            }
        } else {
コード例 #10
0
 /**
 * FrontEnd
 *
 * Module frontend
 *
 * @access public
 */
 function usual(&$out)
 {
     global $op;
     global $ajax;
     if ($ajax) {
         //  DebMes("101msg");
         if (!headers_sent()) {
             header("HTTP/1.0: 200 OK\n");
             header('Content-Type: text/html; charset=utf-8');
         }
         if ($op == 'playstation') {
             global $id;
             $rec = SQLSelectOne("SELECT * FROM ru101_stations WHERE (ID='" . (int) $id . "' OR TITLE LIKE '" . DBSafe($id) . "')");
             DebMes('Getting radio page from ' . $rec['PAGE_URL']);
             if ($rec['PAGE_URL']) {
                 $data = getURL($rec['PAGE_URL'], 5);
                 if (preg_match('/(\\/api\\/channel\\/getServers\\/.+?)\'/isu', $data, $matches)) {
                     $json_url = 'http://101.ru' . $matches[1];
                     $data = getURL($json_url);
                     $radio_data = json_decode($data, true);
                     //DebMes(serialize($radio_data));
                     //return 0;
                     $playlist_url = $radio_data['playlist'][0]['file'];
                     if ($playlist_url != '') {
                         $out['PLAY'] = $playlist_url;
                         $url = BASE_URL . ROOTHTML . 'popup/app_player.html?ajax=1';
                         $url .= "&command=refresh&play=" . urlencode($out['PLAY']);
                         getURL($url, 0);
                     } else {
                         DebMes("Cannot find playlist in " . $json_url);
                     }
                 } else {
                     DebMes("Cannot find playlist in " . $rec['PAGE_URL']);
                 }
             }
             echo "OK";
         }
         exit;
     }
     $categories = SQLSelect("SELECT * FROM ru101_categories ORDER BY TITLE");
     $total = count($categories);
     for ($i = 0; $i < $total; $i++) {
         $categories[$i]['STATIONS'] = SQLSelect("SELECT * FROM ru101_stations WHERE CATEGORY_ID='" . $categories[$i]['ID'] . "' ORDER BY TITLE");
     }
     if (!$categories[0]['ID']) {
         $rec = array('ID' => 0, 'TITLE' => 'All');
         $rec['STATIONS'] = SQLSelect("SELECT * FROM ru101_stations WHERE 1 ORDER BY TITLE");
         $categories = array($rec);
     } else {
     }
     $out['CATEGORIES'] = $categories;
 }
コード例 #11
0
ファイル: market.class.php プロジェクト: cdkisa/majordomo
 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 = $restore;
     } elseif ($file != '') {
         copy($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);
             //echo DOC_ROOT.'/tar xvf ../'.str_replace('.tgz', '.tar', $file);exit;
             exec(DOC_ROOT . '/tar xvf ../' . str_replace('.tgz', '.tar', $file), $output, $res);
         } else {
             exec('tar xzvf ../' . $file, $output, $res);
         }
         $x = 0;
         $dir = opendir('./');
         while (($filec = readdir($dir)) !== false) {
             if ($filec == '.' || $filec == '..') {
                 continue;
             }
             if (is_Dir($filec)) {
                 $latest_dir = $filec;
             } elseif (is_File($filec)) {
                 $latest_file = $filec;
             }
             $x++;
         }
         if ($x == 1 && $latest_dir) {
             $folder = '/' . $latest_dir;
         }
         @unlink(ROOT . 'saverestore/temp' . $folder . '/config.php');
         @unlink(ROOT . 'saverestore/temp' . $folder . '/README.md');
         chdir('../../');
         // UPDATING FILES DIRECTLY
         $this->copyTree(ROOT . 'saverestore/temp' . $folder, ROOT, 1);
         // restore all files
         $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");
         global $name;
         global $version;
         DebMes("Installing/updating plugin {$name} ({$version})");
         $rec = SQLSelectOne("SELECT * FROM plugins WHERE MODULE_NAME LIKE '" . DBSafe($name) . "'");
         $rec['MODULE_NAME'] = $name;
         $rec['CURRENT_VERSION'] = $version;
         $rec['IS_INSTALLED'] = 1;
         $rec['LATEST_UPDATE'] = date('Y-m-d H:i:s');
         if ($rec['ID']) {
             SQLUpdate('plugins', $rec);
         } else {
             SQLInsert('plugins', $rec);
         }
         $this->redirect("?mode=clear&ok_msg=" . urlencode("Updates Installed!"));
     }
 }
コード例 #12
0
ファイル: cycle.php プロジェクト: novozhenets/majordomo
  for($i=0;$i<$total;$i++) {
   $command=utf2win($safe_execs[$i]['COMMAND']);
   SQLExec("DELETE FROM safe_execs WHERE ID='".$safe_execs[$i]['ID']."'");
   echo "Executing (exclusive): ".$command."\n";
   DebMes("Executing (exclusive): ".$command);
   exec($command);
  }


  $safe_execs=SQLSelect("SELECT * FROM safe_execs WHERE EXCLUSIVE=0 ORDER BY PRIORITY DESC, ID");
  $total=count($safe_execs);
  for($i=0;$i<$total;$i++) {
   $command=utf2win($safe_execs[$i]['COMMAND']);
   SQLExec("DELETE FROM safe_execs WHERE ID='".$safe_execs[$i]['ID']."'");
   echo "Executing: ".$command."\n";
   DebMes("Executing: ".$command);
   execInBackground($command);
  }



  runScheduledJobs();

  $m=date('i');
  $h=date('h');
  $dt=date('Y-m-d');
  if ($m!=$old_minute) {
   echo "new minute\n";
   $objects=SQLSelect("SELECT ID, TITLE FROM objects WHERE $o_qry");
   $total=count($objects);
   for($i=0;$i<$total;$i++) {
コード例 #13
0
ファイル: commands.class.php プロジェクト: vasvlad/majordomo
 /**
 * BackEnd
 *
 * Module backend
 *
 * @access public
 */
 function admin(&$out)
 {
     global $ajax;
     if ($ajax) {
         global $op;
         global $item_id;
         if ($op == 'get_label') {
             startMeasure('getLabel');
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             startMeasure('getLabel ' . $item['TITLE'], 1);
             if ($item['ID']) {
                 $res = array();
                 if ($item['TYPE'] == 'custom') {
                     $item['DATA'] = processTitle($item['DATA'], $this);
                     $res['DATA'] = $item['DATA'];
                 } else {
                     $item['TITLE'] = processTitle($item['TITLE'], $this);
                     $res['DATA'] = $item['TITLE'];
                 }
                 if ($item['RENDER_DATA'] != $item['DATA'] || $item['RENDER_TITLE'] != $item['TITLE']) {
                     $tmp = SQLSelectOne("SELECT * FROM commands WHERE ID='" . $item['ID'] . "'");
                     $tmp['RENDER_TITLE'] = $item['TITLE'];
                     $tmp['RENDER_DATA'] = $item['DATA'];
                     $tmp['RENDER_UPDATED'] = date('Y-m-d H:i:s');
                     SQLUpdate('commands', $tmp);
                 }
                 echo json_encode($res);
             }
             endMeasure('getLabel ' . $item['TITLE'], 1);
             endMeasure('getLabel', 1);
             exit;
         }
         if ($op == 'get_value') {
             startMeasure('getValue');
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             if ($item['ID']) {
                 $res = array();
                 $res['DATA'] = $item['CUR_VALUE'];
                 echo json_encode($res);
             }
             endMeasure('getValue', 1);
             exit;
         }
         if ($op == 'value_changed') {
             global $new_value;
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             if ($item['ID']) {
                 $item['CUR_VALUE'] = $new_value;
                 SQLUpdate('commands', $item);
                 if ($item['LINKED_PROPERTY'] != '') {
                     $old_value = gg($item['LINKED_OBJECT'] . '.' . $item['LINKED_PROPERTY']);
                     sg($item['LINKED_OBJECT'] . '.' . $item['LINKED_PROPERTY'], $item['CUR_VALUE'], array('commands' => 'ID!=' . $item['ID']));
                     //DebMes("setting property ".$item['LINKED_OBJECT'].".".$item['LINKED_PROPERTY']." to ".$item['CUR_VALUE']);
                 }
                 $params = array('VALUE' => $item['CUR_VALUE']);
                 if (isset($old_value)) {
                     $params['OLD_VALUE'] = $old_value;
                 }
                 if ($item['ONCHANGE_METHOD'] != '') {
                     getObject($item['ONCHANGE_OBJECT'])->callMethod($item['ONCHANGE_METHOD'], $params);
                     //DebMes("calling method ".$item['ONCHANGE_OBJECT'].".".$item['ONCHANGE_METHOD']." with ".$item['CUR_VALUE']);
                 }
                 if ($item['SCRIPT_ID']) {
                     //DebMes('Running on_change script #'.$item['SCRIPT_ID']);
                     runScript($item['SCRIPT_ID'], $params);
                 }
                 if ($item['CODE']) {
                     //DebMes("Running on_change code");
                     try {
                         $code = $item['CODE'];
                         $success = eval($code);
                         if ($success === false) {
                             DebMes("Error menu item code: " . $code);
                         }
                     } catch (Exception $e) {
                         DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                     }
                 }
             }
             echo "OK";
         }
         exit;
     }
     if (isset($this->data_source) && !$_GET['data_source'] && !$_POST['data_source']) {
         $out['SET_DATASOURCE'] = 1;
     }
     if ($this->data_source == 'commands' || $this->data_source == '') {
         if ($this->view_mode == '' || $this->view_mode == 'search_commands') {
             startMeasure('searchCommands');
             $this->search_commands($out);
             endMeasure('searchCommands', 1);
         }
         if ($this->view_mode == 'edit_commands') {
             $this->edit_commands($out, $this->id);
         }
         if ($this->view_mode == 'clone_commands') {
             $rec = SQLSelectOne("SELECT * FROM commands WHERE ID='" . $this->id . "'");
             unset($rec['ID']);
             $rec['TITLE'] = $rec['TITLE'] . ' (copy)';
             $rec['ID'] = SQLInsert('commands', $rec);
             $this->redirect("?id=" . $rec['ID'] . "&view_mode=edit_commands");
         }
         if ($this->view_mode == 'delete_commands') {
             $this->delete_commands($this->id);
             $this->redirect("?");
         }
     }
 }
コード例 #14
0
ファイル: scenes.class.php プロジェクト: vasvlad/majordomo
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function checkState($id)
 {
     $rec = SQLSelectOne("SELECT * FROM elm_states WHERE ID='" . $id . "'");
     if (!$rec['IS_DYNAMIC']) {
         $status = 1;
     } elseif ($rec['IS_DYNAMIC'] == 1) {
         if ($rec['LINKED_OBJECT'] != '' && $rec['LINKED_PROPERTY'] != '') {
             $value = gg(trim($rec['LINKED_OBJECT']) . '.' . trim($rec['LINKED_PROPERTY']));
         } elseif ($rec['LINKED_PROPERTY'] != '') {
             $value = gg($rec['LINKED_PROPERTY']);
         } else {
             $value = -1;
         }
         if ($rec['CONDITION'] == 1 && $value == $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 2 && (double) $value > (double) $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 3 && (double) $value < (double) $rec['CONDITION_VALUE']) {
             $status = 1;
         } elseif ($rec['CONDITION'] == 4 && $value != $rec['CONDITION_VALUE']) {
             $status = 1;
         } else {
             $status = 0;
         }
     } elseif ($rec['IS_DYNAMIC'] == 2) {
         $display = 0;
         try {
             $code = $rec['CONDITION_ADVANCED'];
             $success = eval($code);
             if ($success === false) {
                 DebMes("Error in scene code: " . $code);
             }
         } catch (Exception $e) {
             DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
         }
         $status = $display;
     }
     if ($rec['CURRENT_STATE'] != $status) {
         $rec['CURRENT_STATE'] = $status;
         SQLExec('UPDATE elm_states SET CURRENT_STATE=' . $rec['CURRENT_STATE'] . ' WHERE ID=' . (int) $rec['ID']);
     }
     return $status;
 }
コード例 #15
0
ファイル: patterns.class.php プロジェクト: vasvlad/majordomo
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function checkPattern($id)
 {
     global $session;
     global $pattern_matched;
     $rec = SQLSelectOne("SELECT * FROM patterns WHERE ID='" . (int) $id . "'");
     if (!$rec['PATTERN']) {
         $pattern = $rec['TITLE'];
     } else {
         $pattern = $rec['PATTERN'];
     }
     $pattern = str_replace("\r", '', $pattern);
     if ($pattern == '') {
         return 0;
     }
     if ($rec['EXECUTED'] > 0 && $rec['TIME_LIMIT'] && time() - $rec['EXECUTED'] <= $rec['TIME_LIMIT']) {
         return 0;
     }
     $lines_pattern = explode("\n", $pattern);
     $total_lines = count($lines_pattern);
     if (!$rec['TIME_LIMIT']) {
         $messages = SQLSelect("SELECT MESSAGE FROM shouts ORDER BY ID DESC LIMIT " . (int) $total_lines);
         $messages = array_reverse($messages);
     } else {
         $start_from = time() - $rec['TIME_LIMIT'];
         $messages = SQLSelect("SELECT MESSAGE FROM shouts WHERE ADDED>=('" . date('Y-m-d H:i:s', $start_from) . "') ORDER BY ADDED");
     }
     $total = count($messages);
     if (!$total) {
         return 0;
     }
     $lines = array();
     for ($i = 0; $i < $total; $i++) {
         $lines[] = $messages[$i]['MESSAGE'];
     }
     $history = implode('@@@@', $lines);
     $check = implode('@@@@', $lines_pattern);
     if (preg_match('/' . $check . '/is', $history, $matches)) {
         if (checkAccess('pattern', $rec['ID'])) {
             $is_common = 0;
             if ($rec['PARENT_ID']) {
                 $parent_rec = SQLSelectOne("SELECT IS_COMMON_CONTEXT FROM patterns WHERE ID='" . $rec['PARENT_ID'] . "'");
                 $is_common = (int) $parent_rec['IS_COMMON_CONTEXT'];
             }
             if ($rec['IS_CONTEXT']) {
                 context_activate($rec['ID']);
             } elseif ($rec['MATCHED_CONTEXT_ID']) {
                 context_activate($rec['MATCHED_CONTEXT_ID']);
             } elseif (!$is_common) {
                 context_activate(0);
             }
             $rec['LOG'] = date('Y-m-d H:i:s') . ' Pattern matched' . "\n" . $rec['LOG'];
             $rec['EXECUTED'] = time();
             SQLUpdate('patterns', $rec);
             global $noPatternMode;
             $noPatternMode = 1;
             $pattern_matched = 1;
             if ($rec['SCRIPT_ID']) {
                 runScript($rec['SCRIPT_ID'], $matches);
             } elseif ($rec['SCRIPT']) {
                 try {
                     $code = $rec['SCRIPT'];
                     $success = eval($code);
                     if ($success === false) {
                         DebMes("Error in pattern code: " . $code);
                     }
                 } catch (Exception $e) {
                     DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                 }
             }
             $noPatternMode = 0;
         }
     }
     if ($pattern_matched) {
         return 1;
     } else {
         return 0;
     }
 }
コード例 #16
0
/**
* Title
*
* Description
*
* @access public
*/
function execInBackground($cmd)
{
    if (IsWindowsOS()) {
        //pclose(popen("start /B ". $cmd, "r"));
        try {
            //pclose(popen("start /B ". $cmd, "r"));
            system($cmd);
            //$WshShell = new COM("WScript.Shell");
            //$oExec = $WshShell->Run("cmd /C ".$cmd, 0, false);
            //exec($cmd);
        } catch (Exception $e) {
            DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
        }
    } else {
        exec($cmd . " > /dev/null &");
    }
}
コード例 #17
0
ファイル: cycle_X101_skype.php プロジェクト: NioFBI/majordomo
        //Подключаемся к скайпу
        $n = $dbus->createProxy('com.Skype.API', '/com/Skype', 'com.Skype.API');
        //Имя нашей программы, авторизация в скайпе
        $n->Invoke('NAME MajorDoMo');
        //Используем последний протокол
        $n->Invoke('PROTOCOL 8');
        break;
    } catch (Exception $e) {
        DebMes('Skype error : ' . $e->getCode() . '. Error message: ' . $e->getMessage());
        $n = null;
    }
    sleep(5);
}
if (i >= 5) {
    $n = $dbus = null;
    DebMes('Skype error : 5 попыток');
    $db->Disconnect();
    exit;
}
//пишем класс по обработке нотификаций
class phpSkype
{
    /*
     * Эту функцию мы будем использовать для проверки последних сообщений в скайпе.
     * Если вы не хотите, чтобы программа реагировала на ваши сообщения, используйте
     * preg_match('/RECEIVED/', $notify)
     */
    public static function notify($notify)
    {
        //echo "$notify"."\n";
        #if (preg_match('#RECEIVED|SENT#Uis', $notify)) {
コード例 #18
0
        @unlink($file);
    }
}
//removing old backups files
$dir = $target_dir;
foreach (glob($dir . "*") as $file) {
    if (filemtime($file) < time() - BACKUP_FILES_EXPIRE * 24 * 60 * 60) {
        DebMes("Removing backup file " . $file);
        @unlink($file);
    }
}
//removing old cached files
$dir = ROOT . "cached/";
foreach (glob($dir . "*") as $file) {
    if (filemtime($file) < time() - BACKUP_FILES_EXPIRE * 24 * 60 * 60) {
        DebMes("Removing cached file " . $file);
        @unlink($file);
    }
}
umask($old_mask);
// CHECK/REPAIR/OPTIMIZE TABLES
$tables = SQLSelect("SHOW TABLES FROM `" . DB_NAME . "`");
$total = count($tables);
for ($i = 0; $i < $total; $i++) {
    $table = $tables[$i]['Tables_in_' . DB_NAME];
    echo 'Checking table [' . $table . '] ...';
    if ($result = SQLExec("CHECK TABLE " . $table . ";")) {
        echo "OK\n";
    } else {
        echo " broken ... repair ...";
        SQLExec("REPAIR TABLE " . $table . ";");
コード例 #19
0
ファイル: pinghosts.class.php プロジェクト: cdkisa/majordomo
 /**
 * 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());
                 }
             }
         }
     }
 }
コード例 #20
0
 function runPatternExitAction($id, $script_exit)
 {
     if ($script_exit) {
         try {
             $code = $script_exit;
             $success = eval($code);
             if ($success === false) {
                 DebMes("Error in pattern exit code: " . $code);
                 registerError('patterns', "Error in pattern exit code: " . $code);
             }
         } catch (Exception $e) {
             DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
             registerError('patterns', get_class($e) . ', ' . $e->getMessage());
         }
     }
 }
コード例 #21
0
ファイル: webvars.class.php プロジェクト: cdkisa/majordomo
 /**
 * Title
 *
 * Description
 *
 * @access public
 */
 function checkAllVars($force = 0)
 {
     // ping hosts
     if ($force) {
         $pings = SQLSelect("SELECT * FROM webvars WHERE 1");
     } else {
         $pings = SQLSelect("SELECT * FROM webvars WHERE CHECK_NEXT<=NOW()");
     }
     $total = count($pings);
     for ($i = 0; $i < $total; $i++) {
         $host = $pings[$i];
         if (!$force) {
             echo date('H:i:s') . " Checking webvar: " . processTitle($host['HOSTNAME']) . "\n";
         }
         if (!$host['HOSTNAME']) {
             continue;
         }
         $online_interval = $host['ONLINE_INTERVAL'];
         if (!$online_interval) {
             $online_interval = 60;
         }
         $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $online_interval);
         SQLUpdate('webvars', $host);
         // checking
         //web host
         $old_status = $host['LATEST_VALUE'];
         if ($host['AUTH'] && $host['USERNAME']) {
             $content = getURL(processTitle($host['HOSTNAME']), $host['ONLINE_INTERVAL'], $host['USERNAME'], $host['PASSWORD']);
         } else {
             $content = getURL(processTitle($host['HOSTNAME']), $host['ONLINE_INTERVAL']);
         }
         if ($host['ENCODING'] != '') {
             $content = iconv($host['ENCODING'], "UTF-8", $content);
         }
         $ok = 1;
         $new_status = '';
         if ($host['SEARCH_PATTERN']) {
             if (preg_match('/' . $host['SEARCH_PATTERN'] . '/is', $content, $m)) {
                 //$new_status=$m[1];
                 $total1 = count($m);
                 for ($i1 = 1; $i1 < $total1; $i1++) {
                     $new_status .= $m[$i1];
                 }
             } else {
                 $ok = 0;
                 // result did not matched
             }
         } else {
             $new_status = $content;
         }
         if ($host['CHECK_PATTERN'] && !preg_match('/' . $host['CHECK_PATTERN'] . '/is', $new_status)) {
             $ok = 0;
             // result did not pass the check
         }
         if (strlen($new_status) > 50 * 1024) {
             $new_status = substr($new_status, 0, 50 * 1024);
         }
         if (!$ok) {
             $host['LOG'] = date('Y-m-d H:i:s') . ' incorrect value:' . $new_status . "\n" . $host['LOG'];
             $tmp = explode("\n", $host['LOG']);
             $total = count($tmp);
             if ($total > 50) {
                 $tmp = array_slice($tmp, 0, 50);
                 $host['LOG'] = implode("\n", $tmp);
             }
             SQLUpdate('webvars', $host);
             continue;
         }
         $host['CHECK_LATEST'] = date('Y-m-d H:i:s');
         $host['CHECK_NEXT'] = date('Y-m-d H:i:s', time() + $online_interval);
         if ($old_status != $new_status) {
             $host['LOG'] = date('Y-m-d H:i:s') . ' new value:' . $new_status . "\n" . $host['LOG'];
             $tmp = explode("\n", $host['LOG']);
             $total = count($tmp);
             if ($total > 50) {
                 $tmp = array_slice($tmp, 0, 50);
                 $host['LOG'] = implode("\n", $tmp);
             }
         }
         $host['LATEST_VALUE'] = $new_status;
         SQLUpdate('webvars', $host);
         if ($host['LINKED_OBJECT'] != '' && $host['LINKED_PROPERTY'] != '') {
             getObject($host['LINKED_OBJECT'])->setProperty($host['LINKED_PROPERTY'], $new_status);
         }
         if ($old_status != $new_status && $old_status != '') {
             $params = array('VALUE' => $new_status);
             // do some status change actions
             $run_script_id = 0;
             $run_code = '';
             // got online
             if ($host['SCRIPT_ID']) {
                 $run_script_id = $host['SCRIPT_ID'];
             } elseif ($host['CODE']) {
                 $run_code = $host['CODE'];
             }
             if ($run_script_id) {
                 //run script
                 runScript($run_script_id, $params);
             } elseif ($run_code) {
                 //run code
                 try {
                     $code = $run_code;
                     $success = eval($code);
                     if ($success === false) {
                         DebMes("Error in webvar code: " . $code);
                         registerError('webvars', "Error in webvar code: " . $code);
                     }
                 } catch (Exception $e) {
                     DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                     registerError('webvars', get_class($e) . ', ' . $e->getMessage());
                 }
             }
         }
     }
 }
コード例 #22
0
  ini_set('date.timezone', TIME_ZONE);
 }


if (Defined('HOME_NETWORK') && HOME_NETWORK!='' && !$argv[0] && 
    !preg_match('/\/gps.php/is', $_SERVER['REQUEST_URI']) &&
//    !preg_match('/\/command.php/is', $_SERVER['REQUEST_URI']) &&
    !preg_match('/\/rss.php/is', $_SERVER['REQUEST_URI']) &&
    1) {
 $p=preg_quote(HOME_NETWORK);
 $p=str_replace('\*', '\d+?', $p);
 $remoteAddr = getenv('HTTP_X_FORWARDED_FOR')?getenv('HTTP_X_FORWARDED_FOR'):$_SERVER["REMOTE_ADDR"];
 if (!preg_match('/'.$p.'/is', $remoteAddr) && $remoteAddr!='127.0.0.1') {
  // password required
  //echo "password required for ".$remoteAddr;exit;
  DebMes("checking access for ".$remoteAddr);

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header("WWW-Authenticate: Basic realm=\"".PROJECT_TITLE."\"");
    header("HTTP/1.0 401 Unauthorized");
    echo "Authorization required\n";
    exit;
  } else {
    if ($_SERVER['PHP_AUTH_USER']!=EXT_ACCESS_USERNAME || $_SERVER['PHP_AUTH_PW']!=EXT_ACCESS_PASSWORD) {
 //    header("Location:$PHP_SELF\n\n");
     header("WWW-Authenticate: Basic realm=\"".PROJECT_TITLE."\"");
     header("HTTP/1.0 401 Unauthorized");
     echo "Authorization required\n";
     exit;
    }
  }
コード例 #23
0
ファイル: cycle.php プロジェクト: NioFBI/majordomo
        echo "OK" . PHP_EOL;
    }
}
echo "ALL CYCLES STARTED" . PHP_EOL;
if (!is_array($restart_threads)) {
    $restart_threads = array('cycle_execs.php', 'cycle_main.php', 'cycle_ping.php', 'cycle_scheduler.php', 'cycle_states.php', 'cycle_webvars.php');
}
while (false !== ($result = $threads->iteration())) {
    if (!empty($result)) {
        //echo "Res: " . $result . PHP_EOL . "---------------------" . PHP_EOL;
        $closePattern = '/THREAD CLOSED:.+?(\\.\\/scripts\\/cycle\\_.+?\\.php)/is';
        if (preg_match_all($closePattern, $result, $matches) && !file_exists('./reboot')) {
            $total_m = count($matches[1]);
            for ($im = 0; $im < $total_m; $im++) {
                $closed_thread = $matches[1][$im];
                foreach ($restart_threads as $item) {
                    if (preg_match('/' . $item . '/is', $closed_thread)) {
                        //restart
                        DebMes("RESTARTING: " . $closed_thread);
                        echo "RESTARTING: " . $closed_thread . PHP_EOL;
                        registerError('cycle_stop', $closed_thread);
                        $pipe_id = $threads->newThread($closed_thread);
                    }
                }
            }
        }
    }
}
unlink('./reboot');
// closing database connection
$db->Disconnect();
コード例 #24
0
ファイル: context.inc.php プロジェクト: szolenko/majordomo
/**
 * Summary of context_timeout
 * @param mixed $id      ID
 * @param mixed $user_id User ID
 * @return void
 */
function context_timeout($id, $user_id)
{
    global $session;
    $user = SQLSelectOne("SELECT * FROM users WHERE ID = '" . (int) $user_id . "'");
    $session->data['SITE_USER_ID'] = $user['ID'];
    $context = SQLSelectOne("SELECT * FROM patterns WHERE ID = '" . (int) $id . "'");
    if (!$context['TIMEOUT_CONTEXT_ID']) {
        context_activate(0);
    }
    if ($context['TIMEOUT_SCRIPT']) {
        try {
            $code = $context['TIMEOUT_SCRIPT'];
            $success = eval($code);
            if ($success === false) {
                DebMes("Error in context timeout code: " . $code);
                registerError('context_timeout_action', "Error in context timeout code: " . $code);
            }
        } catch (Exception $e) {
            DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
            registerError('context_timeout_action', get_class($e) . ', ' . $e->getMessage());
        }
    }
    if ($context['TIMEOUT_CONTEXT_ID']) {
        context_activate((int) $context['TIMEOUT_CONTEXT_ID']);
    }
}
コード例 #25
0
ファイル: threads.php プロジェクト: cdkisa/majordomo
 /**
  * Summary of iteration
  * @return bool|int|string
  */
 public function iteration()
 {
     $result = '';
     if (!count($this->streams)) {
         return false;
     }
     $read = $this->streams;
     $write = null;
     $except = null;
     //echo date('H:i:s')." Selecting streams"."\n";
     if (false === ($number_of_streams = stream_select($read, $write, $except, $this->timeout))) {
         DebMes("No active streams");
         return 0;
     }
     /*
           $stream = next($read);
           if (!$stream) {
           reset($read);
           $stream=current($read);
           }
     */
     global $output_show;
     global $delayed;
     $now = time();
     foreach ($read as $stream) {
         $id = array_search($stream, $this->streams);
         stream_set_blocking($stream, 1);
         stream_set_timeout($stream, $this->timeout);
         $stream_status = stream_get_meta_data($stream);
         $proc_status = proc_get_status($this->handles[$id]);
         if ($output_show[$this->commandLines[$id]] != $now) {
             $output_show[$this->commandLines[$id]] = $now;
             $name = $this->commandLines[$id];
             if (preg_match('/cycle_.+?\\.php/', $name, $m)) {
                 $name = $m[0];
             }
             echo date('H:i:s') . " working thread: " . $name . "\n";
             //echo "Status:\n";
             //print_r($proc_status);
             //echo "\n";
         }
         if (!$proc_status['running']) {
             //feof($stream)
             echo date('H:i:s') . " Closing thread: " . $this->commandLines[$id] . "\n";
             DebMes("Closing thread: " . $this->commandLines[$id]);
             $result .= "THREAD CLOSED: [" . $this->commandLines[$id] . "]\n";
             fclose($this->pipes[$id][0]);
             fclose($this->pipes[$id][1]);
             proc_close($this->handles[$id]);
             unset($this->handles[$id]);
             unset($this->streams[$id]);
             unset($this->pipes[$id]);
             unset($this->commandLines[$id]);
         } else {
             $result .= "1";
         }
         /*
                  //$result = stream_get_contents($this->pipes[$id][1]);
                  if (feof($stream) || ($contents = fread($stream, 150))==false) { //)
                  //if (feof($stream) || ($contents = fgets($stream, 4096))==false) {
                  //if (feof($stream) || ($contents = stream_socket_recvfrom($stream, 4096, STREAM_PEEK))) {
                  echo date('H:i:s')." Closing thread: ".$this->commandLines[$id]."\n";
                  DebMes("Closing thread: ".$this->commandLines[$id]);
                  $result.="THREAD CLOSED: [".$this->commandLines[$id]."]\n";
                  fclose($this->pipes[$id][0]);
                  fclose($this->pipes[$id][1]);
                  proc_close($this->handles[$id]);
                  unset($this->handles[$id]);
                  unset($this->streams[$id]);
                  unset($this->pipes[$id]);
                  unset($this->commandLines[$id]);
                  } else {
                  echo "Got: ";
                  echo $contents;
                  $result.=$contents;
                  }
         */
     }
     if ($delayed != $now) {
         $delayed = $now;
         sleep(1);
     }
     return $result;
 }
コード例 #26
0
ファイル: optimize_history.php プロジェクト: cdkisa/majordomo
                // 1 hour and older
                $interval = 3 * 60;
                // 3 minutes interval
                optimizeHistoryData($value_id, $rule['optimize'], $interval, $start, $end);
            }
            $sqlQuery = "SELECT COUNT(*) as TOTAL\n                        FROM phistory\n                       WHERE VALUE_ID = '" . $value_id . "'";
            $total_after = current(SQLSelectOne($sqlQuery));
            echo " <b>(changed " . $total_before . " -> " . $total_after . ")</b><br />";
        }
    }
}
SQLExec("OPTIMIZE TABLE phistory;");
echo "<h1>DONE!!!</h1>";
$db->Disconnect();
// closing database connection
DebMes("Optimize history script finished");
/**
 * Summary of optimizeHistoryData
 * @param mixed $valueID  Id value
 * @param mixed $type     Type
 * @param mixed $interval Interval
 * @param mixed $start    Begin date
 * @param mixed $end      End date
 * @return double|int
 */
function optimizeHistoryData($valueID, $type, $interval, $start, $end)
{
    $totalRemoved = 0;
    if (!$interval) {
        return 0;
    }
コード例 #27
0
ファイル: commands.class.php プロジェクト: NioFBI/majordomo
 /**
 * BackEnd
 *
 * Module backend
 *
 * @access public
 */
 function admin(&$out)
 {
     global $ajax;
     if ($ajax) {
         global $op;
         global $item_id;
         if ($op == 'get_details') {
             startMeasure('getDetails');
             global $labels;
             global $values;
             $res = array();
             //echo "Debug labels: $labels \nValues: $values\n";
             $res['LABELS'] = array();
             $labels = explode(',', $labels);
             $total = count($labels);
             $seen = array();
             for ($i = 0; $i < $total; $i++) {
                 $item_id = trim($labels[$i]);
                 if (!$item_id || $seen[$item_id]) {
                     continue;
                 }
                 $seen[$item_id] = 1;
                 $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
                 if ($item['ID']) {
                     if ($item['TYPE'] == 'custom') {
                         $item['DATA'] = processTitle($item['DATA'], $this);
                         $data = $item['DATA'];
                     } else {
                         $item['TITLE'] = processTitle($item['TITLE'], $this);
                         $data = $item['TITLE'];
                     }
                     if ($item['RENDER_DATA'] != $item['DATA'] || $item['RENDER_TITLE'] != $item['TITLE']) {
                         $tmp = SQLSelectOne("SELECT * FROM commands WHERE ID='" . $item['ID'] . "'");
                         $tmp['RENDER_TITLE'] = $item['TITLE'];
                         $tmp['RENDER_DATA'] = $item['DATA'];
                         $tmp['RENDER_UPDATED'] = date('Y-m-d H:i:s');
                         SQLUpdate('commands', $tmp);
                     }
                     if (preg_match('/#[\\w\\d]{6}/is', $data, $m)) {
                         $color = $m[0];
                         $data = trim(str_replace($m[0], '<style>#item' . $item['ID'] . ' .ui-btn-active {background-color:' . $color . ';border-color:' . $color . '}</style>', $data));
                     }
                     $res['LABELS'][] = array('ID' => $item['ID'], 'DATA' => $data);
                 }
             }
             $res['VALUES'] = array();
             $values = explode(',', $values);
             $total = count($values);
             $seen = array();
             for ($i = 0; $i < $total; $i++) {
                 $item_id = trim($values[$i]);
                 if (!$item_id || $seen[$item_id]) {
                     continue;
                 }
                 $seen[$item_id] = 1;
                 $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
                 if ($item['ID']) {
                     $data = $item['CUR_VALUE'];
                     $res['VALUES'][] = array('ID' => $item['ID'], 'DATA' => $data);
                 }
             }
             $res['LATEST_REQUEST'] = time();
             echo json_encode($res);
             endMeasure('getDetails');
             exit;
         }
         if ($op == 'get_label') {
             startMeasure('getLabel');
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             startMeasure('getLabel ' . $item['TITLE'], 1);
             if ($item['ID']) {
                 $res = array();
                 if ($item['TYPE'] == 'custom') {
                     $item['DATA'] = processTitle($item['DATA'], $this);
                     $res['DATA'] = $item['DATA'];
                 } else {
                     $item['TITLE'] = processTitle($item['TITLE'], $this);
                     $res['DATA'] = $item['TITLE'];
                 }
                 if ($item['RENDER_DATA'] != $item['DATA'] || $item['RENDER_TITLE'] != $item['TITLE']) {
                     $tmp = SQLSelectOne("SELECT * FROM commands WHERE ID='" . $item['ID'] . "'");
                     $tmp['RENDER_TITLE'] = $item['TITLE'];
                     $tmp['RENDER_DATA'] = $item['DATA'];
                     $tmp['RENDER_UPDATED'] = date('Y-m-d H:i:s');
                     SQLUpdate('commands', $tmp);
                 }
                 echo json_encode($res);
             }
             endMeasure('getLabel ' . $item['TITLE'], 1);
             endMeasure('getLabel', 1);
             exit;
         }
         if ($op == 'get_value') {
             startMeasure('getValue');
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             if ($item['ID']) {
                 $res = array();
                 $res['DATA'] = $item['CUR_VALUE'];
                 echo json_encode($res);
             }
             endMeasure('getValue', 1);
             exit;
         }
         if ($op == 'value_changed') {
             global $new_value;
             $item = SQLSelectOne("SELECT * FROM commands WHERE ID='" . (int) $item_id . "'");
             if ($item['ID']) {
                 $old_value = $item['CUR_VALUE'];
                 $item['CUR_VALUE'] = $new_value;
                 SQLUpdate('commands', $item);
                 if ($item['LINKED_PROPERTY'] != '') {
                     //$old_value=gg($item['LINKED_OBJECT'].'.'.$item['LINKED_PROPERTY']);
                     sg($item['LINKED_OBJECT'] . '.' . $item['LINKED_PROPERTY'], $item['CUR_VALUE'], array($this->name => 'ID!=' . $item['ID']));
                 }
                 $params = array('VALUE' => $item['CUR_VALUE'], 'OLD_VALUE' => $old_value);
                 if ($item['ONCHANGE_METHOD'] != '') {
                     if (!$item['LINKED_OBJECT']) {
                         $item['LINKED_OBJECT'] = $item['ONCHANGE_OBJECT'];
                     }
                     getObject($item['LINKED_OBJECT'])->callMethod($item['ONCHANGE_METHOD'], $params);
                     //ONCHANGE_OBJECT
                     //DebMes("calling method ".$item['ONCHANGE_OBJECT'].".".$item['ONCHANGE_METHOD']." with ".$item['CUR_VALUE']);
                 }
                 if ($item['SCRIPT_ID']) {
                     //DebMes('Running on_change script #'.$item['SCRIPT_ID']);
                     runScript($item['SCRIPT_ID'], $params);
                 }
                 if ($item['CODE']) {
                     //DebMes("Running on_change code");
                     try {
                         $code = $item['CODE'];
                         $success = eval($code);
                         if ($success === false) {
                             DebMes("Error menu item code: " . $code);
                             registerError('menu_item', "Error menu item code: " . $code);
                         }
                     } catch (Exception $e) {
                         DebMes('Error: exception ' . get_class($e) . ', ' . $e->getMessage() . '.');
                         registerError('menu_item', get_class($e) . ', ' . $e->getMessage());
                     }
                 }
             }
             echo "OK";
         }
         exit;
     }
     if (isset($this->data_source) && !$_GET['data_source'] && !$_POST['data_source']) {
         $out['SET_DATASOURCE'] = 1;
     }
     if ($this->data_source == 'commands' || $this->data_source == '') {
         if ($this->view_mode == '' || $this->view_mode == 'search_commands') {
             startMeasure('searchCommands');
             $this->search_commands($out);
             endMeasure('searchCommands', 1);
         }
         if ($this->view_mode == 'moveup' && $this->id) {
             $this->reorder_items($this->id, 'up');
             $this->redirect("?");
         }
         if ($this->view_mode == 'movedown' && $this->id) {
             $this->reorder_items($this->id, 'down');
             $this->redirect("?");
         }
         if ($this->view_mode == 'edit_commands') {
             $this->edit_commands($out, $this->id);
         }
         if ($this->view_mode == 'clone_commands') {
             $rec = SQLSelectOne("SELECT * FROM commands WHERE ID='" . $this->id . "'");
             unset($rec['ID']);
             $rec['TITLE'] = $rec['TITLE'] . ' (copy)';
             $rec['ID'] = SQLInsert('commands', $rec);
             $this->redirect("?id=" . $rec['ID'] . "&view_mode=edit_commands");
         }
         if ($this->view_mode == 'delete_commands') {
             $this->delete_commands($this->id);
             $this->redirect("?");
         }
     }
 }
コード例 #28
0
 /**
  * Title
  *
  * Description
  *
  * @access public
  */
 function api_request($id, $params = '')
 {
     if (!$this->config['ZWAVE_API_URL']) {
         $this->getConfig();
     }
     $url = $this->config['ZWAVE_API_URL'] . 'data_request?output_format=json&id=' . $id . '&' . $params;
     DebMes("Veralite API request: " . $url);
     $data = getURL($url);
     return $data;
 }