Passed
Push — master ( 1165dd...b24e02 )
by Aimeos
04:41
created

Standard::upload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 12
rs 10
cc 1
nc 1
nop 2
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-2023
7
 * @package MShop
8
 * @subpackage Media
9
 */
10
11
12
namespace Aimeos\MShop\Media\Manager;
13
14
use \Psr\Http\Message\UploadedFileInterface;
0 ignored issues
show
Bug introduced by
The type \Psr\Http\Message\UploadedFileInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

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

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

1317
			&& !empty( $supported = $media::/** @scrutinizer ignore-call */ supports( $allowed ) ) && ( $imgtype = reset( $supported ) ) !== false
Loading history...
1318
		) {
1319
			return $imgtype;
1320
		}
1321
1322
		return $mimetype;
1323
	}
1324
1325
1326
	/**
1327
	 * Returns the preview images to be deleted
1328
	 *
1329
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item with new preview URLs
1330
	 * @param array List of preview paths to remove
1331
	 * @return iterable List of preview URLs to remove
1332
	 */
1333
	protected function removePreviews( \Aimeos\MShop\Media\Item\Iface $item, array $paths ) : iterable
1334
	{
1335
		$previews = $item->getPreviews();
1336
1337
		// don't delete first (smallest) image because it may be referenced in past orders
1338
		if( $item->getDomain() === 'product' && in_array( key( $previews ), $paths ) ) {
1339
			return array_slice( $paths, 1 );
1340
		}
1341
1342
		return $paths;
1343
	}
1344
1345
1346
	/**
1347
	 * Called after the image has been scaled
1348
	 * Can be used to update the media item with image information.
1349
	 *
1350
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item with new preview URLs
1351
	 * @param \Aimeos\MW\Media\Image\Iface $media Media object
1352
	 */
1353
	protected function scaled( \Aimeos\MShop\Media\Item\Iface $item, \Aimeos\MW\Media\Image\Iface $media )
1354
	{
1355
	}
1356
1357
1358
	/**
1359
	 * Stores the file content
1360
	 *
1361
	 * @param string $content File content
1362
	 * @param string $filepath Path of the new file
1363
	 * @param \Aimeos\Base\Filesystem\Iface $fs File system object
1364
	 * @return \Aimeos\Controller\Common\Media\Iface Self object for fluent interface
1365
	 */
1366
	protected function store( string $content, string $filepath, \Aimeos\Base\Filesystem\Iface $fs ) : Iface
1367
	{
1368
		$fs->write( $filepath, $content );
1369
		return $this;
1370
	}
1371
}
1372