Passed
Push — master ( 2196ce...ac647e )
by Aimeos
03:24
created

Standard::filename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
cc 1
rs 10
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2024
6
 * @package Controller
7
 * @subpackage Order
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Order\Email\Payment;
12
13
14
/**
15
 * Order payment e-mail job controller.
16
 *
17
 * @package Controller
18
 * @subpackage Order
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Jobs\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	/** controller/jobs/order/email/payment/name
25
	 * Class name of the used order email payment scheduler controller implementation
26
	 *
27
	 * Each default job controller can be replace by an alternative imlementation.
28
	 * To use this implementation, you have to set the last part of the class
29
	 * name as configuration value so the controller factory knows which class it
30
	 * has to instantiate.
31
	 *
32
	 * For example, if the name of the default class is
33
	 *
34
	 *  \Aimeos\Controller\Jobs\Order\Email\Payment\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Order\Email\Payment\Mypayment
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/order/email/payment/name = Mypayment
43
	 *
44
	 * The value is the last part of your own class name and it's case sensitive,
45
	 * so take care that the configuration value is exactly named like the last
46
	 * part of the class name.
47
	 *
48
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
49
	 * characters are possible! You should always start the last part of the class
50
	 * name with an upper case character and continue only with lower case characters
51
	 * or numbers. Avoid chamel case names like "MyPayment"!
52
	 *
53
	 * @param string Last part of the class name
54
	 * @since 2014.03
55
	 */
56
57
	/** controller/jobs/order/email/payment/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the order email payment controllers
59
	 *
60
	 * Decorators extend the functionality of a class by adding new aspects
61
	 * (e.g. log what is currently done), executing the methods of the underlying
62
	 * class only in certain conditions (e.g. only for logged in users) or
63
	 * modify what is returned to the caller.
64
	 *
65
	 * This option allows you to remove a decorator added via
66
	 * "controller/jobs/common/decorators/default" before they are wrapped
67
	 * around the job controller.
68
	 *
69
	 *  controller/jobs/order/email/payment/decorators/excludes = array( 'decorator1' )
70
	 *
71
	 * This would remove the decorator named "decorator1" from the list of
72
	 * common decorators ("\Aimeos\Controller\Jobs\Common\Decorator\*") added via
73
	 * "controller/jobs/common/decorators/default" to this job controller.
74
	 *
75
	 * @param array List of decorator names
76
	 * @since 2015.09
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/order/email/payment/decorators/global
79
	 * @see controller/jobs/order/email/payment/decorators/local
80
	 */
81
82
	/** controller/jobs/order/email/payment/decorators/global
83
	 * Adds a list of globally available decorators only to the order email payment controllers
84
	 *
85
	 * Decorators extend the functionality of a class by adding new aspects
86
	 * (e.g. log what is currently done), executing the methods of the underlying
87
	 * class only in certain conditions (e.g. only for logged in users) or
88
	 * modify what is returned to the caller.
89
	 *
90
	 * This option allows you to wrap global decorators
91
	 * ("\Aimeos\Controller\Jobs\Common\Decorator\*") around the job controller.
92
	 *
93
	 *  controller/jobs/order/email/payment/decorators/global = array( 'decorator1' )
94
	 *
95
	 * This would add the decorator named "decorator1" defined by
96
	 * "\Aimeos\Controller\Jobs\Common\Decorator\Decorator1" only to this job controller.
97
	 *
98
	 * @param array List of decorator names
99
	 * @since 2015.09
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/order/email/payment/decorators/excludes
102
	 * @see controller/jobs/order/email/payment/decorators/local
103
	 */
104
105
	/** controller/jobs/order/email/payment/decorators/local
106
	 * Adds a list of local decorators only to the order email payment controllers
107
	 *
108
	 * Decorators extend the functionality of a class by adding new aspects
109
	 * (e.g. log what is currently done), executing the methods of the underlying
110
	 * class only in certain conditions (e.g. only for logged in users) or
111
	 * modify what is returned to the caller.
112
	 *
113
	 * This option allows you to wrap local decorators
114
	 * ("\Aimeos\Controller\Jobs\Order\Email\Payment\Decorator\*") around this job controller.
115
	 *
116
	 *  controller/jobs/order/email/payment/decorators/local = array( 'decorator2' )
117
	 *
118
	 * This would add the decorator named "decorator2" defined by
119
	 * "\Aimeos\Controller\Jobs\Order\Email\Payment\Decorator\Decorator2" only to this job
120
	 * controller.
121
	 *
122
	 * @param array List of decorator names
123
	 * @since 2015.09
124
	 * @see controller/jobs/common/decorators/default
125
	 * @see controller/jobs/order/email/payment/decorators/excludes
126
	 * @see controller/jobs/order/email/payment/decorators/global
127
	 */
128
129
130
	use \Aimeos\Controller\Jobs\Mail;
131
132
133
	/**
134
	 * Returns the localized name of the job.
135
	 *
136
	 * @return string Name of the job
137
	 */
138
	public function getName() : string
139
	{
140
		return $this->context()->translate( 'controller/jobs', 'Order payment related e-mails' );
141
	}
142
143
144
	/**
145
	 * Returns the localized description of the job.
146
	 *
147
	 * @return string Description of the job
148
	 */
149
	public function getDescription() : string
150
	{
151
		return $this->context()->translate( 'controller/jobs', 'Sends order confirmation or payment status update e-mails' );
152
	}
153
154
155
	/**
156
	 * Executes the job.
157
	 *
158
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
159
	 */
160
	public function run()
161
	{
162
		$context = $this->context();
163
		$config = $context->config();
164
		$limitDate = date( 'Y-m-d H:i:s', time() - $this->limit() * 86400 );
165
166
		$orderManager = \Aimeos\MShop::create( $context, 'order' );
167
168
		foreach( $this->status() as $status )
169
		{
170
			$param = [\Aimeos\MShop\Order\Item\Status\Base::EMAIL_PAYMENT, (string) $status];
171
			$filter = $orderManager->filter();
172
			$filter->add( $filter->and( [
173
				$filter->compare( '>=', 'order.mtime', $limitDate ),
174
				$filter->compare( '==', 'order.statuspayment', $status ),
175
				$filter->compare( '==', $filter->make( 'order:status', $param ), 0 ),
176
			] ) );
177
178
			$start = 0;
179
			$ref = ['order'] + $context->config()->get( 'mshop/order/manager/subdomains', [] );
180
181
			do
182
			{
183
				$items = $orderManager->search( $filter->slice( $start ), $ref );
184
185
				$this->notify( $items, $status );
186
187
				$count = count( $items );
188
				$start += $count;
189
			}
190
			while( $count >= $filter->getLimit() );
191
		}
192
	}
193
194
195
	/**
196
	 * Returns the address item from the order
197
	 *
198
	 * @param \Aimeos\MShop\Order\Item\Iface $basket Order including address items
199
	 * @return \Aimeos\MShop\Common\Item\Address\Iface Address item
200
	 * @throws \Aimeos\Controller\Jobs\Exception If no suitable address item is available
201
	 */
202
	protected function address( \Aimeos\MShop\Order\Item\Iface $basket ) : \Aimeos\MShop\Common\Item\Address\Iface
203
	{
204
		if( ( $addr = current( $basket->getAddress( 'payment' ) ) ) !== false && $addr->getEmail() ) {
205
			return $addr;
206
		};
207
208
		$msg = sprintf( 'No address with e-mail found in order base with ID "%1$s"', $basket->getId() );
209
		throw new \Aimeos\Controller\Jobs\Exception( $msg );
210
	}
211
212
213
	/**
214
	 * Adds the given list of files as attachments to the mail message object
215
	 *
216
	 * @param \Aimeos\Base\Mail\Message\Iface $msg Mail message
217
	 * @param array $files List of absolute file paths
218
	 */
219
	protected function attachments( \Aimeos\Base\Mail\Message\Iface $msg ) : \Aimeos\Base\Mail\Message\Iface
220
	{
221
		$context = $this->context();
222
		$fs = $context->fs();
223
224
		/** controller/jobs/order/email/payment/attachments
225
		 * List of file paths whose content should be attached to all payment e-mails
226
		 *
227
		 * This configuration option allows you to add files to the e-mails that are
228
		 * sent to the customer when the payment status changes, e.g. for the order
229
		 * confirmation e-mail. These files can't be customer specific.
230
		 *
231
		 * @param array List of absolute file paths
232
		 * @since 2016.10
233
		 * @see controller/jobs/order/email/delivery/attachments
234
		 */
235
		$files = $context->config()->get( 'controller/jobs/order/email/payment/attachments', [] );
236
237
		foreach( $files as $filepath )
238
		{
239
			if( $fs->has( $filepath ) ) {
240
				$msg->attach( $fs->read( $filepath ), basename( $filepath ) );
241
			}
242
		}
243
244
		return $msg;
245
	}
246
247
248
	/**
249
	 * Returns the PDF file name
250
	 *
251
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order item
252
	 * @return string PDF file name
253
	 */
254
	protected function filename( \Aimeos\MShop\Order\Item\Iface $order ) : string
255
	{
256
		return $this->context()->translate( 'controller/jobs', 'Invoice' ) . '-' . $order->getInvoiceNumber() . '.pdf';
257
	}
258
259
260
	/**
261
	 * Returns the number of days after no e-mail will be sent anymore
262
	 *
263
	 * @return int Number of days
264
	 */
265
	protected function limit() : int
266
	{
267
		/** controller/jobs/order/email/payment/limit-days
268
		 * Only send payment e-mails of orders that were created in the past within the configured number of days
269
		 *
270
		 * The payment e-mails are normally send immediately after the payment
271
		 * status has changed. This option prevents e-mails for old order from
272
		 * being send in case anything went wrong or an update failed to avoid
273
		 * confusion of customers.
274
		 *
275
		 * @param integer Number of days
276
		 * @since 2014.03
277
		 * @see controller/jobs/order/email/delivery/limit-days
278
		 * @see controller/jobs/service/delivery/process/limit-days
279
		 */
280
		return (int) $this->context()->config()->get( 'controller/jobs/order/email/payment/limit-days', 30 );
281
	}
282
283
284
	/**
285
	 * Sends the payment e-mail for the given orders
286
	 *
287
	 * @param \Aimeos\Map $items List of order items implementing \Aimeos\MShop\Order\Item\Iface with their IDs as keys
288
	 * @param int $status Delivery status value
289
	 */
290
	protected function notify( \Aimeos\Map $items, int $status )
291
	{
292
		$context = $this->context();
293
		$sites = $this->sites( $items->getSiteId()->unique() );
294
295
		foreach( $items as $id => $item )
296
		{
297
			try
298
			{
299
				$list = $sites->get( $item->getSiteId(), map() );
300
301
				$this->send( $item, $list->getTheme()->filter()->last(), $list->getLogo()->filter()->last() );
302
				$this->update( $id, $status );
303
304
				$str = sprintf( 'Sent order payment e-mail for order "%1$s" and status "%2$s"', $item->getId(), $status );
305
				$context->logger()->info( $str, 'email/order/payment' );
306
			}
307
			catch( \Exception $e )
308
			{
309
				$str = 'Error while trying to send payment e-mail for order ID "%1$s" and status "%2$s": %3$s';
310
				$msg = sprintf( $str, $item->getId(), $item->getStatusPayment(), $e->getMessage() );
311
				$context->logger()->error( $msg . PHP_EOL . $e->getTraceAsString(), 'email/order/payment' );
312
			}
313
		}
314
	}
315
316
317
	/**
318
	 * Returns the generated PDF file for the order
319
	 *
320
	 * @param \Aimeos\Base\View\Iface $view View object with address and order item assigned
321
	 * @return string|null PDF content or NULL for no PDF file
322
	 */
323
	protected function pdf( \Aimeos\Base\View\Iface $view ) : ?string
324
	{
325
		$config = $this->context()->config();
326
327
		/** controller/jobs/order/email/payment/pdf
328
		 * Enables attaching the order confirmation PDF to the payment e-mail
329
		 *
330
		 * The order confirmation PDF contains the same information like the
331
		 * HTML e-mail and can be also used as invoice if possible.
332
		 *
333
		 * @param bool TRUE to enable attaching the PDF, FALSE to skip the PDF
334
		 * @since 2022.04
335
		 */
336
		if( !$config->get( 'controller/jobs/order/email/payment/pdf', true ) ) {
337
			return null;
338
		}
339
340
		$pdf = new class( PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false ) extends \TCPDF {
341
			private ?\Closure $headerFcn = null;
342
			private ?\Closure $footerFcn = null;
343
344
			public function Footer() { return ( $fcn = $this->footerFcn ) ? $fcn( $this ) : null; }
345
			public function Header() { return ( $fcn = $this->headerFcn ) ? $fcn( $this ) : null; }
346
			public function setFooterFunction( \Closure $fcn ) { $this->footerFcn = $fcn; }
347
			public function setHeaderFunction( \Closure $fcn ) { $this->headerFcn = $fcn; }
348
		};
349
		$pdf->setCreator( PDF_CREATOR );
350
		$pdf->setAuthor( 'Aimeos' );
351
352
		/** controller/jobs/order/email/payment/template-pdf
353
		 * Relative path to the template for the PDF part of the payment emails.
354
		 *
355
		 * The template file contains the text and processing instructions
356
		 * to generate the result shown in the body of the frontend. The
357
		 * configuration string is the path to the template file relative
358
		 * to the templates directory (usually in templates/controller/jobs).
359
		 * You can overwrite the template file configuration in extensions and
360
		 * provide alternative templates.
361
		 *
362
		 * @param string Relative path to the template
363
		 * @since 2022.10
364
		 * @see controller/jobs/order/email/payment/template-html
365
		 * @see controller/jobs/order/email/payment/template-text
366
		 */
367
		$template = $config->get( 'controller/jobs/order/email/payment/template-pdf', 'order/email/payment/pdf' );
368
369
		// Generate HTML before creating first PDF page to include header added in template
370
		$content = $view->set( 'pdf', $pdf )->render( $template );
371
372
		$pdf->addPage();
373
		$pdf->writeHtml( $content );
374
		$pdf->lastPage();
375
376
		return $pdf->output( '', 'S' );
377
	}
378
379
380
	/**
381
	 * Sends the payment related e-mail for a single order
382
	 *
383
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order item
384
	 * @param string|null $theme Theme name or NULL for default theme
385
	 * @param string|null $logoPath Relative path to the logo in the fs-media file system
386
	 */
387
	protected function send( \Aimeos\MShop\Order\Item\Iface $order, string $theme = null, string $logoPath = null )
388
	{
389
		/** controller/jobs/order/email/payment/template-html
390
		 * Relative path to the template for the HTML part of the payment emails.
391
		 *
392
		 * The template file contains the HTML code and processing instructions
393
		 * to generate the result shown in the body of the frontend. The
394
		 * configuration string is the path to the template file relative
395
		 * to the templates directory (usually in templates/controller/jobs).
396
		 * You can overwrite the template file configuration in extensions and
397
		 * provide alternative templates.
398
		 *
399
		 * @param string Relative path to the template
400
		 * @since 2022.04
401
		 * @see controller/jobs/order/email/payment/template-text
402
		 */
403
404
		/** controller/jobs/order/email/payment/template-text
405
		 * Relative path to the template for the text part of the payment emails.
406
		 *
407
		 * The template file contains the text and processing instructions
408
		 * to generate the result shown in the body of the frontend. The
409
		 * configuration string is the path to the template file relative
410
		 * to the templates directory (usually in templates/controller/jobs).
411
		 * You can overwrite the template file configuration in extensions and
412
		 * provide alternative templates.
413
		 *
414
		 * @param string Relative path to the template
415
		 * @since 2022.04
416
		 * @see controller/jobs/order/email/payment/template-html
417
		 */
418
419
		$address = $this->address( $order );
420
421
		$context = $this->context();
422
		$context->locale()->setLanguageId( $address->getLanguageId() );
423
424
		$msg = $this->call( 'mailTo', $address );
425
		$msg = $this->attachments( $msg );
426
427
		$view = $this->view( $order, $theme );
428
		$view->logo = $msg->embed( $this->call( 'mailLogo', $logoPath ), basename( (string) $logoPath ) );
429
		$view->summaryBasket = $order;
430
		$view->addressItem = $address;
431
		$view->orderItem = $order;
432
433
		$config = $context->config();
434
435
		/** controller/jobs/order/email/payment/cc-email
436
		 * E-Mail address all payment e-mails should be also sent to
437
		 *
438
		 * Using this option you can send a copy of all payment related e-mails
439
		 * to a second e-mail account. This can be handy for testing and checking
440
		 * the e-mails sent to customers.
441
		 *
442
		 * It also allows shop owners with a very small volume of orders to be
443
		 * notified about payment changes. Be aware that this isn't useful if the
444
		 * order volumne is high or has peeks!
445
		 *
446
		 * @param string E-mail address or list of e-mail addresses
447
		 * @since 2023.10
448
		 */
449
		$msg->cc( $config->get( 'controller/jobs/order/email/payment/cc-email', '' ) );
450
451
		/** controller/jobs/order/email/payment/bcc-email
452
		 * Hidden e-mail address all payment e-mails should be also sent to
453
		 *
454
		 * Using this option you can send a copy of all payment related e-mails
455
		 * to a second e-mail account. This can be handy for testing and checking
456
		 * the e-mails sent to customers.
457
		 *
458
		 * It also allows shop owners with a very small volume of orders to be
459
		 * notified about payment changes. Be aware that this isn't useful if the
460
		 * order volumne is high or has peeks!
461
		 *
462
		 * @param string|array E-mail address or list of e-mail addresses
463
		 * @since 2014.03
464
		 */
465
		$msg->bcc( $config->get( 'controller/jobs/order/email/payment/bcc-email', [] ) );
466
467
		$msg->subject( sprintf( $context->translate( 'controller/jobs', 'Your order %1$s' ), $order->getInvoiceNumber() ) )
468
			->html( $view->render( $config->get( 'controller/jobs/order/email/payment/template-html', 'order/email/payment/html' ) ) )
469
			->text( $view->render( $config->get( 'controller/jobs/order/email/payment/template-text', 'order/email/payment/text' ) ) )
470
			->attach( $this->pdf( $view ), $this->call( 'filename', $order ), 'application/pdf' )
471
			->send();
472
	}
473
474
475
	/**
476
	 * Returns the site items for the given site codes
477
	 *
478
	 * @param iterable $siteIds List of site IDs
479
	 * @return \Aimeos\Map Site items with codes as keys
480
	 */
481
	protected function sites( iterable $siteIds ) : \Aimeos\Map
482
	{
483
		$map = [];
484
		$manager = \Aimeos\MShop::create( $this->context(), 'locale/site' );
485
486
		foreach( $siteIds as $siteId )
487
		{
488
			$list = explode( '.', trim( $siteId, '.' ) );
489
			$map[$siteId] = $manager->getPath( end( $list ) );
490
		}
491
492
		return map( $map );
493
	}
494
495
496
	/**
497
	 * Returns the payment status values for which an e-mail should be sent
498
	 *
499
	 * @return array List of payment status values
500
	 */
501
	protected function status() : array
502
	{
503
		$default = [
504
			\Aimeos\MShop\Order\Item\Base::PAY_REFUND,
505
			\Aimeos\MShop\Order\Item\Base::PAY_PENDING,
506
			\Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED,
507
			\Aimeos\MShop\Order\Item\Base::PAY_RECEIVED,
508
		];
509
510
		/** controller/jobs/order/email/payment/status
511
		 * Only send order payment notification e-mails for these payment status values
512
		 *
513
		 * Notification e-mail about payment status changes can be sent for these
514
		 * status values:
515
		 *
516
		 * * 0: deleted
517
		 * * 1: canceled
518
		 * * 2: refused
519
		 * * 3: refund
520
		 * * 4: pending
521
		 * * 5: authorized
522
		 * * 6: received
523
		 * * 7: transferred
524
		 *
525
		 * User-defined status values are possible but should be in the private
526
		 * block of values between 30000 and 32767.
527
		 *
528
		 * @param integer Payment status constant
529
		 * @since 2014.03
530
		 * @see controller/jobs/order/email/delivery/status
531
		 * @see controller/jobs/order/email/payment/limit-days
532
		 */
533
		return (array) $this->context()->config()->get( 'controller/jobs/order/email/payment/status', $default );
534
	}
535
536
537
	/**
538
	 * Adds the status of the delivered e-mail for the given order ID
539
	 *
540
	 * @param string $orderId Unique order ID
541
	 * @param int $value Status value
542
	 */
543
	protected function update( string $orderId, int $value )
544
	{
545
		$manager = \Aimeos\MShop::create( $this->context(), 'order/status' );
546
547
		$item = $manager->create()
548
			->setParentId( $orderId )
549
			->setType( \Aimeos\MShop\Order\Item\Status\Base::EMAIL_PAYMENT )
550
			->setValue( $value );
551
552
		$manager->save( $item );
553
	}
554
555
556
	/**
557
	 * Returns the view populated with common data
558
	 *
559
	 * @param \Aimeos\MShop\Order\Item\Iface $base Basket including addresses
560
	 * @param string|null $theme Theme name
561
	 * @return \Aimeos\Base\View\Iface View object
562
	 */
563
	protected function view( \Aimeos\MShop\Order\Item\Iface $base, string $theme = null ) : \Aimeos\Base\View\Iface
564
	{
565
		$address = $this->address( $base );
566
		$langId = $address->getLanguageId() ?: $base->locale()->getLanguageId();
567
568
		$view = $this->call( 'mailView', $langId );
569
		$view->intro = $this->call( 'mailIntro', $address );
570
		$view->css = $this->call( 'mailCss', $theme );
571
		$view->address = $address;
572
		$view->urlparams = [
573
			'currency' => $base->getPrice()->getCurrencyId(),
574
			'site' => $base->getSiteCode(),
575
			'locale' => $langId,
576
		];
577
578
		return $view;
579
	}
580
}
581