diff --git a/app/app.php b/app/app.php index c26821bd5..64a496756 100644 --- a/app/app.php +++ b/app/app.php @@ -34,9 +34,9 @@ $deletes = new Event('v1-deletes', 'DeletesV1'); * Get All verified client URLs for both console and current projects * + Filter for duplicated entries */ -$clientsConsole = array_map(function ($node) { +$clientsConsole = \array_map(function ($node) { return $node['hostname']; - }, array_filter($console->getAttribute('platforms', []), function ($node) { + }, \array_filter($console->getAttribute('platforms', []), function ($node) { if (isset($node['type']) && $node['type'] === 'web' && isset($node['hostname']) && !empty($node['hostname'])) { return true; } @@ -44,9 +44,9 @@ $clientsConsole = array_map(function ($node) { return false; })); -$clients = array_unique(array_merge($clientsConsole, array_map(function ($node) { +$clients = \array_unique(\array_merge($clientsConsole, \array_map(function ($node) { return $node['hostname']; - }, array_filter($project->getAttribute('platforms', []), function ($node) { + }, \array_filter($project->getAttribute('platforms', []), function ($node) { if (isset($node['type']) && $node['type'] === 'web' && isset($node['hostname']) && !empty($node['hostname'])) { return true; } @@ -63,11 +63,11 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ } $referrer = $request->getServer('HTTP_REFERER', ''); - $origin = parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_HOST); - $protocol = parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_SCHEME); - $port = parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_PORT); + $origin = \parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_HOST); + $protocol = \parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_SCHEME); + $port = \parse_url($request->getServer('HTTP_ORIGIN', $referrer), PHP_URL_PORT); - $refDomain = $protocol.'://'.((in_array($origin, $clients)) + $refDomain = $protocol.'://'.((\in_array($origin, $clients)) ? $origin : 'localhost') . (!empty($port) ? ':'.$port : ''); $selfDomain = new Domain(Config::getParam('hostname')); @@ -93,7 +93,7 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ $response ->addHeader('Server', 'Appwrite') - ->addHeader('X-XSS-Protection', '1; mode=block; report=/v1/xss?url='.urlencode($request->getServer('REQUEST_URI'))) + ->addHeader('X-XSS-Protection', '1; mode=block; report=/v1/xss?url='.\urlencode($request->getServer('REQUEST_URI'))) //->addHeader('X-Frame-Options', ($refDomain == 'http://localhost') ? 'SAMEORIGIN' : 'ALLOW-FROM ' . $refDomain) ->addHeader('X-Content-Type-Options', 'nosniff') ->addHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE') @@ -109,10 +109,10 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ * Skip this check for non-web platforms which are not requiredto send an origin header */ $origin = $request->getServer('HTTP_ORIGIN', $request->getServer('HTTP_REFERER', '')); - $originValidator = new Origin(array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', []))); + $originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', []))); if(!$originValidator->isValid($origin) - && in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE]) + && \in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE]) && $route->getLabel('origin', false) !== '*' && empty($request->getHeader('X-Appwrite-Key', ''))) { throw new Exception($originValidator->getDescription(), 403); @@ -162,7 +162,7 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ ]); $role = Auth::USER_ROLE_APP; - $scopes = array_merge($roles[$role]['scopes'], $key->getAttribute('scopes', [])); + $scopes = \array_merge($roles[$role]['scopes'], $key->getAttribute('scopes', [])); Authorization::setDefaultStatus(false); // Cancel security segmentation for API keys. } @@ -170,7 +170,7 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ Authorization::setRole('user:'.$user->getId()); Authorization::setRole('role:'.$role); - array_map(function ($node) { + \array_map(function ($node) { if (isset($node['teamId']) && isset($node['roles'])) { Authorization::setRole('team:'.$node['teamId']); @@ -182,12 +182,12 @@ $utopia->init(function () use ($utopia, $request, $response, &$user, $project, $ // TDOO Check if user is god - if (!in_array($scope, $scopes)) { + if (!\in_array($scope, $scopes)) { if (empty($project->getId()) || Database::SYSTEM_COLLECTION_PROJECTS !== $project->getCollection()) { // Check if permission is denied because project is missing throw new Exception('Project not found', 404); } - throw new Exception($user->getAttribute('email', 'User').' (role: '.strtolower($roles[$role]['label']).') missing scope ('.$scope.')', 401); + throw new Exception($user->getAttribute('email', 'User').' (role: '.\strtolower($roles[$role]['label']).') missing scope ('.$scope.')', 401); } if (Auth::USER_STATUS_BLOCKED == $user->getAttribute('status')) { // Account has not been activated @@ -396,9 +396,9 @@ $utopia->get('/.well-known/acme-challenge') ->label('docs', false) ->action( function () use ($request, $response) { - $base = realpath(APP_STORAGE_CERTIFICATES); - $path = str_replace('/.well-known/acme-challenge/', '', $request->getParam('q')); - $absolute = realpath($base.'/.well-known/acme-challenge/'.$path); + $base = \realpath(APP_STORAGE_CERTIFICATES); + $path = \str_replace('/.well-known/acme-challenge/', '', $request->getParam('q')); + $absolute = \realpath($base.'/.well-known/acme-challenge/'.$path); if(!$base) { throw new Exception('Storage error', 500); @@ -408,15 +408,15 @@ $utopia->get('/.well-known/acme-challenge') throw new Exception('Unknown path', 404); } - if(!substr($absolute, 0, strlen($base)) === $base) { + if(!\substr($absolute, 0, \strlen($base)) === $base) { throw new Exception('Invalid path', 401); } - if(!file_exists($absolute)) { + if(!\file_exists($absolute)) { throw new Exception('Unknown path', 404); } - $content = @file_get_contents($absolute); + $content = @\file_get_contents($absolute); if(!$content) { throw new Exception('Failed to get contents', 500); @@ -428,9 +428,9 @@ $utopia->get('/.well-known/acme-challenge') $name = APP_NAME; -if (array_key_exists($service, $services)) { /** @noinspection PhpIncludeInspection */ +if (\array_key_exists($service, $services)) { /** @noinspection PhpIncludeInspection */ include_once $services[$service]['controller']; - $name = APP_NAME.' '.ucfirst($services[$service]['name']); + $name = APP_NAME.' '.\ucfirst($services[$service]['name']); } else { /** @noinspection PhpIncludeInspection */ include_once $services['/']['controller']; diff --git a/app/config/collections.php b/app/config/collections.php index 3b1d16791..3141419c1 100644 --- a/app/config/collections.php +++ b/app/config/collections.php @@ -41,7 +41,7 @@ $collections = [ '$collection' => Database::SYSTEM_COLLECTION_PLATFORMS, 'name' => 'Current Host', 'type' => 'web', - 'hostname' => parse_url('https://'.$request->getServer('HTTP_HOST'), PHP_URL_HOST), + 'hostname' => \parse_url('https://'.$request->getServer('HTTP_HOST'), PHP_URL_HOST), ], ], 'legalName' => '', @@ -50,9 +50,9 @@ $collections = [ 'legalCity' => '', 'legalAddress' => '', 'legalTaxId' => '', - 'authWhitelistEmails' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [], - 'authWhitelistIPs' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_IPS', null))) ? explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_IPS', null)) : [], - 'authWhitelistDomains' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_DOMAINS', null))) ? explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_DOMAINS', null)) : [], + 'authWhitelistEmails' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [], + 'authWhitelistIPs' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_IPS', null)) : [], + 'authWhitelistDomains' => (!empty($request->getServer('_APP_CONSOLE_WHITELIST_DOMAINS', null))) ? \explode(',', $request->getServer('_APP_CONSOLE_WHITELIST_DOMAINS', null)) : [], ], Database::SYSTEM_COLLECTION_COLLECTIONS => [ '$collection' => Database::SYSTEM_COLLECTION_COLLECTIONS, @@ -1199,8 +1199,8 @@ foreach ($providers as $index => $provider) { $collections[Database::SYSTEM_COLLECTION_PROJECTS]['rules'][] = [ '$collection' => Database::SYSTEM_COLLECTION_RULES, - 'label' => 'OAuth2 '.ucfirst($index).' ID', - 'key' => 'usersOauth2'.ucfirst($index).'Appid', + 'label' => 'OAuth2 '.\ucfirst($index).' ID', + 'key' => 'usersOauth2'.\ucfirst($index).'Appid', 'type' => 'text', 'default' => '', 'required' => false, @@ -1209,8 +1209,8 @@ foreach ($providers as $index => $provider) { $collections[Database::SYSTEM_COLLECTION_PROJECTS]['rules'][] = [ '$collection' => Database::SYSTEM_COLLECTION_RULES, - 'label' => 'OAuth2 '.ucfirst($index).' Secret', - 'key' => 'usersOauth2'.ucfirst($index).'Secret', + 'label' => 'OAuth2 '.\ucfirst($index).' Secret', + 'key' => 'usersOauth2'.\ucfirst($index).'Secret', 'type' => 'text', 'default' => '', 'required' => false, @@ -1219,8 +1219,8 @@ foreach ($providers as $index => $provider) { $collections[Database::SYSTEM_COLLECTION_USERS]['rules'][] = [ '$collection' => Database::SYSTEM_COLLECTION_RULES, - 'label' => 'OAuth2 '.ucfirst($index).' ID', - 'key' => 'oauth2'.ucfirst($index), + 'label' => 'OAuth2 '.\ucfirst($index).' ID', + 'key' => 'oauth2'.\ucfirst($index), 'type' => 'text', 'default' => '', 'required' => false, @@ -1229,8 +1229,8 @@ foreach ($providers as $index => $provider) { $collections[Database::SYSTEM_COLLECTION_USERS]['rules'][] = [ '$collection' => Database::SYSTEM_COLLECTION_RULES, - 'label' => 'OAuth2 '.ucfirst($index).' Access Token', - 'key' => 'oauth2'.ucfirst($index).'AccessToken', + 'label' => 'OAuth2 '.\ucfirst($index).' Access Token', + 'key' => 'oauth2'.\ucfirst($index).'AccessToken', 'type' => 'text', 'default' => '', 'required' => false, diff --git a/app/config/eu.php b/app/config/eu.php index d63ebef70..fbefd2369 100644 --- a/app/config/eu.php +++ b/app/config/eu.php @@ -30,7 +30,7 @@ $list = [ 'SE', // Sweden ]; -if (time() < strtotime('2020-01-31')) { // @see https://en.wikipedia.org/wiki/Brexit +if (\time() < \strtotime('2020-01-31')) { // @see https://en.wikipedia.org/wiki/Brexit $list[] = 'GB'; // // United Kingdom } diff --git a/app/config/platforms.php b/app/config/platforms.php index f05dcde39..a0b4955a8 100644 --- a/app/config/platforms.php +++ b/app/config/platforms.php @@ -21,7 +21,7 @@ return [ 'beta' => false, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'javascript', - 'source' => realpath(__DIR__ . '/../sdks/client-web'), + 'source' => \realpath(__DIR__ . '/../sdks/client-web'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-js.git', 'gitRepoName' => 'sdk-for-js', 'gitUserName' => 'appwrite', @@ -35,7 +35,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'dart', - 'source' => realpath(__DIR__ . '/../sdks/client-flutter'), + 'source' => \realpath(__DIR__ . '/../sdks/client-flutter'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-flutter.git', 'gitRepoName' => 'sdk-for-flutter', 'gitUserName' => 'appwrite', @@ -110,7 +110,7 @@ return [ 'beta' => false, 'family' => APP_PLATFORM_CONSOLE, 'prism' => 'console', - 'source' => realpath(__DIR__ . '/../sdks/console-web'), + 'source' => \realpath(__DIR__ . '/../sdks/console-web'), 'gitUrl' => null, 'gitRepoName' => 'sdk-for-console', 'gitUserName' => 'appwrite', @@ -134,7 +134,7 @@ return [ 'beta' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'javascript', - 'source' => realpath(__DIR__ . '/../sdks/server-nodejs'), + 'source' => \realpath(__DIR__ . '/../sdks/server-nodejs'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-node.git', 'gitRepoName' => 'sdk-for-node', 'gitUserName' => 'appwrite', @@ -148,7 +148,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'typescript', - 'source' => realpath(__DIR__ . '/../sdks/server-deno'), + 'source' => \realpath(__DIR__ . '/../sdks/server-deno'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-deno.git', 'gitRepoName' => 'sdk-for-deno', 'gitUserName' => 'appwrite', @@ -162,7 +162,7 @@ return [ 'beta' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'php', - 'source' => realpath(__DIR__ . '/../sdks/server-php'), + 'source' => \realpath(__DIR__ . '/../sdks/server-php'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-php.git', 'gitRepoName' => 'sdk-for-php', 'gitUserName' => 'appwrite', @@ -176,7 +176,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'python', - 'source' => realpath(__DIR__ . '/../sdks/server-python'), + 'source' => \realpath(__DIR__ . '/../sdks/server-python'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-python.git', 'gitRepoName' => 'sdk-for-python', 'gitUserName' => 'appwrite', @@ -190,7 +190,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'ruby', - 'source' => realpath(__DIR__ . '/../sdks/server-ruby'), + 'source' => \realpath(__DIR__ . '/../sdks/server-ruby'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-ruby.git', 'gitRepoName' => 'sdk-for-ruby', 'gitUserName' => 'appwrite', @@ -204,7 +204,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'go', - 'source' => realpath(__DIR__ . '/../sdks/server-go'), + 'source' => \realpath(__DIR__ . '/../sdks/server-go'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-go.git', 'gitRepoName' => 'sdk-for-go', 'gitUserName' => 'appwrite', @@ -218,7 +218,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'java', - 'source' => realpath(__DIR__ . '/../sdks/server-java'), + 'source' => \realpath(__DIR__ . '/../sdks/server-java'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-java.git', 'gitRepoName' => 'sdk-for-java', 'gitUserName' => 'appwrite', @@ -232,7 +232,7 @@ return [ 'beta' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'java', - 'source' => realpath(__DIR__ . '/../sdks/server-dart'), + 'source' => \realpath(__DIR__ . '/../sdks/server-dart'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-dart.git', 'gitRepoName' => 'sdk-for-dart', 'gitUserName' => 'appwrite', diff --git a/app/config/roles.php b/app/config/roles.php index 001ebb490..4d2420ec5 100644 --- a/app/config/roles.php +++ b/app/config/roles.php @@ -65,19 +65,19 @@ return [ ], ROLE_MEMBER => [ 'label' => 'Member', - 'scopes' => array_merge($logged, []), + 'scopes' => \array_merge($logged, []), ], ROLE_ADMIN => [ 'label' => 'Admin', - 'scopes' => array_merge($admins, []), + 'scopes' => \array_merge($admins, []), ], ROLE_DEVELOPER => [ 'label' => 'Developer', - 'scopes' => array_merge($admins, []), + 'scopes' => \array_merge($admins, []), ], ROLE_OWNER => [ 'label' => 'Owner', - 'scopes' => array_merge($logged, $admins, []), + 'scopes' => \array_merge($logged, $admins, []), ], ROLE_APP => [ 'label' => 'Application', diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 834fd009e..a7c1c2c53 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -42,8 +42,8 @@ $utopia->init(function() use (&$oauth2Keys) { continue; } - $oauth2Keys[] = 'oauth2'.ucfirst($key); - $oauth2Keys[] = 'oauth2'.ucfirst($key).'AccessToken'; + $oauth2Keys[] = 'oauth2'.\ucfirst($key); + $oauth2Keys[] = 'oauth2'.\ucfirst($key).'AccessToken'; } }); @@ -67,15 +67,15 @@ $utopia->post('/v1/account') $whitlistIPs = $project->getAttribute('authWhitelistIPs'); $whitlistDomains = $project->getAttribute('authWhitelistDomains'); - if (!empty($whitlistEmails) && !in_array($email, $whitlistEmails)) { + if (!empty($whitlistEmails) && !\in_array($email, $whitlistEmails)) { throw new Exception('Console registration is restricted to specific emails. Contact your administrator for more information.', 401); } - if (!empty($whitlistIPs) && !in_array($request->getIP(), $whitlistIPs)) { + if (!empty($whitlistIPs) && !\in_array($request->getIP(), $whitlistIPs)) { throw new Exception('Console registration is restricted to specific IPs. Contact your administrator for more information.', 401); } - if (!empty($whitlistDomains) && !in_array(substr(strrchr($email, '@'), 1), $whitlistDomains)) { + if (!empty($whitlistDomains) && !\in_array(\substr(\strrchr($email, '@'), 1), $whitlistDomains)) { throw new Exception('Console registration is restricted to specific domains. Contact your administrator for more information.', 401); } } @@ -106,8 +106,8 @@ $utopia->post('/v1/account') 'emailVerification' => false, 'status' => Auth::USER_STATUS_UNACTIVATED, 'password' => Auth::passwordHash($password), - 'password-update' => time(), - 'registration' => time(), + 'password-update' => \time(), + 'registration' => \time(), 'reset' => false, 'name' => $name, ], ['email' => $email]); @@ -136,7 +136,7 @@ $utopia->post('/v1/account') $response ->setStatusCode(Response::STATUS_CODE_CREATED) - ->json(array_merge($user->getArrayCopy(array_merge( + ->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'email', @@ -182,7 +182,7 @@ $utopia->post('/v1/account/sessions') throw new Exception('Invalid credentials', 401); // Wrong password or username } - $expiry = time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; + $expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; $secret = Auth::tokenGenerator(); $session = new Document([ '$collection' => Database::SYSTEM_COLLECTION_TOKENS, @@ -225,7 +225,7 @@ $utopia->post('/v1/account/sessions') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([Auth::$cookieName => Auth::encodeSession($profile->getId(), $secret)])) + ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($profile->getId(), $secret)])) ; } @@ -251,7 +251,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider') ->label('sdk.methodType', 'webAuth') ->label('abuse-limit', 50) ->label('abuse-key', 'ip:{ip}') - ->param('provider', '', function () { return new WhiteList(array_keys(Config::getParam('providers'))); }, 'OAuth2 Provider. Currently, supported providers are: ' . implode(', ', array_keys(array_filter(Config::getParam('providers'), function($node) {return (!$node['mock']);}))).'.') + ->param('provider', '', function () { return new WhiteList(\array_keys(Config::getParam('providers'))); }, 'OAuth2 Provider. Currently, supported providers are: ' . \implode(', ', \array_keys(\array_filter(Config::getParam('providers'), function($node) {return (!$node['mock']);}))).'.') ->param('success', $oauthDefaultSuccess, function () use ($clients) { return new Host($clients); }, 'URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true) ->param('failure', $oauthDefaultFailure, function () use ($clients) { return new Host($clients); }, 'URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true) ->param('scopes', [], function () { return new ArrayList(new Text(128)); }, 'A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes.', true) @@ -259,23 +259,23 @@ $utopia->get('/v1/account/sessions/oauth2/:provider') function ($provider, $success, $failure, $scopes) use ($response, $request, $project) { $protocol = Config::getParam('protocol'); $callback = $protocol.'://'.$request->getServer('HTTP_HOST').'/v1/account/sessions/oauth2/callback/'.$provider.'/'.$project->getId(); - $appId = $project->getAttribute('usersOauth2'.ucfirst($provider).'Appid', ''); - $appSecret = $project->getAttribute('usersOauth2'.ucfirst($provider).'Secret', '{}'); + $appId = $project->getAttribute('usersOauth2'.\ucfirst($provider).'Appid', ''); + $appSecret = $project->getAttribute('usersOauth2'.\ucfirst($provider).'Secret', '{}'); - $appSecret = json_decode($appSecret, true); + $appSecret = \json_decode($appSecret, true); if (!empty($appSecret) && isset($appSecret['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$appSecret['version']); - $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, hex2bin($appSecret['iv']), hex2bin($appSecret['tag'])); + $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag'])); } if (empty($appId) || empty($appSecret)) { throw new Exception('This provider is disabled. Please configure the provider app ID and app secret key from your '.APP_NAME.' console to continue.', 412); } - $classname = 'Appwrite\\Auth\\OAuth2\\'.ucfirst($provider); + $classname = 'Appwrite\\Auth\\OAuth2\\'.\ucfirst($provider); - if (!class_exists($classname)) { + if (!\class_exists($classname)) { throw new Exception('Provider is not supported', 501); } @@ -294,7 +294,7 @@ $utopia->get('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->label('scope', 'public') ->label('docs', false) ->param('projectId', '', function () { return new Text(1024); }, 'Project unique ID.') - ->param('provider', '', function () { return new WhiteList(array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') + ->param('provider', '', function () { return new WhiteList(\array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') ->param('code', '', function () { return new Text(1024); }, 'OAuth2 code.') ->param('state', '', function () { return new Text(2048); }, 'Login state params.', true) ->action( @@ -306,7 +306,7 @@ $utopia->get('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') ->redirect($protocol.'://'.$domain.'/v1/account/sessions/oauth2/'.$provider.'/redirect?' - .http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); + .\http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); } ); @@ -317,7 +317,7 @@ $utopia->post('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->label('origin', '*') ->label('docs', false) ->param('projectId', '', function () { return new Text(1024); }, 'Project unique ID.') - ->param('provider', '', function () { return new WhiteList(array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') + ->param('provider', '', function () { return new WhiteList(\array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') ->param('code', '', function () { return new Text(1024); }, 'OAuth2 code.') ->param('state', '', function () { return new Text(2048); }, 'Login state params.', true) ->action( @@ -329,7 +329,7 @@ $utopia->post('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') ->redirect($protocol.'://'.$domain.'/v1/account/sessions/oauth2/'.$provider.'/redirect?' - .http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); + .\http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); } ); @@ -341,7 +341,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') ->label('abuse-limit', 50) ->label('abuse-key', 'ip:{ip}') ->label('docs', false) - ->param('provider', '', function () { return new WhiteList(array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') + ->param('provider', '', function () { return new WhiteList(\array_keys(Config::getParam('providers'))); }, 'OAuth2 provider.') ->param('code', '', function () { return new Text(1024); }, 'OAuth2 code.') ->param('state', '', function () { return new Text(2048); }, 'OAuth2 state params.', true) ->action( @@ -351,19 +351,19 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') $defaultState = ['success' => $project->getAttribute('url', ''), 'failure' => '']; $validateURL = new URL(); - $appId = $project->getAttribute('usersOauth2'.ucfirst($provider).'Appid', ''); - $appSecret = $project->getAttribute('usersOauth2'.ucfirst($provider).'Secret', '{}'); + $appId = $project->getAttribute('usersOauth2'.\ucfirst($provider).'Appid', ''); + $appSecret = $project->getAttribute('usersOauth2'.\ucfirst($provider).'Secret', '{}'); - $appSecret = json_decode($appSecret, true); + $appSecret = \json_decode($appSecret, true); if (!empty($appSecret) && isset($appSecret['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$appSecret['version']); - $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, hex2bin($appSecret['iv']), hex2bin($appSecret['tag'])); + $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag'])); } - $classname = 'Appwrite\\Auth\\OAuth2\\'.ucfirst($provider); + $classname = 'Appwrite\\Auth\\OAuth2\\'.\ucfirst($provider); - if (!class_exists($classname)) { + if (!\class_exists($classname)) { throw new Exception('Provider is not supported', 501); } @@ -371,7 +371,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') if (!empty($state)) { try { - $state = array_merge($defaultState, $oauth2->parseState($state)); + $state = \array_merge($defaultState, $oauth2->parseState($state)); } catch (\Exception $exception) { throw new Exception('Failed to parse login state params as passed from OAuth2 provider'); } @@ -419,7 +419,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') 'first' => true, 'filters' => [ '$collection='.Database::SYSTEM_COLLECTION_USERS, - 'oauth2'.ucfirst($provider).'='.$oauth2ID, + 'oauth2'.\ucfirst($provider).'='.$oauth2ID, ], ]) : $user; @@ -447,8 +447,8 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') 'emailVerification' => true, 'status' => Auth::USER_STATUS_ACTIVATED, // Email should already be authenticated by OAuth2 provider 'password' => Auth::passwordHash(Auth::passwordGenerator()), - 'password-update' => time(), - 'registration' => time(), + 'password-update' => \time(), + 'registration' => \time(), 'reset' => false, 'name' => $name, ], ['email' => $email]); @@ -467,7 +467,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') // Create session token, verify user account and update OAuth2 ID and Access Token $secret = Auth::tokenGenerator(); - $expiry = time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; + $expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; $session = new Document([ '$collection' => Database::SYSTEM_COLLECTION_TOKENS, '$permissions' => ['read' => ['user:'.$user['$id']], 'write' => ['user:'.$user['$id']]], @@ -479,8 +479,8 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') ]); $user - ->setAttribute('oauth2'.ucfirst($provider), $oauth2ID) - ->setAttribute('oauth2'.ucfirst($provider).'AccessToken', $accessToken) + ->setAttribute('oauth2'.\ucfirst($provider), $oauth2ID) + ->setAttribute('oauth2'.\ucfirst($provider).'AccessToken', $accessToken) ->setAttribute('status', Auth::USER_STATUS_ACTIVATED) ->setAttribute('tokens', $session, Document::SET_TYPE_APPEND) ; @@ -502,7 +502,7 @@ $utopia->get('/v1/account/sessions/oauth2/:provider/redirect') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])) + ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])) ; } @@ -537,7 +537,7 @@ $utopia->get('/v1/account') ->label('sdk.response', ['200' => 'user']) ->action( function () use ($response, &$user, $oauth2Keys) { - $response->json(array_merge($user->getArrayCopy(array_merge( + $response->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'email', @@ -562,7 +562,7 @@ $utopia->get('/v1/account/prefs') $prefs = $user->getAttribute('prefs', '{}'); try { - $prefs = json_decode($prefs, true); + $prefs = \json_decode($prefs, true); $prefs = ($prefs) ? $prefs : []; } catch (\Exception $error) { throw new Exception('Failed to parse prefs', 500); @@ -616,7 +616,7 @@ $utopia->get('/v1/account/sessions') try { $record = $reader->country($token->getAttribute('ip', '')); - $sessions[$index]['geo']['isoCode'] = strtolower($record->country->isoCode); + $sessions[$index]['geo']['isoCode'] = \strtolower($record->country->isoCode); $sessions[$index]['geo']['country'] = (isset($countries[$record->country->isoCode])) ? $countries[$record->country->isoCode] : Locale::getText('locale.country.unknown'); } catch (\Exception $e) { $sessions[$index]['geo']['isoCode'] = '--'; @@ -678,7 +678,7 @@ $utopia->get('/v1/account/logs') $output[$i] = [ 'event' => $log['event'], 'ip' => $log['ip'], - 'time' => strtotime($log['time']), + 'time' => \strtotime($log['time']), 'OS' => $dd->getOs(), 'client' => $dd->getClient(), 'device' => $dd->getDevice(), @@ -689,7 +689,7 @@ $utopia->get('/v1/account/logs') try { $record = $reader->country($log['ip']); - $output[$i]['geo']['isoCode'] = strtolower($record->country->isoCode); + $output[$i]['geo']['isoCode'] = \strtolower($record->country->isoCode); $output[$i]['geo']['country'] = $record->country->name; $output[$i]['geo']['country'] = (isset($countries[$record->country->isoCode])) ? $countries[$record->country->isoCode] : Locale::getText('locale.country.unknown'); } catch (\Exception $e) { @@ -713,7 +713,7 @@ $utopia->patch('/v1/account/name') ->param('name', '', function () { return new Text(100); }, 'User name.') ->action( function ($name) use ($response, $user, $projectDB, $audit, $oauth2Keys) { - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ 'name' => $name, ])); @@ -727,7 +727,7 @@ $utopia->patch('/v1/account/name') ->setParam('resource', 'users/'.$user->getId()) ; - $response->json(array_merge($user->getArrayCopy(array_merge( + $response->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'email', @@ -755,7 +755,7 @@ $utopia->patch('/v1/account/password') throw new Exception('Invalid credentials', 401); } - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ 'password' => Auth::passwordHash($password), ])); @@ -769,7 +769,7 @@ $utopia->patch('/v1/account/password') ->setParam('resource', 'users/'.$user->getId()) ; - $response->json(array_merge($user->getArrayCopy(array_merge( + $response->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'email', @@ -812,7 +812,7 @@ $utopia->patch('/v1/account/email') // TODO after this user needs to confirm mail again - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ 'email' => $email, 'emailVerification' => false, ])); @@ -827,7 +827,7 @@ $utopia->patch('/v1/account/email') ->setParam('resource', 'users/'.$user->getId()) ; - $response->json(array_merge($user->getArrayCopy(array_merge( + $response->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'email', @@ -850,11 +850,11 @@ $utopia->patch('/v1/account/prefs') ->label('sdk.description', '/docs/references/account/update-prefs.md') ->action( function ($prefs) use ($response, $user, $projectDB, $audit) { - $old = json_decode($user->getAttribute('prefs', '{}'), true); + $old = \json_decode($user->getAttribute('prefs', '{}'), true); $old = ($old) ? $old : []; - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ - 'prefs' => json_encode(array_merge($old, $prefs)), + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ + 'prefs' => \json_encode(\array_merge($old, $prefs)), ])); if (false === $user) { @@ -869,7 +869,7 @@ $utopia->patch('/v1/account/prefs') $prefs = $user->getAttribute('prefs', '{}'); try { - $prefs = json_decode($prefs, true); + $prefs = \json_decode($prefs, true); $prefs = ($prefs) ? $prefs : []; } catch (\Exception $error) { throw new Exception('Failed to parse prefs', 500); @@ -890,7 +890,7 @@ $utopia->delete('/v1/account') ->action( function () use ($response, $user, $projectDB, $audit, $webhook) { $protocol = Config::getParam('protocol'); - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ 'status' => Auth::USER_STATUS_BLOCKED, ])); @@ -922,13 +922,13 @@ $utopia->delete('/v1/account') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([])) + ->addHeader('X-Fallback-Cookies', \json_encode([])) ; } $response - ->addCookie(Auth::$cookieName.'_legacy', '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) - ->addCookie(Auth::$cookieName, '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) + ->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) ->noContent() ; } @@ -974,14 +974,14 @@ $utopia->delete('/v1/account/sessions/:sessionId') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([])) + ->addHeader('X-Fallback-Cookies', \json_encode([])) ; } if ($token->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too $response - ->addCookie(Auth::$cookieName.'_legacy', '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) - ->addCookie(Auth::$cookieName, '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) + ->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) ; } @@ -1027,14 +1027,14 @@ $utopia->delete('/v1/account/sessions') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([])) + ->addHeader('X-Fallback-Cookies', \json_encode([])) ; } if ($token->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too $response - ->addCookie(Auth::$cookieName.'_legacy', '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) - ->addCookie(Auth::$cookieName, '', time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) + ->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) ; } } @@ -1075,7 +1075,7 @@ $utopia->post('/v1/account/recovery') '$permissions' => ['read' => ['user:'.$profile->getId()], 'write' => ['user:'.$profile->getId()]], 'type' => Auth::TOKEN_TYPE_RECOVERY, 'secret' => Auth::hash($secret), // On way hash encryption to protect DB leak - 'expire' => time() + Auth::TOKEN_EXPIRATION_RECOVERY, + 'expire' => \time() + Auth::TOKEN_EXPIRATION_RECOVERY, 'userAgent' => $request->getServer('HTTP_USER_AGENT', 'UNKNOWN'), 'ip' => $request->getIP(), ]); @@ -1182,9 +1182,9 @@ $utopia->put('/v1/account/recovery') Authorization::setRole('user:'.$profile->getId()); - $profile = $projectDB->updateDocument(array_merge($profile->getArrayCopy(), [ + $profile = $projectDB->updateDocument(\array_merge($profile->getArrayCopy(), [ 'password' => Auth::passwordHash($password), - 'password-update' => time(), + 'password-update' => \time(), 'emailVerification' => true, ])); @@ -1231,7 +1231,7 @@ $utopia->post('/v1/account/verification') '$permissions' => ['read' => ['user:'.$user->getId()], 'write' => ['user:'.$user->getId()]], 'type' => Auth::TOKEN_TYPE_VERIFICATION, 'secret' => Auth::hash($verificationSecret), // On way hash encryption to protect DB leak - 'expire' => time() + Auth::TOKEN_EXPIRATION_CONFIRM, + 'expire' => \time() + Auth::TOKEN_EXPIRATION_CONFIRM, 'userAgent' => $request->getServer('HTTP_USER_AGENT', 'UNKNOWN'), 'ip' => $request->getIP(), ]); @@ -1332,7 +1332,7 @@ $utopia->put('/v1/account/verification') Authorization::setRole('user:'.$profile->getId()); - $profile = $projectDB->updateDocument(array_merge($profile->getArrayCopy(), [ + $profile = $projectDB->updateDocument(\array_merge($profile->getArrayCopy(), [ 'emailVerification' => true, ])); diff --git a/app/controllers/api/avatars.php b/app/controllers/api/avatars.php index b1c8d352b..4bff678c5 100644 --- a/app/controllers/api/avatars.php +++ b/app/controllers/api/avatars.php @@ -27,28 +27,28 @@ $types = [ ]; $avatarCallback = function ($type, $code, $width, $height, $quality) use ($types, $response, $request) { - $code = strtolower($code); - $type = strtolower($type); + $code = \strtolower($code); + $type = \strtolower($type); - if (!array_key_exists($type, $types)) { + if (!\array_key_exists($type, $types)) { throw new Exception('Avatar set not found', 404); } - if (!array_key_exists($code, $types[$type])) { + if (!\array_key_exists($code, $types[$type])) { throw new Exception('Avatar not found', 404); } - if (!extension_loaded('imagick')) { + if (!\extension_loaded('imagick')) { throw new Exception('Imagick extension is missing', 500); } $output = 'png'; - $date = date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache - $key = md5('/v1/avatars/:type/:code-'.$code.$width.$height.$quality.$output); + $date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache + $key = \md5('/v1/avatars/:type/:code-'.$code.$width.$height.$quality.$output); $path = $types[$type][$code]; $type = 'png'; - if (!is_readable($path)) { + if (!\is_readable($path)) { throw new Exception('File not readable in '.$path, 500); } @@ -66,7 +66,7 @@ $avatarCallback = function ($type, $code, $width, $height, $quality) use ($types ; } - $resize = new Resize(file_get_contents($path)); + $resize = new Resize(\file_get_contents($path)); $resize->crop((int) $width, (int) $height); @@ -92,7 +92,7 @@ $avatarCallback = function ($type, $code, $width, $height, $quality) use ($types $utopia->get('/v1/avatars/credit-cards/:code') ->desc('Get Credit Card Icon') - ->param('code', '', function () use ($types) { return new WhiteList(array_keys($types['credit-cards'])); }, 'Credit Card Code. Possible values: '.implode(', ', array_keys($types['credit-cards'])).'.') + ->param('code', '', function () use ($types) { return new WhiteList(\array_keys($types['credit-cards'])); }, 'Credit Card Code. Possible values: '.\implode(', ', \array_keys($types['credit-cards'])).'.') ->param('width', 100, function () { return new Range(0, 2000); }, 'Image width. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('height', 100, function () { return new Range(0, 2000); }, 'Image height. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('quality', 100, function () { return new Range(0, 100); }, 'Image quality. Pass an integer between 0 to 100. Defaults to 100.', true) @@ -107,7 +107,7 @@ $utopia->get('/v1/avatars/credit-cards/:code') $utopia->get('/v1/avatars/browsers/:code') ->desc('Get Browser Icon') - ->param('code', '', function () use ($types) { return new WhiteList(array_keys($types['browsers'])); }, 'Browser Code.') + ->param('code', '', function () use ($types) { return new WhiteList(\array_keys($types['browsers'])); }, 'Browser Code.') ->param('width', 100, function () { return new Range(0, 2000); }, 'Image width. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('height', 100, function () { return new Range(0, 2000); }, 'Image height. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('quality', 100, function () { return new Range(0, 100); }, 'Image quality. Pass an integer between 0 to 100. Defaults to 100.', true) @@ -122,7 +122,7 @@ $utopia->get('/v1/avatars/browsers/:code') $utopia->get('/v1/avatars/flags/:code') ->desc('Get Country Flag') - ->param('code', '', function () use ($types) { return new WhiteList(array_keys($types['flags'])); }, 'Country Code. ISO Alpha-2 country code format.') + ->param('code', '', function () use ($types) { return new WhiteList(\array_keys($types['flags'])); }, 'Country Code. ISO Alpha-2 country code format.') ->param('width', 100, function () { return new Range(0, 2000); }, 'Image width. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('height', 100, function () { return new Range(0, 2000); }, 'Image height. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('quality', 100, function () { return new Range(0, 100); }, 'Image quality. Pass an integer between 0 to 100. Defaults to 100.', true) @@ -150,8 +150,8 @@ $utopia->get('/v1/avatars/image') function ($url, $width, $height) use ($response) { $quality = 80; $output = 'png'; - $date = date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache - $key = md5('/v2/avatars/images-'.$url.'-'.$width.'/'.$height.'/'.$quality); + $date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache + $key = \md5('/v2/avatars/images-'.$url.'-'.$width.'/'.$height.'/'.$quality); $type = 'png'; $cache = new Cache(new Filesystem(APP_STORAGE_CACHE.'/app-0')); // Limit file number or size $data = $cache->load($key, 60 * 60 * 24 * 7 /* 1 week */); @@ -165,11 +165,11 @@ $utopia->get('/v1/avatars/image') ; } - if (!extension_loaded('imagick')) { + if (!\extension_loaded('imagick')) { throw new Exception('Imagick extension is missing', 500); } - $fetch = @file_get_contents($url, false); + $fetch = @\file_get_contents($url, false); if (!$fetch) { throw new Exception('Image not found', 404); @@ -219,8 +219,8 @@ $utopia->get('/v1/avatars/favicon') $height = 56; $quality = 80; $output = 'png'; - $date = date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache - $key = md5('/v2/avatars/favicon-'.$url); + $date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache + $key = \md5('/v2/avatars/favicon-'.$url); $type = 'png'; $cache = new Cache(new Filesystem(APP_STORAGE_CACHE.'/app-0')); // Limit file number or size $data = $cache->load($key, 60 * 60 * 24 * 30 * 3 /* 3 months */); @@ -234,26 +234,26 @@ $utopia->get('/v1/avatars/favicon') ; } - if (!extension_loaded('imagick')) { + if (!\extension_loaded('imagick')) { throw new Exception('Imagick extension is missing', 500); } - $curl = curl_init(); + $curl = \curl_init(); - curl_setopt_array($curl, [ + \curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_URL => $url, - CURLOPT_USERAGENT => sprintf(APP_USERAGENT, + CURLOPT_USERAGENT => \sprintf(APP_USERAGENT, Config::getParam('version'), $request->getServer('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY) ), ]); - $html = curl_exec($curl); + $html = \curl_exec($curl); - curl_close($curl); + \curl_close($curl); if (!$html) { throw new Exception('Failed to fetch remote URL', 404); @@ -272,20 +272,20 @@ $utopia->get('/v1/avatars/favicon') $href = $link->getAttribute('href'); $rel = $link->getAttribute('rel'); $sizes = $link->getAttribute('sizes'); - $absolute = URLParse::unparse(array_merge(parse_url($url), parse_url($href))); + $absolute = URLParse::unparse(\array_merge(\parse_url($url), \parse_url($href))); - switch (strtolower($rel)) { + switch (\strtolower($rel)) { case 'icon': case 'shortcut icon': //case 'apple-touch-icon': - $ext = pathinfo(parse_url($absolute, PHP_URL_PATH), PATHINFO_EXTENSION); + $ext = \pathinfo(\parse_url($absolute, PHP_URL_PATH), PATHINFO_EXTENSION); switch ($ext) { case 'ico': case 'png': case 'jpg': case 'jpeg': - $size = explode('x', strtolower($sizes)); + $size = \explode('x', \strtolower($sizes)); $sizeWidth = (isset($size[0])) ? (int) $size[0] : 0; $sizeHeight = (isset($size[1])) ? (int) $size[1] : 0; @@ -304,16 +304,16 @@ $utopia->get('/v1/avatars/favicon') } if (empty($outputHref) || empty($outputExt)) { - $default = parse_url($url); + $default = \parse_url($url); $outputHref = $default['scheme'].'://'.$default['host'].'/favicon.ico'; $outputExt = 'ico'; } if ('ico' == $outputExt) { // Skip crop, Imagick isn\'t supporting icon files - $data = @file_get_contents($outputHref, false); + $data = @\file_get_contents($outputHref, false); - if (empty($data) || (mb_substr($data, 0, 5) === 'get('/v1/avatars/favicon') ; } - $fetch = @file_get_contents($outputHref, false); + $fetch = @\file_get_contents($outputHref, false); if (!$fetch) { throw new Exception('Icon not found', 404); @@ -384,7 +384,7 @@ $utopia->get('/v1/avatars/qr') } $response - ->addHeader('Expires', date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->setContentType('image/png') ->send($writer->writeString($text)) ; @@ -419,30 +419,30 @@ $utopia->get('/v1/avatars/initials') ['color' => '#610008', 'background' => '#f6d2d5'] // RED ]; - $rand = rand(0, count($themes)-1); + $rand = \rand(0, \count($themes)-1); $name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); - $words = explode(' ', strtoupper($name)); + $words = \explode(' ', \strtoupper($name)); $initials = null; $code = 0; foreach ($words as $key => $w) { $initials .= (isset($w[0])) ? $w[0] : ''; - $code += (isset($w[0])) ? ord($w[0]) : 0; + $code += (isset($w[0])) ? \ord($w[0]) : 0; if($key == 1) { break; } } - $length = count($words); - $rand = substr($code,-1); + $length = \count($words); + $rand = \substr($code,-1); $background = (!empty($background)) ? '#'.$background : $themes[$rand]['background']; $color = (!empty($color)) ? '#'.$color : $themes[$rand]['color']; $image = new \Imagick(); $draw = new \ImagickDraw(); - $fontSize = min($width, $height) / 2; + $fontSize = \min($width, $height) / 2; $draw->setFont(__DIR__."/../../../public/fonts/poppins-v9-latin-500.ttf"); $image->setFont(__DIR__."/../../../public/fonts/poppins-v9-latin-500.ttf"); @@ -460,7 +460,7 @@ $utopia->get('/v1/avatars/initials') //$image->setImageCompressionQuality(9 - round(($quality / 100) * 9)); $response - ->addHeader('Expires', date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->setContentType('image/png') ->send($image->getImageBlob()) ; diff --git a/app/controllers/api/database.php b/app/controllers/api/database.php index f4cddb1cc..d8ecedab8 100644 --- a/app/controllers/api/database.php +++ b/app/controllers/api/database.php @@ -46,7 +46,7 @@ $utopia->post('/v1/database/collections') $parsedRules = []; foreach ($rules as &$rule) { - $parsedRules[] = array_merge([ + $parsedRules[] = \array_merge([ '$collection' => Database::SYSTEM_COLLECTION_RULES, '$permissions' => [ 'read' => $read, @@ -59,8 +59,8 @@ $utopia->post('/v1/database/collections') $data = $projectDB->createDocument([ '$collection' => Database::SYSTEM_COLLECTION_COLLECTIONS, 'name' => $name, - 'dateCreated' => time(), - 'dateUpdated' => time(), + 'dateCreated' => \time(), + 'dateUpdated' => \time(), 'structure' => true, '$permissions' => [ 'read' => $read, @@ -258,7 +258,7 @@ $utopia->put('/v1/database/collections/:collectionId') $parsedRules = []; foreach ($rules as &$rule) { - $parsedRules[] = array_merge([ + $parsedRules[] = \array_merge([ '$collection' => Database::SYSTEM_COLLECTION_RULES, '$permissions' => [ 'read' => $read, @@ -268,10 +268,10 @@ $utopia->put('/v1/database/collections/:collectionId') } try { - $collection = $projectDB->updateDocument(array_merge($collection->getArrayCopy(), [ + $collection = $projectDB->updateDocument(\array_merge($collection->getArrayCopy(), [ 'name' => $name, 'structure' => true, - 'dateUpdated' => time(), + 'dateUpdated' => \time(), '$permissions' => [ 'read' => $read, 'write' => $write, @@ -360,7 +360,7 @@ $utopia->post('/v1/database/collections/:collectionId/documents') ->param('parentPropertyType', Document::SET_TYPE_ASSIGN, function () { return new WhiteList([Document::SET_TYPE_ASSIGN, Document::SET_TYPE_APPEND, Document::SET_TYPE_PREPEND]); }, 'Parent document property connection type. You can set this value to **assign**, **append** or **prepend**, default value is assign. Use when you want your new document to be a child of a parent document.', true) ->action( function ($collectionId, $data, $read, $write, $parentDocument, $parentProperty, $parentPropertyType) use ($response, $projectDB, $webhook, $audit) { - $data = (is_string($data)) ? json_decode($data, true) : $data; // Cast to JSON array + $data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array if (empty($data)) { throw new Exception('Missing payload', 400); @@ -372,7 +372,7 @@ $utopia->post('/v1/database/collections/:collectionId/documents') $collection = $projectDB->getDocument($collectionId/*, $isDev*/); - if (is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { + if (\is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { throw new Exception('Collection not found', 404); } @@ -483,7 +483,7 @@ $utopia->get('/v1/database/collections/:collectionId/documents') function ($collectionId, $filters, $offset, $limit, $orderField, $orderType, $orderCast, $search, $first, $last) use ($response, $projectDB, $isDev) { $collection = $projectDB->getDocument($collectionId, $isDev); - if (is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { + if (\is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { throw new Exception('Collection not found', 404); } @@ -496,7 +496,7 @@ $utopia->get('/v1/database/collections/:collectionId/documents') 'search' => $search, 'first' => (bool) $first, 'last' => (bool) $last, - 'filters' => array_merge($filters, [ + 'filters' => \array_merge($filters, [ '$collection='.$collectionId, ]), ]); @@ -549,20 +549,20 @@ $utopia->get('/v1/database/collections/:collectionId/documents/:documentId') $output = $document->getArrayCopy(); - $paths = explode('/', $request->getParam('q', '')); - $paths = array_slice($paths, 7, count($paths)); + $paths = \explode('/', $request->getParam('q', '')); + $paths = \array_slice($paths, 7, \count($paths)); - if (count($paths) > 0) { - if (count($paths) % 2 == 1) { - $output = $document->getAttribute(implode('.', $paths)); + if (\count($paths) > 0) { + if (\count($paths) % 2 == 1) { + $output = $document->getAttribute(\implode('.', $paths)); } else { - $id = (int) array_pop($paths); - $output = $document->search('$id', $id, $document->getAttribute(implode('.', $paths))); + $id = (int) \array_pop($paths); + $output = $document->search('$id', $id, $document->getAttribute(\implode('.', $paths))); } $output = ($output instanceof Document) ? $output->getArrayCopy() : $output; - if (!is_array($output)) { + if (!\is_array($output)) { throw new Exception('No document found', 404); } } @@ -592,13 +592,13 @@ $utopia->patch('/v1/database/collections/:collectionId/documents/:documentId') $collection = $projectDB->getDocument($collectionId/*, $isDev*/); $document = $projectDB->getDocument($documentId, $isDev); - $data = (is_string($data)) ? json_decode($data, true) : $data; // Cast to JSON array + $data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array - if (!is_array($data)) { + if (!\is_array($data)) { throw new Exception('Data param should be a valid JSON', 400); } - if (is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { + if (\is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { throw new Exception('Collection not found', 404); } @@ -616,7 +616,7 @@ $utopia->patch('/v1/database/collections/:collectionId/documents/:documentId') $data['$permissions']['write'] = $read; } - $data = array_merge($document->getArrayCopy(), $data); + $data = \array_merge($document->getArrayCopy(), $data); $data['$collection'] = $collection->getId(); // Make sure user don't switch collectionID $data['$id'] = $document->getId(); // Make sure user don't switch document unique ID @@ -672,7 +672,7 @@ $utopia->delete('/v1/database/collections/:collectionId/documents/:documentId') throw new Exception('No document found', 404); } - if (is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { + if (\is_null($collection->getId()) || Database::SYSTEM_COLLECTION_COLLECTIONS != $collection->getCollection()) { throw new Exception('Collection not found', 404); } diff --git a/app/controllers/api/health.php b/app/controllers/api/health.php index 475f75b54..94c99bc82 100644 --- a/app/controllers/api/health.php +++ b/app/controllers/api/health.php @@ -75,34 +75,34 @@ $utopia->get('/v1/health/time') $gap = 60; // Allow [X] seconds gap /* Create a socket and connect to NTP server */ - $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); + $sock = \socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); - socket_connect($sock, $host, 123); + \socket_connect($sock, $host, 123); /* Send request */ - $msg = "\010".str_repeat("\0", 47); + $msg = "\010".\str_repeat("\0", 47); - socket_send($sock, $msg, strlen($msg), 0); + \socket_send($sock, $msg, \strlen($msg), 0); /* Receive response and close socket */ - socket_recv($sock, $recv, 48, MSG_WAITALL); - socket_close($sock); + \socket_recv($sock, $recv, 48, MSG_WAITALL); + \socket_close($sock); /* Interpret response */ - $data = unpack('N12', $recv); - $timestamp = sprintf('%u', $data[9]); + $data = \unpack('N12', $recv); + $timestamp = \sprintf('%u', $data[9]); /* NTP is number of seconds since 0000 UT on 1 January 1900 Unix time is seconds since 0000 UT on 1 January 1970 */ $timestamp -= 2208988800; - $diff = ($timestamp - time()); + $diff = ($timestamp - \time()); if ($diff > $gap || $diff < ($gap * -1)) { throw new Exception('Server time gaps detected'); } - $response->json(['remote' => $timestamp, 'local' => time(), 'diff' => $diff]); + $response->json(['remote' => $timestamp, 'local' => \time(), 'diff' => $diff]); } ); @@ -202,11 +202,11 @@ $utopia->get('/v1/health/storage/local') ] as $key => $volume) { $device = new Local($volume); - if (!is_readable($device->getRoot())) { + if (!\is_readable($device->getRoot())) { throw new Exception('Device '.$key.' dir is not readable'); } - if (!is_writable($device->getRoot())) { + if (!\is_writable($device->getRoot())) { throw new Exception('Device '.$key.' dir is not writable'); } } @@ -255,7 +255,7 @@ $utopia->get('/v1/health/stats') // Currently only used internally ->json([ 'server' => [ 'name' => 'nginx', - 'version' => shell_exec('nginx -v 2>&1'), + 'version' => \shell_exec('nginx -v 2>&1'), ], 'storage' => [ 'used' => Storage::human($device->getDirectorySize($device->getRoot().'/')), diff --git a/app/controllers/api/locale.php b/app/controllers/api/locale.php index a58d86113..30a1211e9 100644 --- a/app/controllers/api/locale.php +++ b/app/controllers/api/locale.php @@ -41,10 +41,10 @@ $utopia->get('/v1/locale') //$output['countryTimeZone'] = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $record->country->isoCode); $output['continent'] = (isset($continents[$record->continent->code])) ? $continents[$record->continent->code] : Locale::getText('locale.country.unknown'); $output['continentCode'] = $record->continent->code; - $output['eu'] = (in_array($record->country->isoCode, $eu)) ? true : false; + $output['eu'] = (\in_array($record->country->isoCode, $eu)) ? true : false; foreach ($currencies as $code => $element) { - if (isset($element['locations']) && isset($element['code']) && in_array($record->country->isoCode, $element['locations'])) { + if (isset($element['locations']) && isset($element['code']) && \in_array($record->country->isoCode, $element['locations'])) { $currency = $element['code']; } } @@ -61,7 +61,7 @@ $utopia->get('/v1/locale') $response ->addHeader('Cache-Control', 'public, max-age='.$time) - ->addHeader('Expires', date('D, d M Y H:i:s', time() + $time).' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time).' GMT') // 45 days cache ->json($output); } ); @@ -77,7 +77,7 @@ $utopia->get('/v1/locale/countries') function () use ($response) { $list = Locale::getText('countries'); /* @var $list array */ - asort($list); + \asort($list); $response->json($list); } @@ -97,12 +97,12 @@ $utopia->get('/v1/locale/countries/eu') $list = []; foreach ($eu as $code) { - if (array_key_exists($code, $countries)) { + if (\array_key_exists($code, $countries)) { $list[$code] = $countries[$code]; } } - asort($list); + \asort($list); $response->json($list); } @@ -122,12 +122,12 @@ $utopia->get('/v1/locale/countries/phones') $countries = Locale::getText('countries'); /* @var $countries array */ foreach ($list as $code => $name) { - if (array_key_exists($code, $countries)) { + if (\array_key_exists($code, $countries)) { $list[$code] = '+'.$list[$code]; } } - asort($list); + \asort($list); $response->json($list); } @@ -144,7 +144,7 @@ $utopia->get('/v1/locale/continents') function () use ($response) { $list = Locale::getText('continents'); /* @var $list array */ - asort($list); + \asort($list); $response->json($list); } diff --git a/app/controllers/api/projects.php b/app/controllers/api/projects.php index ee1929a21..4511c3480 100644 --- a/app/controllers/api/projects.php +++ b/app/controllers/api/projects.php @@ -107,11 +107,11 @@ $utopia->get('/v1/projects') foreach ($results as $project) { foreach (Config::getParam('providers') as $provider => $node) { - $secret = json_decode($project->getAttribute('usersOauth2'.ucfirst($provider).'Secret', '{}'), true); + $secret = \json_decode($project->getAttribute('usersOauth2'.\ucfirst($provider).'Secret', '{}'), true); if (!empty($secret) && isset($secret['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$secret['version']); - $project->setAttribute('usersOauth2'.ucfirst($provider).'Secret', OpenSSL::decrypt($secret['data'], $secret['method'], $key, 0, hex2bin($secret['iv']), hex2bin($secret['tag']))); + $project->setAttribute('usersOauth2'.\ucfirst($provider).'Secret', OpenSSL::decrypt($secret['data'], $secret['method'], $key, 0, \hex2bin($secret['iv']), \hex2bin($secret['tag']))); } } } @@ -135,11 +135,11 @@ $utopia->get('/v1/projects/:projectId') } foreach (Config::getParam('providers') as $provider => $node) { - $secret = json_decode($project->getAttribute('usersOauth2'.ucfirst($provider).'Secret', '{}'), true); + $secret = \json_decode($project->getAttribute('usersOauth2'.\ucfirst($provider).'Secret', '{}'), true); if (!empty($secret) && isset($secret['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$secret['version']); - $project->setAttribute('usersOauth2'.ucfirst($provider).'Secret', OpenSSL::decrypt($secret['data'], $secret['method'], $key, 0, hex2bin($secret['iv']), hex2bin($secret['tag']))); + $project->setAttribute('usersOauth2'.\ucfirst($provider).'Secret', OpenSSL::decrypt($secret['data'], $secret['method'], $key, 0, \hex2bin($secret['iv']), \hex2bin($secret['tag']))); } } @@ -164,23 +164,23 @@ $utopia->get('/v1/projects/:projectId/usage') $period = [ 'daily' => [ - 'start' => DateTime::createFromFormat('U', strtotime('today')), - 'end' => DateTime::createFromFormat('U', strtotime('tomorrow')), + 'start' => DateTime::createFromFormat('U', \strtotime('today')), + 'end' => DateTime::createFromFormat('U', \strtotime('tomorrow')), 'group' => '1m', ], 'monthly' => [ - 'start' => DateTime::createFromFormat('U', strtotime('midnight first day of this month')), - 'end' => DateTime::createFromFormat('U', strtotime('midnight last day of this month')), + 'start' => DateTime::createFromFormat('U', \strtotime('midnight first day of this month')), + 'end' => DateTime::createFromFormat('U', \strtotime('midnight last day of this month')), 'group' => '1d', ], 'last30' => [ - 'start' => DateTime::createFromFormat('U', strtotime('-30 days')), - 'end' => DateTime::createFromFormat('U', strtotime('tomorrow')), + 'start' => DateTime::createFromFormat('U', \strtotime('-30 days')), + 'end' => DateTime::createFromFormat('U', \strtotime('tomorrow')), 'group' => '1d', ], 'last90' => [ - 'start' => DateTime::createFromFormat('U', strtotime('-90 days')), - 'end' => DateTime::createFromFormat('U', strtotime('today')), + 'start' => DateTime::createFromFormat('U', \strtotime('-90 days')), + 'end' => DateTime::createFromFormat('U', \strtotime('today')), 'group' => '1d', ], // 'yearly' => [ @@ -207,7 +207,7 @@ $utopia->get('/v1/projects/:projectId/usage') foreach ($points as $point) { $requests[] = [ 'value' => (!empty($point['value'])) ? $point['value'] : 0, - 'date' => strtotime($point['time']), + 'date' => \strtotime($point['time']), ]; } @@ -218,7 +218,7 @@ $utopia->get('/v1/projects/:projectId/usage') foreach ($points as $point) { $network[] = [ 'value' => (!empty($point['value'])) ? $point['value'] : 0, - 'date' => strtotime($point['time']), + 'date' => \strtotime($point['time']), ]; } } @@ -262,18 +262,18 @@ $utopia->get('/v1/projects/:projectId/usage') } // Tasks - $tasksTotal = count($project->getAttribute('tasks', [])); + $tasksTotal = \count($project->getAttribute('tasks', [])); $response->json([ 'requests' => [ 'data' => $requests, - 'total' => array_sum(array_map(function ($item) { + 'total' => \array_sum(\array_map(function ($item) { return $item['value']; }, $requests)), ], 'network' => [ 'data' => $network, - 'total' => array_sum(array_map(function ($item) { + 'total' => \array_sum(\array_map(function ($item) { return $item['value']; }, $network)), ], @@ -283,7 +283,7 @@ $utopia->get('/v1/projects/:projectId/usage') ], 'documents' => [ 'data' => $documents, - 'total' => array_sum(array_map(function ($item) { + 'total' => \array_sum(\array_map(function ($item) { return $item['total']; }, $documents)), ], @@ -332,7 +332,7 @@ $utopia->patch('/v1/projects/:projectId') throw new Exception('Project not found', 404); } - $project = $consoleDB->updateDocument(array_merge($project->getArrayCopy(), [ + $project = $consoleDB->updateDocument(\array_merge($project->getArrayCopy(), [ 'name' => $name, 'description' => $description, 'logo' => $logo, @@ -359,7 +359,7 @@ $utopia->patch('/v1/projects/:projectId/oauth2') ->label('sdk.namespace', 'projects') ->label('sdk.method', 'updateOAuth2') ->param('projectId', '', function () { return new UID(); }, 'Project unique ID.') - ->param('provider', '', function () { return new WhiteList(array_keys(Config::getParam('providers'))); }, 'Provider Name', false) + ->param('provider', '', function () { return new WhiteList(\array_keys(Config::getParam('providers'))); }, 'Provider Name', false) ->param('appId', '', function () { return new Text(256); }, 'Provider app ID.', true) ->param('secret', '', function () { return new text(512); }, 'Provider secret key.', true) ->action( @@ -373,17 +373,17 @@ $utopia->patch('/v1/projects/:projectId/oauth2') $key = $request->getServer('_APP_OPENSSL_KEY_V1'); $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM)); $tag = null; - $secret = json_encode([ + $secret = \json_encode([ 'data' => OpenSSL::encrypt($secret, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag), 'method' => OpenSSL::CIPHER_AES_128_GCM, - 'iv' => bin2hex($iv), - 'tag' => bin2hex($tag), + 'iv' => \bin2hex($iv), + 'tag' => \bin2hex($tag), 'version' => '1', ]); - $project = $consoleDB->updateDocument(array_merge($project->getArrayCopy(), [ - 'usersOauth2'.ucfirst($provider).'Appid' => $appId, - 'usersOauth2'.ucfirst($provider).'Secret' => $secret, + $project = $consoleDB->updateDocument(\array_merge($project->getArrayCopy(), [ + 'usersOauth2'.\ucfirst($provider).'Appid' => $appId, + 'usersOauth2'.\ucfirst($provider).'Secret' => $secret, ])); if (false === $project) { @@ -462,11 +462,11 @@ $utopia->post('/v1/projects/:projectId/webhooks') $key = $request->getServer('_APP_OPENSSL_KEY_V1'); $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM)); $tag = null; - $httpPass = json_encode([ + $httpPass = \json_encode([ 'data' => OpenSSL::encrypt($httpPass, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag), 'method' => OpenSSL::CIPHER_AES_128_GCM, - 'iv' => bin2hex($iv), - 'tag' => bin2hex($tag), + 'iv' => \bin2hex($iv), + 'tag' => \bin2hex($tag), 'version' => '1', ]); @@ -520,7 +520,7 @@ $utopia->get('/v1/projects/:projectId/webhooks') $webhooks = $project->getAttribute('webhooks', []); foreach ($webhooks as $webhook) { /* @var $webhook Document */ - $httpPass = json_decode($webhook->getAttribute('httpPass', '{}'), true); + $httpPass = \json_decode($webhook->getAttribute('httpPass', '{}'), true); if (empty($httpPass) || !isset($httpPass['version'])) { continue; @@ -528,7 +528,7 @@ $utopia->get('/v1/projects/:projectId/webhooks') $key = $request->getServer('_APP_OPENSSL_KEY_V'.$httpPass['version']); - $webhook->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, hex2bin($httpPass['iv']), hex2bin($httpPass['tag']))); + $webhook->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, \hex2bin($httpPass['iv']), \hex2bin($httpPass['tag']))); } $response->json($webhooks); @@ -556,11 +556,11 @@ $utopia->get('/v1/projects/:projectId/webhooks/:webhookId') throw new Exception('Webhook not found', 404); } - $httpPass = json_decode($webhook->getAttribute('httpPass', '{}'), true); + $httpPass = \json_decode($webhook->getAttribute('httpPass', '{}'), true); if (!empty($httpPass) && isset($httpPass['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$httpPass['version']); - $webhook->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, hex2bin($httpPass['iv']), hex2bin($httpPass['tag']))); + $webhook->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, \hex2bin($httpPass['iv']), \hex2bin($httpPass['tag']))); } $response->json($webhook->getArrayCopy()); @@ -592,11 +592,11 @@ $utopia->put('/v1/projects/:projectId/webhooks/:webhookId') $key = $request->getServer('_APP_OPENSSL_KEY_V1'); $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM)); $tag = null; - $httpPass = json_encode([ + $httpPass = \json_encode([ 'data' => OpenSSL::encrypt($httpPass, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag), 'method' => OpenSSL::CIPHER_AES_128_GCM, - 'iv' => bin2hex($iv), - 'tag' => bin2hex($tag), + 'iv' => \bin2hex($iv), + 'tag' => \bin2hex($tag), 'version' => '1', ]); @@ -678,7 +678,7 @@ $utopia->post('/v1/projects/:projectId/keys') ], 'name' => $name, 'scopes' => $scopes, - 'secret' => bin2hex(random_bytes(128)), + 'secret' => \bin2hex(\random_bytes(128)), ]); if (false === $key) { @@ -839,11 +839,11 @@ $utopia->post('/v1/projects/:projectId/tasks') $key = $request->getServer('_APP_OPENSSL_KEY_V1'); $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM)); $tag = null; - $httpPass = json_encode([ + $httpPass = \json_encode([ 'data' => OpenSSL::encrypt($httpPass, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag), 'method' => OpenSSL::CIPHER_AES_128_GCM, - 'iv' => bin2hex($iv), - 'tag' => bin2hex($tag), + 'iv' => \bin2hex($iv), + 'tag' => \bin2hex($tag), 'version' => '1', ]); @@ -856,7 +856,7 @@ $utopia->post('/v1/projects/:projectId/tasks') 'name' => $name, 'status' => $status, 'schedule' => $schedule, - 'updated' => time(), + 'updated' => \time(), 'previous' => null, 'next' => $next, 'security' => (int) $security, @@ -909,7 +909,7 @@ $utopia->get('/v1/projects/:projectId/tasks') $tasks = $project->getAttribute('tasks', []); foreach ($tasks as $task) { /* @var $task Document */ - $httpPass = json_decode($task->getAttribute('httpPass', '{}'), true); + $httpPass = \json_decode($task->getAttribute('httpPass', '{}'), true); if (empty($httpPass) || !isset($httpPass['version'])) { continue; @@ -917,7 +917,7 @@ $utopia->get('/v1/projects/:projectId/tasks') $key = $request->getServer('_APP_OPENSSL_KEY_V'.$httpPass['version']); - $task->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, hex2bin($httpPass['iv']), hex2bin($httpPass['tag']))); + $task->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, \hex2bin($httpPass['iv']), \hex2bin($httpPass['tag']))); } $response->json($tasks); @@ -945,11 +945,11 @@ $utopia->get('/v1/projects/:projectId/tasks/:taskId') throw new Exception('Task not found', 404); } - $httpPass = json_decode($task->getAttribute('httpPass', '{}'), true); + $httpPass = \json_decode($task->getAttribute('httpPass', '{}'), true); if (!empty($httpPass) && isset($httpPass['version'])) { $key = $request->getServer('_APP_OPENSSL_KEY_V'.$httpPass['version']); - $task->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, hex2bin($httpPass['iv']), hex2bin($httpPass['tag']))); + $task->setAttribute('httpPass', OpenSSL::decrypt($httpPass['data'], $httpPass['method'], $key, 0, \hex2bin($httpPass['iv']), \hex2bin($httpPass['tag']))); } $response->json($task->getArrayCopy()); @@ -992,11 +992,11 @@ $utopia->put('/v1/projects/:projectId/tasks/:taskId') $key = $request->getServer('_APP_OPENSSL_KEY_V1'); $iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM)); $tag = null; - $httpPass = json_encode([ + $httpPass = \json_encode([ 'data' => OpenSSL::encrypt($httpPass, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag), 'method' => OpenSSL::CIPHER_AES_128_GCM, - 'iv' => bin2hex($iv), - 'tag' => bin2hex($tag), + 'iv' => \bin2hex($iv), + 'tag' => \bin2hex($tag), 'version' => '1', ]); @@ -1004,7 +1004,7 @@ $utopia->put('/v1/projects/:projectId/tasks/:taskId') ->setAttribute('name', $name) ->setAttribute('status', $status) ->setAttribute('schedule', $schedule) - ->setAttribute('updated', time()) + ->setAttribute('updated', \time()) ->setAttribute('next', $next) ->setAttribute('security', (int) $security) ->setAttribute('httpMethod', $httpMethod) @@ -1087,8 +1087,8 @@ $utopia->post('/v1/projects/:projectId/platforms') 'key' => $key, 'store' => $store, 'hostname' => $hostname, - 'dateCreated' => time(), - 'dateUpdated' => time(), + 'dateCreated' => \time(), + 'dateUpdated' => \time(), ]); if (false === $platform) { @@ -1182,7 +1182,7 @@ $utopia->put('/v1/projects/:projectId/platforms/:platformId') $platform ->setAttribute('name', $name) - ->setAttribute('dateUpdated', time()) + ->setAttribute('dateUpdated', \time()) ->setAttribute('key', $key) ->setAttribute('store', $store) ->setAttribute('hostname', $hostname) @@ -1262,7 +1262,7 @@ $utopia->post('/v1/projects/:projectId/domains') 'read' => ['team:'.$project->getAttribute('teamId', null)], 'write' => ['team:'.$project->getAttribute('teamId', null).'/owner', 'team:'.$project->getAttribute('teamId', null).'/developer'], ], - 'updated' => time(), + 'updated' => \time(), 'domain' => $domain->get(), 'tld' => $domain->getSuffix(), 'registerable' => $domain->getRegisterable(), diff --git a/app/controllers/api/storage.php b/app/controllers/api/storage.php index ebcb85f32..6ffcfbf98 100644 --- a/app/controllers/api/storage.php +++ b/app/controllers/api/storage.php @@ -165,9 +165,9 @@ $utopia->post('/v1/storage/files') } // Make sure we handle a single file and multiple files the same way - $file['name'] = (is_array($file['name']) && isset($file['name'][0])) ? $file['name'][0] : $file['name']; - $file['tmp_name'] = (is_array($file['tmp_name']) && isset($file['tmp_name'][0])) ? $file['tmp_name'][0] : $file['tmp_name']; - $file['size'] = (is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size']; + $file['name'] = (\is_array($file['name']) && isset($file['name'][0])) ? $file['name'][0] : $file['name']; + $file['tmp_name'] = (\is_array($file['tmp_name']) && isset($file['tmp_name'][0])) ? $file['tmp_name'][0] : $file['tmp_name']; + $file['size'] = (\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size']; // Check if file type is allowed (feature for project settings?) //if (!$fileType->isValid($file['tmp_name'])) { @@ -190,7 +190,7 @@ $utopia->post('/v1/storage/files') // Save to storage $size = $device->getFileSize($file['tmp_name']); - $path = $device->getPath(uniqid().'.'.pathinfo($file['name'], PATHINFO_EXTENSION)); + $path = $device->getPath(\uniqid().'.'.\pathinfo($file['name'], PATHINFO_EXTENSION)); if (!$device->upload($file['tmp_name'], $path)) { // TODO deprecate 'upload' and replace with 'move' throw new Exception('Failed moving file', 500); @@ -228,7 +228,7 @@ $utopia->post('/v1/storage/files') 'read' => $read, 'write' => $write, ], - 'dateCreated' => time(), + 'dateCreated' => \time(), 'folderId' => $folderId, 'name' => $file['name'], 'path' => $path, @@ -237,12 +237,12 @@ $utopia->post('/v1/storage/files') 'sizeOriginal' => $size, 'sizeActual' => $sizeActual, 'algorithm' => $compressor->getName(), - 'token' => bin2hex(random_bytes(64)), + 'token' => \bin2hex(\random_bytes(64)), 'comment' => '', 'fileOpenSSLVersion' => '1', 'fileOpenSSLCipher' => OpenSSL::CIPHER_AES_128_GCM, - 'fileOpenSSLTag' => bin2hex($tag), - 'fileOpenSSLIV' => bin2hex($iv), + 'fileOpenSSLTag' => \bin2hex($tag), + 'fileOpenSSLIV' => \bin2hex($iv), ]); if (false === $file) { @@ -294,7 +294,7 @@ $utopia->get('/v1/storage/files') ], ]); - $results = array_map(function ($value) { /* @var $value \Database\Document */ + $results = \array_map(function ($value) { /* @var $value \Database\Document */ return $value->getArrayCopy(['$id', '$permissions', 'name', 'dateCreated', 'signature', 'mimeType', 'sizeOriginal']); }, $results); @@ -336,14 +336,14 @@ $utopia->get('/v1/storage/files/:fileId/preview') ->param('height', 0, function () { return new Range(0, 4000); }, 'Resize preview image height, Pass an integer between 0 to 4000.', true) ->param('quality', 100, function () { return new Range(0, 100); }, 'Preview image quality. Pass an integer between 0 to 100. Defaults to 100.', true) ->param('background', '', function () { return new HexColor(); }, 'Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix.', true) - ->param('output', null, function () use ($outputs) { return new WhiteList(array_merge(array_keys($outputs), [null])); }, 'Output format type (jpeg, jpg, png, gif and webp).', true) + ->param('output', null, function () use ($outputs) { return new WhiteList(\array_merge(\array_keys($outputs), [null])); }, 'Output format type (jpeg, jpg, png, gif and webp).', true) //->param('storage', 'local', function () {return new WhiteList(array('local'));}, 'Selected storage device. defaults to local') //->param('token', '', function () {return new Text(128);}, 'Preview token', true) ->action( function ($fileId, $width, $height, $quality, $background, $output) use ($request, $response, $projectDB, $project, $inputs, $outputs, $fileLogos) { $storage = 'local'; - if (!extension_loaded('imagick')) { + if (!\extension_loaded('imagick')) { throw new Exception('Imagick extension is missing', 500); } @@ -351,12 +351,12 @@ $utopia->get('/v1/storage/files/:fileId/preview') throw new Exception('No such storage device', 400); } - if ((strpos($request->getServer('HTTP_ACCEPT'), 'image/webp') === false) && ('webp' == $output)) { // Fallback webp to jpeg when no browser support + if ((\strpos($request->getServer('HTTP_ACCEPT'), 'image/webp') === false) && ('webp' == $output)) { // Fallback webp to jpeg when no browser support $output = 'jpg'; } - $date = date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache - $key = md5($fileId.$width.$height.$quality.$background.$storage.$output); + $date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT'; // 45 days cache + $key = \md5($fileId.$width.$height.$quality.$background.$storage.$output); $file = $projectDB->getDocument($fileId); @@ -365,24 +365,24 @@ $utopia->get('/v1/storage/files/:fileId/preview') } $path = $file->getAttribute('path'); - $type = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + $type = \strtolower(\pathinfo($path, PATHINFO_EXTENSION)); $algorithm = $file->getAttribute('algorithm'); $cipher = $file->getAttribute('fileOpenSSLCipher'); $mime = $file->getAttribute('mimeType'); - if(!in_array($mime, $inputs)) { - $path = (array_key_exists($mime, $fileLogos)) ? $fileLogos[$mime] : $fileLogos['default']; + if(!\in_array($mime, $inputs)) { + $path = (\array_key_exists($mime, $fileLogos)) ? $fileLogos[$mime] : $fileLogos['default']; $algorithm = null; $cipher = null; $background = (empty($background)) ? 'eceff1' : $background; - $type = strtolower(pathinfo($path, PATHINFO_EXTENSION)); - $key = md5($path.$width.$height.$quality.$background.$storage.$output); + $type = \strtolower(\pathinfo($path, PATHINFO_EXTENSION)); + $key = \md5($path.$width.$height.$quality.$background.$storage.$output); } $compressor = new GZIP(); $device = Storage::getDevice('local'); - if (!file_exists($path)) { + if (!\file_exists($path)) { throw new Exception('File not found', 404); } @@ -393,7 +393,7 @@ $utopia->get('/v1/storage/files/:fileId/preview') $output = (empty($output)) ? $type : $output; $response - ->setContentType((in_array($output, $outputs)) ? $outputs[$output] : $outputs['jpg']) + ->setContentType((\in_array($output, $outputs)) ? $outputs[$output] : $outputs['jpg']) ->addHeader('Expires', $date) ->addHeader('X-Appwrite-Cache', 'hit') ->send($data) @@ -410,8 +410,8 @@ $utopia->get('/v1/storage/files/:fileId/preview') $file->getAttribute('fileOpenSSLCipher'), $request->getServer('_APP_OPENSSL_KEY_V'.$file->getAttribute('fileOpenSSLVersion')), 0, - hex2bin($file->getAttribute('fileOpenSSLIV')), - hex2bin($file->getAttribute('fileOpenSSLTag')) + \hex2bin($file->getAttribute('fileOpenSSLIV')), + \hex2bin($file->getAttribute('fileOpenSSLTag')) ); } @@ -466,7 +466,7 @@ $utopia->get('/v1/storage/files/:fileId/download') $path = $file->getAttribute('path', ''); - if (!file_exists($path)) { + if (!\file_exists($path)) { throw new Exception('File not found in '.$path, 404); } @@ -481,8 +481,8 @@ $utopia->get('/v1/storage/files/:fileId/download') $file->getAttribute('fileOpenSSLCipher'), $request->getServer('_APP_OPENSSL_KEY_V'.$file->getAttribute('fileOpenSSLVersion')), 0, - hex2bin($file->getAttribute('fileOpenSSLIV')), - hex2bin($file->getAttribute('fileOpenSSLTag')) + \hex2bin($file->getAttribute('fileOpenSSLIV')), + \hex2bin($file->getAttribute('fileOpenSSLTag')) ); } @@ -492,8 +492,8 @@ $utopia->get('/v1/storage/files/:fileId/download') $response ->setContentType($file->getAttribute('mimeType')) ->addHeader('Content-Disposition', 'attachment; filename="'.$file->getAttribute('name', '').'"') - ->addHeader('Expires', date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache - ->addHeader('X-Peak', memory_get_peak_usage()) + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache + ->addHeader('X-Peak', \memory_get_peak_usage()) ->send($source) ; } @@ -520,7 +520,7 @@ $utopia->get('/v1/storage/files/:fileId/view') $path = $file->getAttribute('path', ''); - if (!file_exists($path)) { + if (!\file_exists($path)) { throw new Exception('File not found in '.$path, 404); } @@ -529,7 +529,7 @@ $utopia->get('/v1/storage/files/:fileId/view') $contentType = 'text/plain'; - if (in_array($file->getAttribute('mimeType'), $mimes)) { + if (\in_array($file->getAttribute('mimeType'), $mimes)) { $contentType = $file->getAttribute('mimeType'); } @@ -541,8 +541,8 @@ $utopia->get('/v1/storage/files/:fileId/view') $file->getAttribute('fileOpenSSLCipher'), $request->getServer('_APP_OPENSSL_KEY_V'.$file->getAttribute('fileOpenSSLVersion')), 0, - hex2bin($file->getAttribute('fileOpenSSLIV')), - hex2bin($file->getAttribute('fileOpenSSLTag')) + \hex2bin($file->getAttribute('fileOpenSSLIV')), + \hex2bin($file->getAttribute('fileOpenSSLTag')) ); } @@ -554,7 +554,7 @@ $utopia->get('/v1/storage/files/:fileId/view') 'text' => 'text/plain', ]; - $contentType = (array_key_exists($as, $contentTypes)) ? $contentTypes[$as] : $contentType; + $contentType = (\array_key_exists($as, $contentTypes)) ? $contentTypes[$as] : $contentType; // Response $response @@ -562,8 +562,8 @@ $utopia->get('/v1/storage/files/:fileId/view') ->addHeader('Content-Security-Policy', 'script-src none;') ->addHeader('X-Content-Type-Options', 'nosniff') ->addHeader('Content-Disposition', 'inline; filename="'.$fileName.'"') - ->addHeader('Expires', date('D, d M Y H:i:s', time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache - ->addHeader('X-Peak', memory_get_peak_usage()) + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache + ->addHeader('X-Peak', \memory_get_peak_usage()) ->send($output) ; } @@ -589,7 +589,7 @@ $utopia->put('/v1/storage/files/:fileId') throw new Exception('File not found', 404); } - $file = $projectDB->updateDocument(array_merge($file->getArrayCopy(), [ + $file = $projectDB->updateDocument(\array_merge($file->getArrayCopy(), [ '$permissions' => [ 'read' => $read, 'write' => $write, diff --git a/app/controllers/api/teams.php b/app/controllers/api/teams.php index 125f15903..b8e0bf119 100644 --- a/app/controllers/api/teams.php +++ b/app/controllers/api/teams.php @@ -43,7 +43,7 @@ $utopia->post('/v1/teams') ], 'name' => $name, 'sum' => ($mode !== APP_MODE_ADMIN && $user->getId()) ? 1 : 0, - 'dateCreated' => time(), + 'dateCreated' => \time(), ]); Authorization::reset(); @@ -62,8 +62,8 @@ $utopia->post('/v1/teams') 'userId' => $user->getId(), 'teamId' => $team->getId(), 'roles' => $roles, - 'invited' => time(), - 'joined' => time(), + 'invited' => \time(), + 'joined' => \time(), 'confirm' => true, 'secret' => '', ]); @@ -151,7 +151,7 @@ $utopia->put('/v1/teams/:teamId') throw new Exception('Team not found', 404); } - $team = $projectDB->updateDocument(array_merge($team->getArrayCopy(), [ + $team = $projectDB->updateDocument(\array_merge($team->getArrayCopy(), [ 'name' => $name, ])); @@ -256,8 +256,8 @@ $utopia->post('/v1/teams/:teamId/memberships') 'emailVerification' => false, 'status' => Auth::USER_STATUS_UNACTIVATED, 'password' => Auth::passwordHash(Auth::passwordGenerator()), - 'password-update' => time(), - 'registration' => time(), + 'password-update' => \time(), + 'registration' => \time(), 'reset' => false, 'name' => $name, 'tokens' => [], @@ -280,7 +280,7 @@ $utopia->post('/v1/teams/:teamId/memberships') throw new Exception('User has already been invited or is already a member of this team', 409); } - if ($member->getAttribute('userId') == $user->getId() && in_array('owner', $member->getAttribute('roles', []))) { + if ($member->getAttribute('userId') == $user->getId() && \in_array('owner', $member->getAttribute('roles', []))) { $isOwner = true; } } @@ -300,7 +300,7 @@ $utopia->post('/v1/teams/:teamId/memberships') 'userId' => $invitee->getId(), 'teamId' => $team->getId(), 'roles' => $roles, - 'invited' => time(), + 'invited' => \time(), 'joined' => 0, 'confirm' => (APP_MODE_ADMIN === $mode), 'secret' => Auth::hash($secret), @@ -349,7 +349,7 @@ $utopia->post('/v1/teams/:teamId/memberships') ->setParam('event', 'teams.membership.create') ->setParam('recipient', $email) ->setParam('name', $name) - ->setParam('subject', sprintf(Locale::getText('account.emails.invitation.title'), $team->getAttribute('name', '[TEAM-NAME]'), $project->getAttribute('name', ['[APP-NAME]']))) + ->setParam('subject', \sprintf(Locale::getText('account.emails.invitation.title'), $team->getAttribute('name', '[TEAM-NAME]'), $project->getAttribute('name', ['[APP-NAME]']))) ->setParam('body', $body->render()) ->trigger(); ; @@ -363,7 +363,7 @@ $utopia->post('/v1/teams/:teamId/memberships') $response ->setStatusCode(Response::STATUS_CODE_CREATED) // TODO change response of this endpoint - ->json(array_merge($membership->getArrayCopy([ + ->json(\array_merge($membership->getArrayCopy([ '$id', 'userId', 'teamId', @@ -421,7 +421,7 @@ $utopia->get('/v1/teams/:teamId/memberships') $temp = $projectDB->getDocument($membership->getAttribute('userId', null))->getArrayCopy(['email', 'name']); - $users[] = array_merge($temp, $membership->getArrayCopy([ + $users[] = \array_merge($temp, $membership->getArrayCopy([ '$id', 'userId', 'teamId', @@ -495,7 +495,7 @@ $utopia->patch('/v1/teams/:teamId/memberships/:inviteId/status') } $membership // Attach user to team - ->setAttribute('joined', time()) + ->setAttribute('joined', \time()) ->setAttribute('confirm', true) ; @@ -505,7 +505,7 @@ $utopia->patch('/v1/teams/:teamId/memberships/:inviteId/status') ; // Log user in - $expiry = time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; + $expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG; $secret = Auth::tokenGenerator(); $user->setAttribute('tokens', new Document([ @@ -528,7 +528,7 @@ $utopia->patch('/v1/teams/:teamId/memberships/:inviteId/status') Authorization::disable(); - $team = $projectDB->updateDocument(array_merge($team->getArrayCopy(), [ + $team = $projectDB->updateDocument(\array_merge($team->getArrayCopy(), [ 'sum' => $team->getAttribute('sum', 0) + 1, ])); @@ -546,14 +546,14 @@ $utopia->patch('/v1/teams/:teamId/memberships/:inviteId/status') if(!Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])) + ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])) ; } $response ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), $expiry, '/', COOKIE_DOMAIN, ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), $expiry, '/', COOKIE_DOMAIN, ('https' == $protocol), true, COOKIE_SAMESITE) - ->json(array_merge($membership->getArrayCopy([ + ->json(\array_merge($membership->getArrayCopy([ '$id', 'userId', 'teamId', @@ -601,7 +601,7 @@ $utopia->delete('/v1/teams/:teamId/memberships/:inviteId') } if ($membership->getAttribute('confirm')) { // Count only confirmed members - $team = $projectDB->updateDocument(array_merge($team->getArrayCopy(), [ + $team = $projectDB->updateDocument(\array_merge($team->getArrayCopy(), [ 'sum' => $team->getAttribute('sum', 0) - 1, ])); } diff --git a/app/controllers/api/users.php b/app/controllers/api/users.php index 12090ecc6..d032cef94 100644 --- a/app/controllers/api/users.php +++ b/app/controllers/api/users.php @@ -59,8 +59,8 @@ $utopia->post('/v1/users') 'emailVerification' => false, 'status' => Auth::USER_STATUS_UNACTIVATED, 'password' => Auth::passwordHash($password), - 'password-update' => time(), - 'registration' => time(), + 'password-update' => \time(), + 'registration' => \time(), 'reset' => false, 'name' => $name, ], ['email' => $email]); @@ -75,13 +75,13 @@ $utopia->post('/v1/users') continue; } - $oauth2Keys[] = 'oauth2'.ucfirst($key); - $oauth2Keys[] = 'oauth2'.ucfirst($key).'AccessToken'; + $oauth2Keys[] = 'oauth2'.\ucfirst($key); + $oauth2Keys[] = 'oauth2'.\ucfirst($key).'AccessToken'; } $response ->setStatusCode(Response::STATUS_CODE_CREATED) - ->json(array_merge($user->getArrayCopy(array_merge([ + ->json(\array_merge($user->getArrayCopy(\array_merge([ '$id', 'status', 'email', @@ -124,12 +124,12 @@ $utopia->get('/v1/users') continue; } - $oauth2Keys[] = 'oauth2'.ucfirst($key); - $oauth2Keys[] = 'oauth2'.ucfirst($key).'AccessToken'; + $oauth2Keys[] = 'oauth2'.\ucfirst($key); + $oauth2Keys[] = 'oauth2'.\ucfirst($key).'AccessToken'; } - $results = array_map(function ($value) use ($oauth2Keys) { /* @var $value \Database\Document */ - return $value->getArrayCopy(array_merge( + $results = \array_map(function ($value) use ($oauth2Keys) { /* @var $value \Database\Document */ + return $value->getArrayCopy(\array_merge( [ '$id', 'status', @@ -169,11 +169,11 @@ $utopia->get('/v1/users/:userId') continue; } - $oauth2Keys[] = 'oauth2'.ucfirst($key); - $oauth2Keys[] = 'oauth2'.ucfirst($key).'AccessToken'; + $oauth2Keys[] = 'oauth2'.\ucfirst($key); + $oauth2Keys[] = 'oauth2'.\ucfirst($key).'AccessToken'; } - $response->json(array_merge($user->getArrayCopy(array_merge( + $response->json(\array_merge($user->getArrayCopy(\array_merge( [ '$id', 'status', @@ -206,7 +206,7 @@ $utopia->get('/v1/users/:userId/prefs') $prefs = $user->getAttribute('prefs', ''); try { - $prefs = json_decode($prefs, true); + $prefs = \json_decode($prefs, true); $prefs = ($prefs) ? $prefs : []; } catch (\Exception $error) { throw new Exception('Failed to parse prefs', 500); @@ -265,7 +265,7 @@ $utopia->get('/v1/users/:userId/sessions') try { $record = $reader->country($token->getAttribute('ip', '')); - $sessions[$index]['geo']['isoCode'] = strtolower($record->country->isoCode); + $sessions[$index]['geo']['isoCode'] = \strtolower($record->country->isoCode); $sessions[$index]['geo']['country'] = (isset($countries[$record->country->isoCode])) ? $countries[$record->country->isoCode] : Locale::getText('locale.country.unknown'); } catch (\Exception $e) { $sessions[$index]['geo']['isoCode'] = '--'; @@ -335,7 +335,7 @@ $utopia->get('/v1/users/:userId/logs') $output[$i] = [ 'event' => $log['event'], 'ip' => $log['ip'], - 'time' => strtotime($log['time']), + 'time' => \strtotime($log['time']), 'OS' => $dd->getOs(), 'client' => $dd->getClient(), 'device' => $dd->getDevice(), @@ -346,7 +346,7 @@ $utopia->get('/v1/users/:userId/logs') try { $record = $reader->country($log['ip']); - $output[$i]['geo']['isoCode'] = strtolower($record->country->isoCode); + $output[$i]['geo']['isoCode'] = \strtolower($record->country->isoCode); $output[$i]['geo']['country'] = $record->country->name; $output[$i]['geo']['country'] = (isset($countries[$record->country->isoCode])) ? $countries[$record->country->isoCode] : Locale::getText('locale.country.unknown'); } catch (\Exception $e) { @@ -376,7 +376,7 @@ $utopia->patch('/v1/users/:userId/status') throw new Exception('User not found', 404); } - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ 'status' => (int)$status, ])); @@ -391,12 +391,12 @@ $utopia->patch('/v1/users/:userId/status') continue; } - $oauth2Keys[] = 'oauth2'.ucfirst($key); - $oauth2Keys[] = 'oauth2'.ucfirst($key).'AccessToken'; + $oauth2Keys[] = 'oauth2'.\ucfirst($key); + $oauth2Keys[] = 'oauth2'.\ucfirst($key).'AccessToken'; } $response - ->json(array_merge($user->getArrayCopy(array_merge([ + ->json(\array_merge($user->getArrayCopy(\array_merge([ '$id', 'status', 'email', @@ -424,11 +424,11 @@ $utopia->patch('/v1/users/:userId/prefs') throw new Exception('User not found', 404); } - $old = json_decode($user->getAttribute('prefs', '{}'), true); + $old = \json_decode($user->getAttribute('prefs', '{}'), true); $old = ($old) ? $old : []; - $user = $projectDB->updateDocument(array_merge($user->getArrayCopy(), [ - 'prefs' => json_encode(array_merge($old, $prefs)), + $user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [ + 'prefs' => \json_encode(\array_merge($old, $prefs)), ])); if (false === $user) { @@ -438,7 +438,7 @@ $utopia->patch('/v1/users/:userId/prefs') $prefs = $user->getAttribute('prefs', ''); try { - $prefs = json_decode($prefs, true); + $prefs = \json_decode($prefs, true); $prefs = ($prefs) ? $prefs : []; } catch (\Exception $error) { throw new Exception('Failed to parse prefs', 500); diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 1600fa857..67e0776a9 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -175,9 +175,9 @@ $utopia->post('/v1/mock/tests/general/upload') ->action( function ($x, $y, $z, $file) use ($request) { $file = $request->getFiles('file'); - $file['tmp_name'] = (is_array($file['tmp_name'])) ? $file['tmp_name'] : [$file['tmp_name']]; - $file['name'] = (is_array($file['name'])) ? $file['name'] : [$file['name']]; - $file['size'] = (is_array($file['size'])) ? $file['size'] : [$file['size']]; + $file['tmp_name'] = (\is_array($file['tmp_name'])) ? $file['tmp_name'] : [$file['tmp_name']]; + $file['name'] = (\is_array($file['name'])) ? $file['name'] : [$file['name']]; + $file['size'] = (\is_array($file['size'])) ? $file['size'] : [$file['size']]; foreach ($file['name'] as $i => $name) { if($name !== 'file.png') { @@ -192,7 +192,7 @@ $utopia->post('/v1/mock/tests/general/upload') } foreach ($file['tmp_name'] as $i => $tmpName) { - if(md5(file_get_contents($tmpName)) !== 'd80e7e6999a3eb2ae0d631a96fe135a4') { + if(\md5(\file_get_contents($tmpName)) !== 'd80e7e6999a3eb2ae0d631a96fe135a4') { throw new Exception('Wrong file uploaded', 400); } } @@ -230,7 +230,7 @@ $utopia->get('/v1/mock/tests/general/set-cookie') ->label('sdk.description', 'Mock a set cookie request for SDK tests') ->action( function () use ($response) { - $response->addCookie('cookieName', 'cookieValue', time() + 31536000, '/', 'localhost', true, true); + $response->addCookie('cookieName', 'cookieValue', \time() + 31536000, '/', 'localhost', true, true); } ); @@ -271,7 +271,7 @@ $utopia->get('/v1/mock/tests/general/oauth2') ->param('state', '', function () { return new Text(1024); }, 'OAuth2 state.') ->action( function ($clientId, $redirectURI, $scope, $state) use ($response) { - $response->redirect($redirectURI.'?'.http_build_query(['code' => 'abcdef', 'state' => $state])); + $response->redirect($redirectURI.'?'.\http_build_query(['code' => 'abcdef', 'state' => $state])); } ); @@ -348,17 +348,17 @@ $utopia->shutdown(function() use ($response, $request, &$result, $utopia) { $route = $utopia->match($request); $path = APP_STORAGE_CACHE.'/tests.json'; - $tests = (file_exists($path)) ? json_decode(file_get_contents($path), true) : []; + $tests = (\file_exists($path)) ? \json_decode(\file_get_contents($path), true) : []; - if(!is_array($tests)) { + if(!\is_array($tests)) { throw new Exception('Failed to read results', 500); } $result[$route->getMethod() . ':' . $route->getURL()] = true; - $tests = array_merge($tests, $result); + $tests = \array_merge($tests, $result); - if(!file_put_contents($path, json_encode($tests), LOCK_EX)) { + if(!\file_put_contents($path, \json_encode($tests), LOCK_EX)) { throw new Exception('Failed to save resutls', 500); } diff --git a/app/controllers/shared/api.php b/app/controllers/shared/api.php index 0f32809fb..97da51031 100644 --- a/app/controllers/shared/api.php +++ b/app/controllers/shared/api.php @@ -31,7 +31,7 @@ $utopia->init(function () use ($utopia, $request, $response, $register, $user, $ //TODO make sure we get array here foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys - $timeLimit->setParam('{param-'.$key.'}', (is_array($value)) ? json_encode($value) : $value); + $timeLimit->setParam('{param-'.$key.'}', (\is_array($value)) ? \json_encode($value) : $value); } $abuse = new Abuse($timeLimit); diff --git a/app/controllers/shared/web.php b/app/controllers/shared/web.php index 513914df9..fced2de4d 100644 --- a/app/controllers/shared/web.php +++ b/app/controllers/shared/web.php @@ -37,7 +37,7 @@ $utopia->init(function () use ($utopia, $response, $request, $layout) { $response ->addHeader('Cache-Control', 'public, max-age='.$time) - ->addHeader('Expires', date('D, d M Y H:i:s', time() + $time).' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time).' GMT') // 45 days cache ->addHeader('X-UA-Compatible', 'IE=Edge'); // Deny IE browsers from going into quirks mode $route = $utopia->match($request); diff --git a/app/controllers/web/home.php b/app/controllers/web/home.php index 093faf3eb..cfec346b9 100644 --- a/app/controllers/web/home.php +++ b/app/controllers/web/home.php @@ -168,18 +168,18 @@ $utopia->get('/open-api-2.json') function ($platform, $extensions, $tests) use ($response, $request, $utopia, $services) { function fromCamelCase($input) { - preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches); + \preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches); $ret = $matches[0]; foreach ($ret as &$match) { - $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); + $match = $match == \strtoupper($match) ? \strtolower($match) : \lcfirst($match); } - return implode('_', $ret); + return \implode('_', $ret); } function fromCamelCaseToDash($input) { - return str_replace([' ', '_'], '-', strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $input))); + return \str_replace([' ', '_'], '-', \strtolower(\preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $input))); } foreach ($services as $service) { /* @noinspection PhpIncludeInspection */ @@ -196,7 +196,7 @@ $utopia->get('/open-api-2.json') } /** @noinspection PhpIncludeInspection */ - include_once realpath(__DIR__.'/../../'.$service['controller']); + include_once \realpath(__DIR__.'/../../'.$service['controller']); } $security = [ @@ -295,7 +295,7 @@ $utopia->get('/open-api-2.json') 'url' => 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE', ], ], - 'host' => parse_url($request->getServer('_APP_HOME', Config::getParam('domain')), PHP_URL_HOST), + 'host' => \parse_url($request->getServer('_APP_HOME', Config::getParam('domain')), PHP_URL_HOST), 'basePath' => '/v1', 'schemes' => ['https'], 'consumes' => ['application/json', 'multipart/form-data'], @@ -374,11 +374,11 @@ $utopia->get('/open-api-2.json') continue; } - if($platform !== APP_PLATFORM_CONSOLE && !in_array($platforms[$platform], $route->getLabel('sdk.platform', []))) { + if($platform !== APP_PLATFORM_CONSOLE && !\in_array($platforms[$platform], $route->getLabel('sdk.platform', []))) { continue; } - $url = str_replace('/v1', '', $route->getURL()); + $url = \str_replace('/v1', '', $route->getURL()); $scope = $route->getLabel('scope', ''); $hide = $route->getLabel('sdk.hide', false); $consumes = ['application/json']; @@ -387,14 +387,14 @@ $utopia->get('/open-api-2.json') continue; } - $desc = (!empty($route->getLabel('sdk.description', ''))) ? realpath('../'.$route->getLabel('sdk.description', '')) : null; + $desc = (!empty($route->getLabel('sdk.description', ''))) ? \realpath('../'.$route->getLabel('sdk.description', '')) : null; $temp = [ 'summary' => $route->getDesc(), - 'operationId' => $route->getLabel('sdk.method', uniqid()), + 'operationId' => $route->getLabel('sdk.method', \uniqid()), 'consumes' => [], 'tags' => [$route->getLabel('sdk.namespace', 'default')], - 'description' => ($desc) ? file_get_contents($desc) : '', + 'description' => ($desc) ? \file_get_contents($desc) : '', // 'responses' => [ // 200 => [ @@ -440,7 +440,7 @@ $utopia->get('/open-api-2.json') ]; foreach ($route->getParams() as $name => $param) { - $validator = (is_callable($param['validator'])) ? $param['validator']() : $param['validator']; /* @var $validator \Utopia\Validator */ + $validator = (\is_callable($param['validator'])) ? $param['validator']() : $param['validator']; /* @var $validator \Utopia\Validator */ $node = [ 'name' => $name, @@ -448,14 +448,14 @@ $utopia->get('/open-api-2.json') 'required' => !$param['optional'], ]; - switch ((!empty($validator)) ? get_class($validator) : '') { + switch ((!empty($validator)) ? \get_class($validator) : '') { case 'Utopia\Validator\Text': $node['type'] = 'string'; - $node['x-example'] = '['.strtoupper(fromCamelCase($node['name'])).']'; + $node['x-example'] = '['.\strtoupper(fromCamelCase($node['name'])).']'; break; case 'Appwrite\Database\Validator\UID': $node['type'] = 'string'; - $node['x-example'] = '['.strtoupper(fromCamelCase($node['name'])).']'; + $node['x-example'] = '['.\strtoupper(fromCamelCase($node['name'])).']'; break; case 'Utopia\Validator\Email': $node['type'] = 'string'; @@ -517,11 +517,11 @@ $utopia->get('/open-api-2.json') break; } - if ($param['optional'] && !is_null($param['default'])) { // Param has default value + if ($param['optional'] && !\is_null($param['default'])) { // Param has default value $node['default'] = $param['default']; } - if (false !== strpos($url, ':'.$name)) { // Param is in URL path + if (false !== \strpos($url, ':'.$name)) { // Param is in URL path $node['in'] = 'path'; $temp['parameters'][] = $node; } elseif ($key == 'GET') { // Param is in query @@ -537,12 +537,12 @@ $utopia->get('/open-api-2.json') } } - $url = str_replace(':'.$name, '{'.$name.'}', $url); + $url = \str_replace(':'.$name, '{'.$name.'}', $url); } $temp['consumes'] = $consumes; - $output['paths'][$url][strtolower($route->getMethod())] = $temp; + $output['paths'][$url][\strtolower($route->getMethod())] = $temp; } } @@ -550,7 +550,7 @@ $utopia->get('/open-api-2.json') var_dump($mock['name']); }*/ - ksort($output['paths']); + \ksort($output['paths']); $response ->json($output); diff --git a/app/init.php b/app/init.php index 798f27123..c58895859 100644 --- a/app/init.php +++ b/app/init.php @@ -7,7 +7,7 @@ * Set configuration, framework resources, app constants * */ -if (file_exists(__DIR__.'/../vendor/autoload.php')) { +if (\file_exists(__DIR__.'/../vendor/autoload.php')) { require_once __DIR__.'/../vendor/autoload.php'; } @@ -68,22 +68,22 @@ Config::setParam('domain', $request->getServer('HTTP_HOST', '')); Config::setParam('domainVerification', false); Config::setParam('version', $request->getServer('_APP_VERSION', 'UNKNOWN')); Config::setParam('protocol', $request->getServer('HTTP_X_FORWARDED_PROTO', $request->getServer('REQUEST_SCHEME', 'https'))); -Config::setParam('port', (string) parse_url(Config::getParam('protocol').'://'.$request->getServer('HTTP_HOST', ''), PHP_URL_PORT)); -Config::setParam('hostname', parse_url(Config::getParam('protocol').'://'.$request->getServer('HTTP_HOST', null), PHP_URL_HOST)); +Config::setParam('port', (string) \parse_url(Config::getParam('protocol').'://'.$request->getServer('HTTP_HOST', ''), PHP_URL_PORT)); +Config::setParam('hostname', \parse_url(Config::getParam('protocol').'://'.$request->getServer('HTTP_HOST', null), PHP_URL_HOST)); Resque::setBackend($request->getServer('_APP_REDIS_HOST', '') .':'.$request->getServer('_APP_REDIS_PORT', '')); -define('COOKIE_DOMAIN', +\define('COOKIE_DOMAIN', ( $request->getServer('HTTP_HOST', null) === 'localhost' || $request->getServer('HTTP_HOST', null) === 'localhost:'.Config::getParam('port') || - (filter_var(Config::getParam('hostname'), FILTER_VALIDATE_IP) !== false) + (\filter_var(Config::getParam('hostname'), FILTER_VALIDATE_IP) !== false) ) ? null : '.'.Config::getParam('hostname') ); -define('COOKIE_SAMESITE', Response::COOKIE_SAMESITE_NONE); +\define('COOKIE_SAMESITE', Response::COOKIE_SAMESITE_NONE); /* * Registry @@ -152,7 +152,7 @@ $register->set('smtp', function () use ($request) { $mail->SMTPAutoTLS = false; $mail->CharSet = 'UTF-8'; - $from = urldecode($request->getServer('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')); + $from = \urldecode($request->getServer('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')); $email = $request->getServer('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM); $mail->setFrom($email, $from); @@ -219,14 +219,14 @@ Locale::setLanguage('zh-tw', include __DIR__.'/config/locales/zh-tw.php'); Locale::setDefault('en'); -if (in_array($locale, Config::getParam('locales'))) { +if (\in_array($locale, Config::getParam('locales'))) { Locale::setDefault($locale); } -stream_context_set_default([ // Set global user agent and http settings +\stream_context_set_default([ // Set global user agent and http settings 'http' => [ 'method' => 'GET', - 'user_agent' => sprintf(APP_USERAGENT, + 'user_agent' => \sprintf(APP_USERAGENT, Config::getParam('version'), $request->getServer('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)), 'timeout' => 2, @@ -268,7 +268,7 @@ $response->addHeader('X-Debug-Fallback', 'false'); if(empty($session['id']) && empty($session['secret'])) { $response->addHeader('X-Debug-Fallback', 'true'); $fallback = $request->getHeader('X-Fallback-Cookies', ''); - $fallback = json_decode($fallback, true); + $fallback = \json_decode($fallback, true); $session = Auth::decodeSession(((isset($fallback[Auth::$cookieName])) ? $fallback[Auth::$cookieName] : '')); } @@ -310,7 +310,7 @@ $register->get('smtp') ->setFrom( $request->getServer('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), ($project->getId() === 'console') - ? urldecode($request->getServer('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')) - : sprintf(Locale::getText('account.emails.team'), $project->getAttribute('name') + ? \urldecode($request->getServer('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')) + : \sprintf(Locale::getText('account.emails.team'), $project->getAttribute('name') ) ); diff --git a/app/tasks/init.php b/app/tasks/init.php index f3c5b9f72..2038beb2f 100644 --- a/app/tasks/init.php +++ b/app/tasks/init.php @@ -22,7 +22,7 @@ $cli Console::log('Issue a TLS certificate for master domain ('.$domain.')'); - ResqueScheduler::enqueueAt(time() + 30, 'v1-certificates', 'CertificatesV1', [ + ResqueScheduler::enqueueAt(\time() + 30, 'v1-certificates', 'CertificatesV1', [ 'document' => [], 'domain' => $domain, 'validateTarget' => false, @@ -103,7 +103,7 @@ $cli Console::log('🟢 HTTP force option is enabled'); } - sleep(0.2); + \sleep(0.2); try { Console::log("\n".'Checking connectivity...'); @@ -161,9 +161,9 @@ $cli $host = $request->getServer('_APP_STATSD_HOST', 'telegraf'); $port = $request->getServer('_APP_STATSD_PORT', 8125); - if($fp = @fsockopen('udp://'.$host, $port, $errCode, $errStr, 2)){ + if($fp = @\fsockopen('udp://'.$host, $port, $errCode, $errStr, 2)){ Console::success('StatsD..............connected 👍'); - fclose($fp); + \fclose($fp); } else { Console::error('StatsD...........disconnected 👎'); } @@ -171,14 +171,14 @@ $cli $host = $request->getServer('_APP_INFLUXDB_HOST', ''); $port = $request->getServer('_APP_INFLUXDB_PORT', ''); - if($fp = @fsockopen($host, $port, $errCode, $errStr, 2)){ + if($fp = @\fsockopen($host, $port, $errCode, $errStr, 2)){ Console::success('InfluxDB............connected 👍'); - fclose($fp); + \fclose($fp); } else { Console::error('InfluxDB.........disconnected 👎'); } - sleep(0.2); + \sleep(0.2); Console::log(''); Console::log('Checking volumes...'); @@ -191,14 +191,14 @@ $cli ] as $key => $volume) { $device = new Local($volume); - if (is_readable($device->getRoot())) { + if (\is_readable($device->getRoot())) { Console::success('🟢 '.$key.' Volume is readable'); } else { Console::error('🔴 '.$key.' Volume is unreadable'); } - if (is_writable($device->getRoot())) { + if (\is_writable($device->getRoot())) { Console::success('🟢 '.$key.' Volume is writeable'); } else { @@ -206,7 +206,7 @@ $cli } } - sleep(0.2); + \sleep(0.2); Console::log(''); Console::log('Checking disk space usage...'); @@ -222,7 +222,7 @@ $cli $percentage = (($device->getPartitionTotalSpace() - $device->getPartitionFreeSpace()) / $device->getPartitionTotalSpace()) * 100; - $message = $key.' Volume has '.Storage::human($device->getPartitionFreeSpace()) . ' free space ('.round($percentage, 2).'% used)'; + $message = $key.' Volume has '.Storage::human($device->getPartitionFreeSpace()) . ' free space ('.\round($percentage, 2).'% used)'; if ($percentage < 80) { Console::success('🟢 ' . $message); @@ -235,10 +235,10 @@ $cli try { Console::log(''); - $version = json_decode(@file_get_contents($request->getServer('_APP_HOME', 'http://localhost').'/v1/health/version'), true); + $version = \json_decode(@\file_get_contents($request->getServer('_APP_HOME', 'http://localhost').'/v1/health/version'), true); if($version && isset($version['version'])) { - if(version_compare($version['version'], $request->getServer('_APP_VERSION', 'UNKNOWN')) === 0) { + if(\version_compare($version['version'], $request->getServer('_APP_VERSION', 'UNKNOWN')) === 0) { Console::info('You are running the latest version of '.APP_NAME.'! 🥳'); } else { diff --git a/app/tasks/migrate.php b/app/tasks/migrate.php index e05d1bc0f..fe833e27f 100644 --- a/app/tasks/migrate.php +++ b/app/tasks/migrate.php @@ -38,7 +38,7 @@ $callbacks = [ 'orderCast' => 'string', ]); - $sum = count($all); + $sum = \count($all); Console::log('Migrating: '.$offset.' / '.$projectDB->getSum()); @@ -97,17 +97,17 @@ function fixDocument(Document $document) { if($document->getAttribute('$collection') === Database::SYSTEM_COLLECTION_PROJECTS){ foreach($providers as $key => $provider) { - if(!empty($document->getAttribute('usersOauth'.ucfirst($key).'Appid'))) { + if(!empty($document->getAttribute('usersOauth'.\ucfirst($key).'Appid'))) { $document - ->setAttribute('usersOauth2'.ucfirst($key).'Appid', $document->getAttribute('usersOauth'.ucfirst($key).'Appid', '')) - ->removeAttribute('usersOauth'.ucfirst($key).'Appid') + ->setAttribute('usersOauth2'.\ucfirst($key).'Appid', $document->getAttribute('usersOauth'.\ucfirst($key).'Appid', '')) + ->removeAttribute('usersOauth'.\ucfirst($key).'Appid') ; } - if(!empty($document->getAttribute('usersOauth'.ucfirst($key).'Secret'))) { + if(!empty($document->getAttribute('usersOauth'.\ucfirst($key).'Secret'))) { $document - ->setAttribute('usersOauth2'.ucfirst($key).'Secret', $document->getAttribute('usersOauth'.ucfirst($key).'Secret', '')) - ->removeAttribute('usersOauth'.ucfirst($key).'Secret') + ->setAttribute('usersOauth2'.\ucfirst($key).'Secret', $document->getAttribute('usersOauth'.\ucfirst($key).'Secret', '')) + ->removeAttribute('usersOauth'.\ucfirst($key).'Secret') ; } } @@ -115,17 +115,17 @@ function fixDocument(Document $document) { if($document->getAttribute('$collection') === Database::SYSTEM_COLLECTION_USERS) { foreach($providers as $key => $provider) { - if(!empty($document->getAttribute('oauth'.ucfirst($key)))) { + if(!empty($document->getAttribute('oauth'.\ucfirst($key)))) { $document - ->setAttribute('oauth2'.ucfirst($key), $document->getAttribute('oauth'.ucfirst($key), '')) - ->removeAttribute('oauth'.ucfirst($key)) + ->setAttribute('oauth2'.\ucfirst($key), $document->getAttribute('oauth'.\ucfirst($key), '')) + ->removeAttribute('oauth'.\ucfirst($key)) ; } - if(!empty($document->getAttribute('oauth'.ucfirst($key).'AccessToken'))) { + if(!empty($document->getAttribute('oauth'.\ucfirst($key).'AccessToken'))) { $document - ->setAttribute('oauth2'.ucfirst($key).'AccessToken', $document->getAttribute('oauth'.ucfirst($key).'AccessToken', '')) - ->removeAttribute('oauth'.ucfirst($key).'AccessToken') + ->setAttribute('oauth2'.\ucfirst($key).'AccessToken', $document->getAttribute('oauth'.\ucfirst($key).'AccessToken', '')) + ->removeAttribute('oauth'.\ucfirst($key).'AccessToken') ; } } @@ -141,7 +141,7 @@ function fixDocument(Document $document) { if($document->getAttribute('$collection') === Database::SYSTEM_COLLECTION_PLATFORMS) { if($document->getAttribute('url', null) !== null) { $document - ->setAttribute('hostname', parse_url($document->getAttribute('url', $document->getAttribute('hostname', '')), PHP_URL_HOST)) + ->setAttribute('hostname', \parse_url($document->getAttribute('url', $document->getAttribute('hostname', '')), PHP_URL_HOST)) ->removeAttribute('url') ; } @@ -159,7 +159,7 @@ function fixDocument(Document $document) { $attr = fixDocument($attr); } - if(is_array($attr)) { + if(\is_array($attr)) { foreach($attr as &$child) { if($child instanceof Document) { $child = fixDocument($child); @@ -207,7 +207,7 @@ $cli ], ]); - $sum = count($projects); + $sum = \count($projects); $offset = $offset + $limit; Console::log('Fetched '.$sum.' projects...'); diff --git a/app/tasks/sdks.php b/app/tasks/sdks.php index 284344392..0753c4dfe 100644 --- a/app/tasks/sdks.php +++ b/app/tasks/sdks.php @@ -29,20 +29,20 @@ $cli ->action(function () use ($warning, $version) { function getSSLPage($url) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_HEADER, false); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $result = curl_exec($ch); - curl_close($ch); + $ch = \curl_init(); + \curl_setopt($ch, CURLOPT_HEADER, false); + \curl_setopt($ch, CURLOPT_URL, $url); + \curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + \curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + \curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $result = \curl_exec($ch); + \curl_close($ch); return $result; } $platforms = Config::getParam('platforms'); - $selected = strtolower(Console::confirm('Choose SDK ("*" for all):')); + $selected = \strtolower(Console::confirm('Choose SDK ("*" for all):')); $message = Console::confirm('Please enter your commit message:'); $production = (Console::confirm('Type "Appwrite" to deploy for production') == 'Appwrite'); @@ -63,14 +63,14 @@ $cli $spec = getSSLPage('https://appwrite.io/v1/open-api-2.json?extensions=1&platform='.$language['family']); $spec = getSSLPage('https://localhost/v1/open-api-2.json?extensions=1&platform='.$language['family']); - $result = realpath(__DIR__.'/..').'/sdks/'.$key.'-'.$language['key']; - $target = realpath(__DIR__.'/..').'/sdks/git/'.$language['key'].'/'; - $readme = realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/README.md'); - $readme = ($readme) ? file_get_contents($readme) : ''; - $examples = realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/EXAMPLES.md'); - $examples = ($examples) ? file_get_contents($examples) : ''; - $changelog = realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/CHANGELOG.md'); - $changelog = ($changelog) ? file_get_contents($changelog) : '# Change Log'; + $result = \realpath(__DIR__.'/..').'/sdks/'.$key.'-'.$language['key']; + $target = \realpath(__DIR__.'/..').'/sdks/git/'.$language['key'].'/'; + $readme = \realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/README.md'); + $readme = ($readme) ? \file_get_contents($readme) : ''; + $examples = \realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/EXAMPLES.md'); + $examples = ($examples) ? \file_get_contents($examples) : ''; + $changelog = \realpath(__DIR__ . '/../../docs/sdks/'.$language['key'].'/CHANGELOG.md'); + $changelog = ($changelog) ? \file_get_contents($changelog) : '# Change Log'; $warning = ($language['beta']) ? '**This SDK is compatible with Appwrite server version ' . $version . '. For older versions, please check previous releases.**' : ''; $license = 'BSD-3-Clause'; $licenseContent = 'Copyright (c) 2019 Appwrite (https://appwrite.io) and individual contributors. @@ -186,7 +186,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND $gitUrl = 'git@github.com:aw-tests/'.$language['gitRepoName'].'.git'; } - exec('rm -rf '.$target.' && \ + \exec('rm -rf '.$target.' && \ mkdir -p '.$target.' && \ cd '.$target.' && \ git init && \ @@ -201,7 +201,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND Console::success("Pushed {$language['name']} SDK to {$gitUrl}"); - exec('rm -rf '.$target); + \exec('rm -rf '.$target); Console::success("Remove temp directory '{$target}' for {$language['name']} SDK"); } diff --git a/app/workers/audits.php b/app/workers/audits.php index 9524fc89e..9ffb85e57 100644 --- a/app/workers/audits.php +++ b/app/workers/audits.php @@ -2,7 +2,7 @@ require_once __DIR__.'/../init.php'; -cli_set_process_title('Audits V1 Worker'); +\cli_set_process_title('Audits V1 Worker'); echo APP_NAME.' audits worker v1 has started'; diff --git a/app/workers/certificates.php b/app/workers/certificates.php index 4c3c47336..b04c7409c 100644 --- a/app/workers/certificates.php +++ b/app/workers/certificates.php @@ -9,7 +9,7 @@ use Appwrite\Network\Validator\CNAME; require_once __DIR__.'/../init.php'; -cli_set_process_title('Certificates V1 Worker'); +\cli_set_process_title('Certificates V1 Worker'); echo APP_NAME.' certificates worker v1 has started'; @@ -51,7 +51,7 @@ class CertificatesV1 $domain = new Domain((!empty($domain)) ? $domain : ''); $expiry = 60 * 60 * 24 * 30 * 2; // 60 days $safety = 60 * 60; // 1 hour - $renew = (time() + $expiry); + $renew = (\time() + $expiry); if(empty($domain->get())) { throw new Exception('Missing domain'); @@ -101,13 +101,13 @@ class CertificatesV1 if(!empty($certificate) && isset($certificate['issueDate']) - && (($certificate['issueDate'] + ($expiry)) > time())) { // Check last issue time + && (($certificate['issueDate'] + ($expiry)) > \time())) { // Check last issue time throw new Exception('Renew isn\'t required'); } $staging = (Config::getParam('env') === App::MODE_TYPE_PRODUCTION) ? '' : ' --dry-run'; - $response = shell_exec("certbot certonly --webroot --noninteractive --agree-tos{$staging} \ + $response = \shell_exec("certbot certonly --webroot --noninteractive --agree-tos{$staging} \ --email ".$request->getServer('_APP_SYSTEM_EMAIL_ADDRESS', 'security@localhost.test')." \ -w ".APP_STORAGE_CERTIFICATES." \ -d {$domain->get()}"); @@ -118,39 +118,39 @@ class CertificatesV1 $path = APP_STORAGE_CERTIFICATES.'/'.$domain->get(); - if(!is_readable($path)) { - if (!mkdir($path, 0755, true)) { + if(!\is_readable($path)) { + if (!\mkdir($path, 0755, true)) { throw new Exception('Failed to create path...'); } } - if(!@rename('/etc/letsencrypt/live/'.$domain->get().'/cert.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/cert.pem')) { - throw new Exception('Failed to rename certificate cert.pem: '.json_encode($response)); + if(!@\rename('/etc/letsencrypt/live/'.$domain->get().'/cert.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/cert.pem')) { + throw new Exception('Failed to rename certificate cert.pem: '.\json_encode($response)); } - if(!@rename('/etc/letsencrypt/live/'.$domain->get().'/chain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/chain.pem')) { - throw new Exception('Failed to rename certificate chain.pem: '.json_encode($response)); + if(!@\rename('/etc/letsencrypt/live/'.$domain->get().'/chain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/chain.pem')) { + throw new Exception('Failed to rename certificate chain.pem: '.\json_encode($response)); } - if(!@rename('/etc/letsencrypt/live/'.$domain->get().'/fullchain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/fullchain.pem')) { - throw new Exception('Failed to rename certificate fullchain.pem: '.json_encode($response)); + if(!@\rename('/etc/letsencrypt/live/'.$domain->get().'/fullchain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/fullchain.pem')) { + throw new Exception('Failed to rename certificate fullchain.pem: '.\json_encode($response)); } - if(!@rename('/etc/letsencrypt/live/'.$domain->get().'/privkey.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/privkey.pem')) { - throw new Exception('Failed to rename certificate privkey.pem: '.json_encode($response)); + if(!@\rename('/etc/letsencrypt/live/'.$domain->get().'/privkey.pem', APP_STORAGE_CERTIFICATES.'/'.$domain->get().'/privkey.pem')) { + throw new Exception('Failed to rename certificate privkey.pem: '.\json_encode($response)); } - $certificate = array_merge($certificate, [ + $certificate = \array_merge($certificate, [ '$collection' => Database::SYSTEM_COLLECTION_CERTIFICATES, '$permissions' => [ 'read' => [], 'write' => [], ], 'domain' => $domain->get(), - 'issueDate' => time(), + 'issueDate' => \time(), 'renewDate' => $renew, 'attempts' => 0, - 'log' => json_encode($response), + 'log' => \json_encode($response), ]); $certificate = $consoleDB->createDocument($certificate); @@ -160,8 +160,8 @@ class CertificatesV1 } if(!empty($document)) { - $document = array_merge($document, [ - 'updated' => time(), + $document = \array_merge($document, [ + 'updated' => \time(), 'certificateId' => $certificate->getId(), ]); @@ -178,7 +178,7 @@ class CertificatesV1 - certFile: /storage/certificates/{$domain->get()}/fullchain.pem keyFile: /storage/certificates/{$domain->get()}/privkey.pem"; - if(!file_put_contents(APP_STORAGE_CONFIG.'/'.$domain->get().'.yml', $config)) { + if(!\file_put_contents(APP_STORAGE_CONFIG.'/'.$domain->get().'.yml', $config)) { throw new Exception('Failed to save SSL configuration'); } diff --git a/app/workers/deletes.php b/app/workers/deletes.php index 3c9020f5b..aa0cbe6c2 100644 --- a/app/workers/deletes.php +++ b/app/workers/deletes.php @@ -2,7 +2,7 @@ require_once __DIR__.'/../init.php'; -cli_set_process_title('Deletes V1 Worker'); +\cli_set_process_title('Deletes V1 Worker'); echo APP_NAME.' deletes worker v1 has started'; diff --git a/app/workers/mails.php b/app/workers/mails.php index c46fda89d..6835f3071 100644 --- a/app/workers/mails.php +++ b/app/workers/mails.php @@ -2,7 +2,7 @@ require_once __DIR__.'/../init.php'; -cli_set_process_title('Mails V1 Worker'); +\cli_set_process_title('Mails V1 Worker'); echo APP_NAME.' mails worker v1 has started'; @@ -32,7 +32,7 @@ class MailsV1 $mail->addAddress($recipient, $name); $mail->Subject = $subject; $mail->Body = $body; - $mail->AltBody = strip_tags($body); + $mail->AltBody = \strip_tags($body); try { $mail->send(); diff --git a/app/workers/tasks.php b/app/workers/tasks.php index 8ac494c9f..db664d567 100644 --- a/app/workers/tasks.php +++ b/app/workers/tasks.php @@ -7,7 +7,7 @@ use Appwrite\Database\Database; use Appwrite\Database\Validator\Authorization; use Cron\CronExpression; -cli_set_process_title('Tasks V1 Worker'); +\cli_set_process_title('Tasks V1 Worker'); echo APP_NAME.' tasks worker v1 has started'; @@ -42,7 +42,7 @@ class TasksV1 $taskId = (isset($this->args['$id'])) ? $this->args['$id'] : null; $updated = (isset($this->args['updated'])) ? $this->args['updated'] : null; $next = (isset($this->args['next'])) ? $this->args['next'] : null; - $delay = time() - $next; + $delay = \time() - $next; $errors = []; $timeout = 60 * 5; // 5 minutes $errorLimit = 5; @@ -59,7 +59,7 @@ class TasksV1 Authorization::enable(); - if (is_null($task->getId()) || Database::SYSTEM_COLLECTION_TASKS !== $task->getCollection()) { + if (\is_null($task->getId()) || Database::SYSTEM_COLLECTION_TASKS !== $task->getCollection()) { throw new Exception('Task Not Found'); } @@ -75,69 +75,69 @@ class TasksV1 $cron = CronExpression::factory($task->getAttribute('schedule')); $next = (int) $cron->getNextRunDate()->format('U'); - $headers = (is_array($task->getAttribute('httpHeaders', []))) ? $task->getAttribute('httpHeaders', []) : []; + $headers = (\is_array($task->getAttribute('httpHeaders', []))) ? $task->getAttribute('httpHeaders', []) : []; $task ->setAttribute('next', $next) - ->setAttribute('previous', time()) + ->setAttribute('previous', \time()) ; ResqueScheduler::enqueueAt($next, 'v1-tasks', 'TasksV1', $task->getArrayCopy()); // Async task rescheduale - $startTime = microtime(true); + $startTime = \microtime(true); // Execute Task - $ch = curl_init($task->getAttribute('httpUrl')); + $ch = \curl_init($task->getAttribute('httpUrl')); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $task->getAttribute('httpMethod')); - curl_setopt($ch, CURLOPT_POSTFIELDS, ''); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_USERAGENT, sprintf(APP_USERAGENT, + \curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $task->getAttribute('httpMethod')); + \curl_setopt($ch, CURLOPT_POSTFIELDS, ''); + \curl_setopt($ch, CURLOPT_HEADER, 0); + \curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + \curl_setopt($ch, CURLOPT_USERAGENT, \sprintf(APP_USERAGENT, Config::getParam('version'), $request->getServer('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY) )); - curl_setopt( + \curl_setopt( $ch, CURLOPT_HTTPHEADER, - array_merge($headers, [ + \array_merge($headers, [ 'X-'.APP_NAME.'-Task-ID: '.$task->getAttribute('$id', ''), 'X-'.APP_NAME.'-Task-Name: '.$task->getAttribute('name', ''), ]) ); - curl_setopt($ch, CURLOPT_HEADER, true); // we want headers - curl_setopt($ch, CURLOPT_NOBODY, true); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + \curl_setopt($ch, CURLOPT_HEADER, true); // we want headers + \curl_setopt($ch, CURLOPT_NOBODY, true); + \curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (!$task->getAttribute('security', true)) { - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + \curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + \curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $httpUser = $task->getAttribute('httpUser'); $httpPass = $task->getAttribute('httpPass'); if (!empty($httpUser) && !empty($httpPass)) { - curl_setopt($ch, CURLOPT_USERPWD, "$httpUser:$httpPass"); - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + \curl_setopt($ch, CURLOPT_USERPWD, "$httpUser:$httpPass"); + \curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } - $response = curl_exec($ch); + $response = \curl_exec($ch); if (false === $response) { - $errors[] = curl_error($ch).'Failed to execute task'; + $errors[] = \curl_error($ch).'Failed to execute task'; } - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $codeFamily = mb_substr($code, 0, 1); - $headersSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); - $headers = substr($response, 0, $headersSize); - $body = substr($response, $headersSize); + $code = \curl_getinfo($ch, CURLINFO_HTTP_CODE); + $codeFamily = \mb_substr($code, 0, 1); + $headersSize = \curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $headers = \substr($response, 0, $headersSize); + $body = \substr($response, $headersSize); - curl_close($ch); + \curl_close($ch); - $totalTime = round(microtime(true) - $startTime, 2); + $totalTime = \round(\microtime(true) - $startTime, 2); switch ($codeFamily) { case '2': @@ -157,16 +157,16 @@ class TasksV1 ->setAttribute('status', ($task->getAttribute('failures') >= $errorLimit) ? 'pause' : 'play') ; - $alert = 'Task "'.$task->getAttribute('name').'" failed to execute with the following errors: '.implode("\n", $errors); + $alert = 'Task "'.$task->getAttribute('name').'" failed to execute with the following errors: '.\implode("\n", $errors); } - $log = json_decode($task->getAttribute('log', '{}'), true); + $log = \json_decode($task->getAttribute('log', '{}'), true); - if (count($log) >= $logLimit) { - array_pop($log); + if (\count($log) >= $logLimit) { + \array_pop($log); } - array_unshift($log, [ + \array_unshift($log, [ 'code' => $code, 'duration' => $totalTime, 'delay' => $delay, @@ -176,7 +176,7 @@ class TasksV1 ]); $task - ->setAttribute('log', json_encode($log)) + ->setAttribute('log', \json_encode($log)) ->setAttribute('duration', $totalTime) ->setAttribute('delay', $delay) ; diff --git a/app/workers/usage.php b/app/workers/usage.php index e5f673361..0d0811c33 100644 --- a/app/workers/usage.php +++ b/app/workers/usage.php @@ -4,7 +4,7 @@ use Utopia\Config\Config; require_once __DIR__.'/../init.php'; -cli_set_process_title('Usage V1 Worker'); +\cli_set_process_title('Usage V1 Worker'); echo APP_NAME.' usage worker v1 has started'; @@ -36,7 +36,7 @@ class UsageV1 // the global namespace is prepended to every key (optional) $statsd->setNamespace('appwrite.usage'); - $statsd->increment('requests.all'.$tags.',method='.strtolower($method)); + $statsd->increment('requests.all'.$tags.',method='.\strtolower($method)); $statsd->count('network.all'.$tags, $request + $response); $statsd->count('network.inbound'.$tags, $request); diff --git a/app/workers/webhooks.php b/app/workers/webhooks.php index e7c6157a8..ecd9360d2 100644 --- a/app/workers/webhooks.php +++ b/app/workers/webhooks.php @@ -2,7 +2,7 @@ require_once __DIR__.'/../init.php'; -cli_set_process_title('Webhooks V1 Worker'); +\cli_set_process_title('Webhooks V1 Worker'); echo APP_NAME.' webhooks worker v1 has started'; @@ -27,7 +27,7 @@ class WebhooksV1 // Event $projectId = $this->args['projectId']; $event = $this->args['event']; - $payload = json_encode($this->args['payload']); + $payload = \json_encode($this->args['payload']); // Webhook @@ -37,12 +37,12 @@ class WebhooksV1 Authorization::enable(); - if (is_null($project->getId()) || Database::SYSTEM_COLLECTION_PROJECTS !== $project->getCollection()) { + if (\is_null($project->getId()) || Database::SYSTEM_COLLECTION_PROJECTS !== $project->getCollection()) { throw new Exception('Project Not Found'); } foreach ($project->getAttribute('webhooks', []) as $webhook) { - if (!(isset($webhook['events']) && is_array($webhook['events']) && in_array($event, $webhook['events']))) { + if (!(isset($webhook['events']) && \is_array($webhook['events']) && \in_array($event, $webhook['events']))) { continue; } @@ -53,22 +53,22 @@ class WebhooksV1 $httpUser = (isset($webhook['httpUser'])) ? $webhook['httpUser'] : null; $httpPass = (isset($webhook['httpPass'])) ? $webhook['httpPass'] : null; - $ch = curl_init($url); + $ch = \curl_init($url); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); - curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_USERAGENT, sprintf(APP_USERAGENT, + \curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); + \curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + \curl_setopt($ch, CURLOPT_HEADER, 0); + \curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + \curl_setopt($ch, CURLOPT_USERAGENT, \sprintf(APP_USERAGENT, Config::getParam('version'), $request->getServer('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY) )); - curl_setopt( + \curl_setopt( $ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', - 'Content-Length: '.strlen($payload), + 'Content-Length: '.\strlen($payload), 'X-'.APP_NAME.'-Webhook-Event: '.$event, 'X-'.APP_NAME.'-Webhook-Name: '.$name, 'X-'.APP_NAME.'-Webhook-Signature: '.$signature, @@ -76,24 +76,24 @@ class WebhooksV1 ); if (!$security) { - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + \curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + \curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } if (!empty($httpUser) && !empty($httpPass)) { - curl_setopt($ch, CURLOPT_USERPWD, "$httpUser:$httpPass"); - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + \curl_setopt($ch, CURLOPT_USERPWD, "$httpUser:$httpPass"); + \curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } - if (false === curl_exec($ch)) { - $errors[] = curl_error($ch).' in event '.$event.' for webhook '.$name; + if (false === \curl_exec($ch)) { + $errors[] = \curl_error($ch).' in event '.$event.' for webhook '.$name; } - curl_close($ch); + \curl_close($ch); } if (!empty($errors)) { - throw new Exception(implode(" / \n\n", $errors)); + throw new Exception(\implode(" / \n\n", $errors)); } }