Passed
Push — master ( d5e308...4f1c7f )
by Aimeos
09:27
created

Standard   F

Complexity

Total Complexity 84

Size/Duplication

Total Lines 1329
Duplicated Lines 0 %

Importance

Changes 9
Bugs 0 Features 0
Metric Value
wmc 84
eloc 328
c 9
b 0
f 0
dl 0
loc 1329
rs 2

24 Methods

Rating   Name   Duplication   Size   Complexity  
A clear() 0 10 2
B __construct() 0 45 11
B copy() 0 31 7
A create() 0 4 1
A filter() 0 26 3
A get() 0 3 1
B search() 0 172 7
A getSubManager() 0 3 1
A delete() 0 49 6
A getSearchAttributes() 0 22 1
A getResourceType() 0 6 1
A createItemBase() 0 6 1
B saveItem() 0 166 6
A removePreviews() 0 10 3
A getMime() 0 45 4
A filterPreviews() 0 4 1
A getContent() 0 21 5
B scale() 0 39 9
A deletePreviews() 0 15 5
A store() 0 4 1
A scaled() 0 2 1
A createPreviews() 0 99 3
A getPath() 0 29 3
A getFile() 0 26 1

How to fix   Complexity   

Complex Class

Complex classes like Standard often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Standard, and based on these observations, apply Extract Interface, too.

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
		if( $fsname !== 'fs-mimeicon' && empty( $previews ) ) {
363
			return $this->scale( $item, true );
364
		}
365
366
		foreach( $previews as $size => $preview )
367
		{
368
			if( $fsname !== 'fs-mimeicon' && $fs->has( $preview ) )
369
			{
370
				$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

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

619
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
620
		}
621
		else
622
		{
623
			/** mshop/media/manager/update/mysql
624
			 * Updates an existing media record in the database
625
			 *
626
			 * @see mshop/media/manager/update/ansi
627
			 */
628
629
			/** mshop/media/manager/update/ansi
630
			 * Updates an existing media record in the database
631
			 *
632
			 * Items which already have an ID (i.e. the ID is not NULL) will
633
			 * be updated in the database.
634
			 *
635
			 * The SQL statement must be a string suitable for being used as
636
			 * prepared statement. It must include question marks for binding
637
			 * the values from the media item to the statement before they are
638
			 * sent to the database server. The order of the columns must
639
			 * correspond to the order in the save() method, so the
640
			 * correct values are bound to the columns.
641
			 *
642
			 * The SQL statement should conform to the ANSI standard to be
643
			 * compatible with most relational database systems. This also
644
			 * includes using double quotes for table and column names.
645
			 *
646
			 * @param string SQL statement for updating records
647
			 * @since 2014.03
648
			 * @category Developer
649
			 * @see mshop/media/manager/insert/ansi
650
			 * @see mshop/media/manager/newid/ansi
651
			 * @see mshop/media/manager/delete/ansi
652
			 * @see mshop/media/manager/search/ansi
653
			 * @see mshop/media/manager/count/ansi
654
			 */
655
			$path = 'mshop/media/manager/update';
656
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
657
		}
658
659
		$idx = 1;
660
		$stmt = $this->getCachedStatement( $conn, $path, $sql );
661
662
		foreach( $columns as $name => $entry ) {
663
			$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

663
			$stmt->bind( $idx++, $item->get( $name ), /** @scrutinizer ignore-type */ $entry->getInternalType() );
Loading history...
664
		}
665
666
		$stmt->bind( $idx++, $item->getLanguageId() );
667
		$stmt->bind( $idx++, $item->getType() );
668
		$stmt->bind( $idx++, $item->getLabel() );
669
		$stmt->bind( $idx++, $item->getMimeType() );
670
		$stmt->bind( $idx++, $item->getUrl() );
671
		$stmt->bind( $idx++, $item->getStatus(), \Aimeos\Base\DB\Statement\Base::PARAM_INT );
672
		$stmt->bind( $idx++, $item->getFileSystem() );
673
		$stmt->bind( $idx++, $item->getDomain() );
674
		$stmt->bind( $idx++, json_encode( $item->getPreviews(), JSON_FORCE_OBJECT ) );
675
		$stmt->bind( $idx++, $date ); // mtime
676
		$stmt->bind( $idx++, $context->editor() );
677
678
		if( $id !== null ) {
679
			$stmt->bind( $idx++, $context->locale()->getSiteId() . '%' );
680
			$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
681
		} else {
682
			$stmt->bind( $idx++, $this->siteId( $item->getSiteId(), \Aimeos\MShop\Locale\Manager\Base::SITE_SUBTREE ) );
683
			$stmt->bind( $idx++, $date ); // ctime
684
		}
685
686
		$stmt->execute()->finish();
687
688
		if( $id === null )
689
		{
690
			/** mshop/media/manager/newid/mysql
691
			 * Retrieves the ID generated by the database when inserting a new record
692
			 *
693
			 * @see mshop/media/manager/newid/ansi
694
			 */
695
696
			/** mshop/media/manager/newid/ansi
697
			 * Retrieves the ID generated by the database when inserting a new record
698
			 *
699
			 * As soon as a new record is inserted into the database table,
700
			 * the database server generates a new and unique identifier for
701
			 * that record. This ID can be used for retrieving, updating and
702
			 * deleting that specific record from the table again.
703
			 *
704
			 * For MySQL:
705
			 *  SELECT LAST_INSERT_ID()
706
			 * For PostgreSQL:
707
			 *  SELECT currval('seq_mmed_id')
708
			 * For SQL Server:
709
			 *  SELECT SCOPE_IDENTITY()
710
			 * For Oracle:
711
			 *  SELECT "seq_mmed_id".CURRVAL FROM DUAL
712
			 *
713
			 * There's no way to retrive the new ID by a SQL statements that
714
			 * fits for most database servers as they implement their own
715
			 * specific way.
716
			 *
717
			 * @param string SQL statement for retrieving the last inserted record ID
718
			 * @since 2014.03
719
			 * @category Developer
720
			 * @see mshop/media/manager/insert/ansi
721
			 * @see mshop/media/manager/update/ansi
722
			 * @see mshop/media/manager/delete/ansi
723
			 * @see mshop/media/manager/search/ansi
724
			 * @see mshop/media/manager/count/ansi
725
			 */
726
			$path = 'mshop/media/manager/newid';
727
			$id = $this->newId( $conn, $path );
728
		}
729
730
		$item->setId( $id );
731
732
		$item = $this->savePropertyItems( $item, 'media', $fetch );
733
		return $this->saveListItems( $item, 'media', $fetch );
734
	}
735
736
737
	/**
738
	 * Rescales the original file to preview files referenced by the media item
739
	 *
740
	 * The height/width configuration for scaling
741
	 * - mshop/media/<files|preview>/maxheight
742
	 * - mshop/media/<files|preview>/maxwidth
743
	 * - mshop/media/<files|preview>/force-size
744
	 *
745
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be scaled
746
	 * @param bool $force True to enforce creating new preview images
747
	 * @return \Aimeos\MShop\Media\Item\Iface Rescaled media item
748
	 * @todo 2023.01 Add to media manager interface
749
	 */
750
	public function scale( \Aimeos\MShop\Media\Item\Iface $item, bool $force = false ) : \Aimeos\MShop\Media\Item\Iface
751
	{
752
		$url = $item->getUrl();
753
		$context = $this->context();
754
755
		$fs = $context->fs( $item->getFileSystem() );
756
		$is = ( $fs instanceof \Aimeos\Base\Filesystem\MetaIface ? true : false );
757
758
		if( !$force && $is && preg_match( '#^[a-zA-Z]{2,6}:#', $url ) !== 1
759
			&& date( 'Y-m-d H:i:s', $fs->time( $url ) ) < $item->getTimeModified()
760
		) {
761
			return $item;
762
		}
763
764
		$media = $this->getFile( $url );
765
766
		if( $media instanceof \Aimeos\MW\Media\Image\Iface )
767
		{
768
			$previews = [];
769
			$old = $item->getPreviews();
770
			$domain = $item->getDomain();
771
772
			foreach( $this->createPreviews( $media, $domain, $item->getType() ) as $width => $mediaFile )
0 ignored issues
show
Bug introduced by
It seems like $item->getType() can also be of type null; however, parameter $type of Aimeos\MShop\Media\Manag...ndard::createPreviews() 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

772
			foreach( $this->createPreviews( $media, $domain, /** @scrutinizer ignore-type */ $item->getType() ) as $width => $mediaFile )
Loading history...
773
			{
774
				$mime = $this->getMime( $mediaFile );
775
				$path = $old[$width] ?? $this->getPath( $url, $mime, $domain ?: '-' );
776
777
				$this->store( $mediaFile->save( null, $mime ), $path, $fs );
778
				$previews[$width] = $path;
779
				unset( $old[$width] );
780
			}
781
782
			$item = $this->deletePreviews( $item, $old );
783
			$item->setPreviews( $previews );
784
785
			$this->call( 'scaled', $item, $media );
786
		}
787
788
		return $item;
789
	}
790
791
792
	/**
793
	 * Returns the item objects matched by the given search criteria.
794
	 *
795
	 * @param \Aimeos\Base\Criteria\Iface $search Search criteria object
796
	 * @param string[] $ref List of domains to fetch list items and referenced items for
797
	 * @param int|null &$total Number of items that are available in total
798
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Media\Item\Iface with ids as keys
799
	 */
800
	public function search( \Aimeos\Base\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
801
	{
802
		$map = [];
803
		$context = $this->context();
804
		$conn = $context->db( $this->getResourceName() );
805
806
			$required = array( 'media' );
807
808
			/** mshop/media/manager/sitemode
809
			 * Mode how items from levels below or above in the site tree are handled
810
			 *
811
			 * By default, only items from the current site are fetched from the
812
			 * storage. If the ai-sites extension is installed, you can create a
813
			 * tree of sites. Then, this setting allows you to define for the
814
			 * whole media domain if items from parent sites are inherited,
815
			 * sites from child sites are aggregated or both.
816
			 *
817
			 * Available constants for the site mode are:
818
			 * * 0 = only items from the current site
819
			 * * 1 = inherit items from parent sites
820
			 * * 2 = aggregate items from child sites
821
			 * * 3 = inherit and aggregate items at the same time
822
			 *
823
			 * You also need to set the mode in the locale manager
824
			 * (mshop/locale/manager/sitelevel) to one of the constants.
825
			 * If you set it to the same value, it will work as described but you
826
			 * can also use different modes. For example, if inheritance and
827
			 * aggregation is configured the locale manager but only inheritance
828
			 * in the domain manager because aggregating items makes no sense in
829
			 * this domain, then items wil be only inherited. Thus, you have full
830
			 * control over inheritance and aggregation in each domain.
831
			 *
832
			 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
833
			 * @category Developer
834
			 * @since 2018.01
835
			 * @see mshop/locale/manager/sitelevel
836
			 */
837
			$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
838
			$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
839
840
			/** mshop/media/manager/search/mysql
841
			 * Retrieves the records matched by the given criteria in the database
842
			 *
843
			 * @see mshop/media/manager/search/ansi
844
			 */
845
846
			/** mshop/media/manager/search/ansi
847
			 * Retrieves the records matched by the given criteria in the database
848
			 *
849
			 * Fetches the records matched by the given criteria from the media
850
			 * database. The records must be from one of the sites that are
851
			 * configured via the context item. If the current site is part of
852
			 * a tree of sites, the SELECT statement can retrieve all records
853
			 * from the current site and the complete sub-tree of sites.
854
			 *
855
			 * As the records can normally be limited by criteria from sub-managers,
856
			 * their tables must be joined in the SQL context. This is done by
857
			 * using the "internaldeps" property from the definition of the ID
858
			 * column of the sub-managers. These internal dependencies specify
859
			 * the JOIN between the tables and the used columns for joining. The
860
			 * ":joins" placeholder is then replaced by the JOIN strings from
861
			 * the sub-managers.
862
			 *
863
			 * To limit the records matched, conditions can be added to the given
864
			 * criteria object. It can contain comparisons like column names that
865
			 * must match specific values which can be combined by AND, OR or NOT
866
			 * operators. The resulting string of SQL conditions replaces the
867
			 * ":cond" placeholder before the statement is sent to the database
868
			 * server.
869
			 *
870
			 * If the records that are retrieved should be ordered by one or more
871
			 * columns, the generated string of column / sort direction pairs
872
			 * replaces the ":order" placeholder. In case no ordering is required,
873
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
874
			 * markers is removed to speed up retrieving the records. Columns of
875
			 * sub-managers can also be used for ordering the result set but then
876
			 * no index can be used.
877
			 *
878
			 * The number of returned records can be limited and can start at any
879
			 * number between the begining and the end of the result set. For that
880
			 * the ":size" and ":start" placeholders are replaced by the
881
			 * corresponding values from the criteria object. The default values
882
			 * are 0 for the start and 100 for the size value.
883
			 *
884
			 * The SQL statement should conform to the ANSI standard to be
885
			 * compatible with most relational database systems. This also
886
			 * includes using double quotes for table and column names.
887
			 *
888
			 * @param string SQL statement for searching items
889
			 * @since 2014.03
890
			 * @category Developer
891
			 * @see mshop/media/manager/insert/ansi
892
			 * @see mshop/media/manager/update/ansi
893
			 * @see mshop/media/manager/newid/ansi
894
			 * @see mshop/media/manager/delete/ansi
895
			 * @see mshop/media/manager/count/ansi
896
			 */
897
			$cfgPathSearch = 'mshop/media/manager/search';
898
899
			/** mshop/media/manager/count/mysql
900
			 * Counts the number of records matched by the given criteria in the database
901
			 *
902
			 * @see mshop/media/manager/count/ansi
903
			 */
904
905
			/** mshop/media/manager/count/ansi
906
			 * Counts the number of records matched by the given criteria in the database
907
			 *
908
			 * Counts all records matched by the given criteria from the media
909
			 * database. The records must be from one of the sites that are
910
			 * configured via the context item. If the current site is part of
911
			 * a tree of sites, the statement can count all records from the
912
			 * current site and the complete sub-tree of sites.
913
			 *
914
			 * As the records can normally be limited by criteria from sub-managers,
915
			 * their tables must be joined in the SQL context. This is done by
916
			 * using the "internaldeps" property from the definition of the ID
917
			 * column of the sub-managers. These internal dependencies specify
918
			 * the JOIN between the tables and the used columns for joining. The
919
			 * ":joins" placeholder is then replaced by the JOIN strings from
920
			 * the sub-managers.
921
			 *
922
			 * To limit the records matched, conditions can be added to the given
923
			 * criteria object. It can contain comparisons like column names that
924
			 * must match specific values which can be combined by AND, OR or NOT
925
			 * operators. The resulting string of SQL conditions replaces the
926
			 * ":cond" placeholder before the statement is sent to the database
927
			 * server.
928
			 *
929
			 * Both, the strings for ":joins" and for ":cond" are the same as for
930
			 * the "search" SQL statement.
931
			 *
932
			 * Contrary to the "search" statement, it doesn't return any records
933
			 * but instead the number of records that have been found. As counting
934
			 * thousands of records can be a long running task, the maximum number
935
			 * of counted records is limited for performance reasons.
936
			 *
937
			 * The SQL statement should conform to the ANSI standard to be
938
			 * compatible with most relational database systems. This also
939
			 * includes using double quotes for table and column names.
940
			 *
941
			 * @param string SQL statement for counting items
942
			 * @since 2014.03
943
			 * @category Developer
944
			 * @see mshop/media/manager/insert/ansi
945
			 * @see mshop/media/manager/update/ansi
946
			 * @see mshop/media/manager/newid/ansi
947
			 * @see mshop/media/manager/delete/ansi
948
			 * @see mshop/media/manager/search/ansi
949
			 */
950
			$cfgPathCount = 'mshop/media/manager/count';
951
952
			$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
953
954
			while( ( $row = $results->fetch() ) !== null )
955
			{
956
				if( ( $row['media.previews'] = json_decode( $config = $row['media.previews'], true ) ) === null )
957
				{
958
					$msg = sprintf( 'Invalid JSON as result of search for ID "%2$s" in "%1$s": %3$s', 'mshop_media.previews', $row['media.id'], $config );
959
					$this->context()->logger()->warning( $msg, 'core/media' );
960
				}
961
				$map[$row['media.id']] = $row;
962
			}
963
964
		$propItems = []; $name = 'media/property';
965
		if( isset( $ref[$name] ) || in_array( $name, $ref, true ) )
966
		{
967
			$propTypes = isset( $ref[$name] ) && is_array( $ref[$name] ) ? $ref[$name] : null;
968
			$propItems = $this->getPropertyItems( array_keys( $map ), 'media', $propTypes );
969
		}
970
971
		return $this->buildItems( $map, $ref, 'media', $propItems );
972
	}
973
974
975
	/**
976
	 * Creates a new media item instance.
977
	 *
978
	 * @param array $values Associative list of key/value pairs
979
	 * @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of list items
980
	 * @param \Aimeos\MShop\Common\Item\Iface[] $refItems List of items referenced
981
	 * @param \Aimeos\MShop\Common\Item\Property\Iface[] $propItems List of property items
982
	 * @return \Aimeos\MShop\Media\Item\Iface New media item
983
	 */
984
	protected function createItemBase( array $values = [], array $listItems = [], array $refItems = [],
985
		array $propItems = [] ) : \Aimeos\MShop\Common\Item\Iface
986
	{
987
		$values['.languageid'] = $this->languageId;
988
989
		return new \Aimeos\MShop\Media\Item\Standard( $values, $listItems, $refItems, $propItems );
990
	}
991
992
993
	/**
994
	 * Creates scaled images according to the configuration settings
995
	 *
996
	 * @param \Aimeos\MW\Media\Image\Iface $media Media object
997
	 * @param string $domain Domain the item is from, e.g. product, catalog, etc.
998
	 * @param string $type Type of the item within the given domain, e.g. default, stage, etc.
999
	 * @return \Aimeos\MW\Media\Image\Iface[] Associative list of image width as keys and scaled media object as values
1000
	 */
1001
	protected function createPreviews( \Aimeos\MW\Media\Image\Iface $media, string $domain, string $type ) : array
1002
	{
1003
		$list = [];
1004
		$config = $this->context()->config();
1005
1006
		/** controller/common/media/previews
1007
		 * Scaling options for preview images
1008
		 *
1009
		 * For responsive images, several preview images of different sizes are
1010
		 * generated. This setting controls how many preview images are generated,
1011
		 * what's their maximum width and height and if the given width/height is
1012
		 * enforced by cropping images that doesn't fit.
1013
		 *
1014
		 * The setting must consist of a list image size definitions like:
1015
		 *
1016
		 *  [
1017
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => true],
1018
		 *    ['maxwidth' => 720, 'maxheight' => 960, 'force-size' => false],
1019
		 *    ['maxwidth' => 2160, 'maxheight' => 2880, 'force-size' => false],
1020
		 *  ]
1021
		 *
1022
		 * "maxwidth" sets the maximum allowed width of the image whereas
1023
		 * "maxheight" does the same for the maximum allowed height. If both
1024
		 * values are given, the image is scaled proportionally so it fits into
1025
		 * the box defined by both values. In case the image has different
1026
		 * proportions than the specified ones and "force-size" is false, the
1027
		 * image is resized to fit entirely into the specified box. One side of
1028
		 * the image will be shorter than it would be possible by the specified
1029
		 * box.
1030
		 *
1031
		 * If "force-size" is true, scaled images that doesn't fit into the
1032
		 * given maximum width/height are centered and then cropped. By default,
1033
		 * images aren't cropped.
1034
		 *
1035
		 * The values for "maxwidth" and "maxheight" can also be null or not
1036
		 * used. In that case, the width or height or both is unbound. If none
1037
		 * of the values are given, the image won't be scaled at all. If only
1038
		 * one value is set, the image will be scaled exactly to the given width
1039
		 * or height and the other side is scaled proportionally.
1040
		 *
1041
		 * You can also define different preview sizes for different domains (e.g.
1042
		 * for catalog images) and for different types (e.g. catalog stage images).
1043
		 * Use configuration settings like
1044
		 *
1045
		 *  controller/common/media/<domain>/previews
1046
		 *  controller/common/media/<domain>/<type>/previews
1047
		 *
1048
		 * for example:
1049
		 *
1050
		 *  controller/common/media/catalog/previews => [
1051
		 *    ['maxwidth' => 240, 'maxheight' => 320, 'force-size' => true],
1052
		 *  ]
1053
		 *  controller/common/media/catalog/previews => [
1054
		 *    ['maxwidth' => 400, 'maxheight' => 300, 'force-size' => false]
1055
		 *  ]
1056
		 *  controller/common/media/catalog/stage/previews => [
1057
		 *    ['maxwidth' => 360, 'maxheight' => 320, 'force-size' => true],
1058
		 *    ['maxwidth' => 720, 'maxheight' => 480, 'force-size' => true]
1059
		 *  ]
1060
		 *
1061
		 * These settings will create two preview images for catalog stage images,
1062
		 * one with a different size for all other catalog images and all images
1063
		 * from other domains will be sized to 240x320px. The available domains
1064
		 * which can have images are:
1065
		 *
1066
		 * * attribute
1067
		 * * catalog
1068
		 * * product
1069
		 * * service
1070
		 * * supplier
1071
		 *
1072
		 * There are a few image types included per domain ("default" is always
1073
		 * available). You can also add your own types in the admin backend and
1074
		 * extend the frontend to display them where you need them.
1075
		 *
1076
		 * @param array List of image size definitions
1077
		 * @category Developer
1078
		 * @category User
1079
		 * @since 2019.07
1080
		 */
1081
		$previews = $config->get( 'controller/common/media/previews', [] );
1082
		$previews = $config->get( 'controller/common/media/' . $domain . '/previews', $previews );
1083
		$previews = $config->get( 'controller/common/media/' . $domain . '/' . $type . '/previews', $previews );
1084
1085
		foreach( $previews as $entry )
1086
		{
1087
			$force = $entry['force-size'] ?? 0;
1088
			$maxwidth = $entry['maxwidth'] ?? null;
1089
			$maxheight = $entry['maxwidth'] ?? null;
1090
1091
			if( $this->call( 'filterPreviews', $media, $domain, $type, $maxwidth, $maxheight, $force ) )
1092
			{
1093
				$file = $media->scale( $maxwidth, $maxheight, $force );
1094
				$width = $file->getWidth();
1095
				$list[$width] = $file;
1096
			}
1097
		}
1098
1099
		return $list;
1100
	}
1101
1102
1103
	/**
1104
	 * Removes the previes images from the storage
1105
	 *
1106
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item which will contains the image URLs afterwards
1107
	 * @param array List of preview paths to remove
1108
	 * @return \Aimeos\MShop\Media\Item\Iface Media item with preview images removed
1109
	 */
1110
	protected function deletePreviews( \Aimeos\MShop\Media\Item\Iface $item, array $paths ) : \Aimeos\MShop\Media\Item\Iface
1111
	{
1112
		if( !empty( $paths = $this->call( 'removePreviews', $item, $paths ) ) )
1113
		{
1114
			$fs = $this->context()->fs( $item->getFileSystem() );
1115
1116
			foreach( $paths as $preview )
1117
			{
1118
				if( $preview && $fs->has( $preview ) ) {
1119
					$fs->rm( $preview );
1120
				}
1121
			}
1122
		}
1123
1124
		return $item;
1125
	}
1126
1127
1128
	/**
1129
	 * Tests if the preview image should be created
1130
	 *
1131
	 * @param \Aimeos\MW\Media\Image\Iface $media Media object
1132
	 * @param string $domain Domain the item is from, e.g. product, catalog, etc.
1133
	 * @param string $type Type of the item within the given domain, e.g. default, stage, etc.
1134
	 * @param int|null $width New width of the image or null for automatic calculation
1135
	 * @param int|null $height New height of the image or null for automatic calculation
1136
	 * @param int $fit "0" keeps image ratio, "1" adds padding while "2" crops image to enforce image size
1137
	 */
1138
	protected function filterPreviews( \Aimeos\MW\Media\Image\Iface $media, string $domain, string $type,
1139
		?int $maxwidth, ?int $maxheight, int $force ) : bool
1140
	{
1141
		return true;
1142
	}
1143
1144
1145
	/**
1146
	 * Returns the file content of the file or URL
1147
	 *
1148
	 * @param string $path Path to the file or URL
1149
	 * @return string File content
1150
	 * @throws \Aimeos\MShop\Media\Exception If no file is found
1151
	 */
1152
	protected function getContent( string $path ) : string
1153
	{
1154
		if( $path )
1155
		{
1156
			if( preg_match( '#^[a-zA-Z]{1,10}://#', $path ) === 1 )
1157
			{
1158
				if( ( $content = @file_get_contents( $path ) ) === false ) {
1159
					throw new \Aimeos\MShop\Media\Exception( sprintf( 'Downloading file "%1$s" failed', $path ) );
1160
				}
1161
1162
				return $content;
1163
			}
1164
1165
			$fs = $this->context()->fs( 'fs-media' );
1166
1167
			if( $fs->has( $path ) ) {
1168
				return $fs->read( $path );
1169
			}
1170
		}
1171
1172
		throw new \Aimeos\MShop\Media\Exception( sprintf( 'File "%1$s" not found', $path ) );
1173
	}
1174
1175
1176
	/**
1177
	 * Returns the media object for the given file name
1178
	 *
1179
	 * @param string $file Path to the file
1180
	 * @return \Aimeos\MW\Media\Iface Media object
1181
	 */
1182
	protected function getFile( string $filepath ) : \Aimeos\MW\Media\Iface
1183
	{
1184
		/** controller/common/media/options
1185
		 * Options used for processing the uploaded media files
1186
		 *
1187
		 * When uploading a file, a preview image for that file is generated if
1188
		 * possible (especially for images). You can configure certain options
1189
		 * for the generated images, namely the implementation of the scaling
1190
		 * algorithm and the quality of the resulting images with
1191
		 *
1192
		 *  array(
1193
		 *  	'image' => array(
1194
		 *  		'name' => 'Imagick',
1195
		 *  		'quality' => 75,
1196
		 * 			'background' => '#f8f8f8' // only if "force-size" is true
1197
		 *  	)
1198
		 *  )
1199
		 *
1200
		 * @param array Multi-dimendional list of configuration options
1201
		 * @since 2016.01
1202
		 * @category Developer
1203
		 * @category User
1204
		 */
1205
		$options = $this->context()->config()->get( 'controller/common/media/options', [] );
1206
1207
		return \Aimeos\MW\Media\Factory::get( $this->getContent( $filepath ), $options );
1208
	}
1209
1210
1211
	/**
1212
	 * Creates a new file path from the given arguments
1213
	 *
1214
	 * @param string $filepath Original file name, can contain the path as well
1215
	 * @param string $mimetype Mime type
1216
	 * @param string $domain data domain
1217
	 * @return string New file name including the file path
1218
	 */
1219
	protected function getPath( string $filepath, string $mimetype, string $domain ) : string
1220
	{
1221
		$context = $this->context();
1222
1223
		/** controller/common/media/extensions
1224
		 * Available files extensions for mime types of uploaded files
1225
		 *
1226
		 * Uploaded files should have the right file extension (e.g. ".jpg" for
1227
		 * JPEG images) so files are recognized correctly if downloaded by users.
1228
		 * The extension of the uploaded file can't be trusted and only its mime
1229
		 * type can be determined automatically. This configuration setting
1230
		 * provides the file extensions for the configured mime types. You can
1231
		 * add more mime type / file extension combinations if required.
1232
		 *
1233
		 * @param array Associative list of mime types as keys and file extensions as values
1234
		 * @since 2018.04
1235
		 * @category Developer
1236
		 */
1237
		$list = $context->config()->get( 'controller/common/media/extensions', [] );
1238
1239
		$filename = basename( $filepath );
1240
		$filename = \Aimeos\Base\Str::slug( substr( $filename, 0, strrpos( $filename, '.' ) ?: null ) );
1241
		$filename = substr( md5( $filename . getmypid() . microtime( true ) ), -8 ) . '_' . $filename;
1242
1243
		$ext = isset( $list[$mimetype] ) ? '.' . $list[$mimetype] : '';
1244
		$siteid = $context->locale()->getSiteId();
1245
1246
		// the "d" after {siteid} is the required extension for Windows (no dots at the end allowed)
1247
		return "${siteid}d/${domain}/${filename[0]}/${filename[1]}/${filename}${ext}";
1248
	}
1249
1250
1251
	/**
1252
	 * Returns the mime type for the new image
1253
	 *
1254
	 * @param \Aimeos\MW\Media\Iface $media Media object
1255
	 * @return string New mime type
1256
	 * @throws \Aimeos\Controller\Common\Exception If no mime types are configured
1257
	 */
1258
	protected function getMime( \Aimeos\MW\Media\Iface $media ) : string
1259
	{
1260
		$mimetype = $media->getMimetype();
1261
		$config = $this->context()->config();
1262
1263
		/** controller/common/media/files/allowedtypes
1264
		 * A list of image mime types that are allowed for uploaded image files
1265
		 *
1266
		 * The list of allowed image types must be explicitly configured for the
1267
		 * uploaded image files. Trying to upload and store an image file not
1268
		 * available in the list of allowed mime types will result in an exception.
1269
		 *
1270
		 * @param array List of image mime types
1271
		 * @since 2016.01
1272
		 * @category Developer
1273
		 * @category User
1274
		 */
1275
1276
		/** controller/common/media/preview/allowedtypes
1277
		 * A list of image mime types that are allowed for preview image files
1278
		 *
1279
		 * The list of allowed image types must be explicitly configured for the
1280
		 * preview image files. Trying to create a preview image whose mime type
1281
		 * is not available in the list of allowed mime types will result in an
1282
		 * exception.
1283
		 *
1284
		 * @param array List of image mime types
1285
		 * @since 2016.01
1286
		 * @category Developer
1287
		 * @category User
1288
		 */
1289
		$default = [
1290
			'image/webp', 'image/jpeg', 'image/png', 'image/gif', 'image/svg+xml',
1291
			'application/pdf', 'application/zip',
1292
			'video/mp4', 'video/webm'
1293
		];
1294
		$allowed = $config->get( 'controller/common/media/preview/allowedtypes', $default );
1295
1296
		if( in_array( $mimetype, ['image/jpeg', 'image/png'] )
1297
			&& !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

1297
			&& !empty( $supported = $media::/** @scrutinizer ignore-call */ supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
Loading history...
1298
		) {
1299
			return $imgtype;
1300
		}
1301
1302
		return $mimetype;
1303
	}
1304
1305
1306
	/**
1307
	 * Returns the preview images to be deleted
1308
	 *
1309
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item with new preview URLs
1310
	 * @param array List of preview paths to remove
1311
	 * @return iterable List of preview URLs to remove
1312
	 */
1313
	protected function removePreviews( \Aimeos\MShop\Media\Item\Iface $item, array $paths ) : iterable
1314
	{
1315
		$previews = $item->getPreviews();
1316
1317
		// don't delete first (smallest) image because it may be referenced in past orders
1318
		if( $item->getDomain() === 'product' && in_array( key( $previews ), $paths ) ) {
1319
			return array_slice( $paths, 1 );
1320
		}
1321
1322
		return $paths;
1323
	}
1324
1325
1326
	/**
1327
	 * Called after the image has been scaled
1328
	 * Can be used to update the media item with image information.
1329
	 *
1330
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item with new preview URLs
1331
	 * @param \Aimeos\MW\Media\Image\Iface $media Media object
1332
	 */
1333
	protected function scaled( \Aimeos\MShop\Media\Item\Iface $item, \Aimeos\MW\Media\Image\Iface $media )
1334
	{
1335
	}
1336
1337
1338
	/**
1339
	 * Stores the file content
1340
	 *
1341
	 * @param string $content File content
1342
	 * @param string $filepath Path of the new file
1343
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system object
1344
	 * @return \Aimeos\Controller\Common\Media\Iface Self object for fluent interface
1345
	 */
1346
	protected function store( string $content, string $filepath, \Aimeos\Base\Filesystem\Iface $fs ) : Iface
1347
	{
1348
		$fs->write( $filepath, $content );
1349
		return $this;
1350
	}
1351
}
1352