Passed
Push — master ( dda986...554388 )
by Aimeos
05:36
created

Standard::copy()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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

1255
			&& !empty( $supported = $media::/** @scrutinizer ignore-call */ supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
Loading history...
1256
		) {
1257
			return $imgtype;
1258
		}
1259
1260
		return $mimetype;
1261
	}
1262
1263
1264
	/**
1265
	 * Stores the file content
1266
	 *
1267
	 * @param string $content File content
1268
	 * @param string $filepath Path of the new file
1269
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system object
1270
	 * @return \Aimeos\Controller\Common\Media\Iface Self object for fluent interface
1271
	 */
1272
	protected function store( string $content, string $filepath, \Aimeos\Base\Filesystem\Iface $fs ) : Iface
1273
	{
1274
		$fs->write( $filepath, $content );
1275
		return $this;
1276
	}
1277
}
1278