-
Notifications
You must be signed in to change notification settings - Fork 2
/
pixel_googlemybusiness.php
365 lines (321 loc) · 11.6 KB
/
pixel_googlemybusiness.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
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
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Expr\CompositeExpression;
use Doctrine\ORM\EntityManager;
use PrestaShop\PrestaShop\Core\Exception\ContainerNotFoundException;
use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
use Pixel\Module\GoogleMyBusiness\Entity\GooglePlace;
use Pixel\Module\GoogleMyBusiness\Entity\GoogleReview;
class Pixel_googlemybusiness extends Module implements WidgetInterface
{
protected $templateFile;
/**
* Module's constructor.
*/
public function __construct()
{
$this->name = 'pixel_googlemybusiness';
$this->version = '1.1.0';
$this->author = 'Pixel Open';
$this->tab = 'front_office_features';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->trans('Google My Business', [], 'Modules.Pixelgooglemybusiness.Admin');
$this->description = $this->trans('Retrieve and display the Google My Business place data.', [], 'Modules.Pixelgooglemybusiness.Admin');
$this->ps_versions_compliancy = [
'min' => '1.7.6.0',
'max' => _PS_VERSION_,
];
$this->templateFile = 'module:pixel_googlemybusiness/pixel_googlemybusiness.tpl';
}
/**
* @return bool
*/
public function install(): bool
{
return parent::install() &&
$this->createTables() &&
$this->registerHook('actionFrontControllerSetMedia');
}
/**
* Add CSS
*
* @return void
*/
public function hookActionFrontControllerSetMedia()
{
$this->context->controller->addCSS($this->_path . 'views/css/gmb.css');
}
/**
* @return bool
*/
public function uninstall(): bool
{
return parent::uninstall() && $this->deleteTables() && $this->deleteConfigurations();
}
/**
* @param string $hookName
* @param array $configuration
*
* @return string
* @throws ContainerNotFoundException
*/
public function renderWidget($hookName, array $configuration): string
{
$keys = [$this->name, md5(serialize($configuration))];
$cacheId = join('_', $keys);
$template = $configuration['template'] ?? $this->templateFile;
if (!$this->isCached($template, $cacheId)) {
$this->smarty->assign($this->getWidgetVariables($hookName, $configuration));
}
return $this->fetch($template, $cacheId);
}
/**
* @param string $hookName
* @param mixed[] $configuration
*
* @return Object[]
* @throws ContainerNotFoundException
*/
public function getWidgetVariables($hookName, array $configuration): array
{
$placeIds = array_filter(
explode(',', $configuration['place_ids'] ?? '')
);
$display = array_filter(
explode(',', $configuration['display'] ?? 'name,phone,rating,opening-hours,reviews')
);
$reviewNumber = $configuration['review_number'] ?? 5;
$reviewMinRating = $configuration['review_min_rating'] ?? 0;
return [
'places' => $this->getPlaces(
$placeIds,
in_array('reviews', $display),
(int)$reviewNumber,
(int)$reviewMinRating
),
'display' => $display,
];
}
/**
* Retrieve places
*
* @param string[] $placesIds
*
* @return Object[]
* @throws ContainerNotFoundException
*/
protected function getPlaces(
array $placesIds = [],
bool $loadReviews = true,
int $reviewNumber = 5,
int $reviewMinRating = 0
): array {
/** @var EntityManager $entityManager */
$entityManager = $this->getContainer()->get('doctrine.orm.entity_manager');
$placeRepository = $entityManager->getRepository(GooglePlace::class);
$reviewRepository = $entityManager->getRepository(GoogleReview::class);
$criteria = [
'language' => [$this->context->language->iso_code, null],
];
if (!empty($placesIds)) {
$criteria['placeId'] = $placesIds;
}
$places = $placeRepository->findBy($criteria);
if ($loadReviews) {
/** @var GooglePlace $place */
foreach ($places as $place) {
$language = new CompositeExpression(
CompositeExpression::TYPE_OR,
[
Criteria::expr()->eq('language', $this->context->language->iso_code),
Criteria::expr()->eq('language', null)
]
);
$filters = new CompositeExpression(
CompositeExpression::TYPE_AND,
[
$language,
Criteria::expr()->eq('placeId', $place->getPlaceId()),
Criteria::expr()->eq('enabled', 1),
Criteria::expr()->gte('rating', $reviewMinRating),
]
);
$criteria = Criteria::create()
->where($filters)
->orderBy(['time' => Criteria::DESC])
->setMaxResults($reviewNumber);
$reviews = $reviewRepository->matching($criteria)->getValues();
$place->setReviews($reviews);
}
}
return $places;
}
/**
* Retrieve config fields
*
* @return array[]
*/
protected function getConfigFields(): array
{
return [
'GOOGLE_MY_BUSINESS_API_KEY' => [
'type' => 'text',
'label' => $this->trans('Google API Key', [], 'Modules.Pixelgooglemybusiness.Admin'),
'name' => 'GOOGLE_MY_BUSINESS_API_KEY',
'size' => 20,
'required' => true,
],
'GOOGLE_MY_BUSINESS_PLACE_IDS' => [
'type' => 'textarea',
'label' => $this->trans('Google Place IDs', [], 'Modules.Pixelgooglemybusiness.Admin'),
'name' => 'GOOGLE_MY_BUSINESS_PLACE_IDS',
'size' => 20,
'required' => true,
'desc' => $this->trans('One place id per line', [], 'Modules.Pixelgooglemybusiness.Admin'),
]
];
}
/**
* This method handles the module's configuration page
*
* @return string
*/
public function getContent(): string
{
$output = '';
if (Tools::isSubmit('submit' . $this->name)) {
foreach ($this->getConfigFields() as $field) {
$value = (string) Tools::getValue($field['name']);
if ($field['required'] && empty($value)) {
return $this->displayError($this->trans('%field% is empty', ['%field%' => $field['label']], 'Modules.Pixelgooglemybusiness.Admin')) . $this->displayForm();
}
Configuration::updateValue($field['name'], $value);
}
$output = $this->displayConfirmation($this->trans('Settings updated', [], 'Modules.Pixelgooglemybusiness.Admin'));
}
return $output . $this->displayForm();
}
/**
* Builds the configuration form
*
* @return string
*/
public function displayForm(): string
{
$form = [
'form' => [
'legend' => [
'title' => $this->trans('Settings', [], 'Modules.Pixelgooglemybusiness.Admin'),
],
'input' => $this->getConfigFields(),
'submit' => [
'title' => $this->trans('Save', [], 'Modules.Pixelgooglemybusiness.Admin'),
'class' => 'btn btn-default pull-right',
],
],
];
$helper = new HelperForm();
$helper->table = $this->table;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&' . http_build_query(['configure' => $this->name]);
$helper->submit_action = 'submit' . $this->name;
$helper->default_form_language = (int) Configuration::get('PS_LANG_DEFAULT');
foreach ($this->getConfigFields() as $field) {
$helper->fields_value[$field['name']] = Tools::getValue(
$field['name'],
Configuration::get($field['name'])
);
}
return $helper->generateForm([$form]);
}
/**
* Create tables
*/
protected function createTables(): bool
{
try {
Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'google_place` (
`id` INT(11) AUTO_INCREMENT NOT NULL,
`place_id` VARCHAR(255) NOT NULL,
`language` VARCHAR(2) NULL,
`name` VARCHAR(255) NOT NULL,
`phone` VARCHAR(255) DEFAULT NULL,
`opening_hours_periods` TEXT DEFAULT NULL,
`opening_hours_weekday_text` TEXT DEFAULT NULL,
`rating` NUMERIC(4, 2) DEFAULT NULL,
`user_ratings_total` INT DEFAULT NULL,
`price_level` INT DEFAULT NULL,
PRIMARY KEY(`id`),
UNIQUE KEY(`place_id`, `language`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8;
');
Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'google_review` (
`id` INT(11) AUTO_INCREMENT NOT NULL,
`place_id` VARCHAR(255) NOT NULL,
`author_name` VARCHAR(255) DEFAULT NULL,
`author_url` VARCHAR(255) DEFAULT NULL,
`language` VARCHAR(2) NULL,
`original_language` VARCHAR(2) DEFAULT NULL,
`profile_photo_url` VARCHAR(255) DEFAULT NULL,
`rating` SMALLINT DEFAULT NULL,
`relative_time_description` VARCHAR(255) DEFAULT NULL,
`comment` LONGTEXT DEFAULT NULL,
`time` INT DEFAULT NULL,
`translated` TINYINT(1) DEFAULT NULL,
`enabled` TINYINT(1) DEFAULT NULL,
KEY INDEX_PLACE_ID_TIME (`place_id`, `time`),
PRIMARY KEY(`id`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=UTF8;
');
return true;
} catch (Exception $exception) {
$this->_errors[] = $exception->getMessage();
return false;
}
}
/**
* Delete tables
*
* @return bool
*/
protected function deleteTables(): bool
{
try {
Db::getInstance()->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'google_place`;');
Db::getInstance()->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'google_review`;');
return true;
} catch (Exception $exception) {
$this->_errors[] = $exception->getMessage();
return false;
}
}
/**
* Delete configurations
*
* @return bool
*/
protected function deleteConfigurations(): bool
{
foreach ($this->getConfigFields() as $key => $options) {
Configuration::deleteByName($key);
}
return true;
}
/**
* Use the new translation system
*
* @return bool
*/
public function isUsingNewTranslationSystem(): bool
{
return true;
}
}