function diy_compile($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $srcfile = OAuth2\Request::createFromGlobals()->request["srcfile"];
    $srclib = OAuth2\Request::createFromGlobals()->request["srclib"];
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $comp = OAuth2\Request::createFromGlobals()->request["comp"];
    $filename = OAuth2\Request::createFromGlobals()->request["filename"];
    $writedevice = OAuth2\Request::createFromGlobals()->request["writedevice"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["srcfile"] = $srcfile;
    //organisation                                  oauth_devices
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["comp"] = $comp;
    //organisation                                  oauth_devices
    $post["filename"] = $filename;
    //organisation                                  oauth_devices
    $post["writedevice"] = $writedevice;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'filename' => 'required|alpha_numeric', 'comp' => 'required|alpha_numeric', 'writedevice' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'filename' => 'trim|sanitize_string', 'comp' => 'trim|sanitize_string', 'writedevice' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $sourceWriteDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $device . '/' . $filename;
            if (file_exists($sourceWriteDir)) {
                throw new \Exception('Filename ' . $filename . ' for user ' . $client_id . ' and device ' . $device . ' already exists');
            }
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($mode == "devel" && $status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($mode == "devel" && $status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            $result["result"]["sketch1"] = $orgscopeadmin;
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        // *************************************** compiler *********************************
                        // srcfile echeis se base64 ton kodika
                        // compiler echeis ton compiler pou thelei o user   mechri stigmis echoume   gcc, ino
                        // filename to filename pou edosse o user
                        // o poros compilesketch
                        // afou kanei compile
                        // epistrefei
                        // error   ta lathi  h noerrors
                        // binfile    to hex file
                        $compilerserver = diyConfig::read("compiler.host");
                        $compilerserver .= ":" . diyConfig::read("compiler.port");
                        $data1 = 'filename=' . $filename;
                        $data1 .= '&compiler=' . $comp;
                        $data1 .= '&srcfile=' . $srcfile;
                        $fixedFiles = array();
                        foreach ($srclib as $curName => $curFile) {
                            $fixedFiles[] = 'srclib[' . $curName . ']=' . $curFile;
                        }
                        $data1 .= '&' . implode('&', $fixedFiles);
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, "{$compilerserver}/api/compilesketch");
                        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        $or = curl_exec($ch);
                        if (!$or) {
                            $or = curl_error($ch);
                        }
                        $result["compiler"] = $or;
                        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                        $result["status"] = "200";
                        $r = json_decode($or, true);
                        if (!$r) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["compiler"] = $or;
                            $result["status"] = "500";
                            return $result;
                        }
                        if ($r['status'] != 200) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["status"] = "500";
                            return $result;
                        }
                        unset($result["compiler"]);
                        // No need to transfer this to the user
                        //$srcfilebase64encode = base64_encode($srcfile);
                        $apiport = trim($row2["apiport"]);
                        // *************************************** compiler *********************************
                        if ($r['status'] == 200 && $writedevice == "yes") {
                            $apiport = trim($row2["apiport"]);
                            $binfile = $r['hex'];
                            $data1 = 'file=base64';
                            $data1 .= '&binfile=' . $binfile;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/writesketch");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 90);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            $result["sketch"] = $r;
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                            $result["status"] = "200";
                            //$result["result"]=  $r;
                        }
                        // If we are here with no exceptions then everything went well. Lets save the sketch.
                        $ziptmp = tempnam(sys_get_temp_dir(), 'diytmpzip') . '.tgz';
                        file_put_contents($ziptmp, base64_decode($r['zip']));
                        $p = new PharData($ziptmp);
                        $p->decompress();
                        // creates /path/to/my.tar
                        $ziptmpextracted = str_replace('.tgz', '.tar', $ziptmp);
                        $phar = new PharData($ziptmpextracted);
                        $writeDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $filename;
                        $phar->extractTo($sourceWriteDir);
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #2
0
function diy_deverror($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $date = date('Y-m-d H:i:s');
        $error = OAuth2\Request::createFromGlobals()->request["deverror"];
        $action = OAuth2\Request::createFromGlobals()->request["action"];
        $stmt = $storage->prepare('INSERT INTO error_clients (client_id, error, date, action) VALUES (:client_id, :error, :date, :action)');
        $stmt->execute(array('client_id' => $client_id, 'error' => $error, 'date' => $date, 'action' => $action));
        //result_messages===============================================================
        $result["result"] = "ok";
        $result["error"] = $error;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #3
0
/**
 *
 * @SWG\Model(
 *              id="pathModel",
 *              required="path",
 *                  @SWG\Property(name="path",type="string",description="Το path")
 * )
 */
function reload()
{
    global $app;
    $result = array();
    $result["data"] = array();
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    try {
        $result["params"] = $params;
        //do ls
        $parameter = '/root/admin/diyiot.sh killall_socat_ssh; /etc/init.d/diyiotsocat restart; /root/admin/diyiot.sh start_socat;';
        //$parameter = '/root/admin/diyiot.sh reload_socat_ssh';
        $output = shell_exec($parameter);
        $result["result"] = $output;
        //result_messages===============================================================
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #4
0
function writesketch($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $binfile = $params["binfile"];
    //$binfile = $app->request->post('binfile');
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $binfilename = base64_decode($binfile);
    try {
        mkdir("tmp");
        $file = "tmp/file.hex";
        file_put_contents($file, $binfilename);
        $output1 = shell_exec("/etc/init.d/diyiotsocat stop");
        $result["diyiotsocatistop"] = $output1;
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        $result["status"] = "200";
        $result["result"] = "ok";
    } catch (Exception $e) {
        $result["hex"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    try {
        //$output = shell_exec("stty -F /dev/ttyACM0   115200; /usr/bin/avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:$file; /etc/init.d/diyiotsocat start");
        $output = shell_exec("stty -F /dev/ttyACM0   115200; /usr/bin/avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:{$file}");
        $result["avrdude"] = $output;
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        $result["status"] = "200";
        $result["result"] = "ok";
    } catch (Exception $e) {
        $result["avrdude"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    try {
        $output2 = shell_exec("/etc/init.d/diyiotsocat start");
        $result["diyiotsocatstart"] = $output2;
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        $result["status"] = "200";
        $result["result"] = "ok";
    } catch (Exception $e) {
        $result["diyiotsocatstart"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
function diy_wssaddsession($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $session = OAuth2\Request::createFromGlobals()->request["session"];
    $wss_user = OAuth2\Request::createFromGlobals()->request["wss_user"];
    //$device = OAuth2\Request::createFromGlobals()->request["device"];
    try {
        $stmt1 = $storage->prepare('SELECT * FROM oauth_https_wss WHERE client_id = :client_id');
        $stmt1->execute(array('client_id' => trim($client_id)));
        $row = $stmt1->fetch(\PDO::FETCH_ASSOC);
        if ($row) {
            try {
                $stmt3 = $storage->prepare('UPDATE  oauth_https_wss set client_id = :client_id, wss_user = :wss_user, session = :session WHERE client_id = :client_id');
                $stmt3->execute(array('client_id' => $client_id, 'wss_user' => $wss_user, 'session' => $session));
            } catch (Exception $e) {
                echo "error 3" . $e->getMessage();
            }
        } else {
            try {
                $stmt2 = $storage->prepare('INSERT INTO oauth_https_wss (client_id, wss_user, session) VALUES  (:client_id, :wss_user,  :session)');
                $stmt2->execute(array('client_id' => trim($client_id), 'wss_user' => $wss_user, 'session' => $session));
            } catch (Exception $e) {
                echo "error 2" . $e->getCode();
            }
        }
        //result_messages===============================================================
        $result["result"]["session"] = $session;
        $result["result"]["client_id"] = $client_id;
        $result["error"] = $error;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
function diy_activate_account($code)
{
    global $app, $diy_storage;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    try {
        // Update client
        $storage = $diy_storage();
        $updateStmt = $storage->prepare('UPDATE oauth_users SET email_verified = 1 WHERE email_ver_code = :code');
        $updateStmt->execute(array('code' => $code));
        $result = 'Your account has been successfully activated!';
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
function diy_getinfoconfig($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $stmt = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
        $stmt->execute(array('client_id' => $client_id));
        $nr = 0;
        foreach ($stmt as $row) {
            $devices["devinfo"][$nr]["client_id"] = $row["client_id"];
            $devices["devinfo"][$nr]["sshhost"] = $row["sshhost"];
            $devices["devinfo"][$nr]["sshport"] = $row["sshport"];
            $devices["devinfo"][$nr]["apihost"] = $row["apihost"];
            $devices["devinfo"][$nr]["apiport"] = $row["apiport"];
            $devices["devinfo"][$nr]["dataport"] = $row["dataport"];
            $devices["devinfo"][$nr]["tty"] = $row["tty"];
            $devices["devinfo"][$nr]["baud"] = $row["baud"];
            $nr++;
        }
        $stmt1 = $storage->prepare('SELECT * FROM oauth_devices where device = :client_id');
        $stmt1->execute(array('client_id' => $client_id));
        $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
        if ($row1["private_key"]) {
            $devices["devinfo"]["key"] = $row1["private_key"];
        }
        //result_messages===============================================================
        $result["result"] = $devices;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
function diy_seletc($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $m = new MongoClient("mongodb://localhost:27017");
        $db = $m->selectDB("diyiot_sensorsData");
        $collection = $db->mycol;
        switch ((int) $params["operation_id"]) {
            case 1:
                $mongoResult = iterator_to_array($collection->find(array("Map.mapName" => $params["map_name"])));
                break;
            case 2:
                $mongoResult = iterator_to_array($collection->find(array("Date&Time.year" => $params["date_year"], "Date&Time.month" => $params["date_month"], "Date&Time.day" => $params["date_day"])));
                break;
            case 3:
                $mongoResult = iterator_to_array($collection->find(array("Date&Time.year" => $params["date_year"], "Date&Time.month" => $params["date_month"], "Date&Time.day" => $params["date_day"], "Map.mapName" => $params["map_name"])));
                break;
            default:
                $mongoResult = "Wrong number of arguments";
        }
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        $result["status"] = "200";
        $result["result"] = $mongoResult;
    } catch (Exception $e) {
        $diy_error["db"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #9
0
function isAlivelocal()
{
    global $app;
    $result = array();
    $result["data"] = array();
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    try {
        $result["params"] = $params;
        //do ls
        $result["result"] = "ok";
        //result_messages===============================================================
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #10
0
function diy_verifyToken($verify, $client_id)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    try {
        //result_messages===============================================================
        $result["result"]["verify"] = $verify;
        $result["result"]["client_id"] = $client_id;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #11
0
function diyexec()
{
    global $app;
    $result = array();
    $result["data"] = array();
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $exec = $params["exec"];
    $diyexec = base64_decode($exec);
    $result["diyexec"] = $diyexec;
    try {
        $result["params"] = $params;
        exec("{$diyexec} 2>&1", $output, $return_var);
        $result["result"] = $output;
        $result["status"] = "ok";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = "error";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #12
0
function isAlive()
{
    global $app;
    $result = array();
    $result["data"] = array();
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    try {
        $result["params"] = $params;
        //do ls
        $parameter = 'datenow=`date +%s`; echo $datenow >> tmptmptmp';
        $output = shell_exec($parameter);
        $result["result"] = $output;
        //result_messages===============================================================
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #13
0
function diy_removedevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $device = OAuth2\Request::createFromGlobals()->query["device"];
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        $dev = $storage->prepare('SELECT * FROM oauth_devices WHERE device  = :device');
        $dev->execute(array('device' => trim($device)));
        $rowdev = $dev->fetch(PDO::FETCH_ASSOC);
        if ($rowdev) {
            $org = $rowdev["organisation"];
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
        }
        //check if org name exists
        $orgexists = "no";
        $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmtorg->execute(array('org' => trim($org)));
        $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
        if ($roworg) {
            $orgexists = "yes";
            //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
            $orgadmin = "no";
            $orgowner = "no";
            $userscopes = explode(' ', trim($userscope));
            $orgscope = $org . "_admin";
            for ($i = 0; $i <= count($userscopes); $i++) {
                if (trim($userscopes[$i]) == $orgscope) {
                    $orgadmin = "yes";
                }
            }
            if ($orgadmin == "no") {
                //check if org name exists and client_id
                $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                if (!$roworg1) {
                    $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                } else {
                    $orgowner = "yes";
                }
            }
        } else {
            $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
        }
        //check if device name exists
        $orgdeviceexists = "no";
        $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
        $stmt->execute(array('device' => trim($device)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            //$result["result"]["error"] =  ExceptionMessages::DeviceExist." , ". ExceptionCodes::DeviceExist;
            $orgdeviceexists = "yes";
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
            $orgdeviceexists = "no";
        }
        if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "yes") {
            //}else{
            try {
                // oauth_public_keys table
                $encryption_algorithm = "RS256";
                $stmt5 = $storage->prepare('DELETE from oauth_public_keys where client_id = :client_id');
                $stmt5->execute(array('client_id' => $device));
                $stmt1 = $storage->prepare('SELECT * from oauth_clients where client_id = :client_id');
                $stmt1->execute(array('client_id' => $device));
                $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                if ($row1) {
                    $dataport = $row1["dataport"];
                    $apiport = $row1["apiport"];
                    // oauth_users table
                    $user_id = $row1["user_id"];
                    $stmt = $storage->prepare('DELETE from oauth_users where user_id = :user_id');
                    $stmt->execute(array('user_id' => $user_id));
                    // oauth_ports table
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $dataport));
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $apiport));
                    // oauth_clients table
                    $stmt1 = $storage->prepare('DELETE from oauth_clients where client_id = :client_id');
                    $stmt1->execute(array('client_id' => $device));
                    // oauth_devices table
                    $stmt11 = $storage->prepare('DELETE from oauth_devices where device = :device');
                    $stmt11->execute(array('device' => $device));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #14
0
function diy_register()
{
    global $app, $diy_storage;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $client_id = $params["client_id"];
    $client_secret = $params["client_secret"];
    $firstname = $params["first_name"];
    $lastname = $params["last_name"];
    $email = $params["email"];
    $post["client_id"] = $client_id;
    $post["client_secret"] = $client_secret;
    $post["firstname"] = $firstname;
    $post["lastname"] = $lastname;
    $post["email"] = $email;
    foreach ($post as $curKey => $curValue) {
        $diy_error["post"][$curKey] = $curValue;
    }
    $gump = new GUMP();
    $gump->validation_rules(array('client_id' => 'required|alpha_numeric', 'client_secret' => 'required|alpha_numeric', 'firstname' => 'required|alpha_numeric', 'lastname' => 'required|alpha_numeric', 'email' => 'required|valid_email'));
    $gump->filter_rules(array('client_id' => 'trim|sanitize_string', 'client_secret' => 'trim|sanitize_string', 'firstname' => 'trim|sanitize_string', 'lastname' => 'trim|sanitize_string', 'email' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    }
    try {
        if (count($result["parse_errors"]) <= 0) {
            $storage = $diy_storage();
            $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1');
            foreach ($lastkey as $curRow) {
                $lastkey = intval($curRow[0]);
            }
            $code = md5($post["firstname"] . $post["lastname"] . $post["email"]);
            // Create user
            $storage->query('INSERT INTO oauth_users (user_id, first_name, last_name, email, email_verified, email_ver_code)
        VALUES (' . ($lastkey + 1) . ', "' . $post["firstname"] . '", "' . $post["lastname"] . '", "' . $post["email"] . '", 0, "' . $code . '")');
            $user_id = $storage->lastInsertId();
            // Create client
            $publicKey = file_get_contents('../../ssh/CLIENT_ID1_pubkey.pem');
            $privateKey = file_get_contents('../../ssh/CLIENT_ID1_privkey.pem');
            $storage->query('INSERT INTO oauth_clients (client_id, client_secret, scope, user_id) VALUES ("' . $post["client_id"] . '", "' . $post["client_secret"] . '", "main", ' . $user_id . ')');
            $client_id = $storage->lastInsertId();
            $storage->query('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES ("' . $post["client_id"] . '", "' . $publicKey . '", "' . $privateKey . '", "RS256")');
            // Send email
            $mailserver = diyConfig::read('mail.smtpserver');
            $mailserverport = diyConfig::read('mail.smtpport');
            $mailfrom = diyConfig::read('mail.fromuser');
            $link = 'https://' . $_SERVER['HTTP_HOST'] . '/api/activate/' . $code;
            $transport = Swift_SmtpTransport::newInstance($mailserver, $mailserverport);
            $mailer = Swift_Mailer::newInstance($transport);
            $message = Swift_Message::newInstance('Wonderful Subject')->setFrom(array($mailfrom => 'Diyiot'))->setTo(array($post["email"]))->setSubject('Welcome to diyiot')->setBody('Hi ' . $post["firstname"] . ',<BR /><BR />To active your account please click the following link <a href="' . $link . '">' . $link . '</a>.', 'text/html', 'UTF-8');
            $mailer->send($message);
        }
        //result_messages===============================================================
        $result["result"]["user_id"] = $user_id;
        $result["error"] = $error;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        if (isset($user_id)) {
            $storage->query('DELETE FROM oauth_users WHERE user_id = ' . $user_id);
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #15
0
function diy_devsshkeys($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $public_key = OAuth2\Request::createFromGlobals()->request["public_key"];
        $public_key = trim($public_key);
        $pos = mb_strripos($public_key, ' ');
        $s = 0;
        $public = mb_substr($public_key, $s, $pos);
        $pos = mb_strripos($public, ' ');
        $s = $pos;
        $publicstring = mb_substr($public, $s, mb_strlen($public));
        $publicstring = trim($publicstring);
        /*
        	$gump = new GUMP();
        	$gump->validation_rules(array(
        	  'public_key'    => 'required|alpha_numeric'
        	));
        	$gump->filter_rules(array(
        	  'public_key'    => 'trim|sanitize_string'
        	));
        	$validated = $gump->run($post);
        	if($validated === false) {
                	$result["gump1"] = $gump->get_readable_errors(true);
        	} else {
                	$result["gump2"] = $validated; // validation successful
        	}
        */
        if (diy_validate64($publicstring)) {
            $result["v"] = "ok {$publicstring}";
            // validation successful
        } else {
            $result["v"] = "no {$publicstring}";
            // validation successful
        }
        $stmt1 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
        $stmt1->execute(array('client_id' => $client_id));
        foreach ($stmt1 as $row) {
            $sshport = $row["sshport"];
            $apiport = $row["apiport"];
            $dataport = $row["dataport"];
        }
        $stmt = $storage->prepare('UPDATE oauth_devices set public_key=:public_key where device=:client_id');
        $stmt->execute(array('client_id' => $client_id, 'public_key' => $public_key));
        //result_messages===============================================================
        $auth_settings = 'no-pty,no-X11-forwarding,permitopen="localhost:' . $dataport . '",permitopen="localhost:' . $apiport . '",command="/bin/echo do-not-send-commands" ssh-rsa ' . $publicstring . ' ' . $client_id . '=@OpenWrt';
        //file_put_contents('../tmp/authorized_keys', $auth_settings);
        //$result["result"]=  $auth_settings.$public_key;
        $result["result"] = "ok {$auth_settings}";
        $result["error"] = $error;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    return $result;
}
Example #16
0
function diy_diyexec($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $exec = OAuth2\Request::createFromGlobals()->request["exec"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["exec"] = $exec;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'exec' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'exec' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        $stmt3 = $storage->prepare('SELECT * FROM oauth_diyexec WHERE exec = :exec');
                        $stmt3->execute(array('exec' => trim($exec)));
                        $row3 = $stmt3->fetch(PDO::FETCH_ASSOC);
                        if ($row3["exec"]) {
                            $apiport = trim($row2["apiport"]);
                            $diyexec = trim($row3["diyexec"]);
                            $diyexecurl = base64_encode($diyexec);
                            $data1 = 'exec=' . $diyexecurl;
                            //$result["result1"]=  $diyexec;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/diyexec");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            var_dump($r);
                            $result["DEV"] = $r;
                        }
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_wssdeviceAccess($payload, $storage, $exceptions)
{
    global $app;
    $post["session"] = OAuth2\Request::createFromGlobals()->query["session"];
    $post["wss_user"] = OAuth2\Request::createFromGlobals()->query["wss_user"];
    $post["device"] = OAuth2\Request::createFromGlobals()->query["device"];
    $gump = new GUMP();
    $gump->validation_rules(array('wss_user' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'session' => 'required|alpha_numeric'));
    $gump->filter_rules(array('wss_user' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'session' => 'trim|sanitize_string'));
    //$result["gump2"] = $validated; // validation successful
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $result["result"]["view"] = 0;
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $stmt = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt->execute(array('device' => $post["device"]));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row["organisation"]) {
                $organisation = trim($row["organisation"]);
                //$organisation=$row["scope"];
                // o user einai sto scope
                try {
                    $stmt1 = $storage->prepare('SELECT * FROM oauth_https_wss WHERE wss_user = :wss_user and session = :session');
                    $stmt1->execute(array('wss_user' => trim($post["wss_user"]), 'session' => trim($post["session"])));
                    $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                    if ($row1["client_id"]) {
                        $client_user = $row1["client_id"];
                        if ($row["status"] == "org") {
                            try {
                                $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_user');
                                $stmt2->execute(array('client_user' => trim($client_user)));
                                $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                                if ($row2["scope"]) {
                                    $devview = $organisation . "_view";
                                    if (strpos(trim($row2["scope"]), $devview) !== false) {
                                        $result["result"]["view"] = 1;
                                    } else {
                                        $diy_error["errors"] = ExceptionMessages::ScopeNotFound . " , " . ExceptionCodes::ScopeNotFound;
                                    }
                                }
                            } catch (Exception $e) {
                                echo "error " . $e->getCode();
                                $diy_error["db"] = $e->getCode();
                            }
                        } elseif ($row["status"] == "public") {
                            $result["result"]["view"] = 1;
                        } elseif ($row["status"] == "private" && $row["client_id"] == $client_user) {
                            $result["result"]["view"] = 1;
                        } elseif ($row["status"] == "private" && $row["client_id"] != $client_user) {
                            $result["result"]["view"] = 0;
                        }
                    } else {
                        $diy_error["errors"] = ExceptionMessages::UserNotFound . " , " . ExceptionCodes::UserNotFound;
                        //$result["errors"]["select"] = exceptions::MethodNotFound;
                    }
                } catch (Exception $e) {
                    echo "error " . $e->getCode();
                    $diy_error["db"] = $e->getCode();
                }
            }
            //result_messages===============================================================
            $result["status"] = "200";
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        } catch (Exception $e) {
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            echo "error " . $e->getCode();
            $diy_error["db"] = $e->getCode();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #18
0
function diyexecController()
{
    global $app;
    $params = loadParameters();
    switch (strtoupper($app->request()->getMethod())) {
        case 'POST':
            $result = diyexec($params["exec"]);
            break;
    }
    PrepareResponse();
    $app->response()->setBody(json_encode($result));
}
Example #19
0
function diy_adddevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $org = OAuth2\Request::createFromGlobals()->request["org"];
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $client_secret = OAuth2\Request::createFromGlobals()->request["passwd"];
    $device_desc = OAuth2\Request::createFromGlobals()->request["device_desc"];
    $diy_error["post"]["org"] = $org;
    $diy_error["post"]["device"] = $device;
    $diy_error["post"]["client_secret"] = $client_secret;
    $diy_error["post"]["device_desc"] = $device_desc;
    $post["org"] = $org;
    //organisation					oauth_devices
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    $post["client_secret"] = $client_secret;
    //mia perigrafi oti thelei o christis		oauth_devices
    $post["device_desc"] = $device_desc;
    //mia perigrafi oti thelei o christis		oauth_devices
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('org' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'client_secret' => 'required|max_len,100|min_len,6', 'device_desc' => 'required|max_len,100'));
    $gump->filter_rules(array('org' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'client_secret' => 'trim', 'device_desc' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        //check if org name exists
        $orgexists = "no";
        $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmtorg->execute(array('org' => trim($org)));
        $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
        if ($roworg) {
            $orgexists = "yes";
            //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
            $orgadmin = "no";
            $orgowner = "no";
            $userscopes = explode(' ', trim($userscope));
            $orgscope = $org . "_admin";
            for ($i = 0; $i <= count($userscopes); $i++) {
                if (trim($userscopes[$i]) == $orgscope) {
                    $orgadmin = "yes";
                }
            }
            if ($orgadmin == "no") {
                //check if org name exists and client_id
                $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                if (!$roworg1) {
                    $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                } else {
                    $orgowner = "yes";
                }
            }
        } else {
            $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
        }
        //check if device name exists
        $orgdeviceexists = "no";
        $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
        $stmt->execute(array('device' => trim($device)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $result["result"]["error"] = ExceptionMessages::DeviceExist . " , " . ExceptionCodes::DeviceExist;
            $orgdeviceexists = "yes";
        }
        if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "no") {
            //}else{
            try {
                $tempfile = tempnam('tmp/', '');
                if (file_exists($tempfile)) {
                    unlink($tempfile);
                }
                mkdir($tempfile);
                if (is_dir($tempfile)) {
                    exec("openssl genrsa -out {$tempfile}/{$client_id}-privkey.pem 2048");
                    exec("openssl rsa -in {$tempfile}/{$client_id}-privkey.pem -pubout -out {$tempfile}/{$client_id}-pubkey.pem");
                    $publicKey = file_get_contents("{$tempfile}/{$client_id}-pubkey.pem");
                    $privateKey = file_get_contents("{$tempfile}/{$client_id}-privkey.pem");
                    // oauth_public_keys table
                    $encryption_algorithm = "RS256";
                    $stmt5 = $storage->prepare('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (:client_id, :public_key, :private_key, :encryption_algorithm)');
                    $stmt5->execute(array('client_id' => $device, 'public_key' => $publicKey, 'private_key' => $privateKey, ':encryption_algorithm' => $encryption_algorithm));
                    unlink("{$tempfile}/{$client_id}-pubkey.pem");
                    unlink("{$tempfile}/{$client_id}-privkey.pem");
                    // na ftiaxo to key me tis portes na einai etoimo
                    // tha to kano messo cron
                    // o pinakas ta echei ola oauth_clients
                }
                // user_id for dev
                $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1');
                foreach ($lastkey as $curRow) {
                    $lastkey = intval($curRow[0]);
                }
                $lastkey++;
                // oauth_users table
                $stmt = $storage->prepare('INSERT INTO oauth_users (user_id,email_verified) VALUES (:user_id,"1")');
                $stmt->execute(array('user_id' => $lastkey));
                $scope = $org . "_dev";
                $scope .= ' ' . $org . "_dpri";
                $apiport = $storage->query('SELECT apiport FROM oauth_clients ORDER BY apiport DESC LIMIT 1');
                foreach ($apiport as $curRow) {
                    $apiport = intval($curRow[0]);
                }
                $dataport = $apiport + 1;
                $apiport = $apiport + 2;
                $apihost = diyConfig::read('api.host');
                $sshhost = diyConfig::read('ssh.host');
                $sshport = diyConfig::read('ssh.port');
                // oauth_ports table
                $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)');
                $stmt2->execute(array('client_id' => $device, 'port' => $dataport));
                $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)');
                $stmt2->execute(array('client_id' => $device, 'port' => $apiport));
                // oauth_clients table
                $tty = "/dev/ttyACM0";
                $baud = "115200";
                $stmt1 = $storage->prepare('INSERT INTO oauth_clients (client_id, client_secret, user_id, scope, dataport, apiport, apihost, sshhost, sshport, tty, baud) VALUES (:client_id, :client_secret, :user_id, :scope, :dataport, :apiport, :apihost, :sshhost, :sshport, :tty, :baud)');
                $stmt1->execute(array('user_id' => $lastkey, 'client_id' => $device, 'client_secret' => $client_secret, 'scope' => $scope, 'dataport' => $dataport, 'apiport' => $apiport, 'apihost' => $apihost, 'sshhost' => $sshhost, 'sshport' => $sshport, 'tty' => $tty, 'baud' => $baud));
                // oauth_devices table
                $public_key_active = "yes";
                $status = "private";
                $mode = "devel";
                $stmt11 = $storage->prepare('INSERT INTO oauth_devices (device, device_desc, organisation, client_id, public_key_active, status, mode) VALUES (:device, :device_desc, :organisation, :client_id, :public_key_active, :status, :mode)');
                $stmt11->execute(array('device' => $device, 'client_id' => $client_id, 'device_desc' => $device_desc, 'organisation' => $org, 'public_key_active' => $public_key_active, 'status' => $status, 'mode' => $mode));
                $post["status"] = $status;
                $post["mode"] = $mode;
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #20
0
function diy_movedevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $device = OAuth2\Request::createFromGlobals()->query["device"];
    $orgto = OAuth2\Request::createFromGlobals()->query["orgto"];
    $diy_error["post"]["device"] = $device;
    $diy_error["post"]["orgto"] = $orgto;
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    $post["orgto"] = $orgto;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'orgto' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'orgto' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        $movedevice = "no";
        $dev = $storage->prepare('SELECT * FROM oauth_devices WHERE device  = :device');
        $dev->execute(array('device' => trim($device)));
        $rowdev = $dev->fetch(PDO::FETCH_ASSOC);
        if ($rowdev) {
            $org = $rowdev["organisation"];
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
        }
        function check($storage, $userscopes, $org, $client_id, $device)
        {
            //check if org name exists
            $orgexists = "no";
            $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
            $stmtorg->execute(array('org' => trim($org)));
            $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
            if ($roworg) {
                $orgexists = "yes";
                //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
                $orgadmin = "no";
                $orgowner = "no";
                $userscopes = explode(' ', trim($userscope));
                $orgscope = $org . "_admin";
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $orgscope) {
                        $orgadmin = "yes";
                    }
                }
                if ($orgadmin == "no") {
                    //check if org name exists and client_id
                    $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                    $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                    $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                    if (!$roworg1) {
                        $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                    } else {
                        $orgowner = "yes";
                    }
                }
            } else {
                $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
            }
            //check if device name exists
            $orgdeviceexists = "no";
            $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
            $stmt->execute(array('device' => trim($device)));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                //$result["result"]["error"] =  ExceptionMessages::DeviceExist." , ". ExceptionCodes::DeviceExist;
                $orgdeviceexists = "yes";
            } else {
                $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
                $orgdeviceexists = "no";
            }
            if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "yes") {
                $result["result"]["check"] = "ok";
                return $result;
            } else {
                $result["result"]["check"] = "no";
                return $result;
            }
        }
        $diy_error["error"]["check"] = check($storage, $userscopes, $org, $client_id, $device);
        // check if user owned the devices or have admin scope in orgfrom
        $checkr = check($storage, $userscopes, $org, $client_id, $device);
        if ($checkr["result"]["check"] == "ok") {
            $diy_error["error"]["orgfrom"] = "ok";
            // check if user owned the devices or have admin scope in orgto
            $checkr1 = check($storage, $userscopes, $orgto, $client_id, $device);
            if ($checkr1["result"]["check"] == "ok") {
                $diy_error["error"]["orgto"] = "ok";
                $movedevice = "yes";
            }
        }
        //if( ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes")) && $orgdeviceexists == "yes"){
        if ($movedevice == "yes") {
            //}else{
            try {
                $stmt1 = $storage->prepare('SELECT * from oauth_clients where client_id = :client_id');
                $stmt1->execute(array('client_id' => $device));
                $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                if ($row1) {
                    $scopedevt = $row1["scope"];
                    $orgt = $org . "_";
                    $orgtot = $orgto . "_";
                    $scopedev = str_replace($orgt, $orgtot, $scopedevt);
                    // oauth_clients table
                    $stmt1 = $storage->prepare('UPDATE oauth_clients set scope = :scopedev where client_id = :client_id');
                    $stmt1->execute(array('client_id' => $device, 'scopedev' => $scopedev));
                    // oauth_devices table
                    $stmt11 = $storage->prepare('UPDATE oauth_devices set organisation = :orgto  where device = :device');
                    $stmt11->execute(array('device' => $device, 'orgto' => $orgto));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function compilesketch($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $srcfile = urldecode(base64_decode(urldecode($params["srcfile"])));
    $srclib = array();
    foreach ($_POST['srclib'] as $curName => $curFile) {
        $srclib[$curName] = urldecode(base64_decode(urldecode($curFile)));
    }
    $compiler = $params["compiler"];
    $filename = $params["filename"];
    if ($compiler == 'gcc') {
        $tmpfile = tempnam('/tmp', 'avrsrc') . '.c';
        file_put_contents($tmpfile, $srcfile);
        try {
            putenv("PATH=" . getenv('PATH') . ':/var/www/html/tools/build-tools/avr-gcc/src/x64/avr/bin');
            $output = shell_exec("/var/www/html/tools/build-tools/avr-gcc/compile.sh " . $tmpfile . ' 2>&1; echo $?');
            if ($output != null && file_exists($tmpfile . '.hex')) {
                //$result["output"]=  $output; // Don't show output when there were no errors
                $result["zip"] = zipSketch($tmpfile);
                $result["hex"] = base64_encode(file_get_contents($tmpfile . '.hex'));
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                $result["status"] = "200";
                $result["result"] = "ok";
            } else {
                $result["output"] = $output;
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: Error";
                $result["status"] = "500";
                $result["result"] = "error";
            }
        } catch (Exception $e) {
            $result["output"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
        @unlink($tmpfile);
        @unlink($tmpfile . '.hex');
    } else {
        if ($compiler == 'ino') {
            $tmpfile = tempnam('/tmp', 'avrsrc') . '1';
            try {
                if (!mkdir($tmpfile)) {
                    throw new \Exception('Could not create project directory: ' . $tmpfile);
                }
                putenv("PATH=" . getenv('PATH') . ':/var/www/html/tools/build-tools/ino/ino/bin');
                // Create project folder and init
                $output = shell_exec("cd " . $tmpfile . "; /var/www/html/tools/build-tools/ino/ino/bin/ino init 2>&1; echo \$?");
                if (trim($output) != '0') {
                    throw new \Exception('Could not init project dir: ' . trim($output));
                }
                file_put_contents($tmpfile . '/src/sketch.ino', $srcfile);
                foreach ($srclib as $curName => $curFile) {
                    if (!is_dir(dirname($tmpfile . '/lib/' . $curName))) {
                        mkdir(dirname($tmpfile . '/lib/' . $curName), 0777, true);
                    }
                    file_put_contents($tmpfile . '/lib/' . $curName, $curFile);
                }
                $zipSketch = zipSketch($tmpfile);
                $output = shell_exec("cd " . $tmpfile . "; /var/www/html/tools/build-tools/ino/ino/bin/ino build 2>&1; echo \$?");
                $outputParts = explode("\n", $output);
                if ($outputParts[count($outputParts) - 2] != '0') {
                    $result["output"] = $output;
                    throw new \Exception('Compilation failed');
                }
                if ($outputParts[count($outputParts) - 2] == '0' && file_exists($tmpfile . '/.build/uno/firmware.hex')) {
                    //$result["output"]=  $output; // Don't show output when there were no errors
                    $result["zip"] = $zipSketch;
                    $result["hex"] = base64_encode(file_get_contents($tmpfile . '/.build/uno/firmware.hex'));
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                    $result["status"] = "200";
                    $result["result"] = "ok";
                } else {
                    $result["output"] = $output;
                    throw new \Exception('Compilation failed');
                }
            } catch (Exception $e) {
                $result["status"] = "500";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                $result["result"] = "error";
            }
            @unlink($tmpfile);
            @unlink($tmpfile . '.hex');
        } else {
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: UnsupportedCompiler";
            $result["status"] = "500";
            $result["result"] = "error";
        }
    }
    return $result;
}
Example #22
0
function diy_addorg($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $org = OAuth2\Request::createFromGlobals()->request["org"];
    $org_desc = OAuth2\Request::createFromGlobals()->request["org_desc"];
    $diy_error["post"]["org"] = $org;
    $diy_error["post"]["org_desc"] = $org_desc;
    $post["org"] = $org;
    //organisation					oauth_devices
    $post["org_desc"] = $org_desc;
    //mia perigrafi oti thelei o christis		oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('org' => 'required|alpha_numeric', 'org_desc' => 'required|max_len,100'));
    $gump->filter_rules(array('org' => 'trim|sanitize_string', 'org_desc' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        //check if device name exists
        $stmt = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmt->execute(array('org' => trim($org)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $result["result"]["error"] = ExceptionMessages::OrgExist . " , " . ExceptionCodes::OrgExist;
        } else {
            try {
                // oauth_organisation table
                $stmt2 = $storage->prepare('INSERT INTO oauth_organisations (organisation, client_id, desc) VALUES (:org, :client_id, :desc)');
                $stmt2->execute(array('client_id' => $client_id, 'org' => $org, 'desc' => $org_desc));
                // scopes gia devices
                $scope = $org;
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dev";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dpri";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_org";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dpub";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                // scopes gia users
                $scope = $org . "_view";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_devel";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_admin";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $stmt6 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
                $stmt6->execute(array('client_id' => trim($client_id)));
                $row6 = $stmt6->fetch(PDO::FETCH_ASSOC);
                if ($row6) {
                    $scope6 = $row6["scope"];
                    $scope6 .= " " . $org . "_admin";
                    $scope6 .= " " . $org . "_view";
                    $stmt5 = $storage->prepare('UPDATE oauth_clients  set scope = :scope6 where client_id = :client_id');
                    $stmt5->execute(array('scope6' => $scope6, 'client_id' => $client_id));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #23
0
function diy_getdevices($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
        $stmt2->execute(array('client_id' => trim($client_id)));
        $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
        if ($row2["scope"]) {
            $scopes = explode(' ', trim($row2["scope"]));
            $diy_error["scopescount"] = count($scopes);
            $devview = "view";
            $nr = 0;
            for ($i = 0; $i <= count($scopes); $i++) {
                $diy_error["scopes"] = $scopes[$i];
                $view = explode('_', $scopes[$i]);
                if (trim($view[1]) == $devview) {
                    $org = trim($view[0]);
                    $diy_error["org"] = $org;
                    try {
                        $stmt = $storage->prepare('SELECT * FROM oauth_devices WHERE organisation = :org');
                        $stmt->execute(array('org' => $org));
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            if ($row["status"] == "private" && $row["client_id"] == "{$client_id}") {
                                $devices["dev"][$nr]["device"] = $row["device"];
                                $devices["dev"][$nr]["device_desc"] = $row["device_desc"];
                                $devices["dev"][$nr]["organisation"] = $row["organisation"];
                                $devices["dev"][$nr]["status"] = $row["status"];
                                $devices["dev"][$nr]["mode"] = $row["mode"];
                                $nr++;
                            } elseif ($row["status"] == "org" || $row["status"] == "public") {
                                $diy_error["dev"][$nr] = $row["device"];
                                $devices["dev"][$nr]["device"] = $row["device"];
                                $devices["dev"][$nr]["device_desc"] = $row["device_desc"];
                                $devices["dev"][$nr]["organisation"] = $row["organisation"];
                                $devices["dev"][$nr]["status"] = $row["status"];
                                $devices["dev"][$nr]["mode"] = $row["mode"];
                                $nr++;
                            }
                        }
                    } catch (Exception $e) {
                        $diy_error["db"] = $e->getCode();
                        $result["status"] = $e->getCode();
                        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                    }
                }
            }
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            $result["status"] = "200";
            $result["result"] = $devices;
        }
    } catch (Exception $e) {
        $diy_error["db"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}