Passed
Push — master ( 0c09b5...f0a4a0 )
by Aimeos
05:26
created

Standard::createItemBase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2011
6
 * @copyright Aimeos (aimeos.org), 2015-2022
7
 * @package MShop
8
 * @subpackage Media
9
 */
10
11
12
namespace Aimeos\MShop\Media\Manager;
13
14
15
/**
16
 * Default media manager implementation.
17
 *
18
 * @package MShop
19
 * @subpackage Media
20
 */
21
class Standard
22
	extends \Aimeos\MShop\Common\Manager\Base
23
	implements \Aimeos\MShop\Media\Manager\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
24
{
25
	/** mshop/media/manager/name
26
	 * Class name of the used media manager implementation
27
	 *
28
	 * Each default manager can be replace by an alternative imlementation.
29
	 * To use this implementation, you have to set the last part of the class
30
	 * name as configuration value so the manager factory knows which class it
31
	 * has to instantiate.
32
	 *
33
	 * For example, if the name of the default class is
34
	 *
35
	 *  \Aimeos\MShop\Media\Manager\Standard
36
	 *
37
	 * and you want to replace it with your own version named
38
	 *
39
	 *  \Aimeos\MShop\Media\Manager\Mymanager
40
	 *
41
	 * then you have to set the this configuration option:
42
	 *
43
	 *  mshop/media/manager/name = Mymanager
44
	 *
45
	 * The value is the last part of your own class name and it's case sensitive,
46
	 * so take care that the configuration value is exactly named like the last
47
	 * part of the class name.
48
	 *
49
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
50
	 * characters are possible! You should always start the last part of the class
51
	 * name with an upper case character and continue only with lower case characters
52
	 * or numbers. Avoid chamel case names like "MyManager"!
53
	 *
54
	 * @param string Last part of the class name
55
	 * @since 2014.03
56
	 * @category Developer
57
	 */
58
59
	/** mshop/media/manager/decorators/excludes
60
	 * Excludes decorators added by the "common" option from the media manager
61
	 *
62
	 * Decorators extend the functionality of a class by adding new aspects
63
	 * (e.g. log what is currently done), executing the methods of the underlying
64
	 * class only in certain conditions (e.g. only for logged in users) or
65
	 * modify what is returned to the caller.
66
	 *
67
	 * This option allows you to remove a decorator added via
68
	 * "mshop/common/manager/decorators/default" before they are wrapped
69
	 * around the media manager.
70
	 *
71
	 *  mshop/media/manager/decorators/excludes = array( 'decorator1' )
72
	 *
73
	 * This would remove the decorator named "decorator1" from the list of
74
	 * common decorators ("\Aimeos\MShop\Common\Manager\Decorator\*") added via
75
	 * "mshop/common/manager/decorators/default" for the media manager.
76
	 *
77
	 * @param array List of decorator names
78
	 * @since 2014.03
79
	 * @category Developer
80
	 * @see mshop/common/manager/decorators/default
81
	 * @see mshop/media/manager/decorators/global
82
	 * @see mshop/media/manager/decorators/local
83
	 */
84
85
	/** mshop/media/manager/decorators/global
86
	 * Adds a list of globally available decorators only to the media manager
87
	 *
88
	 * Decorators extend the functionality of a class by adding new aspects
89
	 * (e.g. log what is currently done), executing the methods of the underlying
90
	 * class only in certain conditions (e.g. only for logged in users) or
91
	 * modify what is returned to the caller.
92
	 *
93
	 * This option allows you to wrap global decorators
94
	 * ("\Aimeos\MShop\Common\Manager\Decorator\*") around the media manager.
95
	 *
96
	 *  mshop/media/manager/decorators/global = array( 'decorator1' )
97
	 *
98
	 * This would add the decorator named "decorator1" defined by
99
	 * "\Aimeos\MShop\Common\Manager\Decorator\Decorator1" only to the media
100
	 * manager.
101
	 *
102
	 * @param array List of decorator names
103
	 * @since 2014.03
104
	 * @category Developer
105
	 * @see mshop/common/manager/decorators/default
106
	 * @see mshop/media/manager/decorators/excludes
107
	 * @see mshop/media/manager/decorators/local
108
	 */
109
110
	/** mshop/media/manager/decorators/local
111
	 * Adds a list of local decorators only to the media manager
112
	 *
113
	 * Decorators extend the functionality of a class by adding new aspects
114
	 * (e.g. log what is currently done), executing the methods of the underlying
115
	 * class only in certain conditions (e.g. only for logged in users) or
116
	 * modify what is returned to the caller.
117
	 *
118
	 * This option allows you to wrap local decorators
119
	 * ("\Aimeos\MShop\Media\Manager\Decorator\*") around the media manager.
120
	 *
121
	 *  mshop/media/manager/decorators/local = array( 'decorator2' )
122
	 *
123
	 * This would add the decorator named "decorator2" defined by
124
	 * "\Aimeos\MShop\Media\Manager\Decorator\Decorator2" only to the media
125
	 * manager.
126
	 *
127
	 * @param array List of decorator names
128
	 * @since 2014.03
129
	 * @category Developer
130
	 * @see mshop/common/manager/decorators/default
131
	 * @see mshop/media/manager/decorators/excludes
132
	 * @see mshop/media/manager/decorators/global
133
	 */
134
135
136
	use \Aimeos\MShop\Common\Manager\ListsRef\Traits;
137
	use \Aimeos\MShop\Common\Manager\PropertyRef\Traits;
138
139
140
	private $searchConfig = array(
141
		'media.id' => array(
142
			'label' => 'ID',
143
			'code' => 'media.id',
144
			'internalcode' => 'mmed."id"',
145
			'type' => 'integer',
146
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
147
		),
148
		'media.siteid' => array(
149
			'label' => 'Site ID',
150
			'code' => 'media.siteid',
151
			'internalcode' => 'mmed."siteid"',
152
			'type' => 'string',
153
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
154
			'public' => false,
155
		),
156
		'media.type' => array(
157
			'label' => 'Type',
158
			'code' => 'media.type',
159
			'internalcode' => 'mmed."type"',
160
			'type' => 'string',
161
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
162
		),
163
		'media.label' => array(
164
			'label' => 'Label',
165
			'code' => 'media.label',
166
			'internalcode' => 'mmed."label"',
167
			'type' => 'string',
168
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
169
		),
170
		'media.domain' => array(
171
			'label' => 'Domain',
172
			'code' => 'media.domain',
173
			'internalcode' => 'mmed."domain"',
174
			'type' => 'string',
175
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
176
		),
177
		'media.languageid' => array(
178
			'label' => 'Language code',
179
			'code' => 'media.languageid',
180
			'internalcode' => 'mmed."langid"',
181
			'type' => 'string',
182
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
183
		),
184
		'media.mimetype' => array(
185
			'label' => 'Mime type',
186
			'code' => 'media.mimetype',
187
			'internalcode' => 'mmed."mimetype"',
188
			'type' => 'string',
189
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
190
		),
191
		'media.url' => array(
192
			'label' => 'URL',
193
			'code' => 'media.url',
194
			'internalcode' => 'mmed."link"',
195
			'type' => 'string',
196
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
197
		),
198
		'media.preview' => array(
199
			'label' => 'Preview URLs as JSON encoded string',
200
			'code' => 'media.preview',
201
			'internalcode' => 'mmed."preview"',
202
			'type' => 'string',
203
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
204
		),
205
		'media.filesystem' => array(
206
			'label' => 'File sytem name',
207
			'code' => 'media.filesystem',
208
			'internalcode' => 'mmed."fsname"',
209
			'type' => 'string',
210
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
211
		),
212
		'media.status' => array(
213
			'label' => 'Status',
214
			'code' => 'media.status',
215
			'internalcode' => 'mmed."status"',
216
			'type' => 'integer',
217
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_INT,
218
		),
219
		'media.ctime' => array(
220
			'code' => 'media.ctime',
221
			'internalcode' => 'mmed."ctime"',
222
			'label' => 'Create date/time',
223
			'type' => 'datetime',
224
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
225
			'public' => false,
226
		),
227
		'media.mtime' => array(
228
			'code' => 'media.mtime',
229
			'internalcode' => 'mmed."mtime"',
230
			'label' => 'Modify date/time',
231
			'type' => 'datetime',
232
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
233
			'public' => false,
234
		),
235
		'media.editor' => array(
236
			'code' => 'media.editor',
237
			'internalcode' => 'mmed."editor"',
238
			'label' => 'Editor',
239
			'type' => 'string',
240
			'internaltype' => \Aimeos\Base\DB\Statement\Base::PARAM_STR,
241
			'public' => false,
242
		),
243
		'media:has' => array(
244
			'code' => 'media:has()',
245
			'internalcode' => ':site AND :key AND mmedli."id"',
246
			'internaldeps' => ['LEFT JOIN "mshop_media_list" AS mmedli ON ( mmedli."parentid" = mmed."id" )'],
247
			'label' => 'Media has list item, parameter(<domain>[,<list type>[,<reference ID>)]]',
248
			'type' => 'null',
249
			'internaltype' => 'null',
250
			'public' => false,
251
		),
252
		'media:prop' => array(
253
			'code' => 'media:prop()',
254
			'internalcode' => ':site AND :key AND mmedpr."id"',
255
			'internaldeps' => ['LEFT JOIN "mshop_media_property" AS mmedpr ON ( mmedpr."parentid" = mmed."id" )'],
256
			'label' => 'Media has property item, parameter(<property type>[,<language code>[,<property value>]])',
257
			'type' => 'null',
258
			'internaltype' => 'null',
259
			'public' => false,
260
		),
261
	);
262
263
	private $languageId;
264
265
266
	/**
267
	 * Initializes the object.
268
	 *
269
	 * @param \Aimeos\MShop\ContextIface $context Context object
270
	 */
271
	public function __construct( \Aimeos\MShop\ContextIface $context )
272
	{
273
		parent::__construct( $context );
274
275
		$this->setResourceName( 'db-media' );
276
		$this->languageId = $context->locale()->getLanguageId();
277
278
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
279
		$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
280
281
282
		$this->searchConfig['media:has']['function'] = function( &$source, array $params ) use ( $level ) {
283
284
			$keys = [];
285
286
			foreach( (array) ( $params[1] ?? '' ) as $type ) {
287
				foreach( (array) ( $params[2] ?? '' ) as $id ) {
288
					$keys[] = $params[0] . '|' . ( $type ? $type . '|' : '' ) . $id;
289
				}
290
			}
291
292
			$sitestr = $this->siteString( 'mmedli."siteid"', $level );
293
			$keystr = $this->toExpression( 'mmedli."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
294
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
295
296
			return $params;
297
		};
298
299
300
		$this->searchConfig['media:prop']['function'] = function( &$source, array $params ) use ( $level ) {
301
302
			$keys = [];
303
			$langs = array_key_exists( 1, $params ) ? ( $params[1] ?? 'null' ) : '';
304
305
			foreach( (array) $langs as $lang ) {
306
				foreach( (array) ( $params[2] ?? '' ) as $val ) {
307
					$keys[] = substr( $params[0] . '|' . ( $lang === null ? 'null|' : ( $lang ? $lang . '|' : '' ) ) . $val, 0, 255 );
308
				}
309
			}
310
311
			$sitestr = $this->siteString( 'mmedpr."siteid"', $level );
312
			$keystr = $this->toExpression( 'mmedpr."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
313
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
314
315
			return $params;
316
		};
317
	}
318
319
320
	/**
321
	 * Removes old entries from the storage.
322
	 *
323
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
324
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
325
	 */
326
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
327
	{
328
		$path = 'mshop/media/manager/submanagers';
329
		$default = ['lists', 'property', 'type'];
330
331
		foreach( $this->context()->config()->get( $path, $default ) as $domain ) {
332
			$this->object()->getSubManager( $domain )->clear( $siteids );
333
		}
334
335
		return $this->clearBase( $siteids, 'mshop/media/manager/delete' );
336
	}
337
338
339
	/**
340
	 * Copies the media item and the referenced files
341
	 *
342
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be copied
343
	 * @return \Aimeos\MShop\Media\Item\Iface Copied media item with new files
344
	 * @todo 2023.01 Add to media manager interface
345
	 */
346
	public function copy( \Aimeos\MShop\Media\Item\Iface $item ) : \Aimeos\MShop\Media\Item\Iface
347
	{
348
		$item = ( clone $item )->setId( null );
349
350
		$path = $item->getUrl();
351
		$previews = $item->getPreviews();
352
		$fsname = $item->getFileSystem();
353
		$fs = $this->context()->fs( $fsname );
354
355
		if( $fs->has( $path ) )
356
		{
357
			$newPath = $this->getPath( substr( basename( $path ), 9 ), 'files', $item->getMimeType() );
358
			$fs->copy( $path, $newPath );
359
			$item->setUrl( $newPath );
360
		}
361
362
		foreach( $previews as $size => $preview )
363
		{
364
			if( $fsname !== 'fs-mimeicon' && $fs->has( $preview ) )
365
			{
366
				$newPath = $this->getPath( substr( basename( $preview ), 9 ), 'preview', pathinfo( $preview, PATHINFO_EXTENSION ) );
0 ignored issues
show
Bug introduced by
It seems like pathinfo($preview, Aimeo...ger\PATHINFO_EXTENSION) can also be of type array; however, parameter $domain of Aimeos\MShop\Media\Manager\Standard::getPath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

366
				$newPath = $this->getPath( substr( basename( $preview ), 9 ), 'preview', /** @scrutinizer ignore-type */ pathinfo( $preview, PATHINFO_EXTENSION ) );
Loading history...
367
				$fs->copy( $preview, $newPath );
368
				$previews[$size] = $newPath;
369
			}
370
		}
371
372
		return $item->setPreviews( $previews );
373
	}
374
375
376
	/**
377
	 * Creates a new empty item instance
378
	 *
379
	 * @param array $values Values the item should be initialized with
380
	 * @return \Aimeos\MShop\Media\Item\Iface New media item object
381
	 */
382
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
383
	{
384
		$values['media.siteid'] = $this->context()->locale()->getSiteId();
385
		return $this->createItemBase( $values );
386
	}
387
388
389
	/**
390
	 * Removes multiple items.
391
	 *
392
	 * @param \Aimeos\MShop\Common\Item\Iface[]|string[] $itemIds List of item objects or IDs of the items
393
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
394
	 */
395
	public function delete( $itemIds ) : \Aimeos\MShop\Common\Manager\Iface
396
	{
397
		/** mshop/media/manager/delete/mysql
398
		 * Deletes the items matched by the given IDs from the database
399
		 *
400
		 * @see mshop/media/manager/delete/ansi
401
		 */
402
403
		/** mshop/media/manager/delete/ansi
404
		 * Deletes the items matched by the given IDs from the database
405
		 *
406
		 * Removes the records specified by the given IDs from the media database.
407
		 * The records must be from the site that is configured via the
408
		 * context item.
409
		 *
410
		 * The ":cond" placeholder is replaced by the name of the ID column and
411
		 * the given ID or list of IDs while the site ID is bound to the question
412
		 * mark.
413
		 *
414
		 * The SQL statement should conform to the ANSI standard to be
415
		 * compatible with most relational database systems. This also
416
		 * includes using double quotes for table and column names.
417
		 *
418
		 * @param string SQL statement for deleting items
419
		 * @since 2014.03
420
		 * @category Developer
421
		 * @see mshop/media/manager/insert/ansi
422
		 * @see mshop/media/manager/update/ansi
423
		 * @see mshop/media/manager/newid/ansi
424
		 * @see mshop/media/manager/search/ansi
425
		 * @see mshop/media/manager/count/ansi
426
		 */
427
		$path = 'mshop/media/manager/delete';
428
429
		return $this->deleteItemsBase( $itemIds, $path )->deleteRefItems( $itemIds );
430
	}
431
432
433
	/**
434
	 * Creates a filter object.
435
	 *
436
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
437
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
438
	 * @return \Aimeos\Base\Criteria\Iface Returns the filter object
439
	 */
440
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\Base\Criteria\Iface
441
	{
442
		if( $default !== false )
443
		{
444
			$object = $this->filterBase( 'media', $default );
445
			$langid = $this->context()->locale()->getLanguageId();
446
447
			if( $langid !== null )
448
			{
449
				$temp = array(
450
					$object->compare( '==', 'media.languageid', $langid ),
451
					$object->compare( '==', 'media.languageid', null ),
452
				);
453
454
				$expr = array(
455
					$object->getConditions(),
456
					$object->or( $temp ),
457
				);
458
459
				$object->setConditions( $object->and( $expr ) );
460
			}
461
462
			return $object;
463
		}
464
465
		return parent::filter();
466
	}
467
468
469
	/**
470
	 * Returns an item for the given ID.
471
	 *
472
	 * @param string $id ID of the item that should be retrieved
473
	 * @param string[] $ref List of domains to fetch list items and referenced items for
474
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
475
	 * @return \Aimeos\MShop\Media\Item\Iface Returns the media item of the given id
476
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
477
	 */
478
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
479
	{
480
		return $this->getItemBase( 'media.id', $id, $ref, $default );
481
	}
482
483
484
	/**
485
	 * Returns the available manager types
486
	 *
487
	 * @param bool $withsub Return also the resource type of sub-managers if true
488
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
489
	 */
490
	public function getResourceType( bool $withsub = true ) : array
491
	{
492
		$path = 'mshop/media/manager/submanagers';
493
		$default = ['lists', 'property'];
494
495
		return $this->getResourceTypeBase( 'media', $path, $default, $withsub );
496
	}
497
498
499
	/**
500
	 * Returns the attributes that can be used for searching.
501
	 *
502
	 * @param bool $withsub Return also attributes of sub-managers if true
503
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of search attribute items
504
	 */
505
	public function getSearchAttributes( bool $withsub = true ) : array
506
	{
507
		/** mshop/media/manager/submanagers
508
		 * List of manager names that can be instantiated by the media manager
509
		 *
510
		 * Managers provide a generic interface to the underlying storage.
511
		 * Each manager has or can have sub-managers caring about particular
512
		 * aspects. Each of these sub-managers can be instantiated by its
513
		 * parent manager using the getSubManager() method.
514
		 *
515
		 * The search keys from sub-managers can be normally used in the
516
		 * manager as well. It allows you to search for items of the manager
517
		 * using the search keys of the sub-managers to further limit the
518
		 * retrieved list of items.
519
		 *
520
		 * @param array List of sub-manager names
521
		 * @since 2014.03
522
		 * @category Developer
523
		 */
524
		$path = 'mshop/media/manager/submanagers';
525
526
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
527
	}
528
529
530
	/**
531
	 * Returns a new manager for media extensions
532
	 *
533
	 * @param string $manager Name of the sub manager type in lower case
534
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
535
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g stock, tags, locations, etc.
536
	 */
537
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
538
	{
539
		return $this->getSubManagerBase( 'media', $manager, $name );
540
	}
541
542
543
	/**
544
	 * Adds a new item to the storage or updates an existing one.
545
	 *
546
	 * @param \Aimeos\MShop\Media\Item\Iface $item New item that should be saved to the storage
547
	 * @param bool $fetch True if the new ID should be returned in the item
548
	 * @return \Aimeos\MShop\Media\Item\Iface $item Updated item including the generated ID
549
	 */
550
	public function saveItem( \Aimeos\MShop\Media\Item\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Media\Item\Iface
551
	{
552
		if( !$item->isModified() )
553
		{
554
			$item = $this->savePropertyItems( $item, 'media', $fetch );
555
			return $this->saveListItems( $item, 'media', $fetch );
556
		}
557
558
		$context = $this->context();
559
		$conn = $context->db( $this->getResourceName() );
560
561
		$id = $item->getId();
562
		$date = date( 'Y-m-d H:i:s' );
563
		$columns = $this->object()->getSaveAttributes();
564
565
		if( $id === null )
566
		{
567
			/** mshop/media/manager/insert/mysql
568
			 * Inserts a new media record into the database table
569
			 *
570
			 * @see mshop/media/manager/insert/ansi
571
			 */
572
573
			/** mshop/media/manager/insert/ansi
574
			 * Inserts a new media record into the database table
575
			 *
576
			 * Items with no ID yet (i.e. the ID is NULL) will be created in
577
			 * the database and the newly created ID retrieved afterwards
578
			 * using the "newid" SQL statement.
579
			 *
580
			 * The SQL statement must be a string suitable for being used as
581
			 * prepared statement. It must include question marks for binding
582
			 * the values from the media item to the statement before they are
583
			 * sent to the database server. The number of question marks must
584
			 * be the same as the number of columns listed in the INSERT
585
			 * statement. The order of the columns must correspond to the
586
			 * order in the save() method, so the correct values are
587
			 * bound to the columns.
588
			 *
589
			 * The SQL statement should conform to the ANSI standard to be
590
			 * compatible with most relational database systems. This also
591
			 * includes using double quotes for table and column names.
592
			 *
593
			 * @param string SQL statement for inserting records
594
			 * @since 2014.03
595
			 * @category Developer
596
			 * @see mshop/media/manager/update/ansi
597
			 * @see mshop/media/manager/newid/ansi
598
			 * @see mshop/media/manager/delete/ansi
599
			 * @see mshop/media/manager/search/ansi
600
			 * @see mshop/media/manager/count/ansi
601
			 */
602
			$path = 'mshop/media/manager/insert';
603
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ) );
0 ignored issues
show
Bug introduced by
It seems like $this->getSqlConfig($path) can also be of type array; however, parameter $sql of Aimeos\MShop\Common\Manager\Base::addSqlColumns() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

603
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
604
		}
605
		else
606
		{
607
			/** mshop/media/manager/update/mysql
608
			 * Updates an existing media record in the database
609
			 *
610
			 * @see mshop/media/manager/update/ansi
611
			 */
612
613
			/** mshop/media/manager/update/ansi
614
			 * Updates an existing media record in the database
615
			 *
616
			 * Items which already have an ID (i.e. the ID is not NULL) will
617
			 * be updated in the database.
618
			 *
619
			 * The SQL statement must be a string suitable for being used as
620
			 * prepared statement. It must include question marks for binding
621
			 * the values from the media item to the statement before they are
622
			 * sent to the database server. The order of the columns must
623
			 * correspond to the order in the save() method, so the
624
			 * correct values are bound to the columns.
625
			 *
626
			 * The SQL statement should conform to the ANSI standard to be
627
			 * compatible with most relational database systems. This also
628
			 * includes using double quotes for table and column names.
629
			 *
630
			 * @param string SQL statement for updating records
631
			 * @since 2014.03
632
			 * @category Developer
633
			 * @see mshop/media/manager/insert/ansi
634
			 * @see mshop/media/manager/newid/ansi
635
			 * @see mshop/media/manager/delete/ansi
636
			 * @see mshop/media/manager/search/ansi
637
			 * @see mshop/media/manager/count/ansi
638
			 */
639
			$path = 'mshop/media/manager/update';
640
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
641
		}
642
643
		$idx = 1;
644
		$stmt = $this->getCachedStatement( $conn, $path, $sql );
645
646
		foreach( $columns as $name => $entry ) {
647
			$stmt->bind( $idx++, $item->get( $name ), $entry->getInternalType() );
0 ignored issues
show
Bug introduced by
It seems like $entry->getInternalType() can also be of type string; however, parameter $type of Aimeos\Base\DB\Statement\Iface::bind() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

647
			$stmt->bind( $idx++, $item->get( $name ), /** @scrutinizer ignore-type */ $entry->getInternalType() );
Loading history...
648
		}
649
650
		$stmt->bind( $idx++, $item->getLanguageId() );
651
		$stmt->bind( $idx++, $item->getType() );
652
		$stmt->bind( $idx++, $item->getLabel() );
653
		$stmt->bind( $idx++, $item->getMimeType() );
654
		$stmt->bind( $idx++, $item->getUrl() );
655
		$stmt->bind( $idx++, $item->getStatus(), \Aimeos\Base\DB\Statement\Base::PARAM_INT );
656
		$stmt->bind( $idx++, $item->getFileSystem() );
657
		$stmt->bind( $idx++, $item->getDomain() );
658
		$stmt->bind( $idx++, json_encode( $item->getPreviews(), JSON_FORCE_OBJECT ) );
659
		$stmt->bind( $idx++, $date ); // mtime
660
		$stmt->bind( $idx++, $context->editor() );
661
		$stmt->bind( $idx++, $context->locale()->getSiteId() );
662
663
		if( $id !== null ) {
664
			$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
665
		} else {
666
			$stmt->bind( $idx++, $date ); // ctime
667
		}
668
669
		$stmt->execute()->finish();
670
671
		if( $id === null )
672
		{
673
			/** mshop/media/manager/newid/mysql
674
			 * Retrieves the ID generated by the database when inserting a new record
675
			 *
676
			 * @see mshop/media/manager/newid/ansi
677
			 */
678
679
			/** mshop/media/manager/newid/ansi
680
			 * Retrieves the ID generated by the database when inserting a new record
681
			 *
682
			 * As soon as a new record is inserted into the database table,
683
			 * the database server generates a new and unique identifier for
684
			 * that record. This ID can be used for retrieving, updating and
685
			 * deleting that specific record from the table again.
686
			 *
687
			 * For MySQL:
688
			 *  SELECT LAST_INSERT_ID()
689
			 * For PostgreSQL:
690
			 *  SELECT currval('seq_mmed_id')
691
			 * For SQL Server:
692
			 *  SELECT SCOPE_IDENTITY()
693
			 * For Oracle:
694
			 *  SELECT "seq_mmed_id".CURRVAL FROM DUAL
695
			 *
696
			 * There's no way to retrive the new ID by a SQL statements that
697
			 * fits for most database servers as they implement their own
698
			 * specific way.
699
			 *
700
			 * @param string SQL statement for retrieving the last inserted record ID
701
			 * @since 2014.03
702
			 * @category Developer
703
			 * @see mshop/media/manager/insert/ansi
704
			 * @see mshop/media/manager/update/ansi
705
			 * @see mshop/media/manager/delete/ansi
706
			 * @see mshop/media/manager/search/ansi
707
			 * @see mshop/media/manager/count/ansi
708
			 */
709
			$path = 'mshop/media/manager/newid';
710
			$id = $this->newId( $conn, $path );
711
		}
712
713
		$item->setId( $id );
714
715
		$item = $this->savePropertyItems( $item, 'media', $fetch );
716
		return $this->saveListItems( $item, 'media', $fetch );
717
	}
718
719
720
	/**
721
	 * Rescales the original file to preview files referenced by the media item
722
	 *
723
	 * The height/width configuration for scaling
724
	 * - mshop/media/<files|preview>/maxheight
725
	 * - mshop/media/<files|preview>/maxwidth
726
	 * - mshop/media/<files|preview>/force-size
727
	 *
728
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be scaled
729
	 * @param bool $force True to enforce creating new preview images
730
	 * @return \Aimeos\MShop\Media\Item\Iface Rescaled media item
731
	 * @todo 2023.01 Add to media manager interface
732
	 */
733
	public function scale( \Aimeos\MShop\Media\Item\Iface $item, bool $force = false ) : \Aimeos\MShop\Media\Item\Iface
734
	{
735
		if( strncmp( $item->getMimeType(), 'image/', 6 ) ) {
736
			return $item;
737
		}
738
739
		$context = $this->context();
740
		$fsname = $item->getFileSystem();
741
742
		$url = $item->getUrl();
743
		$fs = $context->fs( $fsname );
744
		$is = ( $fs instanceof \Aimeos\Base\Filesystem\MetaIface ? true : false );
745
746
		if( !$force && $is && preg_match( '#^[a-zA-Z]{1,10}://#', $url ) !== 1
747
			&& date( 'Y-m-d H:i:s', $fs->time( $url ) ) < $item->getTimeModified()
748
		) {
749
			return $item;
750
		}
751
752
		$media = $this->getFile( $url );
753
754
		if( $media instanceof \Aimeos\MW\Media\Image\Iface )
755
		{
756
			$previews = [];
757
			$name = basename( $url );
758
			$domain = $item->getDomain();
759
			$item = $this->deletePreviews( $item, $fs );
760
761
			foreach( $this->createPreviews( $media, $item->getDomain(), (string) $item->getType() ) as $mediaFile )
762
			{
763
				$mime = $this->getMime( $mediaFile );
764
				$filepath = $this->getPath( $name, $mime, $domain ?: '-' );
765
766
				$this->store( $mediaFile->save( null, $mime ), $filepath, $fs );
767
				$previews[$mediaFile->getWidth()] = $filepath;
768
			}
769
770
			$item->setPreviews( $previews );
771
		}
772
773
		return $item;
774
	}
775
776
777
	/**
778
	 * Returns the item objects matched by the given search criteria.
779
	 *
780
	 * @param \Aimeos\Base\Criteria\Iface $search Search criteria object
781
	 * @param string[] $ref List of domains to fetch list items and referenced items for
782
	 * @param int|null &$total Number of items that are available in total
783
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Media\Item\Iface with ids as keys
784
	 */
785
	public function search( \Aimeos\Base\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
786
	{
787
		$map = [];
788
		$context = $this->context();
789
		$conn = $context->db( $this->getResourceName() );
790
791
			$required = array( 'media' );
792
793
			/** mshop/media/manager/sitemode
794
			 * Mode how items from levels below or above in the site tree are handled
795
			 *
796
			 * By default, only items from the current site are fetched from the
797
			 * storage. If the ai-sites extension is installed, you can create a
798
			 * tree of sites. Then, this setting allows you to define for the
799
			 * whole media domain if items from parent sites are inherited,
800
			 * sites from child sites are aggregated or both.
801
			 *
802
			 * Available constants for the site mode are:
803
			 * * 0 = only items from the current site
804
			 * * 1 = inherit items from parent sites
805
			 * * 2 = aggregate items from child sites
806
			 * * 3 = inherit and aggregate items at the same time
807
			 *
808
			 * You also need to set the mode in the locale manager
809
			 * (mshop/locale/manager/sitelevel) to one of the constants.
810
			 * If you set it to the same value, it will work as described but you
811
			 * can also use different modes. For example, if inheritance and
812
			 * aggregation is configured the locale manager but only inheritance
813
			 * in the domain manager because aggregating items makes no sense in
814
			 * this domain, then items wil be only inherited. Thus, you have full
815
			 * control over inheritance and aggregation in each domain.
816
			 *
817
			 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
818
			 * @category Developer
819
			 * @since 2018.01
820
			 * @see mshop/locale/manager/sitelevel
821
			 */
822
			$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
823
			$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
824
825
			/** mshop/media/manager/search/mysql
826
			 * Retrieves the records matched by the given criteria in the database
827
			 *
828
			 * @see mshop/media/manager/search/ansi
829
			 */
830
831
			/** mshop/media/manager/search/ansi
832
			 * Retrieves the records matched by the given criteria in the database
833
			 *
834
			 * Fetches the records matched by the given criteria from the media
835
			 * database. The records must be from one of the sites that are
836
			 * configured via the context item. If the current site is part of
837
			 * a tree of sites, the SELECT statement can retrieve all records
838
			 * from the current site and the complete sub-tree of sites.
839
			 *
840
			 * As the records can normally be limited by criteria from sub-managers,
841
			 * their tables must be joined in the SQL context. This is done by
842
			 * using the "internaldeps" property from the definition of the ID
843
			 * column of the sub-managers. These internal dependencies specify
844
			 * the JOIN between the tables and the used columns for joining. The
845
			 * ":joins" placeholder is then replaced by the JOIN strings from
846
			 * the sub-managers.
847
			 *
848
			 * To limit the records matched, conditions can be added to the given
849
			 * criteria object. It can contain comparisons like column names that
850
			 * must match specific values which can be combined by AND, OR or NOT
851
			 * operators. The resulting string of SQL conditions replaces the
852
			 * ":cond" placeholder before the statement is sent to the database
853
			 * server.
854
			 *
855
			 * If the records that are retrieved should be ordered by one or more
856
			 * columns, the generated string of column / sort direction pairs
857
			 * replaces the ":order" placeholder. In case no ordering is required,
858
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
859
			 * markers is removed to speed up retrieving the records. Columns of
860
			 * sub-managers can also be used for ordering the result set but then
861
			 * no index can be used.
862
			 *
863
			 * The number of returned records can be limited and can start at any
864
			 * number between the begining and the end of the result set. For that
865
			 * the ":size" and ":start" placeholders are replaced by the
866
			 * corresponding values from the criteria object. The default values
867
			 * are 0 for the start and 100 for the size value.
868
			 *
869
			 * The SQL statement should conform to the ANSI standard to be
870
			 * compatible with most relational database systems. This also
871
			 * includes using double quotes for table and column names.
872
			 *
873
			 * @param string SQL statement for searching items
874
			 * @since 2014.03
875
			 * @category Developer
876
			 * @see mshop/media/manager/insert/ansi
877
			 * @see mshop/media/manager/update/ansi
878
			 * @see mshop/media/manager/newid/ansi
879
			 * @see mshop/media/manager/delete/ansi
880
			 * @see mshop/media/manager/count/ansi
881
			 */
882
			$cfgPathSearch = 'mshop/media/manager/search';
883
884
			/** mshop/media/manager/count/mysql
885
			 * Counts the number of records matched by the given criteria in the database
886
			 *
887
			 * @see mshop/media/manager/count/ansi
888
			 */
889
890
			/** mshop/media/manager/count/ansi
891
			 * Counts the number of records matched by the given criteria in the database
892
			 *
893
			 * Counts all records matched by the given criteria from the media
894
			 * database. The records must be from one of the sites that are
895
			 * configured via the context item. If the current site is part of
896
			 * a tree of sites, the statement can count all records from the
897
			 * current site and the complete sub-tree of sites.
898
			 *
899
			 * As the records can normally be limited by criteria from sub-managers,
900
			 * their tables must be joined in the SQL context. This is done by
901
			 * using the "internaldeps" property from the definition of the ID
902
			 * column of the sub-managers. These internal dependencies specify
903
			 * the JOIN between the tables and the used columns for joining. The
904
			 * ":joins" placeholder is then replaced by the JOIN strings from
905
			 * the sub-managers.
906
			 *
907
			 * To limit the records matched, conditions can be added to the given
908
			 * criteria object. It can contain comparisons like column names that
909
			 * must match specific values which can be combined by AND, OR or NOT
910
			 * operators. The resulting string of SQL conditions replaces the
911
			 * ":cond" placeholder before the statement is sent to the database
912
			 * server.
913
			 *
914
			 * Both, the strings for ":joins" and for ":cond" are the same as for
915
			 * the "search" SQL statement.
916
			 *
917
			 * Contrary to the "search" statement, it doesn't return any records
918
			 * but instead the number of records that have been found. As counting
919
			 * thousands of records can be a long running task, the maximum number
920
			 * of counted records is limited for performance reasons.
921
			 *
922
			 * The SQL statement should conform to the ANSI standard to be
923
			 * compatible with most relational database systems. This also
924
			 * includes using double quotes for table and column names.
925
			 *
926
			 * @param string SQL statement for counting items
927
			 * @since 2014.03
928
			 * @category Developer
929
			 * @see mshop/media/manager/insert/ansi
930
			 * @see mshop/media/manager/update/ansi
931
			 * @see mshop/media/manager/newid/ansi
932
			 * @see mshop/media/manager/delete/ansi
933
			 * @see mshop/media/manager/search/ansi
934
			 */
935
			$cfgPathCount = 'mshop/media/manager/count';
936
937
			$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
938
939
			while( ( $row = $results->fetch() ) !== null )
940
			{
941
				if( ( $row['media.previews'] = json_decode( $config = $row['media.previews'], true ) ) === null )
942
				{
943
					$msg = sprintf( 'Invalid JSON as result of search for ID "%2$s" in "%1$s": %3$s', 'mshop_media.previews', $row['media.id'], $config );
944
					$this->context()->logger()->warning( $msg, 'core/media' );
945
				}
946
				$map[$row['media.id']] = $row;
947
			}
948
949
		$propItems = []; $name = 'media/property';
950
		if( isset( $ref[$name] ) || in_array( $name, $ref, true ) )
951
		{
952
			$propTypes = isset( $ref[$name] ) && is_array( $ref[$name] ) ? $ref[$name] : null;
953
			$propItems = $this->getPropertyItems( array_keys( $map ), 'media', $propTypes );
954
		}
955
956
		return $this->buildItems( $map, $ref, 'media', $propItems );
957
	}
958
959
960
	/**
961
	 * Creates a new media item instance.
962
	 *
963
	 * @param array $values Associative list of key/value pairs
964
	 * @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of list items
965
	 * @param \Aimeos\MShop\Common\Item\Iface[] $refItems List of items referenced
966
	 * @param \Aimeos\MShop\Common\Item\Property\Iface[] $propItems List of property items
967
	 * @return \Aimeos\MShop\Media\Item\Iface New media item
968
	 */
969
	protected function createItemBase( array $values = [], array $listItems = [], array $refItems = [],
970
		array $propItems = [] ) : \Aimeos\MShop\Common\Item\Iface
971
	{
972
		$values['.languageid'] = $this->languageId;
973
974
		return new \Aimeos\MShop\Media\Item\Standard( $values, $listItems, $refItems, $propItems );
975
	}
976
977
978
	/**
979
	 * Creates scaled images according to the configuration settings
980
	 *
981
	 * @param \Aimeos\MW\Media\Image\Iface $media Media object
982
	 * @param string $domain Domain the item is from, e.g. product, catalog, etc.
983
	 * @param string $type Type of the item within the given domain, e.g. default, stage, etc.
984
	 * @return \Aimeos\MW\Media\Image\Iface[] Associative list of image width as keys and scaled media object as values
985
	 */
986
	protected function createPreviews( \Aimeos\MW\Media\Image\Iface $media, string $domain, string $type ) : array
987
	{
988
		$list = [];
989
		$config = $this->context()->config();
990
991
		/** controller/common/media/previews
992
		 * Scaling options for preview images
993
		 *
994
		 * For responsive images, several preview images of different sizes are
995
		 * generated. This setting controls how many preview images are generated,
996
		 * what's their maximum width and height and if the given width/height is
997
		 * enforced by cropping images that doesn't fit.
998
		 *
999
		 * The setting must consist of a list image size definitions like:
1000
		 *
1001
		 *  [
1002
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => true],
1003
		 *    ['maxwidth' => 720, 'maxheight' => 960, 'force-size' => false],
1004
		 *    ['maxwidth' => 2160, 'maxheight' => 2880, 'force-size' => false],
1005
		 *  ]
1006
		 *
1007
		 * "maxwidth" sets the maximum allowed width of the image whereas
1008
		 * "maxheight" does the same for the maximum allowed height. If both
1009
		 * values are given, the image is scaled proportionally so it fits into
1010
		 * the box defined by both values. In case the image has different
1011
		 * proportions than the specified ones and "force-size" is false, the
1012
		 * image is resized to fit entirely into the specified box. One side of
1013
		 * the image will be shorter than it would be possible by the specified
1014
		 * box.
1015
		 *
1016
		 * If "force-size" is true, scaled images that doesn't fit into the
1017
		 * given maximum width/height are centered and then cropped. By default,
1018
		 * images aren't cropped.
1019
		 *
1020
		 * The values for "maxwidth" and "maxheight" can also be null or not
1021
		 * used. In that case, the width or height or both is unbound. If none
1022
		 * of the values are given, the image won't be scaled at all. If only
1023
		 * one value is set, the image will be scaled exactly to the given width
1024
		 * or height and the other side is scaled proportionally.
1025
		 *
1026
		 * You can also define different preview sizes for different domains (e.g.
1027
		 * for catalog images) and for different types (e.g. catalog stage images).
1028
		 * Use configuration settings like
1029
		 *
1030
		 *  controller/common/media/<domain>/previews
1031
		 *  controller/common/media/<domain>/<type>/previews
1032
		 *
1033
		 * for example:
1034
		 *
1035
		 *  controller/common/media/catalog/previews => [
1036
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => true],
1037
		 *  ]
1038
		 *  controller/common/media/catalog/previews => [
1039
		 *    ['maxwidth' => 400, 'maxheight' => 300, 'force-size' => false]
1040
		 *  ]
1041
		 *  controller/common/media/catalog/stage/previews => [
1042
		 *    ['maxwidth' => 360, 'maxheight' => 320, 'force-size' => true],
1043
		 *    ['maxwidth' => 720, 'maxheight' => 480, 'force-size' => true]
1044
		 *  ]
1045
		 *
1046
		 * These settings will create two preview images for catalog stage images,
1047
		 * one with a different size for all other catalog images and all images
1048
		 * from other domains will be sized to 240x320px. The available domains
1049
		 * which can have images are:
1050
		 *
1051
		 * * attribute
1052
		 * * catalog
1053
		 * * product
1054
		 * * service
1055
		 * * supplier
1056
		 *
1057
		 * There are a few image types included per domain ("default" is always
1058
		 * available). You can also add your own types in the admin backend and
1059
		 * extend the frontend to display them where you need them.
1060
		 *
1061
		 * @param array List of image size definitions
1062
		 * @category Developer
1063
		 * @category User
1064
		 * @since 2019.07
1065
		 */
1066
		$previews = $config->get( 'controller/common/media/previews', [] );
1067
		$previews = $config->get( 'controller/common/media/' . $domain . '/previews', $previews );
1068
		$previews = $config->get( 'controller/common/media/' . $domain . '/' . $type . '/previews', $previews );
1069
1070
		foreach( $previews as $entry )
1071
		{
1072
			$maxwidth = $entry['maxwidth'] ?? null;
1073
			$maxheight = $entry['maxwidth'] ?? null;
1074
1075
			$list[] = $media->scale( $maxwidth, $maxheight, $entry['force-size'] ?? 0 );
1076
		}
1077
1078
		return $list;
1079
	}
1080
1081
1082
	/**
1083
	 * Removes the previes images from the storage
1084
	 *
1085
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item which will contains the image URLs afterwards
1086
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system where the files are stored
1087
	 * @return \Aimeos\MShop\Media\Item\Iface Media item with preview images removed
1088
	 */
1089
	protected function deletePreviews( \Aimeos\MShop\Media\Item\Iface $item,
1090
		\Aimeos\Base\Filesystem\Iface $fs ) : \Aimeos\MShop\Media\Item\Iface
1091
	{
1092
		foreach( $this->call( 'removePreviews', $item ) as $preview )
1093
		{
1094
			if( $preview && $fs->has( $preview ) ) {
1095
				$fs->rm( $preview );
1096
			}
1097
		}
1098
1099
		return $item->setPreviews( [] );
1100
	}
1101
1102
1103
	/**
1104
	 * Returns the file content of the file or URL
1105
	 *
1106
	 * @param string $path Path to the file or URL
1107
	 * @return string File content
1108
	 * @throws \Aimeos\MShop\Media\Exception If no file is found
1109
	 */
1110
	protected function getContent( string $path ) : string
1111
	{
1112
		if( $path )
1113
		{
1114
			if( preg_match( '#^[a-zA-Z]{1,10}://#', $path ) === 1 )
1115
			{
1116
				if( ( $content = @file_get_contents( $path ) ) === false ) {
1117
					throw new \Aimeos\MShop\Media\Exception( sprintf( 'Downloading file "%1$s" failed', $path ) );
1118
				}
1119
1120
				return $content;
1121
			}
1122
1123
			$fs = $this->context()->fs( 'fs-media' );
1124
1125
			if( $fs->has( $path ) ) {
1126
				return $fs->read( $path );
1127
			}
1128
		}
1129
1130
		throw new \Aimeos\MShop\Media\Exception( sprintf( 'File "%1$s" not found', $path ) );
1131
	}
1132
1133
1134
	/**
1135
	 * Returns the media object for the given file name
1136
	 *
1137
	 * @param string $file Path to the file
1138
	 * @return \Aimeos\MW\Media\Iface Media object
1139
	 */
1140
	protected function getFile( string $filepath ) : \Aimeos\MW\Media\Iface
1141
	{
1142
		/** controller/common/media/options
1143
		 * Options used for processing the uploaded media files
1144
		 *
1145
		 * When uploading a file, a preview image for that file is generated if
1146
		 * possible (especially for images). You can configure certain options
1147
		 * for the generated images, namely the implementation of the scaling
1148
		 * algorithm and the quality of the resulting images with
1149
		 *
1150
		 *  array(
1151
		 *  	'image' => array(
1152
		 *  		'name' => 'Imagick',
1153
		 *  		'quality' => 75,
1154
		 * 			'background' => '#f8f8f8' // only if "force-size" is true
1155
		 *  	)
1156
		 *  )
1157
		 *
1158
		 * @param array Multi-dimendional list of configuration options
1159
		 * @since 2016.01
1160
		 * @category Developer
1161
		 * @category User
1162
		 */
1163
		$options = $this->context()->config()->get( 'controller/common/media/options', [] );
1164
1165
		return \Aimeos\MW\Media\Factory::get( $this->getContent( $filepath ), $options );
1166
	}
1167
1168
1169
	/**
1170
	 * Creates a new file path from the given arguments
1171
	 *
1172
	 * @param string $filename Original file name, can contain the path as well
1173
	 * @param string $mimetype Mime type
1174
	 * @param string $domain data domain
1175
	 * @return string New file name including the file path
1176
	 */
1177
	protected function getPath( string $filename, string $mimetype, string $domain ) : string
1178
	{
1179
		$context = $this->context();
1180
1181
		/** controller/common/media/extensions
1182
		 * Available files extensions for mime types of uploaded files
1183
		 *
1184
		 * Uploaded files should have the right file extension (e.g. ".jpg" for
1185
		 * JPEG images) so files are recognized correctly if downloaded by users.
1186
		 * The extension of the uploaded file can't be trusted and only its mime
1187
		 * type can be determined automatically. This configuration setting
1188
		 * provides the file extensions for the configured mime types. You can
1189
		 * add more mime type / file extension combinations if required.
1190
		 *
1191
		 * @param array Associative list of mime types as keys and file extensions as values
1192
		 * @since 2018.04
1193
		 * @category Developer
1194
		 */
1195
		$list = $context->config()->get( 'controller/common/media/extensions', [] );
1196
1197
		$filename = \Aimeos\Base\Str::slug( substr( $filename, 0, strrpos( $filename, '.' ) ?: null ) );
1198
		$filename = substr( md5( $filename . getmypid() . microtime( true ) ), -8 ) . '_' . $filename;
1199
1200
		$ext = isset( $list[$mimetype] ) ? '.' . $list[$mimetype] : '';
1201
		$siteId = $context->locale()->getSiteId();
1202
1203
		// the "d" after {siteid} is the required extension for Windows (no dots at the end allowed)
1204
		return "${siteId}d/${domain}/${filename[0]}/${filename[1]}/${filename}${ext}";
1205
	}
1206
1207
1208
	/**
1209
	 * Returns the mime type for the new image
1210
	 *
1211
	 * @param \Aimeos\MW\Media\Iface $media Media object
1212
	 * @return string New mime type
1213
	 * @throws \Aimeos\Controller\Common\Exception If no mime types are configured
1214
	 */
1215
	protected function getMime( \Aimeos\MW\Media\Iface $media ) : string
1216
	{
1217
		$mimetype = $media->getMimetype();
1218
		$config = $this->context()->config();
1219
1220
		/** controller/common/media/files/allowedtypes
1221
		 * A list of image mime types that are allowed for uploaded image files
1222
		 *
1223
		 * The list of allowed image types must be explicitly configured for the
1224
		 * uploaded image files. Trying to upload and store an image file not
1225
		 * available in the list of allowed mime types will result in an exception.
1226
		 *
1227
		 * @param array List of image mime types
1228
		 * @since 2016.01
1229
		 * @category Developer
1230
		 * @category User
1231
		 */
1232
1233
		/** controller/common/media/preview/allowedtypes
1234
		 * A list of image mime types that are allowed for preview image files
1235
		 *
1236
		 * The list of allowed image types must be explicitly configured for the
1237
		 * preview image files. Trying to create a preview image whose mime type
1238
		 * is not available in the list of allowed mime types will result in an
1239
		 * exception.
1240
		 *
1241
		 * @param array List of image mime types
1242
		 * @since 2016.01
1243
		 * @category Developer
1244
		 * @category User
1245
		 */
1246
		$default = [
1247
			'image/webp', 'image/jpeg', 'image/png', 'image/gif', 'image/svg+xml',
1248
			'application/pdf', 'application/zip',
1249
			'video/mp4', 'video/webm'
1250
		];
1251
		$allowed = $config->get( 'controller/common/media/preview/allowedtypes', $default );
1252
1253
		if( in_array( $mimetype, ['image/jpeg', 'image/png'] )
1254
			&& !empty( $supported = $media::supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
0 ignored issues
show
Bug introduced by
The method supports() does not exist on Aimeos\MW\Media\Iface. It seems like you code against a sub-type of Aimeos\MW\Media\Iface such as Aimeos\MW\Media\Image\Iface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1254
			&& !empty( $supported = $media::/** @scrutinizer ignore-call */ supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
Loading history...
1255
		) {
1256
			return $imgtype;
1257
		}
1258
1259
		return $mimetype;
1260
	}
1261
1262
1263
	/**
1264
	 * Returns the preview images to be deleted
1265
	 *
1266
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item with preview URLs
1267
	 * @return iterable List of preview URLs to remove
1268
	 */
1269
	protected function removePreviews( \Aimeos\MShop\Media\Item\Iface $item ) : iterable
1270
	{
1271
		$previews = $item->getPreviews();
1272
1273
		// don't delete first (smallest) image because it may be referenced in past orders
1274
		if( $item->getDomain() === 'product' ) {
1275
			$previews = array_slice( $previews, 1 );
1276
		}
1277
1278
		return $previews;
1279
	}
1280
1281
1282
	/**
1283
	 * Stores the file content
1284
	 *
1285
	 * @param string $content File content
1286
	 * @param string $filepath Path of the new file
1287
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system object
1288
	 * @return \Aimeos\Controller\Common\Media\Iface Self object for fluent interface
1289
	 */
1290
	protected function store( string $content, string $filepath, \Aimeos\Base\Filesystem\Iface $fs ) : Iface
1291
	{
1292
		$fs->write( $filepath, $content );
1293
		return $this;
1294
	}
1295
}
1296