JFIF $ d d 7 * Z qn )ZP 0 !1 A "#a$2Qr D8 a Ri [f \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H ~ , l s / 9 ć: [=/#f ; ) x { ٛE Q )~ = 𘙲r*2~ a _V = ' ku m F D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq 1dđ #̩ ͑ 0 ; H ] u 搂 @:~ ו K L N s h } O I R* 8 :2 ! lD JV o ( 3 = M ( z Ȱ+i *N A r6K n S l ) ! J J Ӂ* % ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c P A\IL Nj! J ۱+ O\ ͔ ] ޒ S J ȧ c%A N ol ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0 'G=i 2N +0 e 2 ]] 9 VT P O 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P < 0 x < !1AQ "Raq 02Br #S CTb ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV YT D I 6 2 '8Y2 7'\T P.6 d &˦ @V q i |8 -O Ε ] ʔ U= T L 8= ;6c | !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U#6w + +s &r+n ڐ { @ 29gL u " T Ù M=6 (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 ! OS r D 5 7 % | ?x> L | / nD 6?/8 w # [ ) L 7 +6〼T A T g ! %5 Mm Z /c -{1_Je "| ^$ 'O & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@ u6 BԒ i YN * f 0 _ GhKW u lT <nj- 0{ M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q $ H8o Q˼EV ~ k 0 h' L Pp M -M" m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @~p # !1QAa q ? AL0L x LU 4 d ; x " 16ad0 7.\ߋ 0 = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X &Q З non]я u ג./ ; gZ$ M QР 2M ]h ni 0 P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _ 1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3 6 #Ik+ v { v i ( ވ ? a e) X xy/*@Q Ǽ Ծ ) $ IWO l c G; !i k{ gOŀ L ('x T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ) X 5 c QɎMy W ? Q *!R > 6=7)Xj 5`J ] e 8%t ! + ' ! 1Q 5 !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $ v , ,m 㵜5u bV =sY+ @d { N ! dn O < .- B; _w J t 6;Q Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш e黅X ۢ F :)[ F G X ƹ / w _c MeD ,ʡc c . W D tA $ j@ : ) - #u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P 6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L ! ~ y5 g9T̅J kbM' +s :S +B) v @ M j e C f j E 0 Y\Qn z G 1 д~ W o{T 9?` Rm yhsy3 !HAD ] m c1 ~ 2 L S u7x T ;j$ `} 4-> L# vzŏ I L S ֭ T { r jGK C ; b pU= - ` Bs K. S F w4 M q] Z dH S 0 ) tLg
<?php
namespace AmeliaBooking\Application\Controller;
use AmeliaBooking\Application\Commands\Command;
use AmeliaBooking\Application\Commands\CommandResult;
use AmeliaBooking\Application\Common\Exceptions\AccessDeniedException;
use AmeliaBooking\Application\Services\User\UserApplicationService;
use AmeliaBooking\Domain\Common\Exceptions\AuthorizationException;
use AmeliaBooking\Domain\Common\Exceptions\CustomException;
use AmeliaBooking\Domain\Common\Exceptions\PaymentValidationException;
use AmeliaBooking\Domain\Events\DomainEventBus;
use AmeliaBooking\Domain\Services\DateTime\DateTimeService;
use AmeliaBooking\Domain\Services\Logger\LoggerInterface;
use AmeliaBooking\Domain\Services\Permissions\PermissionsService;
use AmeliaBooking\Domain\Services\Settings\SettingsService;
use AmeliaBooking\Infrastructure\Common\Container;
use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage;
use AmeliaBooking\Infrastructure\WP\Translations\FrontendStrings;
use AmeliaVendor\Psr\Http\Message\ResponseInterface as Response;
use AmeliaVendor\Psr\Http\Message\ServerRequestInterface as Request;
use League\Tactician\CommandBus;
/**
* Class Controller
*
* @package AmeliaBooking\Application\Controller
*/
abstract class Controller
{
public const STATUS_OK = 200;
public const STATUS_REDIRECT = 302;
public const STATUS_FORBIDDEN = 403;
public const STATUS_NOT_FOUNT = 404;
public const STATUS_CONFLICT = 409;
public const STATUS_INTERNAL_SERVER_ERROR = 500;
/**
* @var CommandBus
*/
protected $commandBus;
/**
* @var DomainEventBus
*/
protected $eventBus;
/**
* @var PermissionsService
*/
protected $permissionsService;
/**
* @var LoggerInterface
*/
protected $logger;
protected $allowedFields = [
'ameliaNonce',
'wpAmeliaNonce',
];
protected $sendJustData = false;
/**
* @var UserApplicationService
*/
private $userApplicationService;
/**
* Base Controller constructor.
*
* @param Container $container
* @param bool $fromApi
*/
public function __construct(Container $container, $fromApi = false)
{
$this->commandBus = $container->getCommandBus();
$this->eventBus = $container->getEventBus();
$this->permissionsService = $fromApi ? $container->getApiPermissionsService() : $container->getPermissionsService();
$this->userApplicationService = $fromApi ? $container->getApiUserApplicationService() : $container->getUserApplicationService();
$this->logger = $container->getLoggerService()->channel(LoggerInterface::CHANNEL_HTTP);
}
/**
* @param Request $request
* @param $args
*
* @return mixed
*/
abstract protected function instantiateCommand(Request $request, $args);
/**
* Emit a success domain event, do nothing by default
*
* @param DomainEventBus $eventBus
*
* @param CommandResult $result
*
* @return void
*/
protected function emitSuccessEvent(DomainEventBus $eventBus, CommandResult $result)
{
}
/**
* Emit a failure domain event, do nothing by default
*
* @param DomainEventBus $eventBus
*
* @param CommandResult $data
*
* @return null
*/
protected function emitFailureEvent(DomainEventBus $eventBus, CommandResult $data)
{
return null;
}
/**
* @param Request $request
* @param Response $response
* @param $args
*
* @return Response
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __invoke(Request $request, Response $response, $args, $validApiCall = false)
{
/** @var Command $command */
$command = $this->instantiateCommand($request, $args);
/** @var SettingsService $settingsService */
$settingsService = new SettingsService(new SettingsStorage());
if (!$validApiCall && !$command->validateNonce($request)) {
return $response->withStatus(self::STATUS_FORBIDDEN);
}
if (!$validApiCall && !$command->validateCron($request)) {
return $response->withStatus(self::STATUS_FORBIDDEN);
}
$command->setPermissionService($this->permissionsService);
$command->setUserApplicationService($this->userApplicationService);
$command->setValidApiCall($validApiCall);
try {
/** @var CommandResult $commandResult */
$commandResult = $this->commandBus->handle($command);
} catch (PaymentValidationException $e) {
$commandResult = new CommandResult();
$commandResult->setResult(CommandResult::RESULT_ERROR);
$commandResult->setMessage(FrontendStrings::getCommonStrings()['payment_error']);
$commandResult->setData(
[
'paymentSuccessful' => false,
]
);
} catch (AccessDeniedException $e) {
$response = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
$response = $response->withStatus(self::STATUS_FORBIDDEN);
$response->getBody()->write(
json_encode(
[
'data' => [
'message' => $e->getMessage()
]
]
)
);
return $response;
} catch (CustomException $e) {
try {
$this->logger->error('Unhandled exception in controller', [
'command' => get_class($command),
'exception' => $e,
]);
} catch (\Throwable $loggingError) {
// Telemetry must not block the JSON 500 response.
}
$response = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
$response = $response->withStatus(self::STATUS_INTERNAL_SERVER_ERROR);
$response->getBody()->write(
json_encode(
[
'data' => [
'message' => $e->getMessage()
]
]
)
);
return $response;
} catch (AuthorizationException $e) {
$commandResult = new CommandResult();
$commandResult->setResult(CommandResult::RESULT_ERROR);
$commandResult->setData(
[
'reauthorize' => true,
]
);
}
if (in_array($commandResult->getResult(), [CommandResult::RESULT_ERROR, CommandResult::RESULT_CONFLICT], true)) {
$this->logger->warning('Command returned non-success result', [
'command' => get_class($command),
'result' => $commandResult->getResult(),
'message' => $commandResult->getMessage(),
]);
}
if ($commandResult->getResult() === CommandResult::RESULT_ERROR) {
if ($settingsService->getSetting('activation', 'responseErrorAsConflict')) {
$commandResult->setResult(CommandResult::RESULT_CONFLICT);
}
}
if ($commandResult->getUrl() !== null) {
$this->emitSuccessEvent($this->eventBus, $commandResult);
/** @var Response $response */
$response = $response->withHeader('Location', $commandResult->getUrl());
$response = $response->withStatus(self::STATUS_REDIRECT);
return $response;
}
if ($commandResult->hasAttachment() === false && $commandResult->getHtml() === null) {
$responseBody = [
'message' => $commandResult->getMessage(),
'data' => $commandResult->getData()
];
$this->emitSuccessEvent($this->eventBus, $commandResult);
switch ($commandResult->getResult()) {
case (CommandResult::RESULT_SUCCESS):
$response = $response->withStatus(self::STATUS_OK);
break;
case (CommandResult::RESULT_CONFLICT):
$response = $response->withStatus(self::STATUS_CONFLICT);
break;
default:
$response = $response->withStatus(self::STATUS_INTERNAL_SERVER_ERROR);
break;
}
/** @var Response $response */
$response = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
$response->getBody()->write(
$this->sendJustData ? $commandResult->getData() :
json_encode(
$commandResult->hasDataInResponse() ?
$responseBody : array_merge($responseBody, ['data' => []])
)
);
}
if (($html = $commandResult->getHtml()) !== null) {
/** @var Response $response */
$this->emitSuccessEvent($this->eventBus, $commandResult);
switch ($commandResult->getResult()) {
case (CommandResult::RESULT_SUCCESS):
$response = $response->withStatus(self::STATUS_OK);
break;
case (CommandResult::RESULT_CONFLICT):
$response = $response->withStatus(self::STATUS_CONFLICT);
break;
default:
$response = $response->withStatus(self::STATUS_INTERNAL_SERVER_ERROR);
break;
}
$response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
$response = $response->withHeader('Cache-Control', 'max-age=0');
$response->getBody()->write($html);
}
if (($file = $commandResult->getFile()) !== null) {
/** @var Response $response */
$response = $response->withHeader('Content-Type', $file['type']);
$response = $response->withHeader('Content-Disposition', 'inline; filename=' . '"' . $file['name'] . '"');
$response = $response->withHeader('Cache-Control', 'max-age=0');
if (array_key_exists('size', $file)) {
$response = $response->withHeader('Content-Length', $file['size']);
}
$response->getBody()->write($file['content']);
}
return $response;
}
/**
* @param Command $command
* @param $requestBody
*/
protected function setCommandFields($command, $requestBody)
{
foreach ($this->allowedFields as $field) {
if (!isset($requestBody[$field])) {
continue;
}
$command->setField($field, $requestBody[$field]);
}
}
/**
* @param mixed $params
* @param array $keys
*/
protected function setArrayParams(&$params, $keys = [])
{
$names = array_merge([
'customers',
'categories',
'services',
'packages',
'employees',
'providers',
'providerIds',
'locations',
'locationIds',
'ids',
'events',
'tag',
'dates',
'types',
'fields',
'statuses',
'stats',
'bookingTypes',
], $keys);
foreach ($names as $name) {
if (!empty($params[$name])) {
$params[$name] = is_array($params[$name]) ? $params[$name] : explode(',', $params[$name]);
}
}
if (isset($params['dates'][0])) {
$params['dates'][0] = preg_match("/^\d{4}-\d{2}-\d{2}$/", $params['dates'][0]) ?
$params['dates'][0] : DateTimeService::getNowDate();
}
if (isset($params['dates'][1]) && $params['dates'][1]) {
$params['dates'][1] = preg_match("/^\d{4}-\d{2}-\d{2}$/", $params['dates'][1]) ?
$params['dates'][1] : DateTimeService::getNowDate();
}
if (isset($params['date'])) {
$params['date'] = preg_match("/^\d{4}-\d{2}-\d{2}$/", $params['date']) ?
$params['date'] : DateTimeService::getNowDate();
}
}
/**
* @param array $data
* @param string $field
* @param string $translationField
*
* @return void
*/
private function filterField(&$data, $field, $translationField)
{
if (!empty($data[$field])) {
global $allowedposttags;
$data[$field] = wp_kses($data[$field], $allowedposttags);
if (!empty($data['translations']) && ($translations = json_decode($data['translations'], true)) !== null) {
if (!empty($translations[$translationField])) {
foreach ($translations[$translationField] as $lang => $translation) {
$translations[$translationField][$lang] = wp_kses(
$translations[$translationField][$lang],
$allowedposttags
);
}
$data['translations'] = json_encode($translations);
}
}
}
}
/**
* @param array $requestBody
*
* @return void
*/
protected function filter(&$requestBody)
{
if (!current_user_can('unfiltered_html') && $requestBody) {
$this->filterField($requestBody, 'description', 'description');
$this->filterField($requestBody, 'label', 'name');
foreach (!empty($requestBody['extras']) ? $requestBody['extras'] : [] as $index => $extra) {
$this->filterField($requestBody['extras'][$index], 'description', 'description');
}
}
}
/**
* Helper to set HTML content on CommandResult as an inline file
* so the controller can respond with a text/html body.
*
* @param CommandResult $result
* @param string $html
* @param string $filename
*
* @return void
*/
protected function setResultHtml(CommandResult $result, $html, $filename = 'content.html')
{
$result->setFile([
'type' => 'text/html; charset=utf-8',
'name' => $filename,
'size' => strlen($html),
'content' => $html,
]);
}
/**
* @param mixed $default
*
* @return mixed
*/
public static function getParam(Request $request, string $key, $default = null)
{
$params = $request->getQueryParams();
return array_key_exists($key, $params) ? $params[$key] : $default;
}
}