1
0
Fork 0
mirror of synced 2024-06-18 18:54:55 +12:00

Run PHP-CS-FIXER to make sure

code is consisted with PSR-1 + PSR-2
This commit is contained in:
eldadfux 2019-09-06 20:04:26 +03:00
parent c9d3448571
commit 35680bbae9
37 changed files with 928 additions and 753 deletions

View file

@ -9,12 +9,14 @@ abstract class Adapter
protected $namespace = '';
/**
* Set Namespace
* Set Namespace.
*
* Set namespace to divide different scope of data sets
*
* @param $namespace
*
* @throws Exception
*
* @return bool
*/
public function setNamespace($namespace)
@ -29,11 +31,12 @@ abstract class Adapter
}
/**
* Get Namespace
* Get Namespace.
*
* Get namespace of current set scope
*
* @throws Exception
*
* @return string
*/
public function getNamespace()
@ -46,7 +49,7 @@ abstract class Adapter
}
/**
* Log
* Log.
*
* Add specific event log
*
@ -58,29 +61,32 @@ abstract class Adapter
* @param string $ip
* @param string $location
* @param array $data
*
* @return
*/
abstract public function log($userId, $userType, $event, $resource, $userAgent, $ip, $location, $data);
/**
* Get All Logs By User
* Get All Logs By User.
*
* Get all user logs
*
* @param int $userId
* @param int $userType
*
* @return mixed
*/
abstract public function getLogsByUser($userId, $userType);
/**
* Get All Logs By User and Actions
* Get All Logs By User and Actions.
*
* Get all user logs by given action names
*
* @param int $userId
* @param int $userType
* @param array $actions
*
* @return mixed
*/
abstract public function getLogsByUserAndActions($userId, $userType, array $actions);

View file

@ -21,7 +21,7 @@ class MySQL extends Adapter
}
/**
* Log
* Log.
*
* Add specific event log
*
@ -33,7 +33,9 @@ class MySQL extends Adapter
* @param string $ip
* @param string $location
* @param array $data
*
* @return bool
*
* @throws \Exception
*/
public function log($userId, $userType, $event, $resource, $userAgent, $ip, $location, $data)
@ -79,8 +81,9 @@ class MySQL extends Adapter
{
$query = [];
foreach ($actions as $k => $id)
foreach ($actions as $k => $id) {
$query[] = ':action_'.$k;
}
$query = implode(',', $query);
@ -95,8 +98,9 @@ class MySQL extends Adapter
$st->bindValue(':userId', $userId, PDO::PARAM_STR);
$st->bindValue(':userType', $userType, PDO::PARAM_INT);
foreach ($actions as $k => $id)
foreach ($actions as $k => $id) {
$st->bindValue(':action_'.$k, $id);
}
$st->execute();

View file

@ -53,13 +53,14 @@ class Audit
}
/**
* Log
* Log.
*
* Add specific event log
*
* @param string $event
* @param string $resource
* @param array $data
*
* @return mixed
*/
public function log($event, $resource = '', array $data = [])
@ -68,12 +69,13 @@ class Audit
}
/**
* Get All Logs By User and Actions
* Get All Logs By User and Actions.
*
* Get all user logs logs by given action names
*
* @param int $userId
* @param int $userType
*
* @return mixed
*/
public function getLogsByUser($userId, $userType)
@ -82,13 +84,14 @@ class Audit
}
/**
* Get All Logs By User and Actions
* Get All Logs By User and Actions.
*
* Get all user logs logs by given action names
*
* @param int $userId
* @param int $userType
* @param array $actions
*
* @return mixed
*/
public function getLogsByUserAndActions($userId, $userType, array $actions)

View file

@ -7,7 +7,7 @@ use Database\Document;
class Auth
{
/**
* User Gender
* User Gender.
*/
const USER_GENDER_TYPE_NOT_SET = 0;
const USER_GENDER_TYPE_MALE = 1;
@ -15,21 +15,21 @@ class Auth
const USER_GENDER_TYPE_OTHER = 3;
/**
* User Status
* User Status.
*/
const USER_STATUS_UNACTIVATED = 0;
const USER_STATUS_ACTIVATED = 1;
const USER_STATUS_BLOCKED = 2;
/**
* User Types
* User Types.
*/
const USER_TYPE_USER = 0;
const USER_TYPE_PARENT = 1;
const USER_TYPE_APP = 2;
/**
* User Roles
* User Roles.
*/
const USER_ROLE_GUEST = 0;
const USER_ROLE_MEMBER = 1;
@ -41,7 +41,7 @@ class Auth
const USER_ROLE_ALL = '*';
/**
* Token Types
* Token Types.
*/
const TOKEN_TYPE_LOGIN = 1;
const TOKEN_TYPE_CONFIRM = 2;
@ -49,7 +49,7 @@ class Auth
const TOKEN_TYPE_INVITE = 4;
/**
* Token Expiration times
* Token Expiration times.
*/
const TOKEN_EXPIRATION_LOGIN_LONG = 31536000; /* 1 year */
const TOKEN_EXPIRATION_LOGIN_SHORT = 3600; /* 1 hour */
@ -59,41 +59,43 @@ class Auth
/**
* @var string
*/
static public $cookieName = 'a-session';
public static $cookieName = 'a-session';
/**
* User Unique ID
* User Unique ID.
*
* @var int
*/
static public $unique = 0;
public static $unique = 0;
/**
* User Secret Key
* User Secret Key.
*
* @var string
*/
static public $secret = '';
public static $secret = '';
/**
* Set Cookie Name
* Set Cookie Name.
*
* @param $string
*
* @return string
*/
static public function setCookieName($string)
public static function setCookieName($string)
{
return self::$cookieName = $string;
}
/**
* Encode Session
* Encode Session.
*
* @param int $id
* @param string $secret
*
* @return string
*/
static public function encodeSession($id, $secret)
public static function encodeSession($id, $secret)
{
return base64_encode(json_encode([
'id' => $id,
@ -102,16 +104,18 @@ class Auth
}
/**
* Decode Session
* Decode Session.
*
* @param string $session
*
* @return array
*
* @throws \Exception
*/
static public function decodeSession($session)
public static function decodeSession($session)
{
$session = json_decode(base64_decode($session), true);
$default = ['id' => null, 'secret' => '',];
$default = ['id' => null, 'secret' => ''];
if (!is_array($session)) {
return $default;
@ -121,80 +125,88 @@ class Auth
}
/**
* Encode
* Encode.
*
* One-way encryption
*
* @param $string
*
* @return string
*/
static public function hash($string)
public static function hash($string)
{
return hash('sha256', $string);
}
/**
* Password Hash
* Password Hash.
*
* One way string hashing for user passwords
*
* @param $string
*
* @return bool|string
*/
static public function passwordHash($string)
public static function passwordHash($string)
{
return password_hash($string, PASSWORD_BCRYPT, array('cost' => 8));
}
/**
* Password verify
* Password verify.
*
* @param $plain
* @param $hash
*
* @return bool
*/
static public function passwordVerify($plain, $hash)
public static function passwordVerify($plain, $hash)
{
return password_verify($plain, $hash);
}
/**
* Password Generator
* Password Generator.
*
* Generate random password string
*
* @param int $length
*
* @return string
*
* @throws \Exception
*/
static public function passwordGenerator(int $length = 20):string
public static function passwordGenerator(int $length = 20):string
{
return bin2hex(random_bytes($length));
}
/**
* Token Generator
* Token Generator.
*
* Generate random password string
*
* @param int $length
*
* @return string
*
* @throws \Exception
*/
static public function tokenGenerator(int $length = 128):string
public static function tokenGenerator(int $length = 128):string
{
return bin2hex(random_bytes($length));
}
/**
* Verify token and check that its not expired
* Verify token and check that its not expired.
*
* @param array $tokens
* @param int $type
* @param string $secret
*
* @return bool|int
*/
static public function tokenVerify(array $tokens, int $type, string $secret)
public static function tokenVerify(array $tokens, int $type, string $secret)
{
foreach ($tokens as $token) { /* @var $token Document */
if (isset($token['type']) &&

View file

@ -52,24 +52,28 @@ abstract class OAuth
/**
* @param string $code
*
* @return string
*/
abstract public function getAccessToken(string $code):string;
/**
* @param $accessToken
*
* @return string
*/
abstract public function getUserID(string $accessToken):string;
/**
* @param $accessToken
*
* @return string
*/
abstract public function getUserEmail(string $accessToken):string;
/**
* @param $accessToken
*
* @return string
*/
abstract public function getUserName(string $accessToken):string;
@ -79,6 +83,7 @@ abstract class OAuth
* @param string $url
* @param array $headers
* @param string $payload
*
* @return string
*/
protected function request(string $method, string $url = '', array $headers = [], string $payload = ''):string

View file

@ -34,6 +34,7 @@ class Facebook extends OAuth
/**
* @param string $code
*
* @return string
*/
public function getAccessToken(string $code):string
@ -56,6 +57,7 @@ class Facebook extends OAuth
/**
* @param string $accessToken
*
* @return string
*/
public function getUserID(string $accessToken):string
@ -71,6 +73,7 @@ class Facebook extends OAuth
/**
* @param string $accessToken
*
* @return string
*/
public function getUserEmail(string $accessToken):string
@ -86,6 +89,7 @@ class Facebook extends OAuth
/**
* @param string $accessToken
*
* @return string
*/
public function getUserName(string $accessToken):string
@ -101,6 +105,7 @@ class Facebook extends OAuth
/**
* @param string $accessToken
*
* @return array
*/
protected function getUser(string $accessToken):array

View file

@ -29,6 +29,7 @@ class Github extends OAuth
/**
* @param string $code
*
* @return string
*/
public function getAccessToken(string $code):string
@ -53,6 +54,7 @@ class Github extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserID(string $accessToken):string
@ -68,6 +70,7 @@ class Github extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserEmail(string $accessToken):string
@ -85,6 +88,7 @@ class Github extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserName(string $accessToken):string
@ -100,6 +104,7 @@ class Github extends OAuth
/**
* @param string $accessToken
*
* @return array
*/
protected function getUser(string $accessToken)

View file

@ -20,7 +20,7 @@ class LinkedIn extends OAuth
];
/**
* Documentation
* Documentation.
*
* OAuth:
* https://developer.linkedin.com/docs/oauth2
@ -30,7 +30,6 @@ class LinkedIn extends OAuth
*
* Basic Profile Fields:
* https://developer.linkedin.com/docs/fields/basic-profile
*
*/
/**
@ -57,6 +56,7 @@ class LinkedIn extends OAuth
/**
* @param string $code
*
* @return string
*/
public function getAccessToken(string $code):string
@ -82,6 +82,7 @@ class LinkedIn extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserID(string $accessToken):string
@ -97,6 +98,7 @@ class LinkedIn extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserEmail(string $accessToken):string
@ -108,8 +110,7 @@ class LinkedIn extends OAuth
isset($email['elements'][0]) &&
isset($email['elements'][0]['handle~']) &&
isset($email['elements'][0]['handle~']['emailAddress'])
)
{
) {
return $email['elements'][0]['handle~']['emailAddress'];
}
@ -118,6 +119,7 @@ class LinkedIn extends OAuth
/**
* @param $accessToken
*
* @return string
*/
public function getUserName(string $accessToken):string
@ -138,6 +140,7 @@ class LinkedIn extends OAuth
/**
* @param string $accessToken
*
* @return array
*/
protected function getUser(string $accessToken)

View file

@ -5,16 +5,14 @@ namespace Auth\Validator;
use Utopia\Validator;
/**
* Password
* Password.
*
* Validates user password string
*
* @package Utopia\Validator
*/
class Password extends Validator
{
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -26,11 +24,12 @@ class Password extends Validator
}
/**
* Is valid
* Is valid.
*
* Validation username
*
* @param mixed $value
*
* @return bool
*/
public function isValid($value)

View file

@ -12,12 +12,14 @@ abstract class Adapter
protected $namespace = '';
/**
* Set Namespace
* Set Namespace.
*
* Set namespace to divide different scope of data sets
*
* @param $namespace
*
* @throws Exception
*
* @return bool
*/
public function setNamespace($namespace)
@ -32,11 +34,12 @@ abstract class Adapter
}
/**
* Get Namespace
* Get Namespace.
*
* Get namespace of current set scope
*
* @throws Exception
*
* @return string
*/
public function getNamespace()
@ -49,71 +52,80 @@ abstract class Adapter
}
/**
* Get Document
* Get Document.
*
* @param int $id
*
* @return array
*/
abstract public function getDocument($id);
/**
* Create Document
**
**.
*
* @param array $data
*
* @return array
*/
abstract public function createDocument(array $data);
/**
* Update Document
* Update Document.
*
* @param array $data
*
* @return array
*/
abstract public function updateDocument(array $data);
/**
* Delete Node
* Delete Node.
*
* @param int $id
*
* @return array
*/
abstract public function deleteDocument($id);
/**
* Create Namespace
* Create Namespace.
*
* @param string $namespace
*
* @return bool
*/
abstract public function createNamespace($namespace);
/**
* Delete Namespace
* Delete Namespace.
*
* @param string $namespace
*
* @return bool
*/
abstract public function deleteNamespace($namespace);
/**
* Filter
* Filter.
*
* Filter data sets using chosen queries
*
* @param array $options
*
* @return array
*/
abstract public function getCollection(array $options);
/**
* @param array $options
*
* @return int
*/
abstract public function getCount(array $options);
/**
* Last Modified
* Last Modified.
*
* Return unix timestamp of last time a node queried in corrent session has been changed
*
@ -122,7 +134,7 @@ abstract class Adapter
abstract public function lastModified();
/**
* Get Debug Data
* Get Debug Data.
*
* @return array
*/

View file

@ -28,21 +28,21 @@ class MySQL extends Adapter
protected $register;
/**
* Saved nodes
* Saved nodes.
*
* @var array
*/
protected $nodes = [];
/**
* Count documents get usage
* Count documents get usage.
*
* @var int
*/
protected $count = 0;
/**
* Last modified
* Last modified.
*
* Read node with most recent changes
*
@ -56,7 +56,7 @@ class MySQL extends Adapter
protected $debug = [];
/**
* Constructor
* Constructor.
*
* Set connection and settings
*
@ -68,15 +68,17 @@ class MySQL extends Adapter
}
/**
* Get Document
* Get Document.
*
* @param string $id
*
* @return array
*
* @throws Exception
*/
public function getDocument($id)
{
$this->count++;
++$this->count;
// Get fields abstraction
$st = $this->getPDO()->prepare('SELECT * FROM `'.$this->getNamespace().'.database.documents` a
@ -118,8 +120,7 @@ class MySQL extends Adapter
if ($property['array']) {
$output[$property['key']][] = $property['value'];
}
else {
} else {
$output[$property['key']] = $property['value'];
}
}
@ -141,10 +142,12 @@ class MySQL extends Adapter
}
/**
* Create Document
* Create Document.
*
* @param array $data
*
* @throws \Exception
*
* @return array
*/
public function createDocument(array $data = [])
@ -154,7 +157,7 @@ class MySQL extends Adapter
$signature = md5(json_encode($data, true));
$revision = uniqid('', true);
/**
/*
* When updating node, check if there are any changes to update
* by comparing data md5 signatures
*/
@ -225,7 +228,6 @@ class MySQL extends Adapter
// Handle array of relations
if (self::DATA_TYPE_ARRAY === $type) {
foreach ($value as $i => $child) {
if (self::DATA_TYPE_DICTIONARY !== $this->getDataType($child)) { // not dictionary
$props[] = [
@ -292,10 +294,12 @@ class MySQL extends Adapter
}
/**
* Update Document
* Update Document.
*
* @param array $data
*
* @return array
*
* @throws Exception
*/
public function updateDocument(array $data = [])
@ -304,10 +308,12 @@ class MySQL extends Adapter
}
/**
* Delete Document
* Delete Document.
*
* @param int $id
*
* @return array
*
* @throws Exception
*/
public function deleteDocument($id)
@ -340,7 +346,7 @@ class MySQL extends Adapter
}
/**
* Create Relation
* Create Relation.
*
* Adds a new relationship between different nodes
*
@ -350,7 +356,9 @@ class MySQL extends Adapter
* @param string $key
* @param bool $isArray
* @param int $order
*
* @return array
*
* @throws Exception
*/
protected function createRelationship($revision, $start, $end, $key, $isArray = false, $order = 0)
@ -372,10 +380,12 @@ class MySQL extends Adapter
}
/**
* Create Namespace
* Create Namespace.
*
* @param $namespace
*
* @throws Exception
*
* @return bool
*/
public function createNamespace($namespace)
@ -396,8 +406,7 @@ class MySQL extends Adapter
$this->getPDO()->prepare('CREATE TABLE `'.$relationships.'` LIKE `template.database.relationships`;')->execute();
$this->getPDO()->prepare('CREATE TABLE `'.$audit.'` LIKE `template.audit.audit`;')->execute();
$this->getPDO()->prepare('CREATE TABLE `'.$abuse.'` LIKE `template.abuse.abuse`;')->execute();
}
catch (Exception $e) {
} catch (Exception $e) {
throw $e;
}
@ -405,10 +414,12 @@ class MySQL extends Adapter
}
/**
* Delete Namespace
* Delete Namespace.
*
* @param $namespace
*
* @throws Exception
*
* @return bool
*/
public function deleteNamespace($namespace)
@ -429,8 +440,7 @@ class MySQL extends Adapter
$this->getPDO()->prepare('DROP TABLE `'.$relationships.'`;')->execute();
$this->getPDO()->prepare('DROP TABLE `'.$audit.'`;')->execute();
$this->getPDO()->prepare('DROP TABLE `'.$abuse.'`;')->execute();
}
catch (Exception $e) {
} catch (Exception $e) {
throw $e;
}
@ -438,10 +448,12 @@ class MySQL extends Adapter
}
/**
* Get Collection
* Get Collection.
*
* @param array $options
*
* @throws Exception
*
* @return array
*/
public function getCollection(array $options)
@ -484,8 +496,7 @@ class MySQL extends Adapter
if (1 < count($path)) {
$key = array_pop($path);
}
else {
} else {
$path = [];
}
@ -497,10 +508,10 @@ class MySQL extends Adapter
$options['offset'] = (int) $options['offset'];
$options['limit'] = (int) $options['limit'];
if(empty($path)) {//if($path == "''") { // Handle direct attributes queries
$where[] = "JOIN `" . $this->getNamespace() . ".database.properties` b{$i} ON a.uid IS NOT NULL AND b{$i}.documentUid = a.uid AND (b{$i}.key = {$key} AND b{$i}.value {$operator} {$value})";
}
else { // Handle direct child attributes queries
if (empty($path)) {
//if($path == "''") { // Handle direct attributes queries
$where[] = 'JOIN `'.$this->getNamespace().".database.properties` b{$i} ON a.uid IS NOT NULL AND b{$i}.documentUid = a.uid AND (b{$i}.key = {$key} AND b{$i}.value {$operator} {$value})";
} else { // Handle direct child attributes queries
$len = count($original);
$prev = 'c'.$i;
@ -508,13 +519,11 @@ class MySQL extends Adapter
$part = $this->getPDO()->quote($part, PDO::PARAM_STR);
if (0 === $y) { // First key
$join[$i] = "JOIN `" . $this->getNamespace() . ".database.relationships` c{$i} ON a.uid IS NOT NULL AND c{$i}.start = a.uid AND c{$i}.key = {$part}";
}
else if ($y == $len - 1) { // Last key
$join[$i] .= "JOIN `" . $this->getNamespace() . ".database.properties` e{$i} ON e{$i}.documentUid = {$prev}.end AND e{$i}.key = {$part} AND e{$i}.value {$operator} {$value}";
}
else {
$join[$i] .= "JOIN `" . $this->getNamespace() . ".database.relationships` d{$i}{$y} ON d{$i}{$y}.start = {$prev}.end AND d{$i}{$y}.key = {$part}";
$join[$i] = 'JOIN `'.$this->getNamespace().".database.relationships` c{$i} ON a.uid IS NOT NULL AND c{$i}.start = a.uid AND c{$i}.key = {$part}";
} elseif ($y == $len - 1) { // Last key
$join[$i] .= 'JOIN `'.$this->getNamespace().".database.properties` e{$i} ON e{$i}.documentUid = {$prev}.end AND e{$i}.key = {$part} AND e{$i}.value {$operator} {$value}";
} else {
$join[$i] .= 'JOIN `'.$this->getNamespace().".database.relationships` d{$i}{$y} ON d{$i}{$y}.start = {$prev}.end AND d{$i}{$y}.key = {$part}";
$prev = 'd'.$i.$y;
}
}
@ -531,10 +540,10 @@ class MySQL extends Adapter
$part = $this->getPDO()->quote(implode('', $orderPath), PDO::PARAM_STR);
$orderSelect = "CASE WHEN {$orderKey}.key = {$part} THEN CAST({$orderKey}.value AS {$orderCastMap[$options['orderCast']]}) END AS sort_ff";
if(1 === $len) {//if($path == "''") { // Handle direct attributes queries
$sorts[] = "LEFT JOIN `" . $this->getNamespace() . ".database.properties` order_b ON a.uid IS NOT NULL AND order_b.documentUid = a.uid AND (order_b.key = {$part})";
}
else { // Handle direct child attributes queries
if (1 === $len) {
//if($path == "''") { // Handle direct attributes queries
$sorts[] = 'LEFT JOIN `'.$this->getNamespace().".database.properties` order_b ON a.uid IS NOT NULL AND order_b.documentUid = a.uid AND (order_b.key = {$part})";
} else { // Handle direct child attributes queries
$prev = 'c';
$orderKey = 'order_e';
@ -543,19 +552,17 @@ class MySQL extends Adapter
$x = $y - 1;
if (0 === $y) { // First key
$sorts[] = "JOIN `" . $this->getNamespace() . ".database.relationships` order_c{$y} ON a.uid IS NOT NULL AND order_c{$y}.start = a.uid AND order_c{$y}.key = {$part}";
}
else if ($y == $len - 1) { // Last key
$sorts[] .= "JOIN `" . $this->getNamespace() . ".database.properties` order_e ON order_e.documentUid = order_{$prev}{$x}.end AND order_e.key = {$part}";
}
else {
$sorts[] .= "JOIN `" . $this->getNamespace() . ".database.relationships` order_d{$y} ON order_d{$y}.start = order_{$prev}{$x}.end AND order_d{$y}.key = {$part}";
$sorts[] = 'JOIN `'.$this->getNamespace().".database.relationships` order_c{$y} ON a.uid IS NOT NULL AND order_c{$y}.start = a.uid AND order_c{$y}.key = {$part}";
} elseif ($y == $len - 1) { // Last key
$sorts[] .= 'JOIN `'.$this->getNamespace().".database.properties` order_e ON order_e.documentUid = order_{$prev}{$x}.end AND order_e.key = {$part}";
} else {
$sorts[] .= 'JOIN `'.$this->getNamespace().".database.relationships` order_d{$y} ON order_d{$y}.start = order_{$prev}{$x}.end AND order_d{$y}.key = {$part}";
$prev = 'd';
}
}
}
/**
/*
* Workaround for a MySQL bug as reported here:
* https://bugs.mysql.com/bug.php?id=78485
*/
@ -580,11 +587,11 @@ class MySQL extends Adapter
// OR MATCH (f_search.value) AGAINST ({$this->getPDO()->quote($options['search'], PDO::PARAM_STR)} IN BOOLEAN MODE)
// OR f_search.value LIKE {$this->getPDO()->quote('%%' . $options['search'] . '%%', PDO::PARAM_STR)})";
$where[] = "LEFT JOIN `" . $this->getNamespace() . ".database.properties` b_search ON a.uid IS NOT NULL AND b_search.documentUid = a.uid AND b_search.primitive = 'string'
$where[] = 'LEFT JOIN `'.$this->getNamespace().".database.properties` b_search ON a.uid IS NOT NULL AND b_search.documentUid = a.uid AND b_search.primitive = 'string'
LEFT JOIN
`" . $this->getNamespace() . ".database.relationships` c_search ON c_search.start = b_search.documentUid
`".$this->getNamespace().'.database.relationships` c_search ON c_search.start = b_search.documentUid
LEFT JOIN
`" . $this->getNamespace() . ".database.properties` d_search ON d_search.documentUid = c_search.end AND d_search.primitive = 'string'
`'.$this->getNamespace().".database.properties` d_search ON d_search.documentUid = c_search.end AND d_search.primitive = 'string'
\n";
$search = "AND (MATCH (b_search.value) AGAINST ({$this->getPDO()->quote($options['search'], PDO::PARAM_STR)} IN BOOLEAN MODE)
@ -647,10 +654,12 @@ class MySQL extends Adapter
}
/**
* Get Collection
* Get Collection.
*
* @param array $options
*
* @throws Exception
*
* @return int
*/
public function getCount(array $options)
@ -670,18 +679,17 @@ class MySQL extends Adapter
if (1 < count($path)) {
$key = array_pop($path);
}
else {
} else {
$path = [];
}
$key = $this->getPDO()->quote($key, PDO::PARAM_STR);
$value = $this->getPDO()->quote($value, PDO::PARAM_STR);
if(empty($path)) {//if($path == "''") { // Handle direct attributes queries
$where[] = "JOIN `" . $this->getNamespace() . ".database.properties` b{$i} ON a.uid IS NOT NULL AND b{$i}.documentUid = a.uid AND (b{$i}.key = {$key} AND b{$i}.value {$operator} {$value})";
}
else { // Handle direct child attributes queries
if (empty($path)) {
//if($path == "''") { // Handle direct attributes queries
$where[] = 'JOIN `'.$this->getNamespace().".database.properties` b{$i} ON a.uid IS NOT NULL AND b{$i}.documentUid = a.uid AND (b{$i}.key = {$key} AND b{$i}.value {$operator} {$value})";
} else { // Handle direct child attributes queries
$len = count($original);
$prev = 'c'.$i;
@ -689,13 +697,11 @@ class MySQL extends Adapter
$part = $this->getPDO()->quote($part, PDO::PARAM_STR);
if (0 === $y) { // First key
$join[$i] = "JOIN `" . $this->getNamespace() . ".database.relationships` c{$i} ON a.uid IS NOT NULL AND c{$i}.start = a.uid AND c{$i}.key = {$part}";
}
else if ($y == $len - 1) { // Last key
$join[$i] .= "JOIN `" . $this->getNamespace() . ".database.properties` e{$i} ON e{$i}.documentUid = {$prev}.end AND e{$i}.key = {$part} AND e{$i}.value {$operator} {$value}";
}
else {
$join[$i] .= "JOIN `" . $this->getNamespace() . ".database.relationships` d{$i}{$y} ON d{$i}{$y}.start = {$prev}.end AND d{$i}{$y}.key = {$part}";
$join[$i] = 'JOIN `'.$this->getNamespace().".database.relationships` c{$i} ON a.uid IS NOT NULL AND c{$i}.start = a.uid AND c{$i}.key = {$part}";
} elseif ($y == $len - 1) { // Last key
$join[$i] .= 'JOIN `'.$this->getNamespace().".database.properties` e{$i} ON e{$i}.documentUid = {$prev}.end AND e{$i}.key = {$part} AND e{$i}.value {$operator} {$value}";
} else {
$join[$i] .= 'JOIN `'.$this->getNamespace().".database.relationships` d{$i}{$y} ON d{$i}{$y}.start = {$prev}.end AND d{$i}{$y}.key = {$part}";
$prev = 'd'.$i.$y;
}
}
@ -704,7 +710,7 @@ class MySQL extends Adapter
$where = implode("\n", $where);
$join = implode("\n", $join);
$func = "JOIN `" . $this->getNamespace() . ".database.properties` b_func ON a.uid IS NOT NULL
$func = 'JOIN `'.$this->getNamespace().".database.properties` b_func ON a.uid IS NOT NULL
AND a.uid = b_func.documentUid
AND (b_func.key = 'sizeOriginal')";
$roles = [];
@ -717,10 +723,10 @@ class MySQL extends Adapter
$roles = ['1=1'];
}
$query = "SELECT SUM(b_func.value) as result
FROM `" . $this->getNamespace() . ".database.documents` a {$where}{$join}{$func}
$query = 'SELECT SUM(b_func.value) as result
FROM `'.$this->getNamespace().".database.documents` a {$where}{$join}{$func}
WHERE status = 0
AND (" . implode('||', $roles) . ")";
AND (".implode('||', $roles).')';
$st = $this->getPDO()->prepare(sprintf($query));
@ -741,14 +747,14 @@ class MySQL extends Adapter
}
/**
* Get Unique Document ID
* Get Unique Document ID.
*/
public function getUid()
{
$unique = uniqid();
$attempts = 5;
for ($i = 1; $i <= $attempts; $i++) {
for ($i = 1; $i <= $attempts; ++$i) {
$document = $this->getDocument($unique);
if (empty($document) || $document['$uid'] !== $unique) {
@ -760,7 +766,7 @@ class MySQL extends Adapter
}
/**
* Last Modified
* Last Modified.
*
* Return unix timestamp of last time a node queried in corrent session has been changed
*
@ -772,10 +778,12 @@ class MySQL extends Adapter
}
/**
* Parse Filter
* Parse Filter.
*
* @param string $filter
*
* @return array
*
* @throws Exception
*/
protected function parseFilter($filter)
@ -811,13 +819,15 @@ class MySQL extends Adapter
}
/**
* Get Data Type
* Get Data Type.
*
* Check value data type. return value can be on of the following:
* string, integer, float, boolean, object, list or null
*
* @param $value
*
* @return string
*
* @throws \Exception
*/
protected function getDataType($value)
@ -859,6 +869,7 @@ class MySQL extends Adapter
/**
* @param $key
* @param $value
*
* @return $this
*/
public function setDebug($key, $value)
@ -877,7 +888,7 @@ class MySQL extends Adapter
}
/**
* return $this;
* return $this;.
*/
public function resetDebug()
{
@ -886,6 +897,7 @@ class MySQL extends Adapter
/**
* @return PDO
*
* @throws Exception
*/
protected function getPDO():PDO
@ -895,6 +907,7 @@ class MySQL extends Adapter
/**
* @throws Exception
*
* @return Client
*/
protected function getRedis():Client

View file

@ -21,6 +21,7 @@ class Redis extends Adapter
/**
* Redis constructor.
*
* @param Adapter $adapter
* @param Registry $register
*/
@ -31,10 +32,12 @@ class Redis extends Adapter
}
/**
* Get Document
* Get Document.
*
* @param string $id
*
* @return array
*
* @throws Exception
*/
public function getDocument($id)
@ -53,7 +56,9 @@ class Redis extends Adapter
/**
* @param $output
*
* @return mixed
*
* @throws Exception
*/
protected function parseRelations($output)
@ -81,8 +86,7 @@ class Redis extends Adapter
if ($relationship['array']) {
$output[$relationship['key']][] = $node;
}
else {
} else {
$output[$relationship['key']] = $node;
}
}
@ -93,10 +97,12 @@ class Redis extends Adapter
}
/**
* Create Document
* Create Document.
*
* @param array $data
*
* @return array
*
* @throws Exception
*/
public function createDocument(array $data = [])
@ -110,10 +116,12 @@ class Redis extends Adapter
}
/**
* Update Document
* Update Document.
*
* @param array $data
*
* @return array
*
* @throws Exception
*/
public function updateDocument(array $data = [])
@ -127,10 +135,12 @@ class Redis extends Adapter
}
/**
* Delete Document
* Delete Document.
*
* @param $id
*
* @return array
*
* @throws Exception
*/
public function deleteDocument($id)
@ -144,9 +154,10 @@ class Redis extends Adapter
}
/**
* Create Namespace
* Create Namespace.
*
* @param string $namespace
*
* @return bool
*/
public function createNamespace($namespace)
@ -155,9 +166,10 @@ class Redis extends Adapter
}
/**
* Delete Namespace
* Delete Namespace.
*
* @param string $namespace
*
* @return bool
*/
public function deleteNamespace($namespace)
@ -167,7 +179,9 @@ class Redis extends Adapter
/**
* @param array $options
*
* @return array
*
* @throws Exception
*/
public function getCollection(array $options)
@ -194,7 +208,9 @@ class Redis extends Adapter
/**
* @param array $options
*
* @return int
*
* @throws Exception
*/
public function getCount(array $options)
@ -203,7 +219,7 @@ class Redis extends Adapter
}
/**
* Last Modified
* Last Modified.
*
* Return unix timestamp of last time a node queried in current session has been changed
*
@ -211,7 +227,7 @@ class Redis extends Adapter
*/
public function lastModified()
{
return null;
return;
}
/**
@ -224,6 +240,7 @@ class Redis extends Adapter
/**
* @throws Exception
*
* @return Client
*/
protected function getRedis():Client
@ -232,12 +249,14 @@ class Redis extends Adapter
}
/**
* Set Namespace
* Set Namespace.
*
* Set namespace to divide different scope of data sets
*
* @param $namespace
*
* @return bool
*
* @throws Exception
*/
public function setNamespace($namespace)

View file

@ -45,38 +45,44 @@ class Database
protected $adapter;
/**
* Set Adapter
* Set Adapter.
*
* @param Adapter $adapter
*
* @return $this
*/
public function setAdapter(Adapter $adapter)
{
$this->adapter = $adapter;
return $this;
}
/**
* Set Namespace
* Set Namespace.
*
* Set namespace to divide different scope of data sets
*
* @param $namespace
*
* @return $this
*
* @throws Exception
*/
public function setNamespace($namespace)
{
$this->adapter->setNamespace($namespace);
return $this;
}
/**
* Get Namespace
* Get Namespace.
*
* Get namespace of current set scope
*
* @return string
*
* @throws Exception
*/
public function getNamespace()
@ -85,9 +91,10 @@ class Database
}
/**
* Create Namespace
* Create Namespace.
*
* @param int $namespace
*
* @return bool
*/
public function createNamespace($namespace)
@ -96,9 +103,10 @@ class Database
}
/**
* Delete Namespace
* Delete Namespace.
*
* @param int $namespace
*
* @return bool
*/
public function deleteNamespace($namespace)
@ -108,6 +116,7 @@ class Database
/**
* @param array $options
*
* @return Document[]|Document
*/
public function getCollection(array $options)
@ -145,6 +154,7 @@ class Database
/**
* @param int $id
* @param bool $mock is mocked data allowed?
*
* @return Document
*/
public function getDocument($id, $mock = true)
@ -156,7 +166,6 @@ class Database
$document = new Document((isset($this->mocks[$id]) && $mock) ? $this->mocks[$id] : $this->adapter->getDocument($id));
$validator = new Authorization($document, 'read');
if (!$validator->isValid($document->getPermissions())) { // Check if user has read access to this document
return new Document([]);
}
@ -166,7 +175,9 @@ class Database
/**
* @param array $data
*
* @return Document|bool
*
* @throws AuthorizationException
* @throws StructureException
*/
@ -191,7 +202,9 @@ class Database
/**
* @param array $data
*
* @return Document|false
*
* @throws Exception
*/
public function updateDocument(array $data)
@ -229,7 +242,9 @@ class Database
/**
* @param int $id
*
* @return Document|false
*
* @throws AuthorizationException
*/
public function deleteDocument($id)
@ -265,6 +280,7 @@ class Database
/**
* @param array $options
*
* @return int
*/
public function getCount(array $options)
@ -281,31 +297,38 @@ class Database
/**
* @param string $key
* @param string $value
*
* @return array
*/
public function setMock($key, $value) {
public function setMock($key, $value)
{
$this->mocks[$key] = $value;
return $this;
}
/**
* @param string $mocks
*
* @return array
*/
public function setMocks(array $mocks) {
public function setMocks(array $mocks)
{
$this->mocks = $mocks;
return $this;
}
/**
* @return array
*/
public function getMocks() {
public function getMocks()
{
return $this->mocks;
}
/**
* Get Last Modified
* Get Last Modified.
*
* Return unix timestamp of last time a node queried in current session has been changed
*

View file

@ -11,23 +11,23 @@ class Document extends ArrayObject
const SET_TYPE_APPEND = 'append';
/**
* Construct
* Construct.
*
* Construct a new fields object
*
* @see ArrayObject::__construct
*
* @param null $input
* @param int $flags
* @param string $iterator_class
*/
public function __construct($input = null, $flags = 0, $iterator_class = "ArrayIterator")
public function __construct($input = null, $flags = 0, $iterator_class = 'ArrayIterator')
{
foreach ($input as $key => &$value) {
if (is_array($value)) {
if (isset($value['$uid']) || isset($value['$collection'])) {
$input[$key] = new self($value);
}
else {
} else {
foreach ($value as $childKey => $child) {
if (isset($child['$uid']) || isset($child['$collection'])) {
$value[$childKey] = new self($child);
@ -65,12 +65,13 @@ class Document extends ArrayObject
}
/**
* Get Attribute
* Get Attribute.
*
* Method for getting a specific fields attribute. If $name is not found $default value will be returned.
*
* @param string $name
* @param mixed $default
*
* @return mixed
*/
public function getAttribute($name, $default = null)
@ -91,13 +92,14 @@ class Document extends ArrayObject
}
/**
* Set Attribute
* Set Attribute.
*
* Method for setting a specific field attribute
*
* @param string $key
* @param mixed $value
* @param string $type
*
* @return mixed
*/
public function setAttribute($key, $value, $type = self::SET_TYPE_ASSIGN)
@ -120,13 +122,14 @@ class Document extends ArrayObject
}
/**
* Search
* Search.
*
* Get array child by key and value match
*
* @param $key
* @param $value
* @param array|null $scope
*
* @return Document|Document[]|mixed|null|array
*/
public function search($key, $value, $scope = null)
@ -145,8 +148,7 @@ class Document extends ArrayObject
if (!empty($result)) {
return $result;
}
}
else {
} else {
if ($k === $key && $v === $value) {
return $array;
}
@ -158,11 +160,11 @@ class Document extends ArrayObject
return $array;
}
return null;
return;
}
/**
* Checks if document has data
* Checks if document has data.
*
* @return bool
*/
@ -172,12 +174,13 @@ class Document extends ArrayObject
}
/**
* Get Array Copy
* Get Array Copy.
*
* Outputs entity as a PHP array
*
* @param array $whitelist
* @param array $blacklist
*
* @return array
*/
public function getArrayCopy(array $whitelist = [], array $blacklist = [])
@ -197,13 +200,11 @@ class Document extends ArrayObject
if ($value instanceof self) {
$output[$key] = $value->getArrayCopy($whitelist, $blacklist);
}
elseif (is_array($value)) {
} elseif (is_array($value)) {
foreach ($value as $childKey => &$child) {
if ($child instanceof self) {
$output[$key][$childKey] = $child->getArrayCopy($whitelist, $blacklist);
}
else {
} else {
$output[$key][$childKey] = $child;
}
}
@ -211,8 +212,7 @@ class Document extends ArrayObject
if (empty($value)) {
$output[$key] = $value;
}
}
else {
} else {
$output[$key] = $value;
}
}

View file

@ -4,5 +4,4 @@ namespace Database\Exception;
class Authorization extends \Exception
{
}

View file

@ -4,5 +4,4 @@ namespace Database\Exception;
class Structure extends \Exception
{
}

View file

@ -10,7 +10,7 @@ class Authorization extends Validator
/**
* @var array
*/
static protected $roles = ['*'];
protected static $roles = ['*'];
/**
* @var Document
@ -40,7 +40,7 @@ class Authorization extends Validator
}
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -52,11 +52,12 @@ class Authorization extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param array $permissions
*
* @return bool
*/
public function isValid($permissions)
@ -67,6 +68,7 @@ class Authorization extends Validator
if (!isset($permissions[$this->action])) {
$this->message = 'Missing action key: "'.$this->action.'"';
return false;
}
@ -88,7 +90,7 @@ class Authorization extends Validator
/**
* @param string $role
*/
static public function setRole($role)
public static function setRole($role)
{
self::$roles[] = $role;
}
@ -96,7 +98,7 @@ class Authorization extends Validator
/**
* @return array
*/
static public function getRoles()
public static function getRoles()
{
return self::$roles;
}
@ -104,12 +106,12 @@ class Authorization extends Validator
/**
* @var bool
*/
static public $status = true;
public static $status = true;
/**
*
*/
static public function enable()
public static function enable()
{
self::$status = true;
}
@ -117,7 +119,7 @@ class Authorization extends Validator
/**
*
*/
static public function disable()
public static function disable()
{
self::$status = false;
}

View file

@ -30,6 +30,7 @@ class Collection extends Structure
/**
* @param Document $document
*
* @return bool
*/
public function isValid($document)
@ -38,11 +39,13 @@ class Collection extends Structure
if (is_null($document->getCollection())) {
$this->message = 'Missing collection attribute $collection';
return false;
}
if (!in_array($document->getCollection(), $this->collections)) {
$this->message = 'Collection is not allowed';
return false;
}

View file

@ -12,7 +12,7 @@ class Key extends Validator
protected $message = 'Parameter must contain only letters with no spaces or special chars and be shorter than 32 chars';
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -24,17 +24,17 @@ class Key extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param $value
*
* @return bool
*/
public function isValid($value)
{
if (preg_match('/[^A-Za-z0-9\-\_]/', $value))
{
if (preg_match('/[^A-Za-z0-9\-\_]/', $value)) {
return false;
}

View file

@ -28,7 +28,7 @@ class Permissions extends Validator
}
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -40,29 +40,33 @@ class Permissions extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param array $value
*
* @return bool
*/
public function isValid($value)
{
if (!is_array($value) && !empty($value)) {
$this->message = 'Invalid permissions data structure';
return false;
}
foreach ($value as $action => $roles) {
if (!in_array($action, ['read', 'write'])) {
$this->message = 'Unknown action ("'.$action.'")';
return false;
}
foreach ($roles as $role) {
if (!is_string($role)) {
$this->message = 'Permissions role must be a string';
return false;
}
}

View file

@ -19,7 +19,7 @@ class Structure extends Validator
protected $id = null;
/**
* Basic rules to apply on all documents
* Basic rules to apply on all documents.
*
* @var array
*/
@ -93,6 +93,7 @@ class Structure extends Validator
/**
* Structure constructor.
*
* @param Database $database
*/
public function __construct(Database $database)
@ -101,7 +102,7 @@ class Structure extends Validator
}
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -113,11 +114,12 @@ class Structure extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param Document $document
*
* @return bool
*/
public function isValid($document)
@ -128,6 +130,7 @@ class Structure extends Validator
if (is_null($document->getCollection())) {
$this->message = 'Missing collection attribute $collection';
return false;
}
@ -135,6 +138,7 @@ class Structure extends Validator
if (is_null($collection->getUid()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) {
$this->message = 'Collection not found';
return false;
}
@ -145,6 +149,7 @@ class Structure extends Validator
if (isset($rule['key']) && !isset($array[$rule['key']])
&& isset($rule['required']) && true == $rule['required']) {
$this->message = 'Missing required key "'.$rule['key'].'"';
return false;
}
}
@ -197,11 +202,13 @@ class Structure extends Validator
if (empty($validator)) { // Error creating validator for property
$this->message = 'Unknown property "'.$key.'"'.
'. Make sure to follow '.strtolower($collection->getAttribute('name', 'unknown')).' collection structure';
return false;
}
if ($ruleRequired && ('' === $value || null === $value)) {
$this->message = 'Required property "'.$key.'" has no value';
return false;
}
@ -215,6 +222,7 @@ class Structure extends Validator
if ($ruleArray) { // Array of values validation
if (!is_array($value)) {
$this->message = 'Property "'.$key.'" must be an array';
return false;
}
@ -223,13 +231,14 @@ class Structure extends Validator
foreach ($value as $node) {
if (!$validator->isValid($node)) { // Check if property is valid, if not required can also be empty
$this->message = 'Property "'.$key.'" has invalid input. '.$validator->getDescription();
return false;
}
}
}
else { // Single value validation
} else { // Single value validation
if ((!$validator->isValid($value)) && !('' === $value && !$ruleRequired)) { // Error when value is not valid, and is not optional and empty
$this->message = 'Property "'.$key.'" has invalid input. '.$validator->getDescription();
return false;
}
}
@ -241,6 +250,7 @@ class Structure extends Validator
if (!empty($array)) { // No fields should be left unvalidated
$this->message = 'Unknown properties are not allowed ('.implode(', ', array_keys($array)).') for this collection'.
'. Make sure to follow '.strtolower($collection->getAttribute('name', 'unknown')).' collection structure';
return false;
}

View file

@ -7,7 +7,7 @@ use Utopia\Validator;
class UID extends Validator
{
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -19,11 +19,12 @@ class UID extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param string $value
*
* @return bool
*/
public function isValid($value)

View file

@ -23,6 +23,7 @@ class Event
/**
* Event constructor.
*
* @param string $queue
* @param string $class
*/
@ -35,16 +36,19 @@ class Event
/**
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function setParam($key, $value)
{
$this->params[$key] = $value;
return $this;
}
/**
* @param string $key
*
* @return mixed|null
*/
public function getParam($key)
@ -53,7 +57,7 @@ class Event
}
/**
* Execute Event
* Execute Event.
*/
public function trigger()
{

View file

@ -15,9 +15,10 @@ class OpenSSL
* @param null $tag
* @param string $aad
* @param int $tag_length
*
* @return string
*/
static public function encrypt($data, $method, $key, $options = 0, $iv = '', &$tag = null, $aad = '', $tag_length = 16)
public static function encrypt($data, $method, $key, $options = 0, $iv = '', &$tag = null, $aad = '', $tag_length = 16)
{
return openssl_encrypt($data, $method, $key, $options, $iv, $tag, $aad, $tag_length);
}
@ -30,18 +31,20 @@ class OpenSSL
* @param string $iv
* @param string $tag
* @param string $aad
*
* @return string
*/
static public function decrypt($data, $method, $password, $options = 1, $iv = '', $tag = '', $aad = '')
public static function decrypt($data, $method, $password, $options = 1, $iv = '', $tag = '', $aad = '')
{
return openssl_decrypt($data, $method, $password, $options, $iv, $tag, $aad);
}
/**
* @param string $method
*
* @return int
*/
static public function cipherIVLength($method)
public static function cipherIVLength($method)
{
return openssl_cipher_iv_length($method);
}
@ -49,9 +52,10 @@ class OpenSSL
/**
* @param $length
* @param null $crypto_strong
*
* @return int
*/
static public function randomPseudoBytes($length, &$crypto_strong = null)
public static function randomPseudoBytes($length, &$crypto_strong = null)
{
return openssl_random_pseudo_bytes($length, $crypto_strong);
}

View file

@ -15,6 +15,7 @@ class Resize
/**
* @param string $data
*
* @throws Exception
*/
public function __construct($data)
@ -30,7 +31,9 @@ class Resize
/**
* @param int $width
* @param int $height
*
* @return Resize
*
* @throws \ImagickException
*/
public function crop(int $width, int $height)
@ -58,8 +61,7 @@ class Resize
}
$this->image->deconstructImages();
}
else {
} else {
$this->image->cropThumbnailImage($width, $height);
}
@ -68,10 +70,13 @@ class Resize
/**
* @param $color
*
* @return Resize
*
* @throws \ImagickException
*/
public function setBackground($color) {
public function setBackground($color)
{
$this->image->setImageBackgroundColor($color);
$this->image = $this->image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
@ -79,13 +84,15 @@ class Resize
}
/**
* Output
* Output.
*
* Prints manipulated image.
*
* @param string $type
* @param int $quality
*
* @return string
*
* @throws Exception
*/
public function output(string $type, int $quality = 75)
@ -97,7 +104,9 @@ class Resize
* @param string $path
* @param $type
* @param int $quality
*
* @return string
*
* @throws Exception
*/
public function save(string $path = null, string $type = '', int $quality = 75)
@ -137,8 +146,7 @@ class Resize
//load webp
if (empty($path)) {
return $data;
}
else {
} else {
file_put_contents($path, $data, LOCK_EX);
}
@ -149,7 +157,7 @@ class Resize
unlink($output);
unlink($temp);
return null;
return;
break;
@ -162,7 +170,7 @@ class Resize
$this->image->setImageCompressionQuality($invertScaleQuality);
$this->image->setImageFormat("png");
$this->image->setImageFormat('png');
break;
default:
@ -172,8 +180,7 @@ class Resize
if (empty($path)) {
return $this->image->getImagesBlob();
}
else {
} else {
$this->image->writeImages($path, true);
}
@ -183,6 +190,7 @@ class Resize
/**
* @param int $newHeight
*
* @return int
*/
protected function getSizeByFixedHeight(int $newHeight):int
@ -195,6 +203,7 @@ class Resize
/**
* @param int $newWidth
*
* @return int
*/
protected function getSizeByFixedWidth(int $newWidth):int

View file

@ -15,7 +15,7 @@ class GZIP extends Compression
}
/**
* Compress
* Compress.
*
* We use gzencode over gzcompress for better support of the first format among other tools.
* (http://stackoverflow.com/a/621987/2299554)
@ -23,6 +23,7 @@ class GZIP extends Compression
* @see http://php.net/manual/en/function.gzencode.php
*
* @param string $data
*
* @return string
*/
public function compress(string $data):string
@ -31,9 +32,10 @@ class GZIP extends Compression
}
/**
* Decompress
* Decompress.
*
* @param string $data
*
* @return string
*/
public function decompress(string $data):string

View file

@ -5,7 +5,7 @@ namespace Storage\Compression;
abstract class Compression
{
/**
* Return the name of compression algorithm
* Return the name of compression algorithm.
*
* @return string
*/
@ -13,12 +13,14 @@ abstract class Compression
/**
* @param $data
*
* @return string
*/
abstract public function compress(string $data);
/**
* @param $data
*
* @return string
*/
abstract public function decompress(string $data);

View file

@ -7,7 +7,7 @@ use Exception;
abstract class Device
{
/**
* Get Name
* Get Name.
*
* Get storage device name
*
@ -16,7 +16,7 @@ abstract class Device
abstract public function getName();
/**
* Get Description
* Get Description.
*
* Get storage device description and purpose.
*
@ -25,7 +25,7 @@ abstract class Device
abstract public function getDescription();
/**
* Get Root
* Get Root.
*
* Get storage device root path
*
@ -34,11 +34,12 @@ abstract class Device
abstract public function getRoot();
/**
* Get Path
* Get Path.
*
* Each device hold a complex directory structure that is being build in this method.
*
* @param $filename
*
* @return string
*/
public function getPath($filename)
@ -47,13 +48,15 @@ abstract class Device
}
/**
* Upload
* Upload.
*
* Upload a file to desired destination in the selected disk.
*
* @param string $target
* @param string $filename
*
* @throws \Exception
*
* @return string|bool saved destination on success or false on failures
*/
public function upload($target, $filename = '')
@ -81,9 +84,10 @@ abstract class Device
}
/**
* Read file by given path
* Read file by given path.
*
* @param string $path
*
* @return string
*/
public function read(string $path):string
@ -92,10 +96,11 @@ abstract class Device
}
/**
* Write file by given path
* Write file by given path.
*
* @param string $path
* @param string $data
*
* @return string
*/
public function write(string $path, string $data):bool
@ -104,11 +109,12 @@ abstract class Device
}
/**
* Delete file in given path, Return true on success and false on failure
* Delete file in given path, Return true on success and false on failure.
*
* @see http://php.net/manual/en/function.filesize.php
*
* @param string $path
*
* @return bool
*/
public function delete(string $path):bool
@ -117,11 +123,12 @@ abstract class Device
}
/**
* Delete all file and directories in given path, Return true on success and false on failure
* Delete all file and directories in given path, Return true on success and false on failure.
*
* @see https://paulund.co.uk/php-delete-directory-and-files-in-directory
*
* @param string $path
*
* @return bool
*/
public function deleteDir($target):bool
@ -134,8 +141,7 @@ abstract class Device
}
rmdir($target);
}
elseif (is_file($target)) {
} elseif (is_file($target)) {
unlink($target);
}
@ -143,11 +149,12 @@ abstract class Device
}
/**
* Returns given file path its size
* Returns given file path its size.
*
* @see http://php.net/manual/en/function.filesize.php
*
* @param $path
*
* @return int
*/
public function getFileSize(string $path):int
@ -156,11 +163,12 @@ abstract class Device
}
/**
* Returns given file path its mime type
* Returns given file path its mime type.
*
* @see http://php.net/manual/en/function.mime-content-type.php
*
* @param $path
*
* @return string
*/
public function getFileMimeType(string $path):string
@ -169,11 +177,12 @@ abstract class Device
}
/**
* Returns given file path its MD5 hash value
* Returns given file path its MD5 hash value.
*
* @see http://php.net/manual/en/function.md5-file.php
*
* @param $path
*
* @return string
*/
public function getFileHash(string $path):string
@ -182,13 +191,14 @@ abstract class Device
}
/**
* Get directory size in bytes
* Get directory size in bytes.
*
* Return -1 on error
*
* Based on http://www.jonasjohn.de/snippets/php/dir-size.htm
*
* @param $path
*
* @return int
*/
public function getDirectorySize(string $path):int
@ -197,18 +207,20 @@ abstract class Device
$directory = opendir($path);
if (!$directory)
if (!$directory) {
return -1;
}
while (($file = readdir($directory)) !== false) {
// Skip file pointers
if ($file[0] == '.') continue;
if ($file[0] == '.') {
continue;
}
// Go recursive down, or add the file size
if (is_dir($path.$file)) {
$size += $this->getDirectorySize($path.$file.DIRECTORY_SEPARATOR);
}
else {
} else {
$size += filesize($path.$file);
}
}
@ -219,7 +231,7 @@ abstract class Device
}
/**
* Get Partition Free Space
* Get Partition Free Space.
*
* disk_free_space Returns available space on filesystem or disk partition
*
@ -231,7 +243,7 @@ abstract class Device
}
/**
* Get Partition Total Space
* Get Partition Total Space.
*
* disk_total_space Returns the total size of a filesystem or disk partition
*
@ -243,12 +255,13 @@ abstract class Device
}
/**
* Human readable data size format from bytes input
* Human readable data size format from bytes input.
*
* As published on https://gist.github.com/liunian/9338301 (first comment)
*
* @param int $bytes
* @param int $decimals
*
* @return string
*/
public function human($bytes, $decimals = 2)
@ -259,7 +272,7 @@ abstract class Device
while (($bytes / $step) > 0.9) {
$bytes = $bytes / $step;
$i++;
++$i;
}
return round($bytes, $decimals).$units[$i];

View file

@ -13,6 +13,7 @@ class Local extends Device
/**
* Local constructor.
*
* @param string $root
*/
public function __construct($root = '')
@ -46,13 +47,14 @@ class Local extends Device
/**
* @param string $filename
*
* @return string
*/
public function getPath($filename)
{
$path = '';
for ($i = 0; $i < 4; $i++) {
for ($i = 0; $i < 4; ++$i) {
$path = ($i < strlen($filename)) ? $path.DIRECTORY_SEPARATOR.$filename[$i] : $path.DIRECTORY_SEPARATOR.'x';
}

View file

@ -32,13 +32,14 @@ class S3 extends Device
/**
* @param string $filename
*
* @return string
*/
public function getPath($filename)
{
$path = '';
for ($i = 0; $i < 4; $i++) {
for ($i = 0; $i < 4; ++$i) {
$path = ($i < strlen($filename)) ? $path.DIRECTORY_SEPARATOR.$filename[$i] : $path.DIRECTORY_SEPARATOR.'x';
}

View file

@ -7,24 +7,25 @@ use Exception;
class Storage
{
/**
* Devices
* Devices.
*
* List of all available storage devices
*
* @var array
*/
static $devices = array();
public static $devices = array();
/**
* Add Device
* Add Device.
*
* Add device by name
*
* @param string $name
* @param Device $device
*
* @throws Exception
*/
static public function addDevice($name, Device $device)
public static function addDevice($name, Device $device)
{
if (array_key_exists($name, self::$devices)) {
throw new Exception('The device "'.$name.'" is already listed');
@ -34,15 +35,17 @@ class Storage
}
/**
* Get Device
* Get Device.
*
* Get device by name
*
* @param string $name
*
* @return Device
*
* @throws Exception
*/
static public function getDevice($name)
public static function getDevice($name)
{
if (!array_key_exists($name, self::$devices)) {
throw new Exception('The device "'.$name.'" is not listed');
@ -52,14 +55,15 @@ class Storage
}
/**
* Exists
* Exists.
*
* Checks if given storage name is registered or not
*
* @param string $name
*
* @return bool
*/
static public function exists($name)
public static function exists($name)
{
return (bool) array_key_exists($name, self::$devices);
}

View file

@ -6,18 +6,18 @@ use Utopia\Validator;
class File extends Validator
{
public function getDescription()
{
return 'File is not valid';
}
/**
* NOT MUCH RIGHT NOW
* NOT MUCH RIGHT NOW.
*
* TODO think what to do here, currently only used for parameter to be present in SDKs
*
* @param string $name
*
* @return bool
*/
public function isValid($name)

View file

@ -6,16 +6,16 @@ use Utopia\Validator;
class FileName extends Validator
{
public function getDescription()
{
return 'Filename is not valid';
}
/**
* The file name can only contain "a-z", "A-Z", "0-9" and "-" and not empty
* The file name can only contain "a-z", "A-Z", "0-9" and "-" and not empty.
*
* @param string $name
*
* @return bool
*/
public function isValid($name)

View file

@ -25,9 +25,10 @@ class FileSize extends Validator
}
/**
* Finds whether a file size is smaller than required limit
* Finds whether a file size is smaller than required limit.
*
* @param int $fileSize
*
* @return bool
*/
public function isValid($fileSize)

View file

@ -8,14 +8,14 @@ use Utopia\Validator;
class FileType extends Validator
{
/**
* File Types Constants
* File Types Constants.
*/
const FILE_TYPE_JPEG = 'jpeg';
const FILE_TYPE_GIF = 'gif';
const FILE_TYPE_PNG = 'png';
/**
* File Type Binaries
* File Type Binaries.
*
* @var array
*/
@ -32,6 +32,7 @@ class FileType extends Validator
/**
* @param array $whiteList
*
* @throws Exception
*/
public function __construct(array $whiteList)
@ -51,12 +52,14 @@ class FileType extends Validator
}
/**
* Is Valid
* Is Valid.
*
* Binary check to finds whether a file is of valid type
*
* @see http://stackoverflow.com/a/3313196
*
* @param string $path
*
* @return bool
*/
public function isValid($path)

View file

@ -7,9 +7,8 @@ use Utopia\Validator;
class Cron extends Validator
{
/**
* Get Description
* Get Description.
*
* Returns validator description
*
@ -21,11 +20,12 @@ class Cron extends Validator
}
/**
* Is valid
* Is valid.
*
* Returns true if valid or false if not.
*
* @param mixed $value
*
* @return bool
*/
public function isValid($value)

View file

@ -8,12 +8,13 @@ use Utopia\View;
class Template extends View
{
/**
* Render
* Render.
*
* Render view .phtml template file if template has not been set as rendered yet using $this->setRendered(true).
* In case path is not readable throws Exception.
*
* @return string
*
* @throws Exception
*/
public function render()
@ -24,8 +25,7 @@ class Template extends View
if (is_readable($this->path)) {
$template = file_get_contents($this->path); // Include template file
}
else {
} else {
throw new Exception('"'.$this->path.'" template is not readable or not found');
}
@ -35,27 +35,29 @@ class Template extends View
}
/**
* Parse URL
* Parse URL.
*
* Parse URL string to array
*
* @param $url
*
* @return mixed On seriously malformed URLs, parse_url() may return FALSE.
*/
static public function parseURL($url)
public static function parseURL($url)
{
return parse_url($url);
}
/**
* Un-Parse URL
* Un-Parse URL.
*
* Convert PHP array to query string
*
* @param $url
*
* @return string
*/
static public function unParseURL(array $url)
public static function unParseURL(array $url)
{
$scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
$host = isset($url['host']) ? $url['host'] : '';
@ -74,15 +76,16 @@ class Template extends View
}
/**
* Merge Query
* Merge Query.
*
* Merge array of params to query string
*
* @param $query1
* @param array $query2
*
* @return string
*/
static public function mergeQuery($query1, array $query2)
public static function mergeQuery($query1, array $query2)
{
$parsed = [];