Exemplo n.º 1
0
Arquivo: index.php Projeto: r67/cose
            foreach ($GLOBALS['_PUT'] as $key => $value) {
                $data[$key] = sprintf('"%s" = ?', $key);
            }
            $query = array(sprintf('UPDATE "%s" SET %s WHERE "%s" = ?', $table, implode(', ', $data), 'id'));
            $query = sprintf('%s;', implode(' ', $query));
            $result = ArrestDB::Query($query, $GLOBALS['_PUT'], $id);
            if ($result === false) {
                $result = ArrestDB::$HTTP[409];
            } else {
                $result = ArrestDB::$HTTP[200];
            }
        }
    }
    return ArrestDB::Reply($result);
});
exit(ArrestDB::Reply(ArrestDB::$HTTP[400]));
class ArrestDB
{
    public static $HTTP = [200 => ['success' => ['code' => 200, 'status' => 'OK']], 201 => ['success' => ['code' => 201, 'status' => 'Created']], 204 => ['error' => ['code' => 204, 'status' => 'No Content']], 400 => ['error' => ['code' => 400, 'status' => 'Bad Request']], 403 => ['error' => ['code' => 403, 'status' => 'Forbidden']], 404 => ['error' => ['code' => 404, 'status' => 'Not Found']], 409 => ['error' => ['code' => 409, 'status' => 'Conflict']], 503 => ['error' => ['code' => 503, 'status' => 'Service Unavailable']]];
    public static function Query($query = null)
    {
        static $db = null;
        static $result = [];
        try {
            if (isset($db, $query) === true) {
                if (strncasecmp($db->getAttribute(\PDO::ATTR_DRIVER_NAME), 'mysql', 5) === 0) {
                    $query = strtr($query, '"', '`');
                }
                if (empty($result[$hash = crc32($query)]) === true) {
                    $result[$hash] = $db->prepare($query);
                }
Exemplo n.º 2
0
//In this case remove password on User table before return the data
ArrestDBConfig::postProcess(["table" => "User", "method" => ["GET", "GET_INTERNAL"]], function ($method, $table, $id, $data) {
    if (isset($data[0])) {
        foreach ($data as $k => $item) {
            unset($item["password"]);
        }
    } else {
        unset($data["password"]);
    }
    return $data;
});
//In this case when a new user is created, it's inserted
ArrestDBConfig::postProcess(["method" => "POST", "table" => "User"], function ($method, $table, $id, $data) {
    if (isset($_GET["Group_id"])) {
        $group_id = $_GET["Group_id"];
        ArrestDB::query("INSERT INTO UserInGroup(Group_id,User_id) VALUES ({$group_id},{$id})");
    }
    return $data;
});
/**
	CALL function (optional)
	
	Allows to call a function to do complex operations. All functions use POST method. Remember this when you'll call it.
	
	function ($func,$data)
	- $func: function name
	- $data: values in $_POST variable
*/
//In this case
ArrestDBConfig::fnc("sendMsg", function ($func, $data) {
    return sendMsg($data);
Exemplo n.º 3
0
 public static function getAll($table, $extends = null)
 {
     return ArrestDB::getQuery(["TABLE" => $table], $extends);
 }
Exemplo n.º 4
0
//In this case remove password on User table before return the data
ArrestDBConfig::postProcess(["table" => "User", "method" => ["GET", "GET_INTERNAL"]], function ($method, $table, $id, $data) {
    if (isset($data[0])) {
        foreach ($data as $k => $item) {
            unset($item["password"]);
        }
    } else {
        unset($data["password"]);
    }
    return $data;
});
//In this case when a new UserInfo is created when User is created
ArrestDBConfig::postProcess(["method" => "POST", "table" => "User"], function ($method, $table, $id, $data) {
    if (isset($_GET["Name"])) {
        $name = $_GET["Name"];
        ArrestDB::query("INSERT INTO UserInfo(Name,User_id) VALUES ({$name},{$id})");
    }
    return $data;
});
/**
	CALL function (optional)
	
	Allows to call a function to do complex operations. All functions use POST method. Remember this when you'll call it.
	
	function ($func,$data)
	- $func: function name
	- $data: values in $_POST variable
	
	Example
	------------
	- version() api function returns string "Beta 1"
Exemplo n.º 5
0
            $result = ['error' => 'Error retrieving inserted rows.'];
        } else {
            if (count($ids) === 1) {
                $result = array_shift($result);
            }
        }
    }
    return ArrestDB::Reply($result);
});
ArrestDB::Serve('PUT', '/(#any)/(#num)', function ($table, $id) {
    if (empty($GLOBALS['_PUT']) === true || is_array($GLOBALS['_PUT']) !== true) {
        http_response_code(400);
        return false;
    }
    $data = [];
    foreach ($GLOBALS['_PUT'] as $key => $value) {
        $data[$key] = sprintf('"%s" = ?', $key);
    }
    $query = array(sprintf('UPDATE "%s" SET %s WHERE "%s" = ?', $table, implode(', ', $data), 'id'));
    $query = sprintf('%s;', implode(' ', $query));
    $result = ArrestDB::Query($query, $GLOBALS['_PUT'], $id);
    if ($result === false) {
        http_response_code(404);
        return;
    } else {
        //$result = ArrestDB::$HTTP[200];
    }
    return ArrestDB::Reply($result);
});
http_response_code(400);
exit('Request failed to match');
Exemplo n.º 6
0
 public static function Query($query = null)
 {
     static $db = null;
     static $result = [];
     try {
         if (isset($db, $query) === true) {
             if ($query === 'BEGIN') {
                 if ($db->beginTransaction()) {
                     return ArrestDB::GetOption('RETURN_RAW') ? ['db' => $db] : true;
                 }
                 syslog(LOG_ERR, sprintf('ArrestDB::Query - BEGIN failed: %s - %s %s %s', $db->errorCode(), $db->errorInfo()[0], $db->errorInfo()[1], $db->errorInfo()[2]));
                 return false;
             }
             if ($query === 'COMMIT') {
                 if ($db->commit()) {
                     return ArrestDB::GetOption('RETURN_RAW') ? ['db' => $db] : true;
                 }
                 syslog(LOG_ERR, sprintf('ArrestDB::Query - COMMIT failed: %s - %s %s %s', $db->errorCode(), $db->errorInfo()[0], $db->errorInfo()[1], $db->errorInfo()[2]));
                 return false;
             }
             if ($query === 'ROLLBACK') {
                 if ($db->rollBack()) {
                     return ArrestDB::GetOption('RETURN_RAW') ? ['db' => $db] : true;
                 }
                 syslog(LOG_ERR, sprintf('ArrestDB::Query - ROLLBACK failed: %s - %s %s %s', $db->errorCode(), $db->errorInfo()[0], $db->errorInfo()[1], $db->errorInfo()[2]));
                 return false;
             }
             if (strncasecmp($db->getAttribute(\PDO::ATTR_DRIVER_NAME), 'mysql', 5) === 0 && !ArrestDB::GetOption('MYSQL_NOTRDQUOTE')) {
                 $query = strtr($query, '"', '`');
             }
             if (empty($result[$hash = crc32($query)]) === true) {
                 $result[$hash] = $db->prepare($query);
             }
             $data = array_slice(func_get_args(), 1);
             if (count($data, COUNT_RECURSIVE) > count($data)) {
                 $data = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($data)), false);
             }
             if ($result[$hash]->execute($data) === true) {
                 if (ArrestDB::GetOption('RETURN_RAW')) {
                     return ['db' => $db, 'result' => $result[$hash]];
                 }
                 $sequence = null;
                 if (strncmp($db->getAttribute(\PDO::ATTR_DRIVER_NAME), 'pgsql', 5) === 0 && sscanf($query, 'INSERT INTO %s', $sequence) > 0) {
                     $sequence = sprintf('%s_id_seq', trim($sequence, '"'));
                 }
                 switch (strstr($query, ' ', true)) {
                     case 'INSERT':
                     case 'REPLACE':
                         return $db->lastInsertId($sequence);
                     case 'UPDATE':
                     case 'DELETE':
                         return $result[$hash]->rowCount();
                     case 'SELECT':
                     case 'EXPLAIN':
                     case 'PRAGMA':
                     case 'SHOW':
                         return $result[$hash]->fetchAll();
                 }
                 return true;
             }
             syslog(LOG_ERR, sprintf('ArrestDB::Query - query failed: %s - %s %s %s', $result[$hash]->errorCode(), $result[$hash]->errorInfo()[0], $result[$hash]->errorInfo()[1], $result[$hash]->errorInfo()[2]));
             return false;
         } else {
             if (isset($query) === true) {
                 $options = array(\PDO::ATTR_CASE => \PDO::CASE_NATURAL, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_EMULATE_PREPARES => false, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL, \PDO::ATTR_STRINGIFY_FETCHES => false);
                 if (preg_match('~^sqlite://([[:print:]]++)$~i', $query, $dsn) > 0) {
                     $options += array(\PDO::ATTR_TIMEOUT => 3);
                     $db = new \PDO(sprintf('sqlite:%s', $dsn[1]), null, null, $options);
                     $pragmas = array('automatic_index' => 'ON', 'cache_size' => '8192', 'foreign_keys' => 'ON', 'journal_size_limit' => '67110000', 'locking_mode' => 'NORMAL', 'page_size' => '4096', 'recursive_triggers' => 'ON', 'secure_delete' => 'ON', 'synchronous' => 'NORMAL', 'temp_store' => 'MEMORY', 'journal_mode' => 'WAL', 'wal_autocheckpoint' => '4096');
                     if (strncasecmp(PHP_OS, 'WIN', 3) !== 0) {
                         $memory = 131072;
                         if (($page = intval(shell_exec('getconf PAGESIZE'))) > 0) {
                             $pragmas['page_size'] = $page;
                         }
                         if (is_readable('/proc/meminfo') === true) {
                             if (is_resource($handle = fopen('/proc/meminfo', 'rb')) === true) {
                                 while (($line = fgets($handle, 1024)) !== false) {
                                     if (sscanf($line, 'MemTotal: %d kB', $memory) == 1) {
                                         $memory = round($memory / 131072) * 131072;
                                         break;
                                     }
                                 }
                                 fclose($handle);
                             }
                         }
                         $pragmas['cache_size'] = intval($memory * 0.25 / ($pragmas['page_size'] / 1024));
                         $pragmas['wal_autocheckpoint'] = $pragmas['cache_size'] / 2;
                     }
                     foreach ($pragmas as $key => $value) {
                         $db->exec(sprintf('PRAGMA %s=%s;', $key, $value));
                     }
                 } else {
                     if (preg_match('~^(mysql|pgsql)://(?:(.+?)(?::(.+?))?@)?([^/:@]++)(?::(\\d++))?/(\\w++)/?$~i', $query, $dsn) > 0) {
                         if (strncasecmp($query, 'mysql', 5) === 0) {
                             $options += array(\PDO::ATTR_AUTOCOMMIT => true, \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8" COLLATE "utf8_general_ci", time_zone = "+00:00";', \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true);
                         }
                         $db = new \PDO(sprintf('%s:host=%s;port=%s;dbname=%s', $dsn[1], $dsn[4], $dsn[5], $dsn[6]), $dsn[2], $dsn[3], $options);
                     }
                 }
             }
         }
     } catch (\Exception $exception) {
         syslog(LOG_ERR, sprintf('ArrestDB::Query - query failed: %s %s', $exception->getCode(), $exception->getMessage()));
         foreach (explode("\n", $exception->getTraceAsString()) as $e) {
             syslog(LOG_ERR, 'ArrestDB::Query - query failed: ' . $e);
         }
         foreach (explode("\n", $query) as $e) {
             syslog(LOG_ERR, 'ArrestDB::Query - query failed: ' . $e);
         }
         foreach (self::$Options as $k => $v) {
             syslog(LOG_ERR, 'ArrestDB::Query - query failed: ' . $k . ' => ' . $v);
         }
         return false;
     }
     return isset($db) === true ? $db : false;
 }
Exemplo n.º 7
0
        }
        if ($rowCount != $result['result']->rowCount()) {
            syslog(LOG_ERR, sprintf('Archived unloaded %d rows but delete removed %d rows - rolling back.', $rowCount, $result['result']->rowCount()));
            $result = ArrestDB::Query('ROLLBACK');
            if ($result === false) {
                http_response_code(400);
                exit('Unable to ROLLBACK transaction!! Oh noes...');
            }
        }
        $result = ArrestDB::Query('COMMIT');
        if ($result === false) {
            http_response_code(400);
            exit('Unable to COMMIT transaction');
        }
    } catch (Exception $e) {
        $result = ArrestDB::Query('ROLLBACK');
        if ($result === false) {
            http_response_code(400);
            exit('Unable to ROLLBACK transaction!! Oh noes...');
        }
    }
    http_response_code(201);
    header(sprintf('Location: %s/%s', $ARCHIVE_URI_PREFIX, basename($archive)));
    return ArrestDB::Reply(['count' => $rowCount]);
});
ArrestDB::Serve('DELETE', '/(#any)', function () {
    http_response_code(400);
    exit('Not yet implemented');
});
http_response_code(400);
exit('Request failed to match');