Passed
Push — master ( 179271...9dc280 )
by Aimeos
04:18
created

Standard::path()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 30
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 30
rs 9.9666
cc 3
nc 2
nop 3
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 enshrined\svgSanitize\Sanitizer;
15
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...
16
use \Intervention\Image\Interfaces\ImageInterface;
0 ignored issues
show
Bug introduced by
The type \Intervention\Image\Interfaces\ImageInterface 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...
17
18
19
/**
20
 * Default media manager implementation.
21
 *
22
 * @package MShop
23
 * @subpackage Media
24
 */
25
class Standard
26
	extends Base
27
	implements \Aimeos\MShop\Media\Manager\Iface, \Aimeos\MShop\Common\Manager\Factory\Iface
28
{
29
	/** mshop/media/manager/name
30
	 * Class name of the used media manager implementation
31
	 *
32
	 * Each default manager can be replace by an alternative imlementation.
33
	 * To use this implementation, you have to set the last part of the class
34
	 * name as configuration value so the manager factory knows which class it
35
	 * has to instantiate.
36
	 *
37
	 * For example, if the name of the default class is
38
	 *
39
	 *  \Aimeos\MShop\Media\Manager\Standard
40
	 *
41
	 * and you want to replace it with your own version named
42
	 *
43
	 *  \Aimeos\MShop\Media\Manager\Mymanager
44
	 *
45
	 * then you have to set the this configuration option:
46
	 *
47
	 *  mshop/media/manager/name = Mymanager
48
	 *
49
	 * The value is the last part of your own class name and it's case sensitive,
50
	 * so take care that the configuration value is exactly named like the last
51
	 * part of the class name.
52
	 *
53
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
54
	 * characters are possible! You should always start the last part of the class
55
	 * name with an upper case character and continue only with lower case characters
56
	 * or numbers. Avoid chamel case names like "MyManager"!
57
	 *
58
	 * @param string Last part of the class name
59
	 * @since 2014.03
60
	 * @category Developer
61
	 */
62
63
	/** mshop/media/manager/decorators/excludes
64
	 * Excludes decorators added by the "common" option from the media manager
65
	 *
66
	 * Decorators extend the functionality of a class by adding new aspects
67
	 * (e.g. log what is currently done), executing the methods of the underlying
68
	 * class only in certain conditions (e.g. only for logged in users) or
69
	 * modify what is returned to the caller.
70
	 *
71
	 * This option allows you to remove a decorator added via
72
	 * "mshop/common/manager/decorators/default" before they are wrapped
73
	 * around the media manager.
74
	 *
75
	 *  mshop/media/manager/decorators/excludes = array( 'decorator1' )
76
	 *
77
	 * This would remove the decorator named "decorator1" from the list of
78
	 * common decorators ("\Aimeos\MShop\Common\Manager\Decorator\*") added via
79
	 * "mshop/common/manager/decorators/default" for the media manager.
80
	 *
81
	 * @param array List of decorator names
82
	 * @since 2014.03
83
	 * @category Developer
84
	 * @see mshop/common/manager/decorators/default
85
	 * @see mshop/media/manager/decorators/global
86
	 * @see mshop/media/manager/decorators/local
87
	 */
88
89
	/** mshop/media/manager/decorators/global
90
	 * Adds a list of globally available decorators only to the media manager
91
	 *
92
	 * Decorators extend the functionality of a class by adding new aspects
93
	 * (e.g. log what is currently done), executing the methods of the underlying
94
	 * class only in certain conditions (e.g. only for logged in users) or
95
	 * modify what is returned to the caller.
96
	 *
97
	 * This option allows you to wrap global decorators
98
	 * ("\Aimeos\MShop\Common\Manager\Decorator\*") around the media manager.
99
	 *
100
	 *  mshop/media/manager/decorators/global = array( 'decorator1' )
101
	 *
102
	 * This would add the decorator named "decorator1" defined by
103
	 * "\Aimeos\MShop\Common\Manager\Decorator\Decorator1" only to the media
104
	 * manager.
105
	 *
106
	 * @param array List of decorator names
107
	 * @since 2014.03
108
	 * @category Developer
109
	 * @see mshop/common/manager/decorators/default
110
	 * @see mshop/media/manager/decorators/excludes
111
	 * @see mshop/media/manager/decorators/local
112
	 */
113
114
	/** mshop/media/manager/decorators/local
115
	 * Adds a list of local decorators only to the media manager
116
	 *
117
	 * Decorators extend the functionality of a class by adding new aspects
118
	 * (e.g. log what is currently done), executing the methods of the underlying
119
	 * class only in certain conditions (e.g. only for logged in users) or
120
	 * modify what is returned to the caller.
121
	 *
122
	 * This option allows you to wrap local decorators
123
	 * ("\Aimeos\MShop\Media\Manager\Decorator\*") around the media manager.
124
	 *
125
	 *  mshop/media/manager/decorators/local = array( 'decorator2' )
126
	 *
127
	 * This would add the decorator named "decorator2" defined by
128
	 * "\Aimeos\MShop\Media\Manager\Decorator\Decorator2" only to the media
129
	 * manager.
130
	 *
131
	 * @param array List of decorator names
132
	 * @since 2014.03
133
	 * @category Developer
134
	 * @see mshop/common/manager/decorators/default
135
	 * @see mshop/media/manager/decorators/excludes
136
	 * @see mshop/media/manager/decorators/global
137
	 */
138
139
140
	use \Aimeos\MShop\Common\Manager\PropertyRef\Traits;
141
	use \Aimeos\MShop\Common\Manager\ListsRef\Traits;
142
	use \Aimeos\MShop\Upload;
143
	use Preview;
144
145
146
	private array $searchConfig = array(
147
		'media.id' => array(
148
			'label' => 'ID',
149
			'code' => 'media.id',
150
			'internalcode' => 'mmed."id"',
151
			'type' => 'int',
152
		),
153
		'media.siteid' => array(
154
			'label' => 'Site ID',
155
			'code' => 'media.siteid',
156
			'internalcode' => 'mmed."siteid"',
157
			'public' => false,
158
		),
159
		'media.type' => array(
160
			'label' => 'Type',
161
			'code' => 'media.type',
162
			'internalcode' => 'mmed."type"',
163
		),
164
		'media.label' => array(
165
			'label' => 'Label',
166
			'code' => 'media.label',
167
			'internalcode' => 'mmed."label"',
168
		),
169
		'media.domain' => array(
170
			'label' => 'Domain',
171
			'code' => 'media.domain',
172
			'internalcode' => 'mmed."domain"',
173
		),
174
		'media.languageid' => array(
175
			'label' => 'Language code',
176
			'code' => 'media.languageid',
177
			'internalcode' => 'mmed."langid"',
178
		),
179
		'media.mimetype' => array(
180
			'label' => 'Mime type',
181
			'code' => 'media.mimetype',
182
			'internalcode' => 'mmed."mimetype"',
183
		),
184
		'media.url' => array(
185
			'label' => 'URL',
186
			'code' => 'media.url',
187
			'internalcode' => 'mmed."link"',
188
		),
189
		'media.preview' => array(
190
			'label' => 'Preview URLs as JSON encoded string',
191
			'code' => 'media.preview',
192
			'internalcode' => 'mmed."preview"',
193
		),
194
		'media.previews' => array(
195
			'label' => 'Preview URLs as JSON encoded string',
196
			'code' => 'media.previews',
197
			'internalcode' => 'mmed."previews"',
198
			'type' => 'json',
199
		),
200
		'media.filesystem' => array(
201
			'label' => 'File sytem name',
202
			'code' => 'media.filesystem',
203
			'internalcode' => 'mmed."fsname"',
204
		),
205
		'media.status' => array(
206
			'label' => 'Status',
207
			'code' => 'media.status',
208
			'internalcode' => 'mmed."status"',
209
			'type' => 'int',
210
		),
211
		'media.ctime' => array(
212
			'code' => 'media.ctime',
213
			'internalcode' => 'mmed."ctime"',
214
			'label' => 'Create date/time',
215
			'type' => 'datetime',
216
			'public' => false,
217
		),
218
		'media.mtime' => array(
219
			'code' => 'media.mtime',
220
			'internalcode' => 'mmed."mtime"',
221
			'label' => 'Modify date/time',
222
			'type' => 'datetime',
223
			'public' => false,
224
		),
225
		'media.editor' => array(
226
			'code' => 'media.editor',
227
			'internalcode' => 'mmed."editor"',
228
			'label' => 'Editor',
229
			'public' => false,
230
		),
231
		'media:has' => array(
232
			'code' => 'media:has()',
233
			'internalcode' => ':site AND :key AND mmedli."id"',
234
			'internaldeps' => ['LEFT JOIN "mshop_media_list" AS mmedli ON ( mmedli."parentid" = mmed."id" )'],
235
			'label' => 'Media has list item, parameter(<domain>[,<list type>[,<reference ID>)]]',
236
			'type' => 'null',
237
			'public' => false,
238
		),
239
		'media:prop' => array(
240
			'code' => 'media:prop()',
241
			'internalcode' => ':site AND :key AND mmedpr."id"',
242
			'internaldeps' => ['LEFT JOIN "mshop_media_property" AS mmedpr ON ( mmedpr."parentid" = mmed."id" )'],
243
			'label' => 'Media has property item, parameter(<property type>[,<language code>[,<property value>]])',
244
			'type' => 'null',
245
			'public' => false,
246
		),
247
	);
248
249
	private ?string $languageId;
250
251
252
	/**
253
	 * Initializes the object.
254
	 *
255
	 * @param \Aimeos\MShop\ContextIface $context Context object
256
	 */
257
	public function __construct( \Aimeos\MShop\ContextIface $context )
258
	{
259
		parent::__construct( $context );
260
261
		/** mshop/media/manager/resource
262
		 * Name of the database connection resource to use
263
		 *
264
		 * You can configure a different database connection for each data domain
265
		 * and if no such connection name exists, the "db" connection will be used.
266
		 * It's also possible to use the same database connection for different
267
		 * data domains by configuring the same connection name using this setting.
268
		 *
269
		 * @param string Database connection name
270
		 * @since 2023.04
271
		 */
272
		$this->setResourceName( $context->config()->get( 'mshop/media/manager/resource', 'db-media' ) );
273
		$this->languageId = $context->locale()->getLanguageId();
274
275
		$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
276
		$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
277
278
279
		$this->searchConfig['media:has']['function'] = function( &$source, array $params ) use ( $level ) {
280
281
			$keys = [];
282
283
			foreach( (array) ( $params[1] ?? '' ) as $type ) {
284
				foreach( (array) ( $params[2] ?? '' ) as $id ) {
285
					$keys[] = $params[0] . '|' . ( $type ? $type . '|' : '' ) . $id;
286
				}
287
			}
288
289
			$sitestr = $this->siteString( 'mmedli."siteid"', $level );
290
			$keystr = $this->toExpression( 'mmedli."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
291
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
292
293
			return $params;
294
		};
295
296
297
		$this->searchConfig['media:prop']['function'] = function( &$source, array $params ) use ( $level ) {
298
299
			$keys = [];
300
			$langs = array_key_exists( 1, $params ) ? ( $params[1] ?? 'null' ) : '';
301
302
			foreach( (array) $langs as $lang ) {
303
				foreach( (array) ( $params[2] ?? '' ) as $val ) {
304
					$keys[] = substr( $params[0] . '|' . ( $lang === null ? 'null|' : ( $lang ? $lang . '|' : '' ) ) . $val, 0, 255 );
305
				}
306
			}
307
308
			$sitestr = $this->siteString( 'mmedpr."siteid"', $level );
309
			$keystr = $this->toExpression( 'mmedpr."key"', $keys, ( $params[2] ?? null ) ? '==' : '=~' );
310
			$source = str_replace( [':site', ':key'], [$sitestr, $keystr], $source );
311
312
			return $params;
313
		};
314
	}
315
316
317
	/**
318
	 * Removes old entries from the storage.
319
	 *
320
	 * @param iterable $siteids List of IDs for sites whose entries should be deleted
321
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
322
	 */
323
	public function clear( iterable $siteids ) : \Aimeos\MShop\Common\Manager\Iface
324
	{
325
		$path = 'mshop/media/manager/submanagers';
326
		$default = ['lists', 'property', 'type'];
327
328
		foreach( $this->context()->config()->get( $path, $default ) as $domain ) {
329
			$this->object()->getSubManager( $domain )->clear( $siteids );
330
		}
331
332
		return $this->clearBase( $siteids, 'mshop/media/manager/delete' );
333
	}
334
335
336
	/**
337
	 * Copies the media item and the referenced files
338
	 *
339
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be copied
340
	 * @return \Aimeos\MShop\Media\Item\Iface Copied media item with new files
341
	 */
342
	public function copy( \Aimeos\MShop\Media\Item\Iface $item ) : \Aimeos\MShop\Media\Item\Iface
343
	{
344
		$item = ( clone $item )->setId( null );
345
346
		$path = $item->getUrl();
347
		$mime = $item->getMimeType();
348
		$domain = $item->getDomain();
349
		$previews = $item->getPreviews();
350
		$fsname = $item->getFileSystem();
351
		$fs = $this->context()->fs( $fsname );
352
353
		if( $fs->has( $path ) )
354
		{
355
			$newPath = $this->path( substr( basename( $path ), 9 ), $mime, $domain );
356
			$fs->copy( $path, $newPath );
357
			$item->setUrl( $newPath );
358
		}
359
360
		if( empty( $previews ) ) {
361
			return $this->scale( $item, true );
362
		}
363
364
		foreach( $previews as $size => $preview )
365
		{
366
			if( $fsname !== 'fs-mimeicon' && $fs->has( $preview ) )
367
			{
368
				$newPath = $this->path( substr( basename( $preview ), 9 ), $mime, $domain );
369
				$fs->copy( $preview, $newPath );
370
				$previews[$size] = $newPath;
371
			}
372
		}
373
374
		return $item->setPreviews( $previews );
375
	}
376
377
378
	/**
379
	 * Creates a new empty item instance
380
	 *
381
	 * @param array $values Values the item should be initialized with
382
	 * @return \Aimeos\MShop\Media\Item\Iface New media item object
383
	 */
384
	public function create( array $values = [] ) : \Aimeos\MShop\Common\Item\Iface
385
	{
386
		$values['media.siteid'] = $values['media.siteid'] ?? $this->context()->locale()->getSiteId();
387
		return $this->createItemBase( $values );
388
	}
389
390
391
	/**
392
	 * Removes multiple items.
393
	 *
394
	 * @param \Aimeos\MShop\Common\Item\Iface[]|string[] $items List of item objects or IDs of the items
395
	 * @return \Aimeos\MShop\Media\Manager\Iface Manager object for chaining method calls
396
	 */
397
	public function delete( $items ) : \Aimeos\MShop\Common\Manager\Iface
398
	{
399
		/** mshop/media/manager/delete/mysql
400
		 * Deletes the items matched by the given IDs from the database
401
		 *
402
		 * @see mshop/media/manager/delete/ansi
403
		 */
404
405
		/** mshop/media/manager/delete/ansi
406
		 * Deletes the items matched by the given IDs from the database
407
		 *
408
		 * Removes the records specified by the given IDs from the media database.
409
		 * The records must be from the site that is configured via the
410
		 * context item.
411
		 *
412
		 * The ":cond" placeholder is replaced by the name of the ID column and
413
		 * the given ID or list of IDs while the site ID is bound to the question
414
		 * mark.
415
		 *
416
		 * The SQL statement should conform to the ANSI standard to be
417
		 * compatible with most relational database systems. This also
418
		 * includes using double quotes for table and column names.
419
		 *
420
		 * @param string SQL statement for deleting items
421
		 * @since 2014.03
422
		 * @category Developer
423
		 * @see mshop/media/manager/insert/ansi
424
		 * @see mshop/media/manager/update/ansi
425
		 * @see mshop/media/manager/newid/ansi
426
		 * @see mshop/media/manager/search/ansi
427
		 * @see mshop/media/manager/count/ansi
428
		 */
429
		$cfgpath = 'mshop/media/manager/delete';
430
431
		foreach( map( $items ) as $item )
432
		{
433
			if( $item instanceof \Aimeos\MShop\Media\Item\Iface && $item->getFileSystem() === 'fs-media' )
434
			{
435
				$this->deletePreviews( $item, $item->getPreviews() );
436
				$this->deleteFile( $item->getUrl(), 'fs-media' );
437
			}
438
		}
439
440
		return $this->deleteItemsBase( $items, $cfgpath )->deleteRefItems( $items );
441
	}
442
443
444
	/**
445
	 * Creates a filter object.
446
	 *
447
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
448
	 * @param bool $site TRUE for adding site criteria to limit items by the site of related items
449
	 * @return \Aimeos\Base\Criteria\Iface Returns the filter object
450
	 */
451
	public function filter( ?bool $default = false, bool $site = false ) : \Aimeos\Base\Criteria\Iface
452
	{
453
		if( $default !== false )
454
		{
455
			$object = $this->filterBase( 'media', $default );
456
			$langid = $this->context()->locale()->getLanguageId();
457
458
			if( $langid !== null )
459
			{
460
				$temp = array(
461
					$object->compare( '==', 'media.languageid', $langid ),
462
					$object->compare( '==', 'media.languageid', null ),
463
				);
464
465
				$expr = array(
466
					$object->getConditions(),
467
					$object->or( $temp ),
468
				);
469
470
				$object->setConditions( $object->and( $expr ) );
471
			}
472
473
			return $object;
474
		}
475
476
		return parent::filter();
477
	}
478
479
480
	/**
481
	 * Returns an item for the given ID.
482
	 *
483
	 * @param string $id ID of the item that should be retrieved
484
	 * @param string[] $ref List of domains to fetch list items and referenced items for
485
	 * @param bool|null $default Add default criteria or NULL for relaxed default criteria
486
	 * @return \Aimeos\MShop\Media\Item\Iface Returns the media item of the given id
487
	 * @throws \Aimeos\MShop\Exception If item couldn't be found
488
	 */
489
	public function get( string $id, array $ref = [], ?bool $default = false ) : \Aimeos\MShop\Common\Item\Iface
490
	{
491
		return $this->getItemBase( 'media.id', $id, $ref, $default );
492
	}
493
494
495
	/**
496
	 * Returns the available manager types
497
	 *
498
	 * @param bool $withsub Return also the resource type of sub-managers if true
499
	 * @return string[] Type of the manager and submanagers, subtypes are separated by slashes
500
	 */
501
	public function getResourceType( bool $withsub = true ) : array
502
	{
503
		$path = 'mshop/media/manager/submanagers';
504
		$default = ['lists', 'property'];
505
506
		return $this->getResourceTypeBase( 'media', $path, $default, $withsub );
507
	}
508
509
510
	/**
511
	 * Returns the attributes that can be used for searching.
512
	 *
513
	 * @param bool $withsub Return also attributes of sub-managers if true
514
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of search attribute items
515
	 */
516
	public function getSearchAttributes( bool $withsub = true ) : array
517
	{
518
		/** mshop/media/manager/submanagers
519
		 * List of manager names that can be instantiated by the media manager
520
		 *
521
		 * Managers provide a generic interface to the underlying storage.
522
		 * Each manager has or can have sub-managers caring about particular
523
		 * aspects. Each of these sub-managers can be instantiated by its
524
		 * parent manager using the getSubManager() method.
525
		 *
526
		 * The search keys from sub-managers can be normally used in the
527
		 * manager as well. It allows you to search for items of the manager
528
		 * using the search keys of the sub-managers to further limit the
529
		 * retrieved list of items.
530
		 *
531
		 * @param array List of sub-manager names
532
		 * @since 2014.03
533
		 * @category Developer
534
		 */
535
		$path = 'mshop/media/manager/submanagers';
536
537
		return $this->getSearchAttributesBase( $this->searchConfig, $path, [], $withsub );
538
	}
539
540
541
	/**
542
	 * Returns a new manager for media extensions
543
	 *
544
	 * @param string $manager Name of the sub manager type in lower case
545
	 * @param string|null $name Name of the implementation, will be from configuration (or Default) if null
546
	 * @return \Aimeos\MShop\Common\Manager\Iface Manager for different extensions, e.g stock, tags, locations, etc.
547
	 */
548
	public function getSubManager( string $manager, string $name = null ) : \Aimeos\MShop\Common\Manager\Iface
549
	{
550
		return $this->getSubManagerBase( 'media', $manager, $name );
551
	}
552
553
554
	/**
555
	 * Adds a new item to the storage or updates an existing one.
556
	 *
557
	 * @param \Aimeos\MShop\Media\Item\Iface $item New item that should be saved to the storage
558
	 * @param bool $fetch True if the new ID should be returned in the item
559
	 * @return \Aimeos\MShop\Media\Item\Iface $item Updated item including the generated ID
560
	 */
561
	protected function saveItem( \Aimeos\MShop\Media\Item\Iface $item, bool $fetch = true ) : \Aimeos\MShop\Media\Item\Iface
562
	{
563
		if( !$item->isModified() )
564
		{
565
			$item = $this->savePropertyItems( $item, 'media', $fetch );
566
			return $this->saveListItems( $item, 'media', $fetch );
567
		}
568
569
		$context = $this->context();
570
		$conn = $context->db( $this->getResourceName() );
571
572
		$id = $item->getId();
573
		$date = date( 'Y-m-d H:i:s' );
574
		$columns = $this->object()->getSaveAttributes();
575
576
		if( $id === null )
577
		{
578
			/** mshop/media/manager/insert/mysql
579
			 * Inserts a new media record into the database table
580
			 *
581
			 * @see mshop/media/manager/insert/ansi
582
			 */
583
584
			/** mshop/media/manager/insert/ansi
585
			 * Inserts a new media record into the database table
586
			 *
587
			 * Items with no ID yet (i.e. the ID is NULL) will be created in
588
			 * the database and the newly created ID retrieved afterwards
589
			 * using the "newid" SQL statement.
590
			 *
591
			 * The SQL statement must be a string suitable for being used as
592
			 * prepared statement. It must include question marks for binding
593
			 * the values from the media item to the statement before they are
594
			 * sent to the database server. The number of question marks must
595
			 * be the same as the number of columns listed in the INSERT
596
			 * statement. The order of the columns must correspond to the
597
			 * order in the save() method, so the correct values are
598
			 * bound to the columns.
599
			 *
600
			 * The SQL statement should conform to the ANSI standard to be
601
			 * compatible with most relational database systems. This also
602
			 * includes using double quotes for table and column names.
603
			 *
604
			 * @param string SQL statement for inserting records
605
			 * @since 2014.03
606
			 * @category Developer
607
			 * @see mshop/media/manager/update/ansi
608
			 * @see mshop/media/manager/newid/ansi
609
			 * @see mshop/media/manager/delete/ansi
610
			 * @see mshop/media/manager/search/ansi
611
			 * @see mshop/media/manager/count/ansi
612
			 */
613
			$path = 'mshop/media/manager/insert';
614
			$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

614
			$sql = $this->addSqlColumns( array_keys( $columns ), /** @scrutinizer ignore-type */ $this->getSqlConfig( $path ) );
Loading history...
615
		}
616
		else
617
		{
618
			/** mshop/media/manager/update/mysql
619
			 * Updates an existing media record in the database
620
			 *
621
			 * @see mshop/media/manager/update/ansi
622
			 */
623
624
			/** mshop/media/manager/update/ansi
625
			 * Updates an existing media record in the database
626
			 *
627
			 * Items which already have an ID (i.e. the ID is not NULL) will
628
			 * be updated in the database.
629
			 *
630
			 * The SQL statement must be a string suitable for being used as
631
			 * prepared statement. It must include question marks for binding
632
			 * the values from the media item to the statement before they are
633
			 * sent to the database server. The order of the columns must
634
			 * correspond to the order in the save() method, so the
635
			 * correct values are bound to the columns.
636
			 *
637
			 * The SQL statement should conform to the ANSI standard to be
638
			 * compatible with most relational database systems. This also
639
			 * includes using double quotes for table and column names.
640
			 *
641
			 * @param string SQL statement for updating records
642
			 * @since 2014.03
643
			 * @category Developer
644
			 * @see mshop/media/manager/insert/ansi
645
			 * @see mshop/media/manager/newid/ansi
646
			 * @see mshop/media/manager/delete/ansi
647
			 * @see mshop/media/manager/search/ansi
648
			 * @see mshop/media/manager/count/ansi
649
			 */
650
			$path = 'mshop/media/manager/update';
651
			$sql = $this->addSqlColumns( array_keys( $columns ), $this->getSqlConfig( $path ), false );
652
		}
653
654
		$idx = 1;
655
		$stmt = $this->getCachedStatement( $conn, $path, $sql );
656
657
		foreach( $columns as $name => $entry ) {
658
			$stmt->bind( $idx++, $item->get( $name ), \Aimeos\Base\Criteria\SQL::type( $entry->getType() ) );
659
		}
660
661
		$stmt->bind( $idx++, $item->getLanguageId() );
662
		$stmt->bind( $idx++, $item->getType() );
663
		$stmt->bind( $idx++, $item->getLabel() );
664
		$stmt->bind( $idx++, $item->getMimeType() );
665
		$stmt->bind( $idx++, $item->getUrl() );
666
		$stmt->bind( $idx++, $item->getStatus(), \Aimeos\Base\DB\Statement\Base::PARAM_INT );
667
		$stmt->bind( $idx++, $item->getFileSystem() );
668
		$stmt->bind( $idx++, $item->getDomain() );
669
		$stmt->bind( $idx++, json_encode( $item->getPreviews(), JSON_FORCE_OBJECT ) );
670
		$stmt->bind( $idx++, $date ); // mtime
671
		$stmt->bind( $idx++, $context->editor() );
672
673
		if( $id !== null ) {
674
			$stmt->bind( $idx++, $context->locale()->getSiteId() . '%' );
675
			$stmt->bind( $idx++, $id, \Aimeos\Base\DB\Statement\Base::PARAM_INT );
676
		} else {
677
			$stmt->bind( $idx++, $this->siteId( $item->getSiteId(), \Aimeos\MShop\Locale\Manager\Base::SITE_SUBTREE ) );
678
			$stmt->bind( $idx++, $date ); // ctime
679
		}
680
681
		$stmt->execute()->finish();
682
683
		if( $id === null )
684
		{
685
			/** mshop/media/manager/newid/mysql
686
			 * Retrieves the ID generated by the database when inserting a new record
687
			 *
688
			 * @see mshop/media/manager/newid/ansi
689
			 */
690
691
			/** mshop/media/manager/newid/ansi
692
			 * Retrieves the ID generated by the database when inserting a new record
693
			 *
694
			 * As soon as a new record is inserted into the database table,
695
			 * the database server generates a new and unique identifier for
696
			 * that record. This ID can be used for retrieving, updating and
697
			 * deleting that specific record from the table again.
698
			 *
699
			 * For MySQL:
700
			 *  SELECT LAST_INSERT_ID()
701
			 * For PostgreSQL:
702
			 *  SELECT currval('seq_mmed_id')
703
			 * For SQL Server:
704
			 *  SELECT SCOPE_IDENTITY()
705
			 * For Oracle:
706
			 *  SELECT "seq_mmed_id".CURRVAL FROM DUAL
707
			 *
708
			 * There's no way to retrive the new ID by a SQL statements that
709
			 * fits for most database servers as they implement their own
710
			 * specific way.
711
			 *
712
			 * @param string SQL statement for retrieving the last inserted record ID
713
			 * @since 2014.03
714
			 * @category Developer
715
			 * @see mshop/media/manager/insert/ansi
716
			 * @see mshop/media/manager/update/ansi
717
			 * @see mshop/media/manager/delete/ansi
718
			 * @see mshop/media/manager/search/ansi
719
			 * @see mshop/media/manager/count/ansi
720
			 */
721
			$path = 'mshop/media/manager/newid';
722
			$id = $this->newId( $conn, $path );
723
		}
724
725
		$item->setId( $id );
726
727
		$item = $this->savePropertyItems( $item, 'media', $fetch );
728
		return $this->saveListItems( $item, 'media', $fetch );
729
	}
730
731
732
	/**
733
	 * Rescales the original file to preview files referenced by the media item
734
	 *
735
	 * The height/width configuration for scaling
736
	 * - mshop/media/<files|preview>/maxheight
737
	 * - mshop/media/<files|preview>/maxwidth
738
	 * - mshop/media/<files|preview>/force-size
739
	 *
740
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item whose files should be scaled
741
	 * @param bool $force True to enforce creating new preview images
742
	 * @return \Aimeos\MShop\Media\Item\Iface Rescaled media item
743
	 */
744
	public function scale( \Aimeos\MShop\Media\Item\Iface $item, bool $force = false ) : \Aimeos\MShop\Media\Item\Iface
745
	{
746
		$mime = $item->getMimeType();
747
748
		if( empty( $url = $item->getUrl() )
749
			|| $item->getFileSystem() === 'fs-mimeicon'
750
			|| strncmp( 'data:', $url, 5 ) === 0
751
			|| strncmp( 'image/svg', $mime, 9 ) === 0
752
			|| strncmp( 'image/', $mime, 6 ) !== 0
753
		) {
754
			return $item;
755
		}
756
757
		$fs = $this->context()->fs( $item->getFileSystem() );
758
		$is = ( $fs instanceof \Aimeos\Base\Filesystem\MetaIface ? true : false );
759
760
		if( !$force
761
			&& !empty( $item->getPreviews() )
762
			&& preg_match( '#^[a-zA-Z]{2,6}://#', $url ) !== 1
763
			&& ( $is && date( 'Y-m-d H:i:s', $fs->time( $url ) ) < $item->getTimeModified() || $fs->has( $url ) )
764
		) {
765
			return $item;
766
		}
767
768
		$previews = [];
769
		$old = $item->getPreviews();
770
		$domain = $item->getDomain() ?: '-';
771
		$image = $this->image( $fs, $url );
772
		$quality = $this->quality();
773
774
		foreach( $this->createPreviews( $image, $domain, $item->getType() ) as $width => $image )
775
		{
776
			$path = $old[$width] ?? $this->path( $url, 'image/webp', $domain );
777
			$fs->write( $path, (string) $image->toWebp( $quality ) );
778
			$previews[$width] = $path;
779
		}
780
781
		$item = $this->deletePreviews( $item, $old )->setPreviews( $previews );
782
783
		$this->call( 'scaled', $item, $image );
784
785
		return $item;
786
	}
787
788
789
	/**
790
	 * Returns the item objects matched by the given search criteria.
791
	 *
792
	 * @param \Aimeos\Base\Criteria\Iface $search Search criteria object
793
	 * @param string[] $ref List of domains to fetch list items and referenced items for
794
	 * @param int|null &$total Number of items that are available in total
795
	 * @return \Aimeos\Map List of items implementing \Aimeos\MShop\Media\Item\Iface with ids as keys
796
	 */
797
	public function search( \Aimeos\Base\Criteria\Iface $search, array $ref = [], int &$total = null ) : \Aimeos\Map
798
	{
799
		$map = [];
800
		$context = $this->context();
801
		$conn = $context->db( $this->getResourceName() );
802
803
			$required = array( 'media' );
804
805
			/** mshop/media/manager/sitemode
806
			 * Mode how items from levels below or above in the site tree are handled
807
			 *
808
			 * By default, only items from the current site are fetched from the
809
			 * storage. If the ai-sites extension is installed, you can create a
810
			 * tree of sites. Then, this setting allows you to define for the
811
			 * whole media domain if items from parent sites are inherited,
812
			 * sites from child sites are aggregated or both.
813
			 *
814
			 * Available constants for the site mode are:
815
			 * * 0 = only items from the current site
816
			 * * 1 = inherit items from parent sites
817
			 * * 2 = aggregate items from child sites
818
			 * * 3 = inherit and aggregate items at the same time
819
			 *
820
			 * You also need to set the mode in the locale manager
821
			 * (mshop/locale/manager/sitelevel) to one of the constants.
822
			 * If you set it to the same value, it will work as described but you
823
			 * can also use different modes. For example, if inheritance and
824
			 * aggregation is configured the locale manager but only inheritance
825
			 * in the domain manager because aggregating items makes no sense in
826
			 * this domain, then items wil be only inherited. Thus, you have full
827
			 * control over inheritance and aggregation in each domain.
828
			 *
829
			 * @param int Constant from Aimeos\MShop\Locale\Manager\Base class
830
			 * @category Developer
831
			 * @since 2018.01
832
			 * @see mshop/locale/manager/sitelevel
833
			 */
834
			$level = \Aimeos\MShop\Locale\Manager\Base::SITE_ALL;
835
			$level = $context->config()->get( 'mshop/media/manager/sitemode', $level );
836
837
			/** mshop/media/manager/search/mysql
838
			 * Retrieves the records matched by the given criteria in the database
839
			 *
840
			 * @see mshop/media/manager/search/ansi
841
			 */
842
843
			/** mshop/media/manager/search/ansi
844
			 * Retrieves the records matched by the given criteria in the database
845
			 *
846
			 * Fetches the records matched by the given criteria from the media
847
			 * database. The records must be from one of the sites that are
848
			 * configured via the context item. If the current site is part of
849
			 * a tree of sites, the SELECT statement can retrieve all records
850
			 * from the current site and the complete sub-tree of sites.
851
			 *
852
			 * As the records can normally be limited by criteria from sub-managers,
853
			 * their tables must be joined in the SQL context. This is done by
854
			 * using the "internaldeps" property from the definition of the ID
855
			 * column of the sub-managers. These internal dependencies specify
856
			 * the JOIN between the tables and the used columns for joining. The
857
			 * ":joins" placeholder is then replaced by the JOIN strings from
858
			 * the sub-managers.
859
			 *
860
			 * To limit the records matched, conditions can be added to the given
861
			 * criteria object. It can contain comparisons like column names that
862
			 * must match specific values which can be combined by AND, OR or NOT
863
			 * operators. The resulting string of SQL conditions replaces the
864
			 * ":cond" placeholder before the statement is sent to the database
865
			 * server.
866
			 *
867
			 * If the records that are retrieved should be ordered by one or more
868
			 * columns, the generated string of column / sort direction pairs
869
			 * replaces the ":order" placeholder. In case no ordering is required,
870
			 * the complete ORDER BY part including the "\/*-orderby*\/...\/*orderby-*\/"
871
			 * markers is removed to speed up retrieving the records. Columns of
872
			 * sub-managers can also be used for ordering the result set but then
873
			 * no index can be used.
874
			 *
875
			 * The number of returned records can be limited and can start at any
876
			 * number between the begining and the end of the result set. For that
877
			 * the ":size" and ":start" placeholders are replaced by the
878
			 * corresponding values from the criteria object. The default values
879
			 * are 0 for the start and 100 for the size value.
880
			 *
881
			 * The SQL statement should conform to the ANSI standard to be
882
			 * compatible with most relational database systems. This also
883
			 * includes using double quotes for table and column names.
884
			 *
885
			 * @param string SQL statement for searching items
886
			 * @since 2014.03
887
			 * @category Developer
888
			 * @see mshop/media/manager/insert/ansi
889
			 * @see mshop/media/manager/update/ansi
890
			 * @see mshop/media/manager/newid/ansi
891
			 * @see mshop/media/manager/delete/ansi
892
			 * @see mshop/media/manager/count/ansi
893
			 */
894
			$cfgPathSearch = 'mshop/media/manager/search';
895
896
			/** mshop/media/manager/count/mysql
897
			 * Counts the number of records matched by the given criteria in the database
898
			 *
899
			 * @see mshop/media/manager/count/ansi
900
			 */
901
902
			/** mshop/media/manager/count/ansi
903
			 * Counts the number of records matched by the given criteria in the database
904
			 *
905
			 * Counts all records matched by the given criteria from the media
906
			 * database. The records must be from one of the sites that are
907
			 * configured via the context item. If the current site is part of
908
			 * a tree of sites, the statement can count all records from the
909
			 * current site and the complete sub-tree of sites.
910
			 *
911
			 * As the records can normally be limited by criteria from sub-managers,
912
			 * their tables must be joined in the SQL context. This is done by
913
			 * using the "internaldeps" property from the definition of the ID
914
			 * column of the sub-managers. These internal dependencies specify
915
			 * the JOIN between the tables and the used columns for joining. The
916
			 * ":joins" placeholder is then replaced by the JOIN strings from
917
			 * the sub-managers.
918
			 *
919
			 * To limit the records matched, conditions can be added to the given
920
			 * criteria object. It can contain comparisons like column names that
921
			 * must match specific values which can be combined by AND, OR or NOT
922
			 * operators. The resulting string of SQL conditions replaces the
923
			 * ":cond" placeholder before the statement is sent to the database
924
			 * server.
925
			 *
926
			 * Both, the strings for ":joins" and for ":cond" are the same as for
927
			 * the "search" SQL statement.
928
			 *
929
			 * Contrary to the "search" statement, it doesn't return any records
930
			 * but instead the number of records that have been found. As counting
931
			 * thousands of records can be a long running task, the maximum number
932
			 * of counted records is limited for performance reasons.
933
			 *
934
			 * The SQL statement should conform to the ANSI standard to be
935
			 * compatible with most relational database systems. This also
936
			 * includes using double quotes for table and column names.
937
			 *
938
			 * @param string SQL statement for counting items
939
			 * @since 2014.03
940
			 * @category Developer
941
			 * @see mshop/media/manager/insert/ansi
942
			 * @see mshop/media/manager/update/ansi
943
			 * @see mshop/media/manager/newid/ansi
944
			 * @see mshop/media/manager/delete/ansi
945
			 * @see mshop/media/manager/search/ansi
946
			 */
947
			$cfgPathCount = 'mshop/media/manager/count';
948
949
			$results = $this->searchItemsBase( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $level );
950
951
			while( $row = $results->fetch() )
952
			{
953
				if( ( $row['media.previews'] = json_decode( $config = $row['media.previews'], true ) ) === null ) {
954
					$row['media.previews'] = [];
955
				}
956
957
				$map[$row['media.id']] = $row;
958
			}
959
960
		$propItems = []; $name = 'media/property';
961
		if( isset( $ref[$name] ) || in_array( $name, $ref, true ) )
962
		{
963
			$propTypes = isset( $ref[$name] ) && is_array( $ref[$name] ) ? $ref[$name] : null;
964
			$propItems = $this->getPropertyItems( array_keys( $map ), 'media', $propTypes );
965
		}
966
967
		return $this->buildItems( $map, $ref, 'media', $propItems );
968
	}
969
970
971
	/**
972
	 * Stores the uploaded file and returns the updated item
973
	 *
974
	 * @param \Aimeos\MShop\Media\Item\Iface $item Media item for storing the file meta data, "domain" must be set
975
	 * @param \Psr\Http\Message\UploadedFileInterface|null $file Uploaded file object
976
	 * @param \Psr\Http\Message\UploadedFileInterface|null $preview Uploaded preview image
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, UploadedFileInterface $preview = null ) : \Aimeos\MShop\Media\Item\Iface
980
	{
981
		$domain = $item->getDomain() ?: '-';
982
		$fsname = $item->getFileSystem() ?: 'fs-media';
983
984
		if( $file && $file->getError() !== UPLOAD_ERR_NO_FILE && $this->isAllowed( $mime = $this->mimetype( $file ) ) )
985
		{
986
			$path = $this->path( $file->getClientFilename(), $mime, $domain );
987
			$this->context()->fs( $fsname )->write( $path, $this->sanitize( (string) $file->getStream(), $mime ) );
988
989
			$item->setLabel( $file->getClientFilename() )
990
				->setMimetype( $mime )
991
				->setUrl( $path );
992
		}
993
994
		if( $preview && $preview->getError() !== UPLOAD_ERR_NO_FILE && $this->isAllowed( $mime = $this->mimetype( $preview ) ) )
995
		{
996
			$path = $this->path( $preview->getClientFilename(), $mime, $domain );
997
			$this->context()->fs( $fsname )->write( $path, $this->sanitize( (string) $preview->getStream(), $mime ) );
998
999
			$item->setPreview( $path );
1000
		}
1001
1002
		return $this->scale( $item );
1003
	}
1004
1005
1006
	/**
1007
	 * Creates a new media item instance.
1008
	 *
1009
	 * @param array $values Associative list of key/value pairs
1010
	 * @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of list items
1011
	 * @param \Aimeos\MShop\Common\Item\Iface[] $refItems List of items referenced
1012
	 * @param \Aimeos\MShop\Common\Item\Property\Iface[] $propItems List of property items
1013
	 * @return \Aimeos\MShop\Media\Item\Iface New media item
1014
	 */
1015
	protected function createItemBase( array $values = [], array $listItems = [], array $refItems = [],
1016
		array $propItems = [] ) : \Aimeos\MShop\Common\Item\Iface
1017
	{
1018
		$values['.languageid'] = $this->languageId;
1019
1020
		return new \Aimeos\MShop\Media\Item\Standard( $values, $listItems, $refItems, $propItems );
1021
	}
1022
}
1023