64 lines
2.0 KiB
PHP
64 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use CodeIgniter\RESTful\ResourceController;
|
|
|
|
class ProofreadController extends ResourceController
|
|
{
|
|
public function check()
|
|
{
|
|
// Basic per-IP throttling: 10 requests per minute
|
|
$throttler = service('throttler');
|
|
$key = 'proofread-' . $this->request->getIPAddress();
|
|
if (!$throttler->check($key, 10, MINUTE)) {
|
|
return $this->respond([
|
|
'ok' => false,
|
|
'error' => 'Too many requests. Try again in a minute.',
|
|
'csrfHash' => csrf_hash(),
|
|
], 429);
|
|
}
|
|
|
|
// Accept form-urlencoded payload to play nicely with CSRF protection
|
|
$validation = service('validation');
|
|
$payload = sanitize_request_value($this->request->getPost(['text']));
|
|
$validation->setRules([
|
|
'text' => 'required|min_length[1]|max_length[20000]',
|
|
]);
|
|
|
|
if (! $validation->run($payload)) {
|
|
return $this->respond([
|
|
'ok' => false,
|
|
'error' => 'Invalid text payload.',
|
|
'csrfHash' => csrf_hash(),
|
|
], 422);
|
|
}
|
|
|
|
$text = (string) $payload['text'];
|
|
|
|
$client = \Config\Services::curlrequest(['timeout' => 10]);
|
|
|
|
try {
|
|
$resp = $client->post('https://api.languagetool.org/v2/check', [
|
|
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
|
|
'form_params' => [
|
|
'text' => $text,
|
|
'language' => 'en-US',
|
|
],
|
|
]);
|
|
|
|
return $this->respond([
|
|
'ok' => true,
|
|
'result' => json_decode($resp->getBody(), true),
|
|
'csrfHash' => csrf_hash(),
|
|
]);
|
|
} catch (\Throwable $e) {
|
|
return $this->respond([
|
|
'ok' => false,
|
|
'error' => 'Proofread service unavailable.',
|
|
'csrfHash' => csrf_hash(),
|
|
], 502);
|
|
}
|
|
}
|
|
}
|