summaryrefslogtreecommitdiff
path: root/src/App.php
blob: ab5c592632404358dd615b238d5ccca639844610 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php

namespace FlatFileForms;

use FlatFileForms\Controllers\EntriesController;
use FlatFileForms\Controllers\FieldsController;
use FlatFileForms\Controllers\SubmissionController;
use FlatFileForms\Controllers\ValidationController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Yaml\Yaml;

class App
{
  public string $formPath;

  /**
   * App constructor.
   */
  public function __construct()
  {
    /**@var HookManager $hooks*/
    global $hooks;

    /**@var Form $form*/
    global $form;

    $hooks->doAction('init');

    global $request;
    global $response;
    $request = Request::createFromGlobals();
    $response = new Response();

    $content = [
      'data' => [],
    ];
    $contentRoot = $_ENV['app']['contentFolderPath'];

    $method = $request->getMethod();
    $path = $request->getPathInfo();

    $config = [];
    try {
      $config = $this->buildConfig($contentRoot . $path);

      // check referrer
      if (! empty($config['api']['referrer'])) {
        $referrerDomain = $_SERVER['HTTP_REFERER'] ?? '';
        $referrerIp = $_SERVER['REMOTE_ADDR'] ?? 0;
        $referrerIsMatch = false;
        foreach ($config['api']['referrer'] as $referrer) {
          if (
            ($referrer['domain'] ?? $referrerDomain) === $referrerDomain &&
            ($referrer['ip'] ?? $referrerIp) === $referrerIp
          ) {
            $referrerIsMatch = true;
            break;
          }
        }

        if (! $referrerIsMatch) {
          throw new HttpException('Referrer mismatch', Response::HTTP_UNAUTHORIZED);
        }
      }

      // support "Content-Type: application/json"
      if ($request->headers->get('Content-Type') == 'application/json') {
        $_POST = $request->toArray();
      }

      // check api key
      $apiKey = $_GET['key'] ?? $_POST['key'] ?? null;
      if (empty($apiKey)) {
        throw new HttpException('API key missing', Response::HTTP_BAD_REQUEST);
      }
      if (! in_array($apiKey, $config['api']['keys'])) {
        throw new HttpException('API key does not match', Response::HTTP_UNAUTHORIZED);
      }

      // GET
      if ($method == 'GET')  {
        if (str_ends_with($path, '/fields')) {
          $formPath = $contentRoot . str_replace('/fields', '', $path);
          $form = new Form($formPath);

          $builder = new Builder($formPath);

          $fieldsController = new FieldsController();

          $content = $fieldsController->getFields($builder);
        }

        else if (str_ends_with($path, '/entries')) {
          if (! isset($_GET['dateFrom'])) {
            throw new HttpException('dateFrom parameter missing', Response::HTTP_BAD_REQUEST);
          }

          $formPath = $contentRoot . str_replace('/entries', '', $path);
          $form = new Form($formPath);

          $entriesController = new EntriesController();

          $content = $entriesController->getEntries($formPath);
        }

        else {
          $content['data'] = Yaml::parseFile($contentRoot . $path . '.yaml');
        }
      }

      // POST
      else if ($method == 'POST') {
        if (str_ends_with($path, '/validate')) {
          $formPath = $contentRoot . str_replace('/validate', '', $path);
          $form = new Form($formPath);

          $builder = new Builder($formPath);
          $validator = new Validator($formPath);

          $validationController = new ValidationController();

          $content = $validationController->validateRequest($builder, $validator);
        }

        else if (str_ends_with($path, '/submit')) {
          $formPath = $contentRoot . str_replace('/submit', '', $path);
          $form = new Form($formPath);

          $builder = new Builder($formPath);
          $validator = new Validator($formPath);

          $submissionController = new SubmissionController();

          $content = $submissionController->submit($builder, $validator, $formPath);

          if (! empty($content['error'])) {
            throw new HttpException($content['error'], Response::HTTP_UNPROCESSABLE_ENTITY);
          }
        }
      }

      // OPTIONS
      else if ($method == 'OPTIONS') {
        $response->headers->set('Access-Control-Allow-Headers', $request->headers->get('Access-Control-Request-Headers'));
      }
    } catch (\Exception $exception) {
      if ($exception instanceof HttpException) {
        $response->setStatusCode($exception->getCode());
      }

      $content['error'] = basename(get_class($exception)) . ': ' . $exception->getMessage();
    }

    $content = $hooks->applyFilter('response:content', $content, $response);

    $response->headers->set('Content-Type', 'application/json');
    $response->headers->set('Access-Control-Allow-Origin', implode(',', $config['api']['cors']['origins']));
    $response->setContent(json_encode($content));
    $response->send();
  }

  public function buildConfig(string $requestPath): array
  {
    $config = [];
    $currentDirectory = $requestPath;
    while (true) {
      $configFile = $currentDirectory . '/config/config.yaml';
      if (file_exists($configFile)) {
        $parsedConfig = Yaml::parseFile($configFile);

        $apiKeys = array_merge($parsedConfig['api']['keys'] ?? [], $config['api']['keys'] ?? []);
        $config = array_replace_recursive($parsedConfig, $config);
        $config['api']['keys'] = $apiKeys;
      }

      // include custom functions
      $functionsFile = $currentDirectory . '/config/functions.php';
      if (file_exists($functionsFile)) {
        include_once $functionsFile;
      }

      if ($currentDirectory == $_ENV['app']['contentFolderPath'] || $currentDirectory == '/') {
        break;
      }

      $currentDirectory = dirname($currentDirectory);
    }

    return $config;
  }
}