Passed
Push — master ( e7141a...ab4b6a )
by Aimeos
04:16
created

Standard::getContent()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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

566
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
567
		}
568
		else
569
		{
570
			/** mshop/media/manager/update/mysql
571
			 * Updates an existing media record in the database
572
			 *
573
			 * @see mshop/media/manager/update/ansi
574
			 */
575
576
			/** mshop/media/manager/update/ansi
577
			 * Updates an existing media record in the database
578
			 *
579
			 * Items which already have an ID (i.e. the ID is not NULL) will
580
			 * be updated in the database.
581
			 *
582
			 * The SQL statement must be a string suitable for being used as
583
			 * prepared statement. It must include question marks for binding
584
			 * the values from the media item to the statement before they are
585
			 * sent to the database server. The order of the columns must
586
			 * correspond to the order in the save() method, so the
587
			 * correct values are 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 updating records
594
			 * @since 2014.03
595
			 * @category Developer
596
			 * @see mshop/media/manager/insert/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/update';
603
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
604
		}
605
606
		$idx = 1;
607
		$stmt = $this->getCachedStatement( $conn, $path, $sql );
608
609
		foreach( $columns as $name => $entry ) {
610
			$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

610
			$stmt->bind( $idx++, $item->get( $name ), /** @scrutinizer ignore-type */ $entry->getInternalType() );
Loading history...
611
		}
612
613
		$stmt->bind( $idx++, $item->getLanguageId() );
614
		$stmt->bind( $idx++, $item->getType() );
615
		$stmt->bind( $idx++, $item->getLabel() );
616
		$stmt->bind( $idx++, $item->getMimeType() );
617
		$stmt->bind( $idx++, $item->getUrl() );
618
		$stmt->bind( $idx++, $item->getStatus(), \Aimeos\Base\DB\Statement\Base::PARAM_INT );
619
		$stmt->bind( $idx++, $item->getFileSystem() );
620
		$stmt->bind( $idx++, $item->getDomain() );
621
		$stmt->bind( $idx++, json_encode( $item->getPreviews(), JSON_FORCE_OBJECT ) );
622
		$stmt->bind( $idx++, $date ); // mtime
623
		$stmt->bind( $idx++, $context->editor() );
624
		$stmt->bind( $idx++, $context->locale()->getSiteId() );
625
626
		if( $id !== null ) {
627
			$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
628
		} else {
629
			$stmt->bind( $idx++, $date ); // ctime
630
		}
631
632
		$stmt->execute()->finish();
633
634
		if( $id === null )
635
		{
636
			/** mshop/media/manager/newid/mysql
637
			 * Retrieves the ID generated by the database when inserting a new record
638
			 *
639
			 * @see mshop/media/manager/newid/ansi
640
			 */
641
642
			/** mshop/media/manager/newid/ansi
643
			 * Retrieves the ID generated by the database when inserting a new record
644
			 *
645
			 * As soon as a new record is inserted into the database table,
646
			 * the database server generates a new and unique identifier for
647
			 * that record. This ID can be used for retrieving, updating and
648
			 * deleting that specific record from the table again.
649
			 *
650
			 * For MySQL:
651
			 *  SELECT LAST_INSERT_ID()
652
			 * For PostgreSQL:
653
			 *  SELECT currval('seq_mmed_id')
654
			 * For SQL Server:
655
			 *  SELECT SCOPE_IDENTITY()
656
			 * For Oracle:
657
			 *  SELECT "seq_mmed_id".CURRVAL FROM DUAL
658
			 *
659
			 * There's no way to retrive the new ID by a SQL statements that
660
			 * fits for most database servers as they implement their own
661
			 * specific way.
662
			 *
663
			 * @param string SQL statement for retrieving the last inserted record ID
664
			 * @since 2014.03
665
			 * @category Developer
666
			 * @see mshop/media/manager/insert/ansi
667
			 * @see mshop/media/manager/update/ansi
668
			 * @see mshop/media/manager/delete/ansi
669
			 * @see mshop/media/manager/search/ansi
670
			 * @see mshop/media/manager/count/ansi
671
			 */
672
			$path = 'mshop/media/manager/newid';
673
			$id = $this->newId( $conn, $path );
674
		}
675
676
		$item->setId( $id );
677
678
		$item = $this->savePropertyItems( $item, 'media', $fetch );
679
		return $this->saveListItems( $item, 'media', $fetch );
680
	}
681
682
683
	/**
684
	 * Rescales the original file to preview files referenced by the media item
685
	 *
686
	 * The height/width configuration for scaling
687
	 * - mshop/media/<files|preview>/maxheight
688
	 * - mshop/media/<files|preview>/maxwidth
689
	 * - mshop/media/<files|preview>/force-size
690
	 *
691
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be scaled
692
	 * @param bool $force True to enforce creating new preview images
693
	 * @return \Aimeos\MShop\Media\Item\Iface Rescaled media item
694
	 */
695
	public function scale( \Aimeos\MShop\Media\Item\Iface $item, bool $force = false ) : \Aimeos\MShop\Media\Item\Iface
696
	{
697
		if( strncmp( $item->getMimeType(), 'image/', 6 ) ) {
698
			return $item;
699
		}
700
701
		$context = $this->context();
702
		$fsname = $item->getFileSystem();
703
704
		$fs = $context->fs( $fsname );
705
		$is = ( $fs instanceof \Aimeos\Base\Filesystem\MetaIface ? true : false );
706
707
		if( !$force && $is && date( 'Y-m-d H:i:s', $fs->time( $item->getUrl() ) ) < $item->getTimeModified() ) {
708
			return $item;
709
		}
710
711
		$domain = $item->getDomain();
712
		$name = basename( $item->getUrl() );
713
		$media = $this->getFile( $item->getUrl() );
714
715
		$previews = [];
716
		$item = $this->deletePreviews( $item, $fs );
717
718
		foreach( $this->createPreviews( $media, $item->getDomain(), $item->getType() ) as $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

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

1215
			&& !empty( $supported = $media::/** @scrutinizer ignore-call */ supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
Loading history...
1216
		) {
1217
			return $imgtype;
1218
		}
1219
1220
		return $mimetype;
1221
	}
1222
1223
1224
	/**
1225
	 * Stores the file content
1226
	 *
1227
	 * @param string $content File content
1228
	 * @param string $filepath Path of the new file
1229
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system object
1230
	 * @return \Aimeos\Controller\Common\Media\Iface Self object for fluent interface
1231
	 */
1232
	protected function store( string $content, string $filepath, \Aimeos\Base\Filesystem\Iface $fs ) : Iface
1233
	{
1234
		$fs->write( $filepath, $content );
1235
		return $this;
1236
	}
1237
}
1238