Repository navigation
Expand file tree
/
Copy pathComment.php
More file actions
executable file
·422 lines (363 loc) · 16.7 KB
/
Copy pathComment.php
File metadata and controls
executable file
·422 lines (363 loc) · 16.7 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php
declare(strict_types=1);
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Comment;
use Comment\Install\CommentSchemaUpgrade;
use Comment\Repository\CommentRepository;
use Comment\Repository\CommentStorageInterface;
use Comment\Repository\RatingMetaRepository;
use Comment\Repository\RatingMetaStorageInterface;
use Comment\Service\Front\CommentDefinitionResolver;
use Comment\Service\Front\CommentDefinitionResolverInterface;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Propel;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator;
use Thelia\Core\Install\Database;
use Thelia\Core\Translation\Translator;
use Thelia\Domain\Catalog\Product\ProductRatingSourceInterface;
use Thelia\Model\ConfigQuery;
use Thelia\Model\Lang;
use Thelia\Model\LangQuery;
use Thelia\Model\Message;
use Thelia\Model\MessageQuery;
use Thelia\Module\BaseModule;
/**
* Class Comment.
*
* @author Michaël Espeche <michael.espeche@gmail.com>
* @author Julien Chanséaume <jchanseaume@openstudio.fr>
*/
class Comment extends BaseModule
{
public const MESSAGE_DOMAIN = 'comment';
public const MESSAGE_DOMAIN_EMAIL = 'comment.email.default';
/** Use comment */
public const CONFIG_ACTIVATED = 1;
/** Use moderation */
public const CONFIG_MODERATE = 1;
/**
* Allowed ref.
*
* The product alone: it is the only reference the theme hook renders a comment block for.
* A shop that serves its own front through the API can add `content` in the configuration
* screen, where the setting is free text.
*/
public const CONFIG_REF_ALLOWED = 'product';
/** Only customers are abled to post comment */
public const CONFIG_ONLY_CUSTOMER = 1;
/** Allow only verified customer (for product, customers that have bought the product) */
public const CONFIG_ONLY_VERIFIED = 1;
/** request customer comment, x days after an order */
public const CONFIG_REQUEST_CUSTOMMER_TTL = 15;
/** Send an email notification to the store admins when a new comment is posted */
public const CONFIG_NOTIFY_ADMIN_NEW_COMMENT = true;
public const CONFIG_MAX_RATING = 5;
public function postActivation(?ConnectionInterface $con = null): void
{
// Config
if (null === ConfigQuery::read('comment_activated')) {
ConfigQuery::write('comment_activated', self::CONFIG_ACTIVATED);
}
if (null === ConfigQuery::read('comment_moderate')) {
ConfigQuery::write('comment_moderate', self::CONFIG_MODERATE);
}
if (null === ConfigQuery::read('comment_ref_allowed')) {
ConfigQuery::write('comment_ref_allowed', self::CONFIG_REF_ALLOWED);
}
if (null === ConfigQuery::read('comment_only_customer')) {
ConfigQuery::write('comment_only_customer', self::CONFIG_ONLY_CUSTOMER);
}
if (null === ConfigQuery::read('comment_only_verified')) {
ConfigQuery::write('comment_only_verified', self::CONFIG_ONLY_VERIFIED);
}
if (null === ConfigQuery::read('comment_request_customer_ttl')) {
ConfigQuery::write('comment_request_customer_ttl', self::CONFIG_REQUEST_CUSTOMMER_TTL);
}
if (null === ConfigQuery::read('comment_notify_admin_new_comment')) {
ConfigQuery::write('comment_notify_admin_new_comment', self::CONFIG_NOTIFY_ADMIN_NEW_COMMENT);
}
if (null === ConfigQuery::read('comment_max_rating')) {
ConfigQuery::write('comment_max_rating', self::CONFIG_MAX_RATING);
}
// Schema
if (!self::getConfigValue('is_initialized', false)) {
$database = new Database($con);
$database->insertSql(null, [__DIR__.DS.'Config'.DS.'thelia.sql']);
self::setConfigValue('is_initialized', true);
}
// A shop installed before the current schema needs what thelia.sql only gives to a
// first activation. Does nothing when the table is already up to date.
(new CommentSchemaUpgrade())->apply($con);
// A shop that installed the module before this index existed never replays thelia.sql.
$this->createRefStatusIndex($con);
$languages = LangQuery::create()->find();
$this->loadEmailTranslations($languages);
// Request comment from customer
if (null === MessageQuery::create()->findOneByName('comment_request_customer')) {
$message = new Message();
$message
->setName('comment_request_customer')
// The stored names carry no .twig: TwigParser resolves ".html" to ".html.twig"
// and ".txt" to ".txt.twig", so these keep working after the Twig port.
->setHtmlTemplateFileName('request-customer-comment.html')
// No layout file name here: the template extends email-layout.html.twig itself,
// the way the native messages do. Naming the layout as well would render it a
// second time around the already-wrapped body.
->setHtmlLayoutFileName('')
->setTextTemplateFileName('request-customer-comment.txt')
->setTextLayoutFileName('')
->setSecured(0);
foreach ($languages as $language) {
$locale = $language->getLocale();
$message->setLocale($locale);
$message->setTitle(
Translator::getInstance()->trans('Request customer comment', [], self::MESSAGE_DOMAIN, $locale)
);
$message->setSubject($this->requestCustomerSubject($locale));
}
$message->save();
}
// Notify admin of new comment
if (null === MessageQuery::create()->findOneByName('new_comment_notification_admin')) {
$message = new Message();
$message
->setName('new_comment_notification_admin')
->setHtmlTemplateFileName('new-comment-notification-admin.html')
->setHtmlLayoutFileName('')
->setTextTemplateFileName('new-comment-notification-admin.txt')
->setTextLayoutFileName('')
->setSecured(0);
foreach ($languages as $language) {
$locale = $language->getLocale();
$message->setLocale($locale);
$message->setTitle(
Translator::getInstance()->trans(
'Notify store admin of new comment',
[],
self::MESSAGE_DOMAIN_EMAIL,
$locale
)
);
$message->setSubject($this->newCommentAdminSubject($locale));
}
$message->save();
}
}
public function update($currentVersion, $newVersion, ?ConnectionInterface $con = null): void
{
(new CommentSchemaUpgrade())->apply($con);
$languages = LangQuery::create()->find();
$this->loadEmailTranslations($languages);
$this->repairMessageSubjects($languages);
$this->createRefStatusIndex($con);
}
/**
* Index the three equality predicates of an aggregate read on a target's comments.
*
* The module ships its schema as Config/thelia.sql, which postActivation() applies once and
* never replays, and it has no Config/TheliaMain.sql, so Config/update/*.sql is never read
* either (Thelia\Install\Standalone\DatabaseSetup returns before the update directory when
* the main file is missing). An existing shop therefore only ever gets this index from here.
*
* MySQL has no CREATE INDEX IF NOT EXISTS, and the statement is not idempotent: the index is
* looked up first rather than creating it and swallowing the error, so a real failure still
* surfaces.
*/
private function createRefStatusIndex(?ConnectionInterface $con = null): void
{
$con ??= Propel::getConnection();
$statement = $con->prepare(
'SELECT COUNT(*) FROM information_schema.statistics '
.'WHERE table_schema = DATABASE() AND table_name = :table AND index_name = :index'
);
$statement->execute(['table' => 'comment', 'index' => 'idx_comment_ref_status']);
if (0 < (int) $statement->fetchColumn()) {
return;
}
$con->exec('CREATE INDEX `idx_comment_ref_status` ON `comment` (`ref`, `ref_id`, `status`)');
}
/**
* Load the email localization files.
*
* postActivation() and update() both run before the module's own catalogues are registered,
* so the strings written to the message rows would otherwise come out as their English keys.
*
* @param iterable<Lang> $languages
*/
private function loadEmailTranslations(iterable $languages): void
{
/** @var Lang $language */
foreach ($languages as $language) {
Translator::getInstance()->addResource(
'php',
__DIR__.'/I18n/email/default/'.$language->getLocale().'.php',
$language->getLocale(),
self::MESSAGE_DOMAIN_EMAIL
);
}
}
/**
* Repair the two message subjects on shops installed before the Twig port.
*
* The customer request went out with no subject at all, and the admin notification still
* carries the Smarty placeholders `{$ref_type_title}` / `{$ref_title}`, which
* Message::buildMessage() now compiles as an inline Twig template and therefore ships
* verbatim. Only those two cases are rewritten: a subject a merchant has edited in the
* back office is left untouched.
*
* @param iterable<Lang> $languages
*/
private function repairMessageSubjects(iterable $languages): void
{
$subjects = [
'comment_request_customer' => $this->requestCustomerSubject(...),
'new_comment_notification_admin' => $this->newCommentAdminSubject(...),
];
foreach ($subjects as $name => $subjectForLocale) {
$message = MessageQuery::create()->findOneByName($name);
if (null === $message) {
continue;
}
$changed = false;
/** @var Lang $language */
foreach ($languages as $language) {
$locale = $language->getLocale();
$message->setLocale($locale);
$current = (string) $message->getSubject();
if ('' !== $current && !str_contains($current, '{$')) {
continue;
}
$message->setSubject($subjectForLocale($locale));
$changed = true;
}
// The template wraps itself in the layout now, so a layout named on the row would
// render the chrome twice.
if ('email-layout.html.twig' === $message->getHtmlLayoutFileName()) {
$message->setHtmlLayoutFileName('');
$changed = true;
}
if ($changed) {
$message->save();
}
}
}
private function requestCustomerSubject(string $locale): string
{
return Translator::getInstance()->trans(
'Share your opinion on your recent order',
[],
self::MESSAGE_DOMAIN_EMAIL,
$locale
);
}
private function newCommentAdminSubject(string $locale): string
{
$subject = Translator::getInstance()->trans(
'New comment on %ref_type_title "%ref_title"',
[],
self::MESSAGE_DOMAIN_EMAIL,
$locale
);
// The subject is compiled as an inline template by the parser: Twig placeholders now,
// the Smarty ones went out with the rest of the port.
return str_replace(
['%ref_type_title', '%ref_title'],
['{{ ref_type_title|lower }}', '{{ ref_title }}'],
$subject
);
}
public static function getConfig(): array
{
$config = [
'activated' => (
(int) ConfigQuery::read('comment_activated', self::CONFIG_ACTIVATED) === 1
),
'moderate' => (
(int) ConfigQuery::read('comment_moderate', self::CONFIG_MODERATE) === 1
),
'ref_allowed' => explode(
',',
ConfigQuery::read('comment_ref_allowed', self::CONFIG_REF_ALLOWED)
),
'only_customer' => (
(int) ConfigQuery::read('comment_only_customer', self::CONFIG_ONLY_CUSTOMER) === 1
),
'only_verified' => (
(int) ConfigQuery::read('comment_only_verified', self::CONFIG_ONLY_VERIFIED) === 1
),
'request_customer_ttl' => (
(int) ConfigQuery::read('comment_request_customer_ttl', self::CONFIG_REQUEST_CUSTOMMER_TTL)
),
'notify_admin_new_comment' => (
(int) ConfigQuery::read('comment_notify_admin_new_comment', self::CONFIG_NOTIFY_ADMIN_NEW_COMMENT)
=== 1
),
// The maximum rating is a scale (5 by default), not a flag: comparing it to 1
// returned false for every shop whose scale was not exactly 1.
'max_rating' => (
(int) ConfigQuery::read('comment_max_rating', self::CONFIG_MAX_RATING)
),
];
return $config;
}
/**
* The budgets Comment\Service\Front\CommentPostLimiter spends on every posted comment.
*
* Declared here rather than in the shop's framework configuration so that activating the
* module is enough: a shop that lets anyone post gets the limit with it.
*/
public static function configureContainer(ContainerConfigurator $containerConfigurator): void
{
$containerConfigurator->extension('framework', [
'rate_limiter' => [
'comment_post_per_client' => [
'policy' => 'sliding_window',
'limit' => 10,
'interval' => '1 hour',
],
'comment_post_per_element' => [
'policy' => 'sliding_window',
'limit' => 3,
'interval' => '1 hour',
],
// Reporting is a click behind no form and no account: one visitor may flag a
// handful of comments, not walk down a page raising every counter.
'comment_abuse_per_client' => [
'policy' => 'sliding_window',
'limit' => 10,
'interval' => '1 hour',
],
],
], prepend: true);
}
public static function configureServices(ServicesConfigurator $servicesConfigurator): void
{
$servicesConfigurator->load(self::getModuleCode().'\\', __DIR__)
// Tests/ is part of the tree load() walks: a test double implementing an
// autoconfigured interface would otherwise be registered as a real service.
->exclude([
__DIR__.'/I18n/*',
__DIR__.'/Tests/*',
// The rating facet arrived with Thelia 3.3: on an older core its interface
// does not exist, and the class implementing it could not be loaded.
...(interface_exists(ProductRatingSourceInterface::class) ? [] : [__DIR__.'/Front/RatingFacetSource.php']),
])
->autowire(true)
->autoconfigure(true);
// load() registers services under their class name; autowiring an interface needs an
// alias of its own.
$servicesConfigurator->alias(CommentStorageInterface::class, CommentRepository::class);
$servicesConfigurator->alias(RatingMetaStorageInterface::class, RatingMetaRepository::class);
$servicesConfigurator->alias(CommentDefinitionResolverInterface::class, CommentDefinitionResolver::class);
}
}