Skip to content
Snippets Groups Projects
Backend.php 106 KiB
Newer Older
root's avatar
root committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
<?php
namespace SmartData;

if (!extension_loaded('cassandra'))
    die ("Unable to load cassandra extension\n");

require_once( __DIR__ . '/Config.php');
require_once( __DIR__ . '/Logger.php');
require_once( __DIR__ . '/Exception.php');
require_once( __DIR__ . '/Aggregators.php');
require_once( __DIR__ . '/Series.php');
require_once( __DIR__ . '/SmartData.php');
require_once( __DIR__ . '/Unit.php');
require_once( __DIR__ . '/Packer.php');
require_once( __DIR__ . '/Time.php');

use SmartData\Utility\{Pack,Unpack};
use SmartData\Exception\{AuthenticationException,BadRequestException,InternalException};

class Backend_Common
{
    protected $_domain;
    protected $_username;
    protected $_password;

    protected $_client_ip;
    protected $_client_name;

    protected $_gw_id;

    private $_session_id;

    private $_internal;
    protected function internal(){ return $this->_internal; }

    protected const READ = 'r';
    protected const WRITE = 'w';

    // The parameter "$internal" means that the Backend has been called without a requisition.
    // Please, be careful and use only for development tasks.
    public function __construct(Credentials $credentials = NULL, $internal=false) {
        $credentials = $credentials ?? new Credentials();

        $testint = 0x00FF; // Ensure the machine is little-endian
        if(!($testint===current(unpack('v', pack('S', $testint))))) throw new \Exception("The machine is not little-endian");
        $this->_gw_id = -1; //NOTE: That means that the client isn't a known gateway
        $this->_internal = $internal; //NOTE: just for developers

        $USER   = ($credentials->username != NULL and $credentials->password != NULL);
        $DOMAIN = ($credentials->domain != NULL);

        // If it's not in an internal mode and the request is not secure (SSL), only the
        // domains listed in Config::config()::ACCESSIBLE_WITHOUT_SSL can be accessed.
        if (!$internal && !REQUEST_HTTPS && !in_array($credentials->domain, Config::config()::ACCESSIBLE_WITHOUT_SSL)){
            throw new AuthenticationException("Authentication failure [{$credentials}]");
        }

        switch (REQUEST_URI) {
            case 'get.php':
                /**
                 *  ====== Summary of rules ======
                 *  HTTPS ^ CERT ^ domain -> OK, domain = $domain
                 *  HTTPS ^ CERT  -> OK, domain = DB(CERT)->domain
                 *  HTTPS ^ domain ^ valid(usr+password) -> OK, domain = $domain
                 *  HTTPS ^ valid(usr+password) -> OK, domain = public
                 *  HTTPS ^ domain -> OK, domain is public ? domain = $domain : fail
                 *  HTTPS -> OK, domain = public
                 *  HTTP ^ valid(usr+password) -> OK, domain = hydrology
                 *  Fail
                 */

                if ( REQUEST_HTTPS && REQUEST_CERT && $DOMAIN ) {
                    if(!$this->_checkCertificate(REQUEST_SERIAL, self::READ, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(CD) Unauthorized access');
                } else if ( REQUEST_HTTPS && REQUEST_CERT ) {
                    if(!$this->_checkCertificate(REQUEST_SERIAL, self::READ))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(C) Unauthorized access');
                } else if ( REQUEST_HTTPS && $DOMAIN && $USER ) {
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::READ, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(DU) Unauthorized access');
                } else if ( REQUEST_HTTPS && $USER ) {
                    $credentials->domain = Config::config()::PUBLIC_DOMAIN;
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::READ, Config::config()::PUBLIC_DOMAIN))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(U) Unauthorized access');
                } else if ( REQUEST_HTTPS && $DOMAIN ) {
                    // NOTE: Publicly readable domains
                    if(!$this->_checkUser(Config::config()::DEFAULT_USERNAME, Config::config()::DEFAULT_PASSWORD, self::READ, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(D) Unauthorized access');
                } else if ( REQUEST_HTTPS ) {
                    $this->_domain   = Config::config()::PUBLIC_DOMAIN;
                    $this->_username = Config::config()::DEFAULT_USERNAME;
                    $this->_password = Config::config()::DEFAULT_PASSWORD;
                } else if ( !REQUEST_HTTPS && $DOMAIN && $USER ) {
                    //NOTE: Domain that are accessible with HTTP (without SSL)
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::READ, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(DU) Unauthorized access');
                } else {
                    throw new BadRequestException(REQUEST_DBG.' crd:'.$credentials.' Bad protocol and options');
                }
                break;

            case 'create.php'    :
            case 'attach.php'    :
            case 'put.php'       :
            case 'batch.php'     :
            case 'put_batch.php' :
                /**
                 *  ====== Summary of rules ======
                 *  HTTPS ^ CERT ^ domain -> OK, domain = $domain
                 *  HTTPS ^ CERT  -> OK, domain = DB(CERT)->domain
                 *  HTTPS ^ domain ^ valid(usr+password) -> OK, domain = $domain
                 *  HTTPS ^ valid(usr+password) -> OK, domain = public
                 *  HTTP  ^ valid(usr+password) -> OK, domain = hydrology
                 *  Fail
                 */

                if ( REQUEST_HTTPS && REQUEST_CERT && $DOMAIN ) {
                    if(!$this->_checkCertificate(REQUEST_SERIAL, self::WRITE, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(CD) Unauthorized access');
                } else if ( REQUEST_HTTPS && REQUEST_CERT ) {
                    if(!$this->_checkCertificate(REQUEST_SERIAL, self::WRITE))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(C) Unauthorized access');
                } else if ( REQUEST_HTTPS && $DOMAIN && $USER ) {
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::WRITE, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(DU) Unauthorized access');
                } else if ( REQUEST_HTTPS && $USER ) {
                    //TODO: Check what is the main idea
                    $credentials->domain = Config::config()::PUBLIC_DOMAIN;
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::WRITE, Config::config()::PUBLIC_DOMAIN))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(U) Unauthorized access');
                } else if ( REQUEST_HTTPS && $DOMAIN ) {
                    // NOTE: Public writable domains
                    if(!$this->_checkUser(Config::config()::DEFAULT_USERNAME, Config::config()::DEFAULT_PASSWORD, self::WRITE, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(D) Unauthorized access');
                } else if ( !REQUEST_HTTPS && $DOMAIN && $USER ) {
                    //NOTE: Domain that are accessible with HTTP (without SSL)
                    if(!$this->_checkUser($credentials->username, $credentials->password, self::WRITE, $credentials->domain))
                        throw new AuthenticationException(REQUEST_DBG.' crd:'.$credentials.'(DU) Unauthorized access');
                } else {
                    throw new BadRequestException(REQUEST_DBG.' crd:'.$credentials.' Bad protocol and options');
                }
                break;
            default:
                if($this->internal()){
                    $this->_domain = $credentials->domain;
                    $this->_username = $credentials->username;
                    $this->_password = $credentials->password;
                } else
                    throw new BadRequestException(REQUEST_DBG.' crd:'.$credentials.' Bad protocol and options');
                break;
        }

        if($this->_domain == null || $this->_username == null || $this->_password == null){
            throw new BadRequestException("Incorrect use of protocol and options {$credentials}");
        }

        $this->_session_id = $this->_domain.'_'.substr(uniqid(), -5);
        if(REQUEST_URI != 'get.php')
            self::debug_X($this);
    }

    // Checks the health of databases
    public static function health_check() : bool {
        $sucess = true;
        try {
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME,
                                        Config::config()::MYSQL_PORT,
                                        Config::config()::MYSQL_DBNAME,
                                        Config::config()::MYSQL_USERNAME,
                                        Config::config()::MYSQL_PASSWORD);
            $conn = null;
            $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME,
                                               Config::config()::CASSANDRA_PORT,
                                               Config::config()::DEFAULT_USERNAME,
                                               Config::config()::DEFAULT_PASSWORD,
                                               Config::config()::CASSANDRA_KEYSPACE);
            $session->close();
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }
        return $sucess;
    }

    // Check Certificate
    private function _checkCertificate(string $certificate, string $level, string $domain = null) : bool {
        $sucess = true;
        $target_domain = "";
        $gw_id = -1;

        $parameters = array(':certificate' => $certificate,
                            ':level'       => $level);

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            if(Config::config()::api_version() == Config::config()::VERSION_1_1) // TODO: Remove from development_mode
                $table = 'clients';
            else
                $table = 'gateways'; // table that has to be changed to clients

            if($domain == null){
                $stmt = $conn->prepare("SELECT id, domain FROM {$table} WHERE enable = true AND certificate = :certificate AND INSTR(level, :level) > 0 ORDER BY id ASC LIMIT 1");
            } else {
                $parameters = array_merge($parameters, array(':domain'=> $domain));
                $stmt = $conn->prepare("SELECT id, domain FROM {$table} WHERE enable = true AND certificate = :certificate AND (domain = :domain OR domain = '*') AND INSTR(level, :level) > 0");
            }

            $stmt->execute($parameters);
            if($stmt->rowCount() != 1)
                throw new AuthenticationException("Permission not found or number of domains larger than one [{$certificate} / {$level}]");
            else{
                $result = $stmt->fetch(\PDO::FETCH_OBJ);
                $target_domain = $domain ?? $result->domain;
                $gw_id = $result->id;
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        if ($sucess) {
            $this->_domain = $target_domain;
            $this->_username = Config::config()::CASSANDRA_SUPERUSER;
            $this->_password = Config::config()::CASSANDRA_SUPERPASS;
            $this->_gw_id = $gw_id;
            return true;
        } else {
            return false;
        }
    }

    // Check User Connection
    private function _checkUserConnection(string $username, string $password) : bool {
        $sucess = false;
        try {
            $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $username, $password, Config::config()::CASSANDRA_KEYSPACE);
            $sucess = true;
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
        }
        return $sucess;
    }

    // Check if an user has permission to read/write on a domain
    private function _checkUser(string $username, string $password, string $level, string $domain = null) : bool {
        //TODO: Check what is the main idea
        if($domain == NULL) return false;

        $sucess = false;

        try {
            $permission = array();
            switch($level) {
                case self::READ:
                    array_push($permission, 'SELECT');
                case self::WRITE:
                    array_push($permission, 'MODIFY');
                    break; // Test to write
                default; return false; // invalid option
            }

            if(Config::config()::api_version() == Config::config()::VERSION_1_1) { // TODO: Remove from development_mode
                $keyspace = Config::config()::CASSANDRA_KEYSPACE;
                //$query = "LIST ALL PERMISSIONS ON table {$keyspace}.{$domain} OF {$username};";
                $query = "LIST ALL PERMISSIONS OF {$username};";
                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, Config::config()::CASSANDRA_SUPERUSER, Config::config()::CASSANDRA_SUPERPASS, Config::config()::CASSANDRA_KEYSPACE);
                $statement = new \Cassandra\SimpleStatement($query);
                $result = $session->execute($statement);

                foreach ($result as $column) {
                    $pattern = "<table {$keyspace}.{$domain}_v";
                    if((strpos($column['resource'], $pattern) !== false)) {
                        if(in_array($column['permission'], $permission)){
                            $sucess = true;
                            break;
                        }
                    }
                }
                if($sucess)
                    $sucess = $this->_checkUserConnection($username, $password);
            } else {
                $keyspace = Config::config()::CASSANDRA_KEYSPACE;
                $query = "LIST ALL PERMISSIONS ON table {$keyspace}.{$domain} OF {$username};";

                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, Config::config()::CASSANDRA_SUPERUSER, Config::config()::CASSANDRA_SUPERPASS, Config::config()::CASSANDRA_KEYSPACE);
                $statement = new \Cassandra\SimpleStatement($query);
                $result = $session->execute($statement);

                foreach ($result as $column) {
                    if(in_array($column['permission'], $permission)){
                        $sucess = $this->_checkUserConnection($username, $password);
                        break;
                    }
                }
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
        }

        if ($sucess) {
            $this->_domain = $domain;
            $this->_username = $username;
            $this->_password = $password;
            return true;
        } else {
            return false;
        }
    }

    // Open a connection with MySQL database
    protected static function _mysqlConnect(string $servername, int $port, string $dbname, string $username, string $password) : \PDO {
        $conn = new \PDO("mysql:host=$servername;port=$port;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        return $conn;
    }

    // Open a connection with Cassandra database
    protected static function _cassandraConnect(string $servername, int $port, string $username, string $password, string $keyspace) : \Cassandra\DefaultSession {
        $cluster = \Cassandra::cluster()->withContactPoints($servername)
                                        ->withPort($port)
                                        ->withCredentials($username, $password)
                                        //->withDefaultPageSize(200)
                                        ->build();
        $session = $cluster->connect($keyspace);
        return $session;
    }

    protected function debug_X(string $message, $ctrl=false) {
        Logger::debug_X('['.$this->_session_id.'] '.$message, ($ctrl === false) ? get_called_class() : $ctrl);
    }

    public function __toString() { return REQUEST_DBG.' crd:{'.$this->_username.'@'.$this->_domain.'}'; }
}

class Tracker
{
    public $version;
    public $unit;
    public $signature;
    public $t0;
    public $t1;

    public function __construct($version, $unit, $signature, $t0, $t1) {
        // Conditions for a valid tracker.
        if ((gmp_cmp(gmp_init($t0), gmp_init($t1)) > 0) or (false)){
            throw new BadRequestException("Invalid tracker");
        }

        $this->version   = $version;
        $this->unit      = $unit;
        $this->signature = $signature;
        $this->t0        = $t0;
        $this->t1        = $t1;
    }
}

final class Credentials
{
    public $domain;
    public $username;
    public $password;

    public function __construct($d=null, $u=null, $p=null) {
        if ($u == null xor $p == null) {
            throw new Exception\BadCredentialsException("Invalid credentials fields [{$username}@{$domain}]");
        }
        $this->domain   = $d;
        $this->username = $u;
        $this->password = $p;
    }

    public function pack(array $suppress = array()) {
        $bin  = '';
        $bin .= Pack::string($this->domain);
        $bin .= Pack::string($this->username);
        $bin .= Pack::string($this->password);
        return $bin;
    }

    public static function unpack(& $bin, array $compl = array()) {
        $domain   = Unpack::string($bin, true);
        $username = Unpack::string($bin, true);
        $password = Unpack::string($bin, true);
        return new self($domain, $username, $password);
    }

    public static function fromJson(\stdClass $json) {
        return new self($json->domain   ?? null, $json->username ?? null, $json->password ?? null);
    }

    public function __toString() {
        $string  = "{";
        $string .= "{$this->username}@{$this->domain}, ";
        $string .= strlen($this->password);
        $string .= '}';
        return $string;
    }
}

## Backend of API version 1.0 ##############################################################################
class Backend_V1_0 extends Backend_Common
{
    // Create a new series if not exist
    //public function create(Series $series) : bool {
    public function create($series) {
        $sucess = true;
        $parameters = array(':version'  => $series->version,
                            ':unit'     => $series->unit,
                            ':x'        => $series->x,
                            ':y'        => $series->y,
                            ':z'        => $series->z,
                            ':r'        => $series->r,
                            ':t0'       => $series->t0,
                            ':t1'       => $series->t1,
                            ':domain'   => $this->_domain,
                            ':count'    => Config::config()::CASSANDRA_MAX_ROW_SIZE);
        try {
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($series->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE version = :version
                                              AND unit = :unit
                                              AND x = :x
                                              AND y = :y
                                              AND z = :z
                                              AND r = :r
                                              AND t0 = :t0
                                              AND t1 = :t1
                                              AND domain = :domain
                                              AND count < :count
                                            ORDER BY id DESC LIMIT 1;");

            $stmt_select->execute($parameters);
            $series = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($series == NULL) {
                // Not exists yet
                $stmt_insert = $conn->prepare("INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :x, :y, :z, :r, :t0, :t1, DEFAULT, :domain, (SELECT counter(:domain)), DEFAULT);");
                $stmt_insert->execute($parameters);
            }
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }
    // Create a new series if there is not one that contains it
    //public function attach(Series $series) : bool {
    public function attach($series) {
        $sucess = true;

        $table = Config::config()::MySQL_Table($series->version);

        if($series->version == SmartData::MOBILE_VERSION){
            $parameters = array(':version'   => $series->version,
                                ':unit'      => $series->unit,
                                ':signature' => $series->signature,
                                ':x'         => $series->x,
                                ':y'         => $series->y,
                                ':z'         => $series->z,
                                ':r'         => $series->r,
                                ':t0'        => $series->t0,
                                ':t1'        => $series->t1,
                                ':domain'    => $this->_domain,
                                ':count'     => Config::config()::CASSANDRA_MAX_ROW_SIZE);

            $query = "SELECT * FROM {$table} WHERE version = :version
                  AND unit = :unit
                  AND signature = :signature
                  AND r >= (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2)) + :r)
                  AND t0 <= :t0 AND t1 >= :t1
                  AND domain = :domain
                  AND count < :count
                ORDER BY r ASC LIMIT 1;";

            $insert = "INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :x, :y, :z, :r, :t0, :t1, DEFAULT, :domain, (SELECT counter(:domain)), DEFAULT, :signature);";

            Logger::debug('Attaching MOBILE:'.$series, true);

        }else{
            Logger::debug('Attaching STATIC'.$series, true);
            $parameters = array(':version'   => $series->version,
                                ':unit'      => $series->unit,
                                ':x'         => $series->x,
                                ':y'         => $series->y,
                                ':z'         => $series->z,
                                ':r'         => $series->r,
                                ':t0'        => $series->t0,
                                ':t1'        => $series->t1,
                                ':domain'    => $this->_domain,
                                ':count'     => Config::config()::CASSANDRA_MAX_ROW_SIZE);

            $query = "SELECT * FROM {$table} WHERE version = :version
                  AND unit = :unit
                  AND r >= (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2)) + :r)
                  AND t0 <= :t0 AND t1 >= :t1
                  AND domain = :domain
                  AND count < :count
                ORDER BY r ASC LIMIT 1;";

            $insert = "INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :x, :y, :z, :r, :t0, :t1, DEFAULT, :domain, (SELECT counter(:domain)), DEFAULT, DEFAULT);";
        }

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME,
                                        Config::config()::MYSQL_PORT,
                                        Config::config()::MYSQL_DBNAME,
                                        Config::config()::MYSQL_USERNAME,
                                        Config::config()::MYSQL_PASSWORD);

            $stmt_select = $conn->prepare($query);

            $stmt_select->execute($parameters);
            $series = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($series == NULL) {
                $stmt_insert = $conn->prepare($insert);
                $stmt_insert->execute($parameters);

                Logger::debug(__FILE__."> Attach (new series)");
            }else{
                //print_r($series);
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }
    // Insert SmartData into series/tracker matched
    public function insert(SmartData $smart_data) {
        if ($smart_data instanceof StaticSmartData)
            return $this->_insertStaticSmartData($smart_data);
        else if ($smart_data instanceof MobileSmartData)
            return $this->_insertMobileSmartData($smart_data);
        else
            throw new BadRequestException("Error processing JSON request: unsupported SmartData version");
    }
    // Insert a static version of smartdata
    private function _insertStaticSmartData(StaticSmartData $smart_data) : bool {
        $sucess = true;

        $parameters = array(':unit'       => $smart_data->unit,
                            ':x'          => $smart_data->x,
                            ':y'          => $smart_data->y,
                            ':z'          => $smart_data->z,
                            ':time'       => $smart_data->time,
                            ':domain'     => $this->_domain);

        $is_digital = $smart_data->unit()->is_digital();

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($smart_data->version);
            $series = NULL;
            $first = true;
            do {
                $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE unit = :unit
                                                              AND (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2))) <= r
                                                              AND :time >= t0 AND :time <= t1
                                                              AND domain = :domain
                                                            ORDER BY r ASC, count ASC LIMIT 1;");

                $stmt_select->execute($parameters);
                $series = $stmt_select->fetch(\PDO::FETCH_OBJ);

                if ($first && $series!=NULL && $series->count>=Config::config()::CASSANDRA_MAX_ROW_SIZE) {
                    $this->create(new Series($series->version,
                                      $series->unit,
                                      $series->x,
                                      $series->y,
                                      $series->z,
                                      $series->r,
                                      $series->t0,
                                      $series->t1));

                    $first = false;
                } else {
                    break;
                }
            } while (true);

            if ($series == NULL) {
                throw new Exception\NoMatchingSeriesException('No matching series');
            }else{

                //Logger::debug("Inserting StaticSmartData");

                $entry_type = \Cassandra\Type::userType(
                    // Just for attend projects requirements of SO2 -------------------------------------
                    'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                    // ----------------------------------------------------------------------------------
                    'error',      \Cassandra\Type::tinyint(),
                    'confidence', \Cassandra\Type::tinyint(),
                    'x',          \Cassandra\Type::int(),
                    'y',          \Cassandra\Type::int(),
                    'z',          \Cassandra\Type::int(),
                    'd',          \Cassandra\Type::bigint(),
                    'gw',         \Cassandra\Type::bigint()
                );

                $smart_data->confidence = $this->assign_confidence($smart_data);

                $arguments = array(
                    new \Cassandra\Bigint($series->slice),
                    new \Cassandra\Varint($smart_data->time),
                    $entry_type->create(
                        'value',      ($is_digital) ? new \Cassandra\Blob($smart_data->value) : (double) $smart_data->value,
                        'error',      new \Cassandra\Tinyint($smart_data->error),
                        'confidence', new \Cassandra\Tinyint($smart_data->confidence),
                        'x',          (int)$smart_data->x,
                        'y',          (int)$smart_data->y,
                        'z',          (int)$smart_data->z,
                        'd',          new \Cassandra\Bigint($smart_data->dev??0), //TODO: remove the ??
                        //'gw',         new \Cassandra\Bigint($smart_data->gw->id)
                        'gw',         new \Cassandra\Bigint($this->_gw_id) // TODO: CHECK THIS
                    )
                );

                $cassandra_table = "{$this->_domain}" . (($is_digital) ? '_dig' : '');

                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);
                $insert_stmt = $session->prepare("INSERT INTO {$cassandra_table} (id, timestamp, entry) VALUES (?, ?, ?);");
                $session->execute($insert_stmt, array('arguments' => $arguments));

                $update_stmt = $conn->prepare("UPDATE {$table} SET count = count + 1 WHERE id = :id LIMIT 1;");
                $update_stmt->execute(array('id' => $series->id));
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $sucess;
    }
    // Insert a mobile version of smartdata
    private function _insertMobileSmartData(MobileSmartData $smart_data) : bool {

        Logger::debug("_insertMobileSmartData".$smart_data, true);

        $sucess = true;

        $parameters = array(':unit'       => $smart_data->unit,
                            ':signature'  => $smart_data->signature,
                            ':x'          => $smart_data->x,
                            ':y'          => $smart_data->y,
                            ':z'          => $smart_data->z,
                            ':time'       => $smart_data->time,
                            ':domain'     => $this->_domain);

        $is_digital = $smart_data->unit()->is_digital();

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($smart_data->version);
            $series = NULL;
            $first = true;
            do {
                $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE unit = :unit
                                                              AND (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2))) <= r
                                                              AND :time >= t0 AND :time <= t1
                                                              AND domain = :domain
                                                              AND signature = :signature
                                                            ORDER BY r ASC, count ASC LIMIT 1;");

                $stmt_select->execute($parameters);
                $series = $stmt_select->fetch(\PDO::FETCH_OBJ);

                if ($first && $series!=NULL && $series->count>=Config::config()::CASSANDRA_MAX_ROW_SIZE) {
                    $this->create(new Series($series->version,
                                      $series->unit,
                                      $series->x,
                                      $series->y,
                                      $series->z,
                                      $series->r,
                                      $series->t0,
                                      $series->t1));

                    $first = false;
                } else {
                    break;
                }
            } while (true);

            if ($series == NULL) {
                throw new Exception\NoMatchingSeriesException('No matching series');
            }else{

                //Logger::debug("Inserting StaticSmartData");

                $entry_type = \Cassandra\Type::userType(
                    // Just for attend projects requirements of SO2 -------------------------------------
                    'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                    // ----------------------------------------------------------------------------------
                    'error',      \Cassandra\Type::tinyint(),
                    'confidence', \Cassandra\Type::tinyint(),
                    'x',          \Cassandra\Type::int(),
                    'y',          \Cassandra\Type::int(),
                    'z',          \Cassandra\Type::int(),
                    'd',          \Cassandra\Type::bigint(),
                    'gw',         \Cassandra\Type::bigint()
                );

                $smart_data->confidence = $this->assign_confidence($smart_data);

                $arguments = array(
                    new \Cassandra\Bigint($series->slice),
                    new \Cassandra\Varint($smart_data->time),
                    $entry_type->create(
                        'value',      ($is_digital) ? new \Cassandra\Blob($smart_data->value) : (double) $smart_data->value,
                        'error',      new \Cassandra\Tinyint($smart_data->error),
                        'confidence', new \Cassandra\Tinyint($smart_data->confidence),
                        'x',          (int)$smart_data->x,
                        'y',          (int)$smart_data->y,
                        'z',          (int)$smart_data->z,
                        'd',          new \Cassandra\Bigint($smart_data->dev??0), //TODO: remove the ??
                        //'gw',         new \Cassandra\Bigint($smart_data->gw->id)
                        'gw',         new \Cassandra\Bigint($this->_gw_id) // TODO: CHECK THIS
                    )
                );

                $cassandra_table = "{$this->_domain}" . (($is_digital) ? '_dig' : '');

                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);
                $insert_stmt = $session->prepare("INSERT INTO {$cassandra_table} (id, timestamp, entry) VALUES (?, ?, ?);");
                $session->execute($insert_stmt, array('arguments' => $arguments));

                $update_stmt = $conn->prepare("UPDATE {$table} SET count = count + 1 WHERE id = :id LIMIT 1;");
                $update_stmt->execute(array('id' => $series->id));
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $sucess;
    }
    // Query data from series
    public function query(Series $series, $aggr=null, $options=null) {
        $response_json = NULL;

        try {

            $parameters = array(':version'  => $series->version,
                                ':t0'       => $series->t0,
                                ':t1'       => $series->t1,
                                ':domain'   => $this->_domain);

            $table = Config::config()::MySQL_Table($series->version);
            $query = "SELECT slice, unit FROM {$table}
                      WHERE version = :version AND ( (:t0 >= t0 AND :t0 <= t1) OR (:t0 <= t0 AND :t1 >= t1) OR (:t1 >= t0 AND :t1 <= t1 ) )";

            if($series->unit != null){
                $parameters = array_merge($parameters, array(':unit' => $series->unit));
                //$parameters = array_merge($parameters, array(':dev' => $series->dev));
                $query .= ' AND unit = :unit';
                //$query .= ' AND dev = :dev';
            }

            $invalid_sphere = (int)($series->x === null) +
                              (int)($series->y === null) +
                              (int)($series->z === null) +
                              (int)($series->r === null);

            if ($invalid_sphere != 0 && $invalid_sphere != 4) {
                throw new BadRequestException("Invalid sphere parameters");
            } else if($invalid_sphere == 0) {
                $parameters = array_merge($parameters, array(':x'    => $series->x,
                                                             ':y'    => $series->y,
                                                             ':z'    => $series->z,
                                                             ':r'    => $series->r));
                $query .= ' AND SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2)) <= :r + r';
                $filter_sphere = true;
            } else {
                $filter_sphere = false;
            }

            $query .= ' AND domain = :domain AND count > 0;';

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME,
                                        Config::config()::MYSQL_PORT,
                                        Config::config()::MYSQL_DBNAME,
                                        Config::config()::MYSQL_USERNAME,
                                        Config::config()::MYSQL_PASSWORD);

            $select_stmt = $conn->prepare($query);
            $select_stmt->execute($parameters);

            $id_set = \Cassandra\Type::collection(\Cassandra\Type::bigint())->create();

            $selected_slices = array_column($select_stmt->fetchAll(), 'unit', 'slice');

            foreach ($selected_slices as $slice => $unit)
                $id_set->add(new \Cassandra\Bigint($slice));

            $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);

            $is_digital  = $series->unit()->is_digital();
            if($is_digital) {
                $type = $_GET['type'] ?? $options->type ?? null;
                $type = $type << 29;
            }

            $cassandra_table = "{$this->_domain}" . (($is_digital) ? '_dig' : '');

            $cass_select_stmt = $session->prepare("SELECT * FROM {$cassandra_table} WHERE (id IN ?) AND (timestamp >= ?) AND (timestamp <= ?);");

            $result_page = $session->execute($cass_select_stmt,
                            array('arguments' => array($id_set, new \Cassandra\Varint($series->t0), new \Cassandra\Varint($series->t1))));

            //ini_set('memory_limit', '-1'); // check this
            //ini_set('max_execution_time', 300); // check this

            $index = 0;
            $response_json = array('series' => array());

            $aggregator = ($this->internal()) ? null : Aggregator::new($aggr);

            while($result_page) {
                foreach ($result_page as $column) {
                    $slice = (int)$column['id'];
                    $entry = $column['entry'];
                    $time  = (string)$column['timestamp']->value(); //bigint
                    if($is_digital){
                        $value_blob = $entry->get('value')->toBinaryString();
                        switch ($type) {
                            case Unit::I32:
                                $value = Unpack::uInt32($value_blob);
                                break;
                            case Unit::I64:
                                $value = Unpack::uInt64($value_blob);
                                break;
                            case Unit::F32:
                                $value = Unpack::f32($value_blob);
                                break;
                            case Unit::D64:
                                break;
                            default:
                                $value = Unpack::d64($value_blob);
                                break;
                        }

                        if($value === null){
                            if($value_blob != null)
                                $value = $value_blob; // TODO: remove this in the new API
                            else
                                $value = -400; // TODO: remover isso quando valores inválidos não puderem mais ser inseridos
                        }
                    } else {
                        $value = (double)$entry->get('value'); // double
                    }

                    $error = (int)$entry->get('error');             //tinyint
                    $conf  = (int)$entry->get('confidence');        //tinyint
                    $x     = (int)$entry->get('x');                 //int
                    $y     = (int)$entry->get('y');                 //int
                    $z     = (int)$entry->get('z');                 //int
                    $d     = (int)$entry->get('d');                 //int
                    $gw    = (int)$entry->get('gw');                //int (TO DO GET GATEWAY)

                    if ( $filter_sphere && !$series->contains_point($x, $y, $z) )
                        continue;

                    if ($series->unit == 2226272548 && $d != $series->dev) //Angle Rate Sensor (testing)
                        continue;

                    if ($this->_domain == 'tutorial' && $series->unit == 2224179556 && $d != $series->dev) //Debuging
                        continue;

                    $smartdata = null;

                    switch ($series->version) {
                        case SmartData::STATIC_VERSION:
                            $smartdata = new StaticSmartData($series->unit,$value,$error,$conf,$x,$y,$z,$time,$d,$gw);
                            break;
                        case SmartData::MOBILE_VERSION:
                            $smartdata = new MobileSmartData($series->unit,$value,$error,$conf,$x,$y,$z,$time,$d,$gw, null);
                            break;
                        default:
                            continue 2;
                            break;
                    }

                    if($aggregator != null) {
                        $smartdata = $aggregator->aggregate($smartdata);
                    }

                    if($smartdata != null) {
                        if(is_array($smartdata)){
                            foreach ($smartdata as $key => $data) {
                                $response_json['series'][$index++] = $data->toArray();
                                if ($index >= Config::config()::POINTS_LIMIT) break;
                            }
                        } else {
                            $response_json['series'][$index++] = $smartdata->toArray();
                            if($this->internal()){
                                $response_json['series'][$index-1]['slice'] = $slice;
                                $response_json['series'][$index-1]['gw'] = $gw;
                            }
                        }
                    } else {
                        continue;
                    }

                    if ($index >= Config::config()::POINTS_LIMIT) break 2;
                }

                $result_page = $result_page->nextPage();

                if(!$result_page && isset($aggregator) && $index < Config::config()::POINTS_LIMIT){
                    $smartdata = $aggregator->finish();
                    if($smartdata != null) {
                        $response_json['series'][$index++] = $smartdata->toArray();
                    }
                }
            }

            $session->close();

            usort($response_json['series'], function ($a, $b) {
                $a_timestamp  = gmp_init($a['timestamp']);
                $b_timestamp  = gmp_init($b['timestamp']);
                return gmp_cmp($a_timestamp, $b_timestamp);
            });

        } catch (\Exception $e) {
            Logger::exception($e);
            $response_json = NULL;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $response_json;
    }
    // Track mobile node
    //public function track(Tracker $tracker) : bool {
    public function track(Series $series, $aggr=null) {
        //throw new Exception\NotImplementedException("Tracker has not been implemented yet");
        $response_json = NULL;

        try {

            $parameters = array(':version'   => $series->version,
                                ':signature' => $series->signature,
                                ':t0'        => $series->t0,
                                ':t1'        => $series->t1,
                                ':domain'    => $this->_domain);

            $table = Config::config()::MySQL_Table($series->version);
            $query = "SELECT slice, unit FROM {$table}
                      WHERE version = :version AND signature = :signature AND ( (:t0 >= t0 AND :t0 <= t1) OR (:t0 <= t0 AND :t1 >= t1) OR (:t1 >= t0 AND :t1 <= t1 ) )";

            if($series->unit != null){
                $parameters = array_merge($parameters, array(':unit' => $series->unit));
                $query .= ' AND unit = :unit';
            }

            $invalid_sphere = (int)($series->x === null) +
                              (int)($series->y === null) +
                              (int)($series->z === null) +