diff --git a/api.knowyourfood/.htaccess b/api.knowyourfood/.htaccess new file mode 100755 index 0000000..99ea233 --- /dev/null +++ b/api.knowyourfood/.htaccess @@ -0,0 +1,12 @@ +RewriteEngine On + + + Header set Access-Control-Allow-Origin "*" + Header set Access-Control-Allow-Headers "*" + Header set Access-Control-Allow-Methods "*" + + +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^(.*)$ index.php [L] + diff --git a/api.knowyourfood/.idea/.gitignore b/api.knowyourfood/.idea/.gitignore new file mode 100755 index 0000000..1c2fda5 --- /dev/null +++ b/api.knowyourfood/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/api.knowyourfood/.idea/api.knowyourfood.iml b/api.knowyourfood/.idea/api.knowyourfood.iml new file mode 100644 index 0000000..928ea4e --- /dev/null +++ b/api.knowyourfood/.idea/api.knowyourfood.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/api.knowyourfood/.idea/modules.xml b/api.knowyourfood/.idea/modules.xml new file mode 100755 index 0000000..2e766bb --- /dev/null +++ b/api.knowyourfood/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/api.knowyourfood/.idea/php.xml b/api.knowyourfood/.idea/php.xml new file mode 100755 index 0000000..bccf9a4 --- /dev/null +++ b/api.knowyourfood/.idea/php.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/api.knowyourfood/composer.json b/api.knowyourfood/composer.json new file mode 100755 index 0000000..4d28886 --- /dev/null +++ b/api.knowyourfood/composer.json @@ -0,0 +1,12 @@ +{ + "name": "andrei_robert/api.knowyourfood", + "autoload": { + "psr-4": { + "app\\": "./" + } + }, + "require": { + "ext-curl": "*", + "ext-ssh2": "*" + } +} diff --git a/api.knowyourfood/composer.lock b/api.knowyourfood/composer.lock new file mode 100755 index 0000000..07783ca --- /dev/null +++ b/api.knowyourfood/composer.lock @@ -0,0 +1,20 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "d0c0dc1923200d7104286e6b4706aaad", + "packages": [], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "ext-curl": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/api.knowyourfood/core/DVC.php b/api.knowyourfood/core/DVC.php new file mode 100755 index 0000000..54c1246 --- /dev/null +++ b/api.knowyourfood/core/DVC.php @@ -0,0 +1,96 @@ + [ + DVC::$returnCode => 460, + DVC::$returnMessage => "Operation done successfully" + ], + DVC::$genericExceptionName => [ + DVC::$returnCode => 461, + DVC::$returnMessage => "Internal Server Error" + ], + DVC::$invalidTokenName => [ + DVC::$returnCode => 462, + DVC::$returnMessage => "Unauthorized access" + ], + DVC::$invalidRequestName => [ + DVC::$returnCode => 463, + DVC::$returnMessage => "Service doesn't provide this type of request" + ], + DVC::$invalidBodyName => [ + DVC::$returnCode => 464, + DVC::$returnMessage => "Not valid parameters sent" + ], + DVC::$alreadyExistsName => [ + + DVC::$returnCode => 465, + DVC::$returnMessage => "Field already existing" + ], + DVC::$fieldNotExistingName => [ + DVC::$returnCode => 466, + DVC::$returnMessage => "Field not existing anymore" + ], + DVC::$invalidCurlStructureName => [ + DVC::$returnCode => 467, + DVC::$returnMessage => "cURL class needs URL, request method and headers to run" + ], + DVC::$userNotExistingName => [ + DVC::$returnCode => 468, + DVC::$returnMessage => "User account doesn't exists" + ], + DVC::$pageNotFoundName => [ + DVC::$returnCode => 469, + DVC::$returnMessage => "Page not found" + ], + DVC::$forbiddenAccessName => [ + DVC::$returnCode => 470, + DVC::$returnMessage => "You are not authorised to access this page" + ], + DVC::$serviceNotFoundName => [ + DVC::$returnCode => 471, + DVC::$returnMessage => "Service not existing" + ] + }; + } + + public static function getHttpCodeWithCode(int $code): int + { + return match ($code){ + 460 => 200, + 461 => 500, + 462 => 401, + 463 => 405, + 464 => 400, + 465, 466 => 204, + 467 => 409, + 468, 469, 471 => 404, + 470 => 403, + default => 100 + }; + } +} \ No newline at end of file diff --git a/api.knowyourfood/core/Request.php b/api.knowyourfood/core/Request.php new file mode 100755 index 0000000..572d064 --- /dev/null +++ b/api.knowyourfood/core/Request.php @@ -0,0 +1,43 @@ +request = $request; + $this->token = $token; + } + + public function set($path, $callback): void + { + $this->routes[$path] = $callback; + } + + public function getHeaders(string $path): array + { + $array = $_SESSION['headers_configuration'][$path]; + + if($path === '/authentication'){ + $array = $array[$this->request->getAuthRequest()]; + } + + $array["Content-Length"] = empty($this->request->getBody()) ? 0 : strlen(json_encode($this->request->getBody())); + + $toReturn = array(); + foreach ($array as $key => $value){ + $value = $key . ": " . $value; + $toReturn[] = $value; + } + + return $toReturn; + } + + + public function resolve(): void + { + try { + if (!$this->isTokenValid()) throw new InvalidTokenException(); + + $path = $this->request->getPath(); + $method = $this->request->method(); + $body = $this->request->getBody(); + $callback = $this->routes[$path] ?? false; + + if (!$callback) throw new ServiceNotFoundException(); + + $headers = $this->getHeaders($path); + + $requestBuilder = new CurlRequestBuilder(); + + $requestBuilder->setRequest($method); + $requestBuilder->setUrl($callback); + $requestBuilder->setHeaders($headers); + $requestBuilder->setBody($body); + $requestBuilder->setIsReturnable(true); + $request = $requestBuilder->getCurlRequestObject(); + + $response = $request->makeRequest(); + $this->writeResponse( + DVC::getHttpCodeWithCode(DVC::$successReturnCode), + DVC::$successReturnCode, $response + ); + } catch (Exception $e){ + $this->writeResponse(DVC::getHttpCodeWithCode($e->getCode()), + $e->getCode(), $e->getMessage() + ); + } + } + + private function isTokenValid(): bool + { + $validToken = hash('md5', 'api.knowyourfood'); + return $validToken == $this->token; + } + + private function writeResponse(int $httpCode, int $returnCode, string $returnMessage): void + { + header("Content-Disposition: ".DVC::$nameOfResponsePackage); + header("Content-Type: application/json"); + http_response_code($httpCode); + if($httpCode != 200) { + echo json_encode([ + "code" => $returnCode, + "message" => $returnMessage + ]); + }else{ + echo $returnMessage; + } + } +} \ No newline at end of file diff --git a/knowyourfood/dbconfig.php b/api.knowyourfood/database config.php old mode 100644 new mode 100755 similarity index 77% rename from knowyourfood/dbconfig.php rename to api.knowyourfood/database config.php index ab75e91..fda94ed --- a/knowyourfood/dbconfig.php +++ b/api.knowyourfood/database config.php @@ -1,10 +1,11 @@ - \app\models\User::class, - 'db' => [ - 'dsn' => 'mysql:host=localhost;port=3306;dbname=Web', - 'user' => 'root', - 'password' => '', - ] + [ + 'dsn' => 'mysql:host=localhost;port=3306;dbname=Web', + 'user' => 'root', + 'password' => '', + ] ]; \ No newline at end of file diff --git a/api.knowyourfood/exceptions/GenericErrorException.php b/api.knowyourfood/exceptions/GenericErrorException.php new file mode 100755 index 0000000..b1f51bb --- /dev/null +++ b/api.knowyourfood/exceptions/GenericErrorException.php @@ -0,0 +1,13 @@ +url = $url; + $this->request = $request; + $this->headers = $headers; + $this->body = $body; + $this->isReturnable = $isReturnable; + } + + /** + * @throws GenericErrorException + */ + public function makeRequest(): string + { + $curl = curl_init(); + $this->setCurlBody($curl); + + $response = curl_exec($curl); + + if(!$response){ + throw new GenericErrorException(); + } + if(curl_errno($curl)){ + echo curl_error($curl); + die; + } + + curl_close($curl); + + return $response; + } + + public function setCurlBody(CurlHandle &$curl): void + { + curl_setopt($curl, CURLOPT_URL, $this->url); + curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers); + + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->request); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, $this->isReturnable); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + + curl_setopt($curl,CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->body)); + } +} \ No newline at end of file diff --git a/api.knowyourfood/external_requests/CurlRequestBuilder.php b/api.knowyourfood/external_requests/CurlRequestBuilder.php new file mode 100755 index 0000000..5eab95e --- /dev/null +++ b/api.knowyourfood/external_requests/CurlRequestBuilder.php @@ -0,0 +1,37 @@ +url = $url;} + public function setHeaders(?array $headers): void{$this->headers = $headers;} + public function setRequest(?string $request): void{$this->request = $request;} + public function setBody(?array $body): void{$this->body = $body;} + public function setIsReturnable(?bool $isReturnable): void{$this->isReturnable = $isReturnable;} + + private function areMainParametersNotSet(): bool{ + return $this->url == NULL || $this->request == NULL || $this->headers == NULL; + } + + /** + * @throws InvalidCurlStructureException + */ + public function getCurlRequestObject(): CurlRequest{ + if($this->areMainParametersNotSet()){ + throw new InvalidCurlStructureException(); + } + + return new CurlRequest($this->url, $this->request, $this->headers, $this->body, $this->isReturnable); + } +} \ No newline at end of file diff --git a/api.knowyourfood/headers_config.php b/api.knowyourfood/headers_config.php new file mode 100644 index 0000000..644a9ee --- /dev/null +++ b/api.knowyourfood/headers_config.php @@ -0,0 +1,23 @@ + [ + "register" => [ + "Content-Type" => "application/json", + "Authorization" => hash('md5', 'service_authentication'), + "Auth-Request" => "register" + ], + "login" => [ + "Content-Type" => "application/json", + "Authorization" => hash('md5', 'service_authentication'), + "Auth-Request" => "login" + ], + + "default" => [ + "Content-Type" => "application/json", + "Authorization" => hash('md5', 'service_authentication') + ], + ] +]; + +$_SESSION['headers_configuration'] = $headers_array; \ No newline at end of file diff --git a/api.knowyourfood/index.php b/api.knowyourfood/index.php new file mode 100755 index 0000000..4fe39df --- /dev/null +++ b/api.knowyourfood/index.php @@ -0,0 +1,16 @@ +getToken()); + +$router->set("/authentication", '89.137.67.2:702'); + +$request->getAuthRequest(); + +$router->resolve(); diff --git a/api.knowyourfood/test.php b/api.knowyourfood/test.php new file mode 100644 index 0000000..b3d9bbc --- /dev/null +++ b/api.knowyourfood/test.php @@ -0,0 +1 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/api.knowyourfood/vendor/composer/InstalledVersions.php b/api.knowyourfood/vendor/composer/InstalledVersions.php new file mode 100755 index 0000000..51e734a --- /dev/null +++ b/api.knowyourfood/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/api.knowyourfood/vendor/composer/LICENSE b/api.knowyourfood/vendor/composer/LICENSE new file mode 100755 index 0000000..f27399a --- /dev/null +++ b/api.knowyourfood/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/api.knowyourfood/vendor/composer/autoload_classmap.php b/api.knowyourfood/vendor/composer/autoload_classmap.php new file mode 100755 index 0000000..0fb0a2c --- /dev/null +++ b/api.knowyourfood/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/api.knowyourfood/vendor/composer/autoload_namespaces.php b/api.knowyourfood/vendor/composer/autoload_namespaces.php new file mode 100755 index 0000000..15a2ff3 --- /dev/null +++ b/api.knowyourfood/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/'), +); diff --git a/api.knowyourfood/vendor/composer/autoload_real.php b/api.knowyourfood/vendor/composer/autoload_real.php new file mode 100755 index 0000000..7b58fad --- /dev/null +++ b/api.knowyourfood/vendor/composer/autoload_real.php @@ -0,0 +1,36 @@ +register(true); + + return $loader; + } +} diff --git a/api.knowyourfood/vendor/composer/autoload_static.php b/api.knowyourfood/vendor/composer/autoload_static.php new file mode 100755 index 0000000..47c793b --- /dev/null +++ b/api.knowyourfood/vendor/composer/autoload_static.php @@ -0,0 +1,36 @@ + + array ( + 'app\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'app\\' => + array ( + 0 => __DIR__ . '/../..' . '/', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit345c1a817a7f402322a2ecae01a96071::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/api.knowyourfood/vendor/composer/installed.json b/api.knowyourfood/vendor/composer/installed.json new file mode 100755 index 0000000..87fda74 --- /dev/null +++ b/api.knowyourfood/vendor/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": true, + "dev-package-names": [] +} diff --git a/api.knowyourfood/vendor/composer/installed.php b/api.knowyourfood/vendor/composer/installed.php new file mode 100755 index 0000000..a116754 --- /dev/null +++ b/api.knowyourfood/vendor/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => 'andrei_robert/api.knowyourfood', + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'andrei_robert/api.knowyourfood' => array( + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/knowyourfood/.env.example b/knowyourfood/.env.example deleted file mode 100644 index e499597..0000000 --- a/knowyourfood/.env.example +++ /dev/null @@ -1,3 +0,0 @@ -DB_DSN = mysql:host=localhost;port=3306;dbname=Web -DB_USER = root -DB_PASSWORD = root \ No newline at end of file diff --git a/knowyourfood/.gitignore b/knowyourfood/.gitignore old mode 100644 new mode 100755 index 105e5d8..1907110 --- a/knowyourfood/.gitignore +++ b/knowyourfood/.gitignore @@ -1,4 +1,4 @@ -vendor -.idea -dbconfig +vendor +.idea +dbconfig !.gitignore \ No newline at end of file diff --git a/knowyourfood/.htaccess b/knowyourfood/.htaccess index 8d79af1..dbd5b49 100644 --- a/knowyourfood/.htaccess +++ b/knowyourfood/.htaccess @@ -1,14 +1,4 @@ -ErrorDocument 403 /404.php -ErrorDocument 404 /404.php -DirectoryINdex index.php - - -RewriteEngine on +RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d -RewriteRule ^(.*)$ index.php?page=$1 [L,QSA] - -RewriteCond %{REQUEST_URI} !^/$ -RewriteCond %{REQUEST_URI} !^/admin -RewriteRule .*/ [L,R=301] - \ No newline at end of file +RewriteRule ^(.*)$ index.php [L] \ No newline at end of file diff --git a/knowyourfood/composer.json b/knowyourfood/composer.json old mode 100644 new mode 100755 index ce8993e..d598cb7 --- a/knowyourfood/composer.json +++ b/knowyourfood/composer.json @@ -1,17 +1,11 @@ { - "name": "andrei/knowyourfood", - "authors": [ - { - "name": "Cerbu Andrei Mihnea", - "email": "andreimihneacerbu@gmail.com" - } - ], - "autoload" : { - "psr-4" : { + "name": "andrei_cerbu/knowyourfood", + "autoload": { + "psr-4": { "app\\": "./" } }, "require": { - "vlucas/phpdotenv": "^5.5" + "ext-curl": "*" } } diff --git a/knowyourfood/composer.lock b/knowyourfood/composer.lock old mode 100644 new mode 100755 index 5a0612e..481155d --- a/knowyourfood/composer.lock +++ b/knowyourfood/composer.lock @@ -4,485 +4,17 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c85ce2bf1fa0099ca65ec02d2a26abb1", - "packages": [ - { - "name": "graham-campbell/result-type", - "version": "v1.1.1", - "source": { - "type": "git", - "url": "https://github.com/GrahamCampbell/Result-Type.git", - "reference": "672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831", - "reference": "672eff8cf1d6fe1ef09ca0f89c4b287d6a3eb831", - "shasum": "" - }, - "require": { - "php": "^7.2.5 || ^8.0", - "phpoption/phpoption": "^1.9.1" - }, - "require-dev": { - "phpunit/phpunit": "^8.5.32 || ^9.6.3 || ^10.0.12" - }, - "type": "library", - "autoload": { - "psr-4": { - "GrahamCampbell\\ResultType\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Graham Campbell", - "email": "hello@gjcampbell.co.uk", - "homepage": "https://github.com/GrahamCampbell" - } - ], - "description": "An Implementation Of The Result Type", - "keywords": [ - "Graham Campbell", - "GrahamCampbell", - "Result Type", - "Result-Type", - "result" - ], - "support": { - "issues": "https://github.com/GrahamCampbell/Result-Type/issues", - "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.1" - }, - "funding": [ - { - "url": "https://github.com/GrahamCampbell", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", - "type": "tidelift" - } - ], - "time": "2023-02-25T20:23:15+00:00" - }, - { - "name": "phpoption/phpoption", - "version": "1.9.1", - "source": { - "type": "git", - "url": "https://github.com/schmittjoh/php-option.git", - "reference": "dd3a383e599f49777d8b628dadbb90cae435b87e" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/dd3a383e599f49777d8b628dadbb90cae435b87e", - "reference": "dd3a383e599f49777d8b628dadbb90cae435b87e", - "shasum": "" - }, - "require": { - "php": "^7.2.5 || ^8.0" - }, - "require-dev": { - "bamarni/composer-bin-plugin": "^1.8.2", - "phpunit/phpunit": "^8.5.32 || ^9.6.3 || ^10.0.12" - }, - "type": "library", - "extra": { - "bamarni-bin": { - "bin-links": true, - "forward-command": true - }, - "branch-alias": { - "dev-master": "1.9-dev" - } - }, - "autoload": { - "psr-4": { - "PhpOption\\": "src/PhpOption/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "Apache-2.0" - ], - "authors": [ - { - "name": "Johannes M. Schmitt", - "email": "schmittjoh@gmail.com", - "homepage": "https://github.com/schmittjoh" - }, - { - "name": "Graham Campbell", - "email": "hello@gjcampbell.co.uk", - "homepage": "https://github.com/GrahamCampbell" - } - ], - "description": "Option Type for PHP", - "keywords": [ - "language", - "option", - "php", - "type" - ], - "support": { - "issues": "https://github.com/schmittjoh/php-option/issues", - "source": "https://github.com/schmittjoh/php-option/tree/1.9.1" - }, - "funding": [ - { - "url": "https://github.com/GrahamCampbell", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", - "type": "tidelift" - } - ], - "time": "2023-02-25T19:38:58+00:00" - }, - { - "name": "symfony/polyfill-ctype", - "version": "v1.27.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "5bbc823adecdae860bb64756d639ecfec17b050a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/5bbc823adecdae860bb64756d639ecfec17b050a", - "reference": "5bbc823adecdae860bb64756d639ecfec17b050a", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "provide": { - "ext-ctype": "*" - }, - "suggest": { - "ext-ctype": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.27-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Ctype\\": "" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Gert de Pagter", - "email": "BackEndTea@gmail.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for ctype functions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "ctype", - "polyfill", - "portable" - ], - "support": { - "source": "https://github.com/symfony/polyfill-ctype/tree/v1.27.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2022-11-03T14:55:06+00:00" - }, - { - "name": "symfony/polyfill-mbstring", - "version": "v1.27.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/8ad114f6b39e2c98a8b0e3bd907732c207c2b534", - "reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "provide": { - "ext-mbstring": "*" - }, - "suggest": { - "ext-mbstring": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.27-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Mbstring\\": "" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for the Mbstring extension", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "mbstring", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.27.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2022-11-03T14:55:06+00:00" - }, - { - "name": "symfony/polyfill-php80", - "version": "v1.27.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", - "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.27-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Php80\\": "" - }, - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ion Bazan", - "email": "ion.bazan@gmail.com" - }, - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.27.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2022-11-03T14:55:06+00:00" - }, - { - "name": "vlucas/phpdotenv", - "version": "v5.5.0", - "source": { - "type": "git", - "url": "https://github.com/vlucas/phpdotenv.git", - "reference": "1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7", - "reference": "1a7ea2afc49c3ee6d87061f5a233e3a035d0eae7", - "shasum": "" - }, - "require": { - "ext-pcre": "*", - "graham-campbell/result-type": "^1.0.2", - "php": "^7.1.3 || ^8.0", - "phpoption/phpoption": "^1.8", - "symfony/polyfill-ctype": "^1.23", - "symfony/polyfill-mbstring": "^1.23.1", - "symfony/polyfill-php80": "^1.23.1" - }, - "require-dev": { - "bamarni/composer-bin-plugin": "^1.4.1", - "ext-filter": "*", - "phpunit/phpunit": "^7.5.20 || ^8.5.30 || ^9.5.25" - }, - "suggest": { - "ext-filter": "Required to use the boolean validator." - }, - "type": "library", - "extra": { - "bamarni-bin": { - "bin-links": true, - "forward-command": true - }, - "branch-alias": { - "dev-master": "5.5-dev" - } - }, - "autoload": { - "psr-4": { - "Dotenv\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Graham Campbell", - "email": "hello@gjcampbell.co.uk", - "homepage": "https://github.com/GrahamCampbell" - }, - { - "name": "Vance Lucas", - "email": "vance@vancelucas.com", - "homepage": "https://github.com/vlucas" - } - ], - "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", - "keywords": [ - "dotenv", - "env", - "environment" - ], - "support": { - "issues": "https://github.com/vlucas/phpdotenv/issues", - "source": "https://github.com/vlucas/phpdotenv/tree/v5.5.0" - }, - "funding": [ - { - "url": "https://github.com/GrahamCampbell", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", - "type": "tidelift" - } - ], - "time": "2022-10-16T01:01:54+00:00" - } - ], + "content-hash": "d99f7bada71212307c9485da334476d5", + "packages": [], "packages-dev": [], "aliases": [], "minimum-stability": "stable", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, - "platform": [], + "platform": { + "ext-curl": "*" + }, "platform-dev": [], "plugin-api-version": "2.3.0" } diff --git a/knowyourfood/controllers/AuthController.php b/knowyourfood/controllers/AuthController.php old mode 100644 new mode 100755 index 052974c..15b2999 --- a/knowyourfood/controllers/AuthController.php +++ b/knowyourfood/controllers/AuthController.php @@ -1,70 +1,88 @@ -registerMiddleware(new AuthMiddleware(['profile'])); - } - - public function login(Request $request, Response $response){ - $loginForm = new LoginForm(); - - if($request->isPost()){ - $loginForm->loadData($request->getBody()); - if($loginForm->validate() && $loginForm->login()){ - $response->redirect('home'); - exit; - } - - $this->setLayout('auth'); - return $this->render('login', [ - 'model' => $loginForm - ]); - } - - $this->setLayout('auth'); - return $this->render('login', [ - 'model' => $loginForm - ]); - } - - public function register(Request $request, $response){ - $user = new User(); - - if($request->isPost()){ - $user->loadData($request->getBody()); - - if($user->validate() && $user->save()){ - $response->redirect('home'); - exit; - } - - $this->setLayout('auth'); - return $this->render('register', [ - 'model'=>$user - ]); - } - - $this->setLayout('auth'); - return $this->render('register', [ - 'model'=>$user - ]); - } - - public function logout($request, $response){ - Application::$app->logout(); - $response->redirect('/'); - } - - public function profile(){ - return $this->render('profile'); - } +isPost()){ + $model->loadData($request->getPOSTBody()); + $model->checkForErrors(); + + if($model->hasErrors()){ + self::setControllerParams("Login", "Login", "Auth", $model); + return Application::$app->controller->render(); + } + $model->removeErrors(); + + $body = $model->createBody(); + $headers = $model->createHeaders(json_encode($body)); + + $model->setParametersForRequest("GET", $headers, $body); + + $model->execute(); + if($model->isRequestFulfilled()){ + //Application::$app->response->redirect("homepage"); + } + + $model->setRequestError(); + self::setControllerParams("Login", "Login", "Auth", $model); + return Application::$app->controller->render(); + } + + self::setControllerParams("Login", "Login", "Auth", $model); + return Application::$app->controller->render(); + } + + public static function registerPage(Request $request): string + { + $model = new RegisterModel(); + + if($request->isPost()){ + $model->loadData($request->getPOSTBody()); + $model->checkForErrors(); + + if($model->hasErrors()){ + self::setControllerParams("Register", "Register", "Auth", $model); + return Application::$app->controller->render(); + } + $model->removeErrors(); + + $body = $model->createBody(); + $headers = $model->createHeaders(json_encode($body)); + + $model->setParametersForRequest("PUT", $headers, $body); + + $model->execute(); + if($model->isRequestFulfilled()){ + Application::$app->response->redirect("login"); + } + + $model->setRequestError(); + self::setControllerParams("Register", "Register", "Auth", $model); + return Application::$app->controller->render(); + } + + self::setControllerParams("Register", "Register", "Auth", $model); + return Application::$app->controller->render(); + } + + public static function setControllerParams(string $title, string $view, string $layout, ?Model $model): void + { + Application::$app->controller->setLayout($layout); + Application::$app->controller->setModel($model); + Application::$app->controller->setTitle($title); + Application::$app->controller->setView($view); + } } \ No newline at end of file diff --git a/knowyourfood/controllers/SiteController.php b/knowyourfood/controllers/SiteController.php new file mode 100755 index 0000000..366fae9 --- /dev/null +++ b/knowyourfood/controllers/SiteController.php @@ -0,0 +1,47 @@ +render(); + } + + public function profile(): string + { + return $this->render('profile'); + } + + public static function renderMainPage(): string + { + Application::$app->view->setLayout('Main'); + return Application::$app->view->renderLayout(); + } + + public function _404(): string + { + return $this->render(); + } + + public function _403(): string + { + return $this->render(); + } + + protected static function setControllerParams(string $title, string $view, string $layout, ?Model $model) + { + // TODO: Implement setControllerParams() method. + } +} \ No newline at end of file diff --git a/knowyourfood/controllers/siteController.php b/knowyourfood/controllers/siteController.php deleted file mode 100644 index bc8dc36..0000000 --- a/knowyourfood/controllers/siteController.php +++ /dev/null @@ -1,55 +0,0 @@ -isPost()) { - $contact->loadData($request->getBody()); - - if ($contact->validate() && $contact->send()) { - Application::$app->session->setFlash('success', 'The form has been succesfully sent!'); - var_dump($_SESSION['flash_messages']); - $response->redirect('contact'); - exit; - } - - return $this->render('contact', [ - 'model' => $contact - ]); - } - - return $this->render('contact', [ - 'model' => $contact - ]); - } - - public function home() - { - $params = [ - 'name' => "TheCodeholic" - ]; - - return $this->render('home', $params); - } - - public function profile() - { - return $this->render('profile'); - } - - public function _404() - { - return $this->render('_404'); - } -} \ No newline at end of file diff --git a/knowyourfood/core/Application.php b/knowyourfood/core/Application.php old mode 100644 new mode 100755 index 9f414fd..358a2b2 --- a/knowyourfood/core/Application.php +++ b/knowyourfood/core/Application.php @@ -1,93 +1,42 @@ -userClass = $config['userClass']; - self::$app = $this; - - $this->request = new Request(); - $this->response = new Response(); - $this->router = new Router($this->request, $this->response); - $this->view = new View(); - - $this->db = new Database($config['db']); - $this->session = new Session(); - - $primaryValue = $this->session->get('user'); - if ($primaryValue) { - $userObj = new $this->userClass(); - $primaryKey = $userObj->primaryKey(); - $this->user = $userObj->findOne([$primaryKey => $primaryValue]); - } else { - $this->user = null; - } - } - - public function setController($controller) - { - $this->controller = $controller; - } - - public function getController() - { - return $this->controller; - } - - public function login(DbModel $user) - { - $this->user = $user; - $primaryKey = $user->primaryKey(); - $primaryValue = $user->{$primaryKey}; - $this->session->set('user', $primaryValue); - return true; - } - - public function logout() - { - $this->user = null; - $this->session->remove('user'); - } - - public static function isLoggedIn() - { - return !self::$app->user; - } - - public function run() - { - try{ - echo $this->router->resolve(); - }catch(ForbiddenException $e){ - $this->response->setStatusCode(403); - echo $this->view->renderView('_error', [ - 'exception' => $e - ]); - }catch(NotFoundException $e){ - $this->response->setStatusCode(404); - echo $this->view->renderView('_error', [ - 'exception' => $e - ]); - } - } +request = new Request(); + $this->response = new Response(); + $this->router = new Router($this->request); + $this->view = new View(); + $this->session = new Session(); + } + + public function run(): void + { + try{ + echo $this->router->resolve(); + }catch(ForbiddenAccessException $e){ + + }catch(PageNotFoundException $e){ + + } + } } \ No newline at end of file diff --git a/knowyourfood/core/Controller.php b/knowyourfood/core/Controller.php old mode 100644 new mode 100755 index 39577ca..39f940e --- a/knowyourfood/core/Controller.php +++ b/knowyourfood/core/Controller.php @@ -1,26 +1,26 @@ -view->renderView($view, $params); - } - - public function setLayout($layout){ - $this->layout = $layout; - } - - public function registerMiddleware(BaseMiddleware $middleware){ - $this->middlewares[] = $middleware; - } - - public function getMiddlewares(){ - return $this->middlewares; - } +view->setLayout($this->layout); + Application::$app->view->setTitle($this->title); + Application::$app->view->setView($this->view); + Application::$app->view->setModel($this->model); + + return Application::$app->view->render(); + } + + protected static abstract function setControllerParams(string $title, string $view, string $layout, ?Model $model); + + public function setView(string $view): void {$this->view = $view;} + public function setTitle(string $title): void {$this->title = $title;} + public function setLayout(string $layout): void {$this->layout = $layout;} + public function setModel(?Model $model): void {$this->model = $model;} } \ No newline at end of file diff --git a/knowyourfood/core/DVC.php b/knowyourfood/core/DVC.php new file mode 100755 index 0000000..76ed874 --- /dev/null +++ b/knowyourfood/core/DVC.php @@ -0,0 +1,96 @@ + [ + DVC::$returnCode => 460, + DVC::$returnMessage => "Operation done successfully" + ], + DVC::$genericExceptionName => [ + DVC::$returnCode => 461, + DVC::$returnMessage => "Internal Server Error" + ], + DVC::$invalidTokenName => [ + DVC::$returnCode => 462, + DVC::$returnMessage => "Unauthorized access" + ], + DVC::$invalidRequestName => [ + DVC::$returnCode => 463, + DVC::$returnMessage => "Service doesn't provide this type of request" + ], + DVC::$invalidBodyName => [ + DVC::$returnCode => 464, + DVC::$returnMessage => "Not valid parameters sent" + ], + DVC::$alreadyExistsName => [ + + DVC::$returnCode => 465, + DVC::$returnMessage => "Field already existing" + ], + DVC::$fieldNotExistingName => [ + DVC::$returnCode => 466, + DVC::$returnMessage => "Field not existing anymore" + ], + DVC::$invalidCurlStructureName => [ + DVC::$returnCode => 467, + DVC::$returnMessage => "cURL class needs URL, request method and headers to run" + ], + DVC::$userNotExistingName => [ + DVC::$returnCode => 468, + DVC::$returnMessage => "User account doesn't exists" + ], + DVC::$pageNotFoundName => [ + DVC::$returnCode => 469, + DVC::$returnMessage => "Page not found" + ], + DVC::$forbiddenAccessName => [ + DVC::$returnCode => 470, + DVC::$returnMessage => "You are not authorised to access this page" + ], + DVC::$serviceNotFoundName => [ + DVC::$returnCode => 471, + DVC::$returnCode => "Service not existing" + ] + }; + } + + public static function getHttpCodeWithCode(int $code): int + { + return match ($code){ + 460 => 200, + 461 => 500, + 462 => 401, + 463 => 405, + 464 => 400, + 465, 466 => 204, + 467 => 409, + 468, 469, 471 => 404, + 470 => 403, + default => 100 + }; + } +} \ No newline at end of file diff --git a/knowyourfood/core/Database.php b/knowyourfood/core/Database.php old mode 100644 new mode 100755 index ba3a5bd..e1de97d --- a/knowyourfood/core/Database.php +++ b/knowyourfood/core/Database.php @@ -1,78 +1,78 @@ -pdo = new \PDO($dsn, $user, $password); - $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - } - - public function applyMigrations(){ - $this->createMigrationsTable(); - $appliedMigrations = $this->getAppliedMigrations(); - - $newMigrations = []; - $files = scandir(Application::$ROOT_DIR.'/migrations'); - $toApplyMigrations = array_diff($files, $appliedMigrations); - - foreach($toApplyMigrations as $migration){ - if($migration === '.' || $migration === '..'){ - continue; - } - - require_once Application::$ROOT_DIR.'/migrations/'.$migration; - $className = pathinfo($migration, PATHINFO_FILENAME); - - $instance = new $className(); - $this->log("Applying migration $migration" . PHP_EOL); - $instance->up(); - $this->log("Applied migration $migration" . PHP_EOL); - - $newMigrations[] = $migration; - } - - if(!empty($newMigrations)){ - $this->saveMigrations($newMigrations); - }else{ - $this->log('All migrations are applied'); - } - } - - public function createMigrationsTable(){ - $this->pdo->exec(" - CREATE TABLE IF NOT EXISTS migrations ( - id INT AUTO_INCREMENT, - migration varchar(255), - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (id) - ) - ENGINE=INNODB;"); - } - - public function getAppliedMigrations(){ - $statement = $this->pdo->prepare("SELECT migration FROM migrations"); - $statement->execute(); - - return $statement->fetchAll(\PDO::FETCH_COLUMN); - } - - public function saveMigrations(array $migrations){ - $str = implode(",", array_map(fn($m) => "('$m')", $migrations)); - $statement = $this->pdo->prepare("INSERT INTO migrations (migration) VALUES $str"); - $statement->execute(); - } - - public function prepare($sql){ - return $this->pdo->prepare($sql); - } - - protected function log($message){ - echo '['.date('Y-m-d H:i:s').'] - '.$message.PHP_EOL; - } +pdo = new \PDO($dsn, $user, $password); + $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + } + + public function applyMigrations(){ + $this->createMigrationsTable(); + $appliedMigrations = $this->getAppliedMigrations(); + + $newMigrations = []; + $files = scandir(Application::$ROOT_DIR.'/migrations'); + $toApplyMigrations = array_diff($files, $appliedMigrations); + + foreach($toApplyMigrations as $migration){ + if($migration === '.' || $migration === '..'){ + continue; + } + + require_once Application::$ROOT_DIR.'/migrations/'.$migration; + $className = pathinfo($migration, PATHINFO_FILENAME); + + $instance = new $className(); + $this->log("Applying migration $migration" . PHP_EOL); + $instance->up(); + $this->log("Applied migration $migration" . PHP_EOL); + + $newMigrations[] = $migration; + } + + if(!empty($newMigrations)){ + $this->saveMigrations($newMigrations); + }else{ + $this->log('All migrations are applied'); + } + } + + public function createMigrationsTable(){ + $this->pdo->exec(" + CREATE TABLE IF NOT EXISTS migrations ( + id INT AUTO_INCREMENT, + migration varchar(255), + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id) + ) + ENGINE=INNODB;"); + } + + public function getAppliedMigrations(){ + $statement = $this->pdo->prepare("SELECT migration FROM migrations"); + $statement->execute(); + + return $statement->fetchAll(\PDO::FETCH_COLUMN); + } + + public function saveMigrations(array $migrations){ + $str = implode(",", array_map(fn($m) => "('$m')", $migrations)); + $statement = $this->pdo->prepare("INSERT INTO migrations (migration) VALUES $str"); + $statement->execute(); + } + + public function prepare($sql){ + return $this->pdo->prepare($sql); + } + + protected function log($message){ + echo '['.date('Y-m-d H:i:s').'] - '.$message.PHP_EOL; + } } \ No newline at end of file diff --git a/knowyourfood/core/DbModel.php b/knowyourfood/core/DbModel.php deleted file mode 100644 index b6928c0..0000000 --- a/knowyourfood/core/DbModel.php +++ /dev/null @@ -1,51 +0,0 @@ -tableName(); - $attributes = $this->attributes(); - $params = array_map(fn($attr) => ":$attr", $attributes); - - $statement = self::prepare("INSERT INTO $tableName (" - .implode(',', $attributes) - .") VALUES (" - .implode(',', $params) - .")" - ); - - foreach($attributes as $attribute){ - $statement->bindValue(":$attribute", $this->{$attribute}); - } - - $statement->execute(); - return true; - } - - public static function prepare($sql){ - return Application::$app->db->pdo->prepare($sql); - } - - public function findOne($where){ - $tableName = static::tableName(); - $attributes = array_keys($where); - - $sql = implode("AND ", array_map(fn($attr) => "$attr = :$attr", $attributes)); - $statement = self::prepare("SELECT * from $tableName WHERE $sql"); - - foreach($where as $key => $item){ - $statement->bindValue(":$key", $item); - } - - $statement->execute(); - - return $statement->fetchObject(static::class); - } -} \ No newline at end of file diff --git a/knowyourfood/core/Model.php b/knowyourfood/core/Model.php old mode 100644 new mode 100755 index 250c137..143a678 --- a/knowyourfood/core/Model.php +++ b/knowyourfood/core/Model.php @@ -1,104 +1,119 @@ - $value){ - if(property_exists($this, $key)){ - $this->{$key} = $value; - } - } - } - - abstract public function rules():array; - - public function labels(): array{ - return []; - } - - public array $errors = []; - - private function addErrorForRule(string $attribute, string $rule, $params =[]){ - $message = $this->errorMessages()[$rule] ?? ''; - foreach($params as $key => $value){ - $message = str_replace("{{$key}}", $value, $message); - } - - $this->errors[$attribute][] = $message; - } - - public function addError(string $attribute, string $message){ - $this->errors[$attribute][] = $message; - } - - public function errorMessages(){ - return [ - self::RULE_REQUIRED => 'This field is required', - self::RULE_EMAIL => 'This field must be valid email address', - self::RULE_MIN => 'Min length of this field must be {min}', - self::RULE_MAX => 'Max length of this field must be {max}', - self::RULE_UNIQUE => 'Email already exists' - ]; - } - - public function validate(){ - foreach($this->rules() as $attribute => $rules){ - $value = $this->{$attribute}; - foreach($rules as $rule){ - $ruleName = $rule; - - if(!is_string($ruleName)){ - $ruleName = $rule[0]; - } - - if($ruleName === self::RULE_REQUIRED && !$value){ - $this->addErrorForRule($attribute, self::RULE_REQUIRED); - } - - if($ruleName === self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)){ - $this->addErrorForRule($attribute, self::RULE_EMAIL); - } - - if($ruleName === self::RULE_MIN && strlen($value) < $rule['min']){ - $this->addErrorForRule($attribute, self::RULE_MIN, $rule); - } - - if($ruleName === self::RULE_MAX && strlen($value) > $rule['max']){ - $this->addErrorForRule($attribute, self::RULE_MAX, $rule); - } - - if($ruleName === self::RULE_UNIQUE){ - $className = $rule['class']; - $uniqueAttr = $rule['attirubute'] ?? $attribute; - $tableName = $className::tableName(); - - $statement = Application::$app->db->prepare(("SELECT * FROM $tableName WHERE $uniqueAttr = :attr")); - $statement->bindValue(":attr", $value); - $statement->execute(); - $record = $statement->fetchObject(); - - if($record){ - $this->addErrorForRule($attribute, SELF::RULE_UNIQUE); - } - } - } - } - - return empty($this->errors); - } - - public function hasError($attribute){ - return $this->errors[$attribute] ?? false; - } - - public function getFirstError($attribute){ - return $this->errors[$attribute][0] ?? ''; - } + $value){ + if(property_exists($this, $key)){ + $this->{$key} = $value; + } + } + } + abstract public function rules(): array; + public abstract function labels(): array; + public function errorMessages(): array{ + return [ + self::RULE_REQUIRED => 'This field is required', + self::RULE_EMAIL => 'This field must be a valid email address', + ]; + } + + public function checkForErrors(): void{ + foreach($this->rules() as $field => $rules){ + $value = $this->{$field}; + foreach ($rules as $rule){ + if($rule == self::RULE_REQUIRED && !strlen($value)) { + $this->addError($field, $this->errorMessages()[$rule]); + break; + } + + if($rule == self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)) { + $this->addError($field, $this->errorMessages()[$rule]); + break; + } + } + } + } + + protected abstract function createBody(): array; + protected abstract function createHeaders(string $body): array; + protected abstract function formatHeaderArray(array $headers): array; + public function setParametersForRequest(string $request, array $headers, array $body): void + { + $this->request = $request; + $this->headers = $headers; + $this->body = $body; + } + + public function execute(): void + { + $requestBuilder = new CurlRequestBuilder(); + + $requestBuilder->setRequest($this->request); + $requestBuilder->setUrl($this->url); + $requestBuilder->setHeaders($this->headers); + $requestBuilder->setBody($this->body); + $requestBuilder->setIsReturnable(true); + + $curl = $requestBuilder->getCurlRequestObject(); + $response = json_decode($curl->makeRequest(), true); + + $this->code = $response["code"]; + $this->message = $response["message"]; + } + + public function isRequestFulfilled(): bool + { + return $this->code == DVC::$successReturnCode; + } + + public function setRequestError(): void + { + Application::$app->view->setActionError($this->message); + } + + + public function addError($attribute, $message): void + { + $this->errors[$attribute] = $message; + } + + public function removeErrors(): void + { + unset($this->errors); + $this->errors = array(); + } + + public function hasErrors(): bool + { + return count($this->errors); + } + + public function getError($field): ?string + { + return array_key_exists($field, $this->errors) ? $this->errors[$field] : NULL; + } + + public function getValueForField($field):string + { + return $this->{$field}; + } } \ No newline at end of file diff --git a/knowyourfood/core/Request.php b/knowyourfood/core/Request.php old mode 100644 new mode 100755 index b59f214..d7841b2 --- a/knowyourfood/core/Request.php +++ b/knowyourfood/core/Request.php @@ -1,54 +1,54 @@ -lengthOfRoot = strlen('knowyourfood') + 1; - } - - public function getPath(){//identificam din URL pe pagina trebuie accesata - $path = $_SERVER['REQUEST_URI']; - $path = substr($path, $this->lengthOfRoot); - - $position = strpos($path, '?'); - - if(!$position){ - return $path; - } - - return substr($path, 0, $position); - } - - public function method(){ - return strtolower($_SERVER['REQUEST_METHOD']); - } - - public function isGet(){ - return $this->method() === 'get'; - } - - public function isPost(){ - return $this->method() === 'post'; - } - - //bazat pe tipul de request, accesam tuplele key/value pentru a identifica body ul requestului - public function getBody(){ - $body = []; - if($this->method() === 'get'){ - foreach($_GET as $key => $value){ - $body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS); - } - } - - if($this->method() === 'post'){ - foreach($_POST as $key => $value){ - $body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS); - } - } - - return $body; - } +method() === 'GET'){ + foreach($_GET as $key => $value){ + $body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS); + } + } + + return $body; + } + + public function getPOSTBody(): ?array + { + $body = []; + + if($this->method() === 'POST'){ + foreach($_POST as $key => $value){ + $body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS); + } + } + + return $body; + } } \ No newline at end of file diff --git a/knowyourfood/core/Response.php b/knowyourfood/core/Response.php old mode 100644 new mode 100755 index 27487ed..99adb04 --- a/knowyourfood/core/Response.php +++ b/knowyourfood/core/Response.php @@ -1,13 +1,13 @@ -request = $request; - $this->response = $response; - } - - public function get($path, $callback) - { - $this->routes['get'][$path] = $callback; - } - - public function post($path, $callback) - { - $this->routes['post'][$path] = $callback; - } - - public function resolve() - { - $path = $this->request->getPath(); - $method = $this->request->method(); - $callback = $this->routes[$method][$path] ?? false; - - if (!$callback) { - throw new NotFoundException(); - } - - $controller = new $callback[0](); - Application::$app->controller = $controller; - $controller->action = $callback[1]; - $callback[0] = $controller; - - foreach ($controller->getMiddlewares() as $middleware) { - $middleware->execute(); - } - - return call_user_func($callback, $this->request, $this->response); - } +request = $request; + } + + public function get($path, $callback): void + { + $this->routes['GET'][$path] = $callback; + } + + public function post($path, $callback): void + { + $this->routes['POST'][$path] = $callback; + } + + /** + * @throws PageNotFoundException + */ + public function resolve() + { + $path = $this->request->getPath(); + $method = $this->request->method(); + $callback = $this->routes[$method][$path] ?? false; + + if (!$callback) { + throw new PageNotFoundException(); + } + + Application::$app->controller = new $callback[0](); + + /* + * TODO: + * de adaugat aici middleware urile asociate unui controller + */ + + return call_user_func($callback, $this->request); + } } \ No newline at end of file diff --git a/knowyourfood/core/Session.php b/knowyourfood/core/Session.php old mode 100644 new mode 100755 index 84c7679..da0de53 --- a/knowyourfood/core/Session.php +++ b/knowyourfood/core/Session.php @@ -1,48 +1,7 @@ - &$flashMessage){ - $flashMessage['remove'] = 'true'; - } - } - - public function setFlash($key, $message){ - $_SESSION[self::FLASH_KEY][$key] = [ - 'value' => $message, - 'remove' => 'false' - ]; - } - - public function getFlash($key){ - return $_SESSION[self::FLASH_KEY][$key]['value'] ?? false; - } - - public function set($key, $value){ - $_SESSION[$key] = $value; - } - - public function get($key){ - return $_SESSION[$key]; - } - - public function remove($key){ - unset($_SESSION[$key]); - } - - public function __destruct(){ - $flashMessages = $_SESSION[self::FLASH_KEY] ?? []; - foreach($flashMessages as $key => &$flashMessage){ - if($flashMessage['remove'] == 'true'){ - unset($flashMessages[$key]); - } - } - - $_SESSION[self::FLASH_KEY] = $flashMessages; - } +layout; - if (Application::$app->controller) { - $layout = Application::$app->controller->layout; - } - - ob_start(); - include_once Application::$ROOT_DIR . "/views/layouts/$layout.php"; - return ob_get_clean(); - } - - - public function renderView($view, $params = []) - { - $viewContent = $this->renderOnlyView($view, $params); - $layoutContent = $this->layoutContent(); - - return str_replace('{{content}}', $viewContent, $layoutContent); - } - - public function renderContent($viewContent) - { - $layoutContent = $this->layoutContent(); - return str_replace('{{content}}', $viewContent, $layoutContent); - } - - protected function renderOnlyView($view, $params) - { - foreach ($params as $key => $value) { - $$key = $value; - } - - ob_start(); - include_once Application::$ROOT_DIR."/views/$view.php"; - return ob_get_clean(); - } +renderView(); + $layoutContent = $this->renderLayout(); + + return str_replace('{{content}}', $viewContent, $layoutContent); + } + + public function renderView(): string + { + ob_start(); + include_once Application::$ROOT_DIR . "/views/$this->view.php"; + return ob_get_clean(); + } + + public function renderLayout(): string + { + ob_start(); + include_once Application::$ROOT_DIR . "/views/layouts/HTML/$this->layout.php"; + return ob_get_clean(); + } + + public function setLayout($layout): void {$this->layout = $layout;} + public function setTitle($title): void {$this->title = $title;} + public function setView($view): void {$this->view = $view;} + public function setModel(?Model $model): void {$this->model = $model;} + public function setActionError(string $actionError): void {$this->actionError = $actionError;} + + public function getTitle(): string {return $this->title;} + public function getView(): string {return $this->view;} + public function getLayout(): string {return $this->layout;} + public function getModel(): ?Model {return $this->model;} + public function getActionError(): string {return $this->actionError;} } \ No newline at end of file diff --git a/knowyourfood/core/exceptions/ForbiddenException.php b/knowyourfood/core/exceptions/ForbiddenException.php deleted file mode 100644 index b6ed42a..0000000 --- a/knowyourfood/core/exceptions/ForbiddenException.php +++ /dev/null @@ -1,8 +0,0 @@ -model = $model; - $this->attribute = $attribute; - } - - abstract public function renderInput(): string; - - public function __toString() - { - return sprintf(' -
- - %s -
- %s -
-
- ', - $this->model->labels()[$this->attribute] ?? $this->attribute, - $this->renderInput(), - $this->model->getFirstError($this->attribute) - ); - } -} \ No newline at end of file diff --git a/knowyourfood/core/form/Button.php b/knowyourfood/core/form/Button.php old mode 100644 new mode 100755 index e7fe40a..60be67e --- a/knowyourfood/core/form/Button.php +++ b/knowyourfood/core/form/Button.php @@ -1,12 +1,12 @@ -Submit - ', - ); - } +Submit + ', + ); + } } \ No newline at end of file diff --git a/knowyourfood/core/form/Field.php b/knowyourfood/core/form/Field.php deleted file mode 100644 index 2d7379b..0000000 --- a/knowyourfood/core/form/Field.php +++ /dev/null @@ -1,43 +0,0 @@ -type = self::TYPE_TEXT; - $this->model = $model; - $this->attribute = $attribute; - } - - public function __toString(){ - return sprintf(' -
- - -
- %s -
-
- ', - $this->model->labels()[$this->attribute] ?? $this->attribute, - $this->type, - $this->attribute, - $this->model->{$this->attribute}, - $this->model->hasError($this->attribute) ? ' is invalid' : '', - $this->model->getFirstError($this->attribute) - ); - } - - public function passwordField(){ - $this->type = self::TYPE_PASSWORD; - return $this; - } -} \ No newline at end of file diff --git a/knowyourfood/core/form/Form.php b/knowyourfood/core/form/Form.php old mode 100644 new mode 100755 index bbadec2..cfc9713 --- a/knowyourfood/core/form/Form.php +++ b/knowyourfood/core/form/Form.php @@ -1,23 +1,31 @@ -', $action, $method); - return new Form(); - } - - public static function end(){ - echo ''; - } - - public function inputField(Model $model, $attribute){ - return new InputField($model, $attribute); - } - - public function button(){ - return new Button(); - } +formDestinationPage = $formDestinationPage; + } + public function beginForm(): void + { + echo "
"; + } + + public function endForm(): void + { + echo "
"; + } + + public function renderInputField(string $type, string $name, string $placeholder, string $value, ?string $error): void + { + echo new InputField($type, $name, $placeholder, $value, $error); + } + + public function renderButton(): void + { + echo new Button(); + } } \ No newline at end of file diff --git a/knowyourfood/core/form/InputField.php b/knowyourfood/core/form/InputField.php old mode 100644 new mode 100755 index d370de7..1db8935 --- a/knowyourfood/core/form/InputField.php +++ b/knowyourfood/core/form/InputField.php @@ -1,36 +1,42 @@ -type = self::TYPE_TEXT; - parent::__construct($model, $attribute); - } - - public function passwordField() - { - $this->type = self::TYPE_PASSWORD; - return $this; - } - - public function renderInput(): string - { - return sprintf( - '', - $this->type, - $this->attribute, - $this->model->{$this->attribute}, - $this->model->hasError($this->attribute) ? ' is invalid' : '' - ); - } +type = $this->getInputType($type); + $this->name = $name; + $this->placeholder = $placeholder; + $this->value = $value; + $this->error = $error; + } + public function __toString():string + { + $field = sprintf( + '', + $this->type, $this->name, $this->placeholder, $this->value + ); + + $errorField = NULL; + if(!$this->error == NULL){ + $errorField = sprintf('

%s

', $this->error); + } + + return $field.$errorField; + } + + private function getInputType(string $type): string{ + return match($type){ + "username", "email" => "text", + "password" => "password" + }; + } } \ No newline at end of file diff --git a/knowyourfood/core/form/Region.php b/knowyourfood/core/form/Region.php new file mode 100755 index 0000000..a2f35f2 --- /dev/null +++ b/knowyourfood/core/form/Region.php @@ -0,0 +1,40 @@ +type = self::TYPE_TEXT; + parent::__construct($model, $attribute); + } + + public function startSelect(): string + { + return sprintf(''; + } + + public function renderInput(): string + { + return $this->startSelect().$this->content().$this->endSelect(); + } +} \ No newline at end of file diff --git a/knowyourfood/core/form/TextareaField.php b/knowyourfood/core/form/TextareaField.php old mode 100644 new mode 100755 index 43baa3d..888e678 --- a/knowyourfood/core/form/TextareaField.php +++ b/knowyourfood/core/form/TextareaField.php @@ -1,13 +1,13 @@ -%s', - $this->attribute, - $this->model->hasError($this->attribute) ? ' is invalid' : '', - $this->model->{$this->attribute} - ); - } +%s', + $this->attribute, + $this->model->hasError($this->attribute) ? ' is invalid' : '', + $this->model->{$this->attribute} + ); + } } \ No newline at end of file diff --git a/knowyourfood/core/middlewares/AuthMiddleware.php b/knowyourfood/core/middlewares/AuthMiddleware.php deleted file mode 100644 index aa6a702..0000000 --- a/knowyourfood/core/middlewares/AuthMiddleware.php +++ /dev/null @@ -1,21 +0,0 @@ -actions = $actions; - } - - public function execute(){ - if(Application::isLoggedIn()){ - if(empty($this->actions) || in_array(Application::$app->controller->action, $this->actions)){ - throw new ForbiddenException; - } - } - } -} \ No newline at end of file diff --git a/knowyourfood/core/middlewares/BaseMiddleware.php b/knowyourfood/core/middlewares/BaseMiddleware.php deleted file mode 100644 index 4bb4ec1..0000000 --- a/knowyourfood/core/middlewares/BaseMiddleware.php +++ /dev/null @@ -1,7 +0,0 @@ -url = $url; + $this->request = $request; + $this->headers = $headers; + $this->body = $body; + $this->isReturnable = $isReturnable; + } + + /** + * @throws GenericErrorException + */ + public function makeRequest(): string + { + $curl = curl_init(); + $this->setCurlBody($curl); + + $response = curl_exec($curl); + if(!$response){ + throw new GenericErrorException(); + } + curl_close($curl); + + return $response; + } + + public function setCurlBody(\CurlHandle &$curl): void + { + curl_setopt($curl, CURLOPT_URL, $this->url); + curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers); + + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->request); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, $this->isReturnable); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + + curl_setopt($curl,CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->body)); + } +} \ No newline at end of file diff --git a/knowyourfood/external_requests/CurlRequestBuilder.php b/knowyourfood/external_requests/CurlRequestBuilder.php new file mode 100755 index 0000000..333d462 --- /dev/null +++ b/knowyourfood/external_requests/CurlRequestBuilder.php @@ -0,0 +1,37 @@ +url = $url;} + public function setHeaders(?array $headers): void{$this->headers = $headers;} + public function setRequest(?string $request): void{$this->request = $request;} + public function setBody(?array $body): void{$this->body = $body;} + public function setIsReturnable(?bool $isReturnable): void{$this->isReturnable = $isReturnable;} + + private function areMainParametersNotSet(): bool{ + return $this->url == NULL || $this->request == NULL || $this->headers == NULL; + } + + /** + * @throws InvalidCurlStructureException + */ + public function getCurlRequestObject(): CurlRequest{ + if($this->areMainParametersNotSet()){ + throw new InvalidCurlStructureException("Invalid structure for making a request"); + } + + return new CurlRequest($this->url, $this->request, $this->headers, $this->body, $this->isReturnable); + } +} \ No newline at end of file diff --git a/knowyourfood/index.php b/knowyourfood/index.php old mode 100644 new mode 100755 index 2533f16..8858009 --- a/knowyourfood/index.php +++ b/knowyourfood/index.php @@ -1,41 +1,25 @@ -router->get('/', [SiteController::class, '/']); - -$app->router->get('/home', [SiteController::class, 'home']); - -$app->router->get('/_404', [SiteController::class, '_404']); - -$app->router->get('/contact', [SiteController::class, 'contact']); -$app->router->post('/contact', [SiteController::class, 'contact']); - -$app->router->get('/login', [AuthController::class, 'login']); -$app->router->post('/login', [AuthController::class, 'login']); - -$app->router->get('/register', [AuthController::class, 'register']); -$app->router->post('/register', [AuthController::class, 'register']); - -$app->router->get('/profile', [AuthController::class, 'profile']); -$app->router->post('/profile', [AuthController::class, 'profile']); - -$app->router->get('/logout', [AuthController::class, 'logout']); - -$app->router->get('/login/{id}', [SiteController::class, 'login']); - -$app->run(); +router->get('/', [SiteController::class, 'renderMainPage']); +$app->router->get('/homepage', [SiteController::class, 'homepage']); + +$app->router->get('/login', [AuthController::class, 'loginPage']); +$app->router->post('/login', [AuthController::class, 'loginPage']); + +$app->router->get('/register', [AuthController::class, 'registerPage']); +$app->router->post('/register', [AuthController::class, 'registerPage']); + +$app->router->get('/profile', [AuthController::class, 'profile']); +$app->router->post('/profile', [AuthController::class, 'profile']); + +$app->router->get('/logout', [AuthController::class, 'logout']); + +$app->run(); \ No newline at end of file diff --git a/knowyourfood/migrations.php b/knowyourfood/migrations.php deleted file mode 100644 index 8924ef1..0000000 --- a/knowyourfood/migrations.php +++ /dev/null @@ -1,10 +0,0 @@ -db->applyMigrations(); diff --git a/knowyourfood/migrations/m01_initial.php b/knowyourfood/migrations/m01_initial.php deleted file mode 100644 index 3e5fef3..0000000 --- a/knowyourfood/migrations/m01_initial.php +++ /dev/null @@ -1,25 +0,0 @@ -db; - $SQL = "CREATE TABLE users( - id INT AUTO_INCREMENT, - email VARCHAR(255) NOT NULL, - firstname VARCHAR(255) NOT NULL, - lastname VARCHAR(255) NOT NULL, - status TINYINT NOT NULL, - create_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (id) - ) Engine=INNODB; - "; - $db->pdo->exec($SQL); - } - - public function down(){ - $db = Application::$app->db; - $SQL = "DROP TABLE users"; - $db->pdo->exec($SQL); - } -} \ No newline at end of file diff --git a/knowyourfood/migrations/m02_add_password_column.php b/knowyourfood/migrations/m02_add_password_column.php deleted file mode 100644 index 5061466..0000000 --- a/knowyourfood/migrations/m02_add_password_column.php +++ /dev/null @@ -1,17 +0,0 @@ -db; - $SQL = "ALTER TABLE users ADD COLUMN password VARCHAR(512) NOT NULL"; - $db->pdo->exec($SQL); - } - - public function down(){ - $db = Application::$app->db; - $SQL = "ALTER TABLE users DROP COLUMN password"; - $db->pdo->exec($SQL); - } -} \ No newline at end of file diff --git a/knowyourfood/models/ContactForm.php b/knowyourfood/models/ContactForm.php old mode 100644 new mode 100755 index 083c247..a10229a --- a/knowyourfood/models/ContactForm.php +++ b/knowyourfood/models/ContactForm.php @@ -1,28 +1,28 @@ - [self::RULE_REQUIRED], - 'body' => [self::RULE_REQUIRED] - ]; - } - - public function labels(): array{ - return [ - 'subject' => 'Enter your subject', - 'body' => 'Enter the body' - ]; - } - - public function send(){ - return true; - } + [self::RULE_REQUIRED], + 'body' => [self::RULE_REQUIRED] + ]; + } + + public function labels(): array{ + return [ + 'subject' => 'Enter your subject', + 'body' => 'Enter the body' + ]; + } + + public function send(){ + return true; + } } \ No newline at end of file diff --git a/knowyourfood/models/LoginForm.php b/knowyourfood/models/LoginForm.php deleted file mode 100644 index b9e1894..0000000 --- a/knowyourfood/models/LoginForm.php +++ /dev/null @@ -1,40 +0,0 @@ - [self::RULE_REQUIRED, self::RULE_EMAIL], - 'password' => [self::RULE_REQUIRED] - ]; - } - - public function labels():array { - return [ - 'email' => 'Email', - 'password' => 'Password' - ]; - } - - public function login(){ - $user = new User(); - $user = $user->findOne(['email' => $this->email]); - if(!$user){ - $this->addError('email', 'User does not exist with this email'); - return false; - } - - if(!password_verify($this->password, $user->password)){ - $this->addError('password', 'Incorrect password'); - return false; - } - - return Application::$app->login($user); - } -} \ No newline at end of file diff --git a/knowyourfood/models/LoginModel.php b/knowyourfood/models/LoginModel.php new file mode 100755 index 0000000..41a886e --- /dev/null +++ b/knowyourfood/models/LoginModel.php @@ -0,0 +1,58 @@ + [self::RULE_REQUIRED, self::RULE_EMAIL], + 'password' => [self::RULE_REQUIRED] + ]; + } + + public function labels():array + { + return [ + 'email' => 'Email', + 'password' => 'Password' + ]; + } + + + public function createBody(): array + { + $body = array(); + $body["values"] = [ + "email" => $this->email, + "password" => $this->password + ]; + + return $body; + } + + public function createHeaders(string $body): array + { + $headers = array(); + $headers["Content-type"] = "application/json"; + $headers["Content-Length"] = strlen($body); + $headers["Authorization"] = hash('md5', 'api.knowyourfood'); + $headers["Auth-Request"] = "login"; + + return $this->formatHeaderArray($headers); + } + + protected function formatHeaderArray(array $headers): array{ + $array = array(); + + foreach ($headers as $key => $value){ + $array[] = $key . ": " . $value; + } + + return $array; + } +} \ No newline at end of file diff --git a/knowyourfood/models/RegisterModel.php b/knowyourfood/models/RegisterModel.php new file mode 100644 index 0000000..c2cd4ae --- /dev/null +++ b/knowyourfood/models/RegisterModel.php @@ -0,0 +1,59 @@ + [self::RULE_REQUIRED], + 'email' => [self::RULE_REQUIRED, self::RULE_EMAIL], + 'password' => [self::RULE_REQUIRED] + ]; + } + + public function labels():array { + return [ + 'username' => 'Username', + 'email' => 'Email', + 'password' => 'Password', + ]; + } + + public function createBody(): array + { + $body = array(); + $body["values"] = [ + "username" => $this->username, + "email" => $this->email, + "password" => $this->password + ]; + + return $body; + } + + public function createHeaders(string $body): array + { + $headers = array(); + $headers["Content-type"] = "application/json"; + $headers["Content-Length"] = strlen($body); + $headers["Authorization"] = hash('md5', 'api.knowyourfood'); + $headers["Auth-Request"] = "register"; + + return $this->formatHeaderArray($headers); + } + + protected function formatHeaderArray(array $headers): array{ + $array = array(); + + foreach ($headers as $key => $value){ + $array[] = $key . ": " . $value; + } + + return $array; + } +} \ No newline at end of file diff --git a/knowyourfood/models/User.php b/knowyourfood/models/User.php deleted file mode 100644 index 281b244..0000000 --- a/knowyourfood/models/User.php +++ /dev/null @@ -1,53 +0,0 @@ -status = self::STATUS_INACTIVE; - $this->password = password_hash($this->password, PASSWORD_DEFAULT); - return parent::save(); - } - - public function tableName(): string{ - return 'users'; - } - - public function rules(): array{ - return [ - 'firstname' => [self::RULE_REQUIRED], - 'lastname' => [self::RULE_REQUIRED], - 'email' => [self::RULE_REQUIRED, self::RULE_EMAIL, [self::RULE_UNIQUE, 'class' => self::class]], - 'password' => [self::RULE_REQUIRED, [self::RULE_MIN, 'min' => 8], [self::RULE_MAX, 'max' => 15]] - ]; - } - - public function primaryKey(): string{ - return 'id'; - } - - public function labels():array { - return [ - 'firstname' => 'First name', - 'lastname' => 'Last name', - 'email' => 'Email', - 'password' => 'Password' - ]; - } - - public function attributes(): array{ - return ['firstname', 'lastname', 'email', 'password', 'status']; - } -} \ No newline at end of file diff --git a/knowyourfood/runtime/.gitignore b/knowyourfood/runtime/.gitignore old mode 100644 new mode 100755 diff --git a/knowyourfood/views/Login.php b/knowyourfood/views/Login.php new file mode 100644 index 0000000..2b4d5b0 --- /dev/null +++ b/knowyourfood/views/Login.php @@ -0,0 +1,28 @@ +view->getModel(); +$loginError = Application::$app->view->getActionError(); + +if(!$loginError == ''){ + echo "

$loginError

"; +} + +echo '
'; +$form->beginForm(); + +foreach($model->labels() as $key=>$value){ + $form->renderInputField( + $key, $key, $value, $model->getValueForField($key), $model->getError($key) + ); +} + +echo '
'; + +$form->renderButton(); + +$form->endForm(); + diff --git a/knowyourfood/views/Register.php b/knowyourfood/views/Register.php new file mode 100644 index 0000000..0ada2e1 --- /dev/null +++ b/knowyourfood/views/Register.php @@ -0,0 +1,28 @@ +view->getModel(); +$loginError = Application::$app->view->getActionError(); + +if(!$loginError == ''){ + echo "

$loginError

"; +} + +echo '
'; +$form->beginForm(); + +foreach($model->labels() as $key=>$value){ + $form->renderInputField( + $key, $key, $value, $model->getValueForField($key), $model->getError($key) + ); +} + +echo '
'; + +$form->renderButton(); + +$form->endForm(); + diff --git a/knowyourfood/views/_error.php b/knowyourfood/views/_error.php deleted file mode 100644 index 53bbef0..0000000 --- a/knowyourfood/views/_error.php +++ /dev/null @@ -1 +0,0 @@ -

getCode() ?> - getMessage();?>

\ No newline at end of file diff --git a/knowyourfood/views/contact.php b/knowyourfood/views/contact.php deleted file mode 100644 index 63fcce0..0000000 --- a/knowyourfood/views/contact.php +++ /dev/null @@ -1,12 +0,0 @@ -title = 'Contact'; - -$form = Form::begin('', 'post'); -echo $form->inputField($model, 'subject'); -echo new TextareaField($model, 'body'); -echo $form->button(); - -Form::end(); -?> \ No newline at end of file diff --git a/knowyourfood/views/home.php b/knowyourfood/views/home.php deleted file mode 100644 index 8717747..0000000 --- a/knowyourfood/views/home.php +++ /dev/null @@ -1,6 +0,0 @@ -title = 'Home'; -?> - -

Home

-

Welcome to our site!

\ No newline at end of file diff --git a/knowyourfood/views/layouts/CSS/styleAuth.css b/knowyourfood/views/layouts/CSS/styleAuth.css new file mode 100755 index 0000000..48f052d --- /dev/null +++ b/knowyourfood/views/layouts/CSS/styleAuth.css @@ -0,0 +1,148 @@ +*{ + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: 'Josefin Sans', sans-serif; + } + + html, + body{ + height: 100%; + } + + body{ + background-image: url("../Images/background/background.jpg"); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + background-attachment: fixed; + } + + body{ + display: flex; + flex-direction: column; + justify-content: space-evenly; + align-items: center; + } + + h1{ + color: white; + text-shadow: + -1px -1px 0 #000, + 0 -1px 0 #000, + 1px -1px 0 #000, + 1px 0 0 #000, + 1px 1px 0 #000, + 0 1px 0 #000, + -1px 1px 0 #000, + -1px 0 0 #000; + } + + .hr1{ + width: 70%; + } + + .Title{ + margin: 3vh; + margin-top: 0; + font-size: 3rem; + } + + input, button{ + margin: 1rem; + margin-left: 0; + margin-right: 0; + background-color: #60FF8C; + border: 0.1em solid black; + border-radius: 20px; + padding: 1vh; + padding-left: 5vh; + padding-right: 5vh; + min-width: 100%; + cursor: default; + } + + button{ + background-color: #FF5555 + } + + button:hover{ + background-color: #FF2B2B; + cursor: pointer; + } + + .Inputs{ + display: flex; + flex-direction: column; + } + + .Inputs > *, button{ + padding: 1rem; + } + + input[type="radio"]{ + margin:0; + } + + input:focus{ + outline: none; + } + + .LoginButtons{ + width: 70%; + } + + .LoginForm{ + display: flex; + flex-direction: column; + justify-content: center; + width: 100%; + } + + .errorStyle{ + text-align: center; + color: white; + } + + .LoginButtons hr{ + width:100%; + } + + .BigContainer{ + background-color: rgba(0, 0, 0, 0.5); + border-radius: 20px; + position: fixed; + display: flex; + flex-direction: column; + align-items: center; + padding: 2rem; + transform: scale(1); + flex: 100%; + width:50%; + } + + @media screen and (max-width: 800px){ + *{ + overflow: hidden; + } + .BigContainer{ + margin-top: 5vh; + margin-bottom: 5vh; + min-width: 70%; + transform: scale(1); + } + .Inputs > *{ + width: 100%; + } + h1{ + font-size: 1rem; + text-align: center; + } + .LoginButtons{ + width:100%; + } + .hr1{ + width:100%; + } + } + \ No newline at end of file diff --git a/knowyourfood/views/layouts/CSS/styleMain.css b/knowyourfood/views/layouts/CSS/styleMain.css new file mode 100755 index 0000000..d6c0690 --- /dev/null +++ b/knowyourfood/views/layouts/CSS/styleMain.css @@ -0,0 +1,100 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: 'Josefin Sans', sans-serif; +} + +html, +body { + height: 100%; +} + +body { + background-image: url("../Images/background/background.jpg"); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + background-attachment: fixed; +} + +body { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +h1, h3 { + color: white; + text-shadow: -1px -1px 0 #000, 0 -1px 0 #000, 1px -1px 0 #000, 1px 0 0 #000, 1px 1px 0 #000, 0 1px 0 #000, -1px 1px 0 #000, -1px 0 0 #000; +} + +.Title { + margin: 5vh; + font-size: 3rem; +} + +button { + margin: 1rem; + background-color: #60FF8C; + border: 0.1em solid black; + border-radius: 20px; + padding: 1vh; + padding-left: 5vh; + padding-right: 5vh; + max-width: 100%; + cursor: default; + width: 100%; +} + + button:hover { + margin: 1rem; + background-color: #FF5555; + border: 0.1em solid black; + border-radius: 20px; + padding: 1vh; + padding-left: 5vh; + padding-right: 5vh; + max-width: 100%; + cursor: pointer; + width: 100%; + } + +.RegisterButton { + margin-bottom: 0; +} + + .RegisterButton:hover { + margin-bottom: 0; + cursor: pointer; + } + +.LoginButtons { + display: flex; + flex-direction: column; + align-items: center; + margin-bottom: 0; + margin-top: 0; +} + +.BigContainer { + position: fixed; + display: flex; + flex-direction: column; + align-items: center; + justify-content: space-between; + transform: scale(1.5); + flex: 100%; +} + +@media screen and (max-width: 888px) { + .BigContainer { + width: 30%; + } + + h1, h3 { + font-size: 1rem; + text-align: center; + } +} diff --git a/knowyourfood/views/layouts/HTML/Auth.php b/knowyourfood/views/layouts/HTML/Auth.php new file mode 100644 index 0000000..6d409e8 --- /dev/null +++ b/knowyourfood/views/layouts/HTML/Auth.php @@ -0,0 +1,28 @@ + + + + + + + + + /> + + + + <?php echo Application::$app->view->getTitle()?> + + + +
+

view->getTitle()?>

+
+ {{content}} +
+
+ + + \ No newline at end of file diff --git a/knowyourfood/views/layouts/HTML/Main.php b/knowyourfood/views/layouts/HTML/Main.php new file mode 100644 index 0000000..5b20e36 --- /dev/null +++ b/knowyourfood/views/layouts/HTML/Main.php @@ -0,0 +1,28 @@ + + + + + + + + + > + + + + Know Your Food. + + + +
+

Know Your Food.

+
+

If you have an account already

+ +

or

+ +
+
+ + + \ No newline at end of file diff --git a/knowyourfood/views/layouts/Images/admin_files/admin_background.jpg b/knowyourfood/views/layouts/Images/admin_files/admin_background.jpg new file mode 100755 index 0000000..33622d1 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/admin_background.jpg differ diff --git a/knowyourfood/views/layouts/Images/admin_files/admin_background.psd b/knowyourfood/views/layouts/Images/admin_files/admin_background.psd new file mode 100755 index 0000000..e1cc147 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/admin_background.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/dashboard icon.png b/knowyourfood/views/layouts/Images/admin_files/dashboard icon.png new file mode 100755 index 0000000..b182a29 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/dashboard icon.png differ diff --git a/knowyourfood/views/layouts/Images/admin_files/dashboard icon.psd b/knowyourfood/views/layouts/Images/admin_files/dashboard icon.psd new file mode 100755 index 0000000..ccab25e Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/dashboard icon.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/database icon.png b/knowyourfood/views/layouts/Images/admin_files/database icon.png new file mode 100755 index 0000000..2a0eca9 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/database icon.png differ diff --git a/knowyourfood/views/layouts/Images/admin_files/database icon.psd b/knowyourfood/views/layouts/Images/admin_files/database icon.psd new file mode 100755 index 0000000..3457878 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/database icon.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/exit icon.png b/knowyourfood/views/layouts/Images/admin_files/exit icon.png new file mode 100755 index 0000000..2929937 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/exit icon.png differ diff --git a/knowyourfood/views/layouts/Images/admin_files/exit icon.psd b/knowyourfood/views/layouts/Images/admin_files/exit icon.psd new file mode 100755 index 0000000..1018baa Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/exit icon.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/recipes-database.jpg b/knowyourfood/views/layouts/Images/admin_files/recipes-database.jpg new file mode 100755 index 0000000..c4278dc Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/recipes-database.jpg differ diff --git a/knowyourfood/views/layouts/Images/admin_files/recipes-database.psd b/knowyourfood/views/layouts/Images/admin_files/recipes-database.psd new file mode 100755 index 0000000..b558582 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/recipes-database.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/restaurants-database.jpg b/knowyourfood/views/layouts/Images/admin_files/restaurants-database.jpg new file mode 100755 index 0000000..d915390 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/restaurants-database.jpg differ diff --git a/knowyourfood/views/layouts/Images/admin_files/restaurants-database.psd b/knowyourfood/views/layouts/Images/admin_files/restaurants-database.psd new file mode 100755 index 0000000..9de08b9 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/restaurants-database.psd differ diff --git a/knowyourfood/views/layouts/Images/admin_files/user icon.png b/knowyourfood/views/layouts/Images/admin_files/user icon.png new file mode 100755 index 0000000..4f35535 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/user icon.png differ diff --git a/knowyourfood/views/layouts/Images/admin_files/user icon.psd b/knowyourfood/views/layouts/Images/admin_files/user icon.psd new file mode 100755 index 0000000..ce1f0e4 Binary files /dev/null and b/knowyourfood/views/layouts/Images/admin_files/user icon.psd differ diff --git a/knowyourfood/views/layouts/Images/background/backgroudn.psd b/knowyourfood/views/layouts/Images/background/backgroudn.psd new file mode 100755 index 0000000..5f8239e Binary files /dev/null and b/knowyourfood/views/layouts/Images/background/backgroudn.psd differ diff --git a/knowyourfood/views/layouts/Images/background/background.jpg b/knowyourfood/views/layouts/Images/background/background.jpg new file mode 100755 index 0000000..26c3c89 Binary files /dev/null and b/knowyourfood/views/layouts/Images/background/background.jpg differ diff --git a/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.png b/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.png new file mode 100755 index 0000000..c64f7a5 Binary files /dev/null and b/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.png differ diff --git a/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.psd b/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.psd new file mode 100755 index 0000000..0ef7141 Binary files /dev/null and b/knowyourfood/views/layouts/Images/menu_icon/dropdown_menu_icon.psd differ diff --git a/knowyourfood/views/layouts/Images/recipes/recipe.txt b/knowyourfood/views/layouts/Images/recipes/recipe.txt new file mode 100755 index 0000000..5eafef4 --- /dev/null +++ b/knowyourfood/views/layouts/Images/recipes/recipe.txt @@ -0,0 +1,5 @@ +recipe1 - chilli pork +recipe2 - garlic & paprika chicken +recipe3 - garlic butter chicken +recipe4 - Marry Me Chicken +recipe5 - Teriyaki Chicken Noodle \ No newline at end of file diff --git a/knowyourfood/views/layouts/Images/recipes/recipe1.jpg b/knowyourfood/views/layouts/Images/recipes/recipe1.jpg new file mode 100755 index 0000000..f9f6192 Binary files /dev/null and b/knowyourfood/views/layouts/Images/recipes/recipe1.jpg differ diff --git a/knowyourfood/views/layouts/Images/recipes/recipe2.jpg b/knowyourfood/views/layouts/Images/recipes/recipe2.jpg new file mode 100755 index 0000000..e2aa6af Binary files /dev/null and b/knowyourfood/views/layouts/Images/recipes/recipe2.jpg differ diff --git a/knowyourfood/views/layouts/Images/recipes/recipe3.webp b/knowyourfood/views/layouts/Images/recipes/recipe3.webp new file mode 100755 index 0000000..1f20d4f Binary files /dev/null and b/knowyourfood/views/layouts/Images/recipes/recipe3.webp differ diff --git a/knowyourfood/views/layouts/Images/recipes/recipe4.jpg b/knowyourfood/views/layouts/Images/recipes/recipe4.jpg new file mode 100755 index 0000000..1fab21c Binary files /dev/null and b/knowyourfood/views/layouts/Images/recipes/recipe4.jpg differ diff --git a/knowyourfood/views/layouts/Images/recipes/recipe5.jpg b/knowyourfood/views/layouts/Images/recipes/recipe5.jpg new file mode 100755 index 0000000..9e08398 Binary files /dev/null and b/knowyourfood/views/layouts/Images/recipes/recipe5.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant1.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant1.jpg new file mode 100755 index 0000000..4ba1e4c Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant1.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant2.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant2.jpg new file mode 100755 index 0000000..a472f42 Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant2.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant3.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant3.jpg new file mode 100755 index 0000000..fffa684 Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant3.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant4.webp b/knowyourfood/views/layouts/Images/restaurants/restaurant4.webp new file mode 100755 index 0000000..f77e074 Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant4.webp differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant5.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant5.jpg new file mode 100755 index 0000000..6b31389 Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant5.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant6.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant6.jpg new file mode 100755 index 0000000..53efacd Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant6.jpg differ diff --git a/knowyourfood/views/layouts/Images/restaurants/restaurant7.jpg b/knowyourfood/views/layouts/Images/restaurants/restaurant7.jpg new file mode 100755 index 0000000..e1c02ad Binary files /dev/null and b/knowyourfood/views/layouts/Images/restaurants/restaurant7.jpg differ diff --git a/knowyourfood/views/layouts/Videos/Another-Clock.gif b/knowyourfood/views/layouts/Videos/Another-Clock.gif new file mode 100755 index 0000000..40eae53 Binary files /dev/null and b/knowyourfood/views/layouts/Videos/Another-Clock.gif differ diff --git a/knowyourfood/views/layouts/Videos/analog-clock.mp4 b/knowyourfood/views/layouts/Videos/analog-clock.mp4 new file mode 100755 index 0000000..e0dfe5c Binary files /dev/null and b/knowyourfood/views/layouts/Videos/analog-clock.mp4 differ diff --git a/knowyourfood/views/layouts/auth.php b/knowyourfood/views/layouts/auth.php deleted file mode 100644 index a8dc0b9..0000000 --- a/knowyourfood/views/layouts/auth.php +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - Bootstrap demo - - - - -
- session->getFlash('success')): ?> -
- session->getFlash('success'); - ?> -
- - {{content}} -
- - - - \ No newline at end of file diff --git a/knowyourfood/views/layouts/main.php b/knowyourfood/views/layouts/main.php deleted file mode 100644 index 0c031b3..0000000 --- a/knowyourfood/views/layouts/main.php +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - <?php echo $this->title; ?> - - - - - - -
- session->getFlash('success'); - if($flashMessage){ - echo $flashMessage; - } - ?> - {{content}} -
- - - - \ No newline at end of file diff --git a/knowyourfood/views/login.php b/knowyourfood/views/login.php deleted file mode 100644 index 21a886b..0000000 --- a/knowyourfood/views/login.php +++ /dev/null @@ -1,15 +0,0 @@ -title='Login'; - -$form = Form::begin('', 'post'); - -echo $form->InputField($model, 'email'); -echo $form->inputField($model, 'password')->passwordField(); - -echo $form->button(); - -Form::end() -?> - -

Login

\ No newline at end of file diff --git a/knowyourfood/views/profile.php b/knowyourfood/views/profile.php deleted file mode 100644 index 02e4a57..0000000 --- a/knowyourfood/views/profile.php +++ /dev/null @@ -1,7 +0,0 @@ -title = 'Profile'; - -?> - -

Profile

\ No newline at end of file diff --git a/knowyourfood/views/register.php b/knowyourfood/views/register.php deleted file mode 100644 index f2b6088..0000000 --- a/knowyourfood/views/register.php +++ /dev/null @@ -1,17 +0,0 @@ -title = 'Register'; - -$form = Form::begin('', 'post'); - -echo $form->inputField($model, 'firstname'); -echo $form->inputField($model, 'lastname'); -echo $form->inputField($model, 'email'); -echo $form->inputField($model, 'password')->passwordField(); - -echo $form->button(); - -Form::end() -?> - -

Create An Account

diff --git a/service_authentication/.htaccess b/service_authentication/.htaccess new file mode 100755 index 0000000..dbd5b49 --- /dev/null +++ b/service_authentication/.htaccess @@ -0,0 +1,4 @@ +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^(.*)$ index.php [L] \ No newline at end of file diff --git a/service_authentication/.idea/.gitignore b/service_authentication/.idea/.gitignore new file mode 100755 index 0000000..1c2fda5 --- /dev/null +++ b/service_authentication/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/service_authentication/.idea/dataSources.xml b/service_authentication/.idea/dataSources.xml new file mode 100755 index 0000000..d78a740 --- /dev/null +++ b/service_authentication/.idea/dataSources.xml @@ -0,0 +1,12 @@ + + + + + mariadb + true + org.mariadb.jdbc.Driver + jdbc:mariadb://192.168.0.12:3306/Web + $ProjectFileDir$ + + + \ No newline at end of file diff --git a/service_authentication/.idea/modules.xml b/service_authentication/.idea/modules.xml new file mode 100755 index 0000000..5c29242 --- /dev/null +++ b/service_authentication/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/service_authentication/.idea/php.xml b/service_authentication/.idea/php.xml new file mode 100755 index 0000000..bccf9a4 --- /dev/null +++ b/service_authentication/.idea/php.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/service_authentication/.idea/service_regions.iml b/service_authentication/.idea/service_regions.iml new file mode 100755 index 0000000..bf4c9d3 --- /dev/null +++ b/service_authentication/.idea/service_regions.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/service_authentication/.idea/sqldialects.xml b/service_authentication/.idea/sqldialects.xml new file mode 100644 index 0000000..8d0fef2 --- /dev/null +++ b/service_authentication/.idea/sqldialects.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/service_authentication/composer.json b/service_authentication/composer.json new file mode 100755 index 0000000..d5e00e5 --- /dev/null +++ b/service_authentication/composer.json @@ -0,0 +1,12 @@ +{ + "name": "andrei_robert/service_regions", + "autoload": { + "psr-4": { + "app\\": "./" + } + }, + "require": { + "ext-curl": "*", + "ext-mysqli": "*" + } +} diff --git a/service_authentication/composer.lock b/service_authentication/composer.lock new file mode 100755 index 0000000..d5c9935 --- /dev/null +++ b/service_authentication/composer.lock @@ -0,0 +1,21 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "90164c790ffbc59c682c71b0d3d51029", + "packages": [], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "ext-curl": "*", + "ext-mysqli": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/service_authentication/core/AuthInterface.php b/service_authentication/core/AuthInterface.php new file mode 100755 index 0000000..e57bfd5 --- /dev/null +++ b/service_authentication/core/AuthInterface.php @@ -0,0 +1,8 @@ +method = $method; + $this->body = $body; + $this->authRequest = $authRequest; + $this->token = $token; + } + + public function run(): void + { + try { + if (!$this->isTokenValid()) throw new InvalidAuthTokenException(); + if (!$this->isAuthRequestValid()) throw new InvalidAuthRequestException(); + if (!$this->body) throw new InvalidBodyException(); + + $model = match ($this->method) { + 'GET' => new LoginModel(), + 'PUT' => new RegisterModel(), + default => throw new InvalidRequestException(), + }; + + $model->createConnection(); + $result = $model->executeReq($this->body); + + $this->writeResponse( + DVC::getHttpCodeWithCode(DVC::$successReturnCode), + DVC::$successReturnCode, $result + ); + + } catch (Exception $e){ + $this->writeResponse(DVC::getHttpCodeWithCode($e->getCode()), + $e->getCode(), $e->getMessage() + ); + } + } + + private function isTokenValid(): bool + { + $validToken = hash('md5', 'service_authentication'); + return $validToken === $this->token; + } + + private function isAuthRequestValid(): bool + { + return match ($this->authRequest){ + "register", "login" => true, + default => false + }; + } + + private function writeResponse(int $httpCode, int $returnCode, string|array $returnMessage): void + { + header("Content-Disposition: ".DVC::$nameOfResponsePackage); + header("Content-Type: application/json"); + http_response_code($httpCode); + echo json_encode([ + "code" => $returnCode, + "message" => $returnMessage + ]); + } +} \ No newline at end of file diff --git a/service_authentication/core/DVC.php b/service_authentication/core/DVC.php new file mode 100755 index 0000000..f960308 --- /dev/null +++ b/service_authentication/core/DVC.php @@ -0,0 +1,80 @@ + [ + DVC::$returnCode => 460, + DVC::$returnMessage => "Operation done successfully" + ], + DVC::$genericExceptionName => [ + DVC::$returnCode => 461, + DVC::$returnMessage => "Internal Server Error" + ], + DVC::$invalidTokenName => [ + DVC::$returnCode => 462, + DVC::$returnMessage => "Unauthorized access" + ], + DVC::$invalidRequestName => [ + DVC::$returnCode => 463, + DVC::$returnMessage => "Service doesn't provide this type of request" + ], + DVC::$invalidBodyName => [ + DVC::$returnCode => 464, + DVC::$returnMessage => "Not valid parameters sent" + ], + DVC::$alreadyExistsName => [ + + DVC::$returnCode => 465, + DVC::$returnMessage => "Field already existing" + ], + DVC::$fieldNotExistingName => [ + DVC::$returnCode => 466, + DVC::$returnMessage => "Field not existing anymore" + ], + DVC::$userAlreadyExistsName => [ + DVC::$returnCode => 467, + DVC::$returnMessage => "User already exists with this email" + ], + DVC::$userNotExistingName => [ + DVC::$returnCode => 468, + DVC::$returnMessage => "User account doesn't exists" + ] + }; + } + + public static function getHttpCodeWithCode(int $code): int + { + return match ($code){ + 460 => 200, + 461 => 500, + 462 => 401, + 463 => 405, + 464 => 400, + 465, 466 => 204, + 467 => 409, + 468 => 404, + default => 100 + }; + } +} \ No newline at end of file diff --git a/service_authentication/core/Request.php b/service_authentication/core/Request.php new file mode 100755 index 0000000..f4e2c36 --- /dev/null +++ b/service_authentication/core/Request.php @@ -0,0 +1,37 @@ + '192.168.0.12', + 'user' => 'andreicerbu', + 'password' => 'Theodor2002!', + 'dbname' => 'Web' +]; + +$_SESSION['database_configuration'] = $config; \ No newline at end of file diff --git a/service_authentication/exceptions/GenericErrorException.php b/service_authentication/exceptions/GenericErrorException.php new file mode 100755 index 0000000..b1f51bb --- /dev/null +++ b/service_authentication/exceptions/GenericErrorException.php @@ -0,0 +1,13 @@ +method(), $request->getAuthRequest(), $request->getBody(), $request->getAuthToken()); +$controller -> run(); \ No newline at end of file diff --git a/service_authentication/models/LoginModel.php b/service_authentication/models/LoginModel.php new file mode 100755 index 0000000..76f872b --- /dev/null +++ b/service_authentication/models/LoginModel.php @@ -0,0 +1,48 @@ +config = $_SESSION['database_configuration']; + } + + /** + * @throws GenericErrorException + */ + public function createConnection(): void + { + try { + $this->conn = new mysqli($this->config['dsn'], $this->config['user'], $this->config['password'], $this->config['dbname']); + } catch (Exception){ + throw new GenericErrorException(); + } + } + + /** + * @throws UserNotExistingException + */ + public function executeReq(array $body): int|string + { + $email = $body["email"]; + $password = $body["password"]; + + $query = "SELECT id FROM Users WHERE email = '$email' AND password = '$password'"; + $result = $this->conn->query($query); + if(!$result->num_rows) throw new UserNotExistingException(); + + $row = mysqli_fetch_row($result); + return $row[0]; + } +} \ No newline at end of file diff --git a/service_authentication/models/RegisterModel.php b/service_authentication/models/RegisterModel.php new file mode 100755 index 0000000..e12f290 --- /dev/null +++ b/service_authentication/models/RegisterModel.php @@ -0,0 +1,51 @@ +config = $_SESSION['database_configuration']; + } + + /** + * @throws GenericErrorException + */ + public function createConnection(): void + { + try { + $this->conn = new mysqli($this->config['dsn'], $this->config['user'], $this->config['password'], $this->config['dbname']); + } catch (Exception){ + throw new GenericErrorException(); + } + } + + /** + * @throws UserAlreadyExistsException + */ + public function executeReq(array $body): int|string + { + $username = $body["username"]; + $email = $body["email"]; + $password = $body["password"]; + + $query = "SELECT * FROM Users WHERE email = '$email'"; + $result = $this->conn->query($query); + if($result->num_rows) throw new UserAlreadyExistsException(); + + $query = "INSERT INTO Users (username, email, password) VALUES ('$username', '$email', '$password')"; + $result = $this->conn->query($query); + + return "Success"; + } +} \ No newline at end of file diff --git a/service_authentication/vendor/autoload.php b/service_authentication/vendor/autoload.php new file mode 100755 index 0000000..028092f --- /dev/null +++ b/service_authentication/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/service_authentication/vendor/composer/InstalledVersions.php b/service_authentication/vendor/composer/InstalledVersions.php new file mode 100755 index 0000000..51e734a --- /dev/null +++ b/service_authentication/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/service_authentication/vendor/composer/LICENSE b/service_authentication/vendor/composer/LICENSE new file mode 100755 index 0000000..f27399a --- /dev/null +++ b/service_authentication/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/service_authentication/vendor/composer/autoload_classmap.php b/service_authentication/vendor/composer/autoload_classmap.php new file mode 100755 index 0000000..0fb0a2c --- /dev/null +++ b/service_authentication/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/service_authentication/vendor/composer/autoload_namespaces.php b/service_authentication/vendor/composer/autoload_namespaces.php new file mode 100755 index 0000000..15a2ff3 --- /dev/null +++ b/service_authentication/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/'), +); diff --git a/service_authentication/vendor/composer/autoload_real.php b/service_authentication/vendor/composer/autoload_real.php new file mode 100755 index 0000000..c47ec0e --- /dev/null +++ b/service_authentication/vendor/composer/autoload_real.php @@ -0,0 +1,36 @@ +register(true); + + return $loader; + } +} diff --git a/service_authentication/vendor/composer/autoload_static.php b/service_authentication/vendor/composer/autoload_static.php new file mode 100755 index 0000000..3c18f05 --- /dev/null +++ b/service_authentication/vendor/composer/autoload_static.php @@ -0,0 +1,36 @@ + + array ( + 'app\\' => 4, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'app\\' => + array ( + 0 => __DIR__ . '/../..' . '/', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitb7a0d563da90d5c08d67839e2f768897::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitb7a0d563da90d5c08d67839e2f768897::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitb7a0d563da90d5c08d67839e2f768897::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/service_authentication/vendor/composer/installed.json b/service_authentication/vendor/composer/installed.json new file mode 100755 index 0000000..87fda74 --- /dev/null +++ b/service_authentication/vendor/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": true, + "dev-package-names": [] +} diff --git a/service_authentication/vendor/composer/installed.php b/service_authentication/vendor/composer/installed.php new file mode 100755 index 0000000..3676fd7 --- /dev/null +++ b/service_authentication/vendor/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => 'andrei_robert/service_regions', + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'andrei_robert/service_regions' => array( + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +);