/
Bootstrap.php
389 lines (361 loc) · 13.3 KB
/
Bootstrap.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<?php
/**
* 2015 Darwin Pricing
*
* For support please visit www.darwinpricing.com
*
* NOTICE OF LICENSE
*
* This source file is subject to the GNU Affero General Public License (AGPL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/agpl-3.0.html
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@darwinpricing.com so we can send you a copy immediately.
*
* @author Darwin Pricing <support@darwinpricing.com>
* @copyright 2015 Darwin Pricing
* @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License (AGPL 3.0)
*/
/**
* Darwin Pricing plugin for Shopware
*/
class Shopware_Plugins_Frontend_DarwinPricing_Bootstrap extends Shopware_Components_Plugin_Bootstrap {
/**
* @return string
* @throws Exception
*/
public function getDescription() {
static $description = null;
if (!isset($description)) {
$description = @file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'info.txt');
if (false === $description) {
throw new Exception('Plugin description not found');
}
}
return $description;
}
public function getInfo() {
return array(
'label' => $this->getLabel(),
'version' => $this->getVersion(),
'author' => $this->getPluginInfo('author'),
'copyright' => $this->getPluginInfo('copyright'),
'description' => $this->getDescription(),
'license' => $this->getPluginInfo('license'),
'support' => 'support@darwinpricing.com',
'link' => $this->getPluginInfo('link'),
);
}
public function getLabel() {
return $this->getPluginInfo('label', 'de');
}
public function getVersion() {
return $this->getPluginInfo('currentVersion');
}
public function createForm() {
$form = $this->Form();
$parent = $this->Forms()->findOneBy(array('name' => 'Interface'));
$form->setParent($parent);
$form->setElement('text', 'serverUrl', array(
'label' => 'API-Server',
'description' => 'Die URL des Darwin Pricing API-Servers für Ihre Website',
'value' => null,
'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP
));
$form->setElement('text', 'clientId', array(
'label' => 'Client-ID',
'description' => 'Die Client-ID für Ihre Website',
'value' => null,
'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP
));
$form->setElement('text', 'clientSecret', array(
'label' => 'Client-Schlüssel',
'description' => 'Der geheime Client-Schlüssel für Ihre Website',
'value' => null,
'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP
));
$form->setElement('checkbox', 'disabled', array(
'label' => 'Plugin deaktivieren',
'description' => 'Darwin Pricing auf diesem Subshop deaktivieren',
'value' => false,
'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP
));
$form->setElement('button', 'darwinPricingSignUp', array(
'label' => '<b>Jetzt kostenlosen Darwin Pricing-Account erhalten</b>',
'handler' => 'function() { window.open("https://admin.darwinpricing.com/sign-up")}',
)
);
$this->addFormTranslations($this->getFormTranslations());
}
public function install() {
$this->registerEvents();
$this->createForm();
return array('success' => true, 'invalidateCache' => array('frontend'));
}
public function onPostDispatch(Enlight_Controller_ActionEventArgs $arguments) {
try {
$controller = $arguments->getSubject();
$request = $controller->Request();
$response = $controller->Response();
$view = $controller->View();
if (!$request->isDispatched() || $response->isException() || !$view->hasTemplate() || 'frontend' !== $request->getModuleName() || !$this->isActive()) {
return;
}
if ('checkout' === $request->getControllerName() && 'finish' === $request->getActionName()) {
$sOrderNumber = $view->getAssign('sOrderNumber');
$visitorIp = $request->getClientIp(true);
$this->trackOrder($sOrderNumber, $visitorIp);
} else {
$this->loadWidget($view);
}
} catch (\Exception $exception) {
}
}
public function uninstall() {
return array('success' => true, 'invalidateCache' => array('frontend'));
}
/**
* @param array $sOrder
* @return array
*/
protected function addUnitCosts($sOrder) {
if (is_array($sOrder) && isset($sOrder['details']) && is_array($sOrder['details'])) {
foreach ($sOrder['details'] as &$item) {
if (is_array($item) && isset($item['articleId'])) {
$sArticleDetail = $this->getArticleDetail($item['articleId']);
if (null !== $sArticleDetail) {
$unitCost = $this->getUnitCost($sArticleDetail);
if ($unitCost > 0) {
$item['unitCost'] = $unitCost;
}
}
}
}
}
return $sOrder;
}
/**
* @param callable $workload
*/
protected function executeOnShutdown(callable $workload) {
register_shutdown_function(function() use ($workload) {
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
$workload();
});
}
/**
* @param string $path
* @param string|null $visitorIp
* @return string
*/
protected function getApiUrl($path, $visitorIp = null) {
$config = $this->Config();
$serverUrl = rtrim($config->serverUrl, '/');
$apiUrl = $serverUrl . $path;
$parameterList = array('platform' => 'shopware-' . Shopware::VERSION, 'site-id' => $config->clientId);
if (null !== $visitorIp) {
$parameterList['hash'] = $config->clientSecret;
$parameterList['visitor-ip'] = $visitorIp;
}
$apiUrl .= '?' . http_build_query($parameterList, '', '&');
return $apiUrl;
}
/**
* @param int $sArticleId
* @return \Shopware\Models\Article\Article|null
*/
protected function getArticle($sArticleId) {
/** @var \Shopware\Components\Api\Resource\Article $resource */
$resource = \Shopware\Components\Api\Manager::getResource('article');
$resource->setResultMode(\Shopware\Components\Api\Resource\Resource::HYDRATE_OBJECT);
try {
return $resource->getOne($sArticleId);
} catch (\Exception $exception) {
return null;
}
}
/**
* @param int $sArticleId
* @return \Shopware\Models\Article\Detail|null
*/
protected function getArticleDetail($sArticleId) {
$sArticle = $this->getArticle($sArticleId);
if (null === $sArticle) {
return null;
}
return $sArticle->getMainDetail();
}
/**
* @return array
*/
protected function getFormTranslations() {
return array(
'en_GB' => array(
'serverUrl' => array(
'label' => 'API Server',
'description' => 'The URL of the Darwin Pricing API server for your website',
),
'clientId' => array(
'label' => 'Client ID',
'description' => 'The client ID for your website',
),
'clientSecret' => array(
'label' => 'Client Secret',
'description' => 'The client secret for your website',
),
'disabled' => array(
'label' => 'Disable plugin',
'description' => 'Disable Darwin Pricing on this subshop',
),
'darwinPricingSignUp' => array(
'label' => '<b>Get your free Darwin Pricing account</b>',
),
)
);
}
/**
* @param string $sOrderNumber
* @return array|null
*/
protected function getOrder($sOrderNumber) {
/** @var \Shopware\Components\Api\Resource\Order $resource */
$resource = \Shopware\Components\Api\Manager::getResource('order');
try {
return $resource->getOneByNumber($sOrderNumber);
} catch (\Exception $exception) {
return null;
}
}
/**
* @param string $key
* @param string|null $language
* @return string
* @throws Exception
*/
protected function getPluginInfo($key, $language = null) {
$pluginInfo = $this->readPluginInfo();
if (!isset($pluginInfo[$key])) {
throw new Exception('Plugin ' . $key . ' not found');
}
if (null === $language) {
return (string) $pluginInfo[$key];
}
if (!isset($pluginInfo[$key][$language])) {
throw new Exception('Plugin ' . $key . ' not found');
}
return (string) $pluginInfo[$key][$language];
}
/**
* @param \Shopware\Models\Article\Detail $sArticleDetail
* @return float
*/
protected function getUnitCost($sArticleDetail) {
if (method_exists($sArticleDetail, 'getPurchasePrice')) {
return $sArticleDetail->getPurchasePrice();
}
if (method_exists($sArticleDetail, 'getPrices')) {
$sPrices = $sArticleDetail->getPrices();
/** @var \Shopware\Models\Article\Price $sPrice */
foreach ($sPrices as $sPrice) {
if (method_exists($sPrice, 'getBasePrice')) {
$unitCost = $sPrice->getBasePrice();
if ($unitCost > 0) {
return $unitCost;
}
}
}
}
return 0.;
}
/**
* @return bool
*/
protected function isActive() {
$config = $this->Config();
return (empty($config->disabled) && !empty($config->serverUrl) && !empty($config->clientId) && !empty($config->clientSecret));
}
/**
* @param string $src
* @return string
*/
protected function loadAsynchronousJavascript($src) {
$src = json_encode($src);
return "<script>(function(d,t,s,f){s=d.createElement(t);s.async=1;s.src={$src};f=d.getElementsByTagName(t)[0];f.parentNode.insertBefore(s,f)})(document,'script')</script>";
}
/**
* @param Enlight_View_Default $view
*/
protected function loadWidget(Enlight_View_Default $view) {
$view->addTemplateDir(__DIR__ . '/Views/Common');
$version = Shopware()->Shop()->getTemplate()->getVersion();
if ($version >= 3) {
$view->addTemplateDir(__DIR__ . '/Views/Responsive');
} else {
$view->addTemplateDir(__DIR__ . '/Views/Emotion');
$view->extendsTemplate('frontend/checkout/index_darwinpricing.tpl');
}
$widgetUrl = $this->getApiUrl('/widget');
$darwinPricingWidget = $this->loadAsynchronousJavascript($widgetUrl);
$view->assign('darwinPricingWidget', $darwinPricingWidget);
}
/**
* @return array
* @throws Exception
*/
protected function readPluginInfo() {
static $pluginInfo = null;
if (!isset($pluginInfo)) {
$pluginInfoJson = @file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'plugin.json');
if (false === $pluginInfoJson) {
throw new Exception('Plugin info not found');
}
$pluginInfo = json_decode($pluginInfoJson, true);
if (!is_array($pluginInfo)) {
throw new Exception('Plugin info invalid');
}
}
return $pluginInfo;
}
protected function registerEvents() {
$this->subscribeEvent('Enlight_Controller_Action_PostDispatchSecure_Frontend', 'onPostDispatch');
}
/**
* @param string $sOrderNumber
* @param string $visitorIp
*/
protected function trackOrder($sOrderNumber, $visitorIp) {
$url = $this->getApiUrl('/shopware/webhook-order', $visitorIp);
$sOrder = $this->getOrder($sOrderNumber);
if (null === $sOrder) {
return;
}
$sOrder = $this->addUnitCosts($sOrder);
$body = json_encode($sOrder);
$this->webhook($url, $body);
}
/**
* @param string $url
* @param string $body
*/
protected function webhook($url, $body) {
$optionList = array(
CURLOPT_POST => true,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT_MS => 3000,
CURLOPT_POSTFIELDS => $body,
);
$this->executeOnShutdown(function() use($optionList) {
$ch = curl_init();
curl_setopt_array($ch, $optionList);
curl_exec($ch);
curl_close($ch);
});
}
}