-
Notifications
You must be signed in to change notification settings - Fork 4
/
RequestHandler.php
209 lines (182 loc) · 8.12 KB
/
RequestHandler.php
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
declare(strict_types=1);
namespace EvanG\Modules\MailSystem;
use DateTimeImmutable;
use EvanG\Modules\MailSystem\Helpers\Anniversaries;
use EvanG\Modules\MailSystem\Helpers\Changes;
use EvanG\Modules\MailSystem\Helpers\Images;
use EvanG\Modules\MailSystem\Helpers\News;
use Exception;
use Fisharebest\Localization\Locale;
use Fisharebest\Localization\Translator;
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Contracts\UserInterface;
use Fisharebest\Webtrees\GuestUser;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\Log;
use Fisharebest\Webtrees\NoReplyUser;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Services\CalendarService;
use Fisharebest\Webtrees\Services\EmailService;
use Fisharebest\Webtrees\Services\TreeService;
use Fisharebest\Webtrees\Services\UserService;
use Fisharebest\Webtrees\SiteUser;
use Fisharebest\Webtrees\User;
use Illuminate\Support\Collection;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface;
class RequestHandler implements RequestHandlerInterface
{
const ROUTE_PREFIX = "/mail-sys";
protected MailSystem $module;
protected array $actions;
protected UserService $users;
protected TreeService $trees;
protected EmailService $email;
protected CalendarService $calendar;
private News $news;
private Changes $changes;
private Anniversaries $anniversaries;
public function __construct(MailSystem $msys)
{
$this->module = $msys;
$this->users = app(UserService::class);
$this->trees = app(TreeService::class);
$this->email = app(EmailService::class);
$this->news = new News();
$this->changes = new Changes();
$this->anniversaries = new Anniversaries();
$this->actions = [
'help' => function () { return response($this->help()); },
'cron' => function () { return $this->cron(); },
'get' => function () { return response($this->api($this->module->getSettings())); },
'image' => function (Request $request) {
if ($this->module->getSettings()->getImageDataType() != "link") return response(["message" => "Direct links are disabled"], 403);
$loggedUser = Auth::user();
if (!Auth::isAdmin()) {
Auth::login($this->users->administrators()->first());
Registry::cache()->array()->forget('all-trees');
}
$query = $request->getQueryParams();
$record = Registry::gedcomRecordFactory()->make($query["xref"], $this->trees->find((int)$query["tree"]));
$img = $record instanceof Individual ? Images::getImageDataResponse(Images::getIndividualPicture($record)) : null;
if ($loggedUser instanceof GuestUser) Auth::logout();
else Auth::login($loggedUser);
return $img ?? response();
},
'html' => function (Request $request) {
$query = $request->getQueryParams();
return response($this->html($this->htmlData($this->module->getSettings(), $query["lang"] ?? null)));
},
'send' => function () { if (Auth::isAdmin()) return response($this->sendMails($this->module->getSettings())); else return null; }
];
}
private function help(): array
{
$endpoints = [];
foreach ($this->actions as $action => $fct) {
$endpoints[$action] = [
"name" => $action,
"url" => route(RequestHandler::class, ['action' => $action])
];
}
return [
"version" => $this->module->customModuleVersion(),
"latest_version" => $this->module->customModuleLatestVersion(),
"update_available" => version_compare($this->module->customModuleLatestVersion(), $this->module->customModuleVersion()) > 0,
"endpoints" => $endpoints
];
}
private function cron(): Response
{
$settings = $this->module->getSettings();
$today = new DateTimeImmutable("midnight");
$nextCron = $settings->getThisSend();
if ($today < $nextCron) return response(["message" => "Skip", "today" => $today->format("Y-m-d"), "next" => $nextCron->format("Y-m-d")]);
$response = $this->sendMails($settings);
$settings->setLastSend($today);
return response($response);
}
private function sendMails(Settings $args): array
{
$sent = [];
$failed = [];
foreach ($this->users->all() as $user) {
if ($args->getUsers() == null || in_array($user->username(), $args->getUsers())) {
if ($this->sendMail($user, $args)) $sent[] = $user->username();
else $failed[] = $user->username();
}
}
return ["success" => $sent, "failure" => $failed];
}
private function sendMail(User $user, Settings $args): bool
{
try {
$data = $this->htmlData($args, $user->getPreference(UserInterface::PREF_LANGUAGE), $user);
$html = $this->html($data);
if ($html == null) {
Log::addErrorLog("Mail System: HTML page is null (" . $user->userName() . ")");
return false;
}
return $this->email->send(new SiteUser(), $user, new NoReplyUser(), $data["subject"], strip_tags($html), $html);
} catch (Exception $e) {
Log::addErrorLog("Mail System: Error (" . $e->getMessage() . ")\n" . $e->getTraceAsString());
return false;
}
}
private function htmlData(Settings $args, $languageCode = null, $user = null): array
{
$locale = empty($languageCode) ? I18N::locale() : Locale::create($languageCode);
$translations = $this->module->customTranslations($locale->languageTag());
$translator = new Translator($translations, $locale->pluralRule());
$items = $this->api($args, $user);
return [
'args' => $args,
'subject' => $translator->translate('Newsletter'),
'items' => $items,
'module' => $this->module,
'translator' => $translator,
'locale' => $locale
];
}
public function api(Settings $args, User $user = null): array
{
if ($user != null) {
Auth::login($user);
Registry::cache()->array()->forget('all-trees');
}
$data = $this->trees->all()
->filter(function ($tree) use ($args) {
return $args->getTrees() == null || in_array($tree->name(), $args->getTrees());
})->map(function ($tree) use ($args) {
$treeData = new Collection();
$lastCron = $args->getLastSend();
$thisCron = $args->getThisSend();
$nextCron = $args->getNextSend();
$treeData["dates"] = [
"last" => $lastCron == null ? null : $lastCron->format("Y-m-d"),
"this" => $thisCron->format("Y-m-d"),
"next" => $nextCron->format("Y-m-d")
];
if ($args->getNewsEnabled()) $treeData["news"] = $this->news->get($args, $tree);
if ($args->getChangelistEnabled()) $treeData["changes"] = $this->changes->get($args, $tree);
if ($args->getAnniversariesEnabled()) $treeData["anniversaries"] = $this->anniversaries->get($args, $tree);
return !$args->getEmpty() && empty($treeData->whereNotNull()->count()) ? null : $treeData;
})->whereNotNull();
if ($user != null) Auth::logout();
return $data->toArray();
}
private function html(array $data): ?string
{
if (empty($data["items"])) return null;
return view("{$this->module->name()}::email", $data);
}
public function handle(Request $request): Response
{
$action = $request->getAttribute('action');
if (key_exists($action, $this->actions)) return $this->actions[$action]($request);
else return redirect(route(RequestHandler::class, ['action' => 'help']));
}
}