Passed
Branch develop (a7390e)
by
unknown
25:38
created

vignette()   F

Complexity

Conditions 49
Paths > 20000

Size

Total Lines 245
Code Lines 145

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 49
eloc 145
c 0
b 0
f 0
nc 28902773
nop 7
dl 0
loc 245
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2004-2010 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2005-2007 Regis Houssin        <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 * or see http://www.gnu.org/
18
 */
19
20
/**
21
 *  \file		htdocs/core/lib/images.lib.php
22
 *  \brief		Set of function for manipulating images
23
 */
24
25
// Define size of logo small and mini
26
$maxwidthsmall=270;$maxheightsmall=150;
27
$maxwidthmini=128;$maxheightmini=72;
28
$quality = 80;
29
30
31
32
/**
33
 *      Return if a filename is file name of a supported image format
34
 *
35
 *      @param	string	$file       Filename
36
 *      @return int         		-1=Not image filename, 0=Image filename but format not supported by PHP, 1=Image filename with format supported by this PHP
37
 */
38
function image_format_supported($file)
39
{
40
    $regeximgext='\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.xpm|\.xbm|\.svg';   // See also into product.class.php
41
42
    // Case filename is not a format image
43
    if (! preg_match('/('.$regeximgext.')$/i', $file, $reg)) return -1;
44
45
    // Case filename is a format image but not supported by this PHP
46
    $imgfonction='';
47
    if (strtolower($reg[1]) == '.gif')  $imgfonction = 'imagecreatefromgif';
48
    if (strtolower($reg[1]) == '.png')  $imgfonction = 'imagecreatefrompng';
49
    if (strtolower($reg[1]) == '.jpg')  $imgfonction = 'imagecreatefromjpeg';
50
    if (strtolower($reg[1]) == '.jpeg') $imgfonction = 'imagecreatefromjpeg';
51
    if (strtolower($reg[1]) == '.bmp')  $imgfonction = 'imagecreatefromwbmp';
52
    if (strtolower($reg[1]) == '.xpm')  $imgfonction = 'imagecreatefromxpm';
53
    if (strtolower($reg[1]) == '.xbm')  $imgfonction = 'imagecreatefromxbm';
54
    if ($imgfonction)
55
    {
56
        if (! function_exists($imgfonction))
57
        {
58
            // Fonctions de conversion non presente dans ce PHP
59
            return 0;
60
        }
61
    }
62
63
    // Filename is a format image and supported by this PHP
64
    return 1;
65
}
66
67
68
/**
69
 *    	Return size of image file on disk (Supported extensions are gif, jpg, png and bmp)
70
 *
71
 * 		@param	string	$file		Full path name of file
72
 * 		@param	bool	$url		Image with url (true or false)
73
 * 		@return	array				array('width'=>width, 'height'=>height)
74
 */
75
function dol_getImageSize($file, $url = false)
76
{
77
	$ret=array();
78
79
	if (image_format_supported($file) < 0) return $ret;
80
81
	$filetoread = $file;
82
	if (!$url)
83
	{
84
		$filetoread = realpath(dol_osencode($file)); 	// Chemin canonique absolu de l'image
85
	}
86
87
	if ($filetoread)
88
	{
89
    	$infoImg = getimagesize($filetoread); // Recuperation des infos de l'image
90
    	$ret['width']=$infoImg[0]; // Largeur de l'image
91
    	$ret['height']=$infoImg[1]; // Hauteur de l'image
92
	}
93
94
	return $ret;
95
}
96
97
98
/**
99
 *    	Resize or crop an image file (Supported extensions are gif, jpg, png and bmp)
100
 *
101
 *    	@param	string	$file          	Path of file to resize/crop
102
 * 		@param	int		$mode			0=Resize, 1=Crop
103
 *    	@param  int		$newWidth      	Largeur maximum que dois faire l'image destination (0=keep ratio)
104
 *    	@param  int		$newHeight     	Hauteur maximum que dois faire l'image destination (0=keep ratio)
105
 * 		@param	int		$src_x			Position of croping image in source image (not use if mode=0)
106
 * 		@param	int		$src_y			Position of croping image in source image (not use if mode=0)
107
 *		@return	string                  File name if OK, error message if KO
108
 */
109
function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $src_y = 0)
110
{
111
	require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
112
113
	global $conf,$langs;
114
115
	dol_syslog("dol_imageResizeOrCrop file=".$file." mode=".$mode." newWidth=".$newWidth." newHeight=".$newHeight." src_x=".$src_x." src_y=".$src_y);
116
117
	// Clean parameters
118
	$file=trim($file);
119
120
	// Check parameters
121
	if (! $file)
122
	{
123
		// Si le fichier n'a pas ete indique
124
		return 'Bad parameter file';
125
	}
126
	elseif (! file_exists($file))
127
	{
128
		// Si le fichier passe en parametre n'existe pas
129
		return $langs->trans("ErrorFileNotFound", $file);
130
	}
131
	elseif(image_format_supported($file) < 0)
132
	{
133
		return 'This filename '.$file.' does not seem to be an image filename.';
134
	}
135
	elseif(!is_numeric($newWidth) && !is_numeric($newHeight))
1 ignored issue
show
introduced by
The condition is_numeric($newWidth) is always true.
Loading history...
136
	{
137
		return 'Wrong value for parameter newWidth or newHeight';
138
	}
139
	elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0)
140
	{
141
		return 'At least newHeight or newWidth must be defined for resizing';
142
	}
143
	elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0))
144
	{
145
		return 'Both newHeight or newWidth must be defined for croping';
146
	}
147
148
	$filetoread = realpath(dol_osencode($file)); 	// Chemin canonique absolu de l'image
149
150
	$infoImg = getimagesize($filetoread); // Recuperation des infos de l'image
151
	$imgWidth = $infoImg[0]; // Largeur de l'image
152
	$imgHeight = $infoImg[1]; // Hauteur de l'image
153
154
	if ($mode == 0)	// If resize, we check parameters
155
	{
156
		if ($newWidth  <= 0)
157
		{
158
			$newWidth=intval(($newHeight / $imgHeight) * $imgWidth);	// Keep ratio
159
		}
160
		if ($newHeight <= 0)
161
		{
162
			$newHeight=intval(($newWidth / $imgWidth) * $imgHeight);	// Keep ratio
163
		}
164
	}
165
166
	$imgfonction='';
167
	switch($infoImg[2])
168
	{
169
		case 1:	// IMG_GIF
170
			$imgfonction = 'imagecreatefromgif';
171
			break;
172
		case 2:	// IMG_JPG
173
			$imgfonction = 'imagecreatefromjpeg';
174
			break;
175
		case 3:	// IMG_PNG
176
			$imgfonction = 'imagecreatefrompng';
177
			break;
178
		case 4:	// IMG_WBMP
179
			$imgfonction = 'imagecreatefromwbmp';
180
			break;
181
	}
182
	if ($imgfonction)
183
	{
184
		if (! function_exists($imgfonction))
185
		{
186
			// Fonctions de conversion non presente dans ce PHP
187
			return 'Resize not possible. This PHP does not support GD functions '.$imgfonction;
188
		}
189
	}
190
191
	// Initialisation des variables selon l'extension de l'image
192
	switch($infoImg[2])
193
	{
194
		case 1:	// Gif
195
			$img = imagecreatefromgif($filetoread);
196
			$extImg = '.gif';	// File name extension of image
197
			$newquality='NU';	// Quality is not used for this format
198
			break;
199
		case 2:	// Jpg
200
			$img = imagecreatefromjpeg($filetoread);
201
			$extImg = '.jpg';
202
			$newquality=100;	// % quality maximum
203
			break;
204
		case 3:	// Png
205
			$img = imagecreatefrompng($filetoread);
206
			$extImg = '.png';
207
			$newquality=0;		// No compression (0-9)
208
			break;
209
		case 4:	// Bmp
210
			$img = imagecreatefromwbmp($filetoread);
211
			$extImg = '.bmp';
212
			$newquality='NU';	// Quality is not used for this format
213
			break;
214
	}
215
216
	// Create empty image
217
	if ($infoImg[2] == 1)
218
	{
219
		// Compatibilite image GIF
220
		$imgThumb = imagecreate($newWidth, $newHeight);
221
	}
222
	else
223
	{
224
		$imgThumb = imagecreatetruecolor($newWidth, $newHeight);
225
	}
226
227
	// Activate antialiasing for better quality
228
	if (function_exists('imageantialias'))
229
	{
230
		imageantialias($imgThumb, true);
231
	}
232
233
	// This is to keep transparent alpha channel if exists (PHP >= 4.2)
234
	if (function_exists('imagesavealpha'))
235
	{
236
		imagesavealpha($imgThumb, true);
237
	}
238
239
	// Initialisation des variables selon l'extension de l'image
240
	switch($infoImg[2])
241
	{
242
		case 1:	// Gif
243
			$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
244
			imagecolortransparent($imgThumb, $trans_colour);
245
			break;
246
		case 2:	// Jpg
247
			$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
248
			break;
249
		case 3:	// Png
250
			imagealphablending($imgThumb, false); // Pour compatibilite sur certain systeme
251
			$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127);	// Keep transparent channel
252
			break;
253
		case 4:	// Bmp
254
			$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
255
			break;
256
	}
257
	if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $trans_colour does not seem to be defined for all execution paths leading up to this point.
Loading history...
258
259
	dol_syslog("dol_imageResizeOrCrop: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as $extImg, newquality=$newquality");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extImg does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $newquality does not seem to be defined for all execution paths leading up to this point.
Loading history...
260
	//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
261
	imagecopyresampled($imgThumb, $img, 0, 0, $src_x, $src_y, $newWidth, $newHeight, ($mode==0?$imgWidth:$newWidth), ($mode==0?$imgHeight:$newHeight)); // Insere l'image de base redimensionnee
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $img does not seem to be defined for all execution paths leading up to this point.
Loading history...
262
263
	$imgThumbName = $file;
264
265
	// Check if permission are ok
266
	//$fp = fopen($imgThumbName, "w");
267
	//fclose($fp);
268
269
	// Create image on disk
270
	switch($infoImg[2])
271
	{
272
		case 1:	// Gif
273
			imagegif($imgThumb, $imgThumbName);
274
			break;
275
		case 2:	// Jpg
276
			imagejpeg($imgThumb, $imgThumbName, $newquality);
277
			break;
278
		case 3:	// Png
279
			imagepng($imgThumb, $imgThumbName, $newquality);
280
			break;
281
		case 4:	// Bmp
282
			image2wbmp($imgThumb, $imgThumbName);
0 ignored issues
show
Deprecated Code introduced by
The function image2wbmp() has been deprecated: 7.3.0 Use imagewbmp() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

282
			/** @scrutinizer ignore-deprecated */ image2wbmp($imgThumb, $imgThumbName);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
283
			break;
284
	}
285
286
	// Set permissions on file
287
	if (! empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

287
	if (! empty($conf->global->MAIN_UMASK)) /** @scrutinizer ignore-unhandled */ @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
288
289
	// Free memory. This does not delete image.
290
    imagedestroy($img);
291
	imagedestroy($imgThumb);
292
293
	clearstatcache();	// File was replaced by a modified one, so we clear file caches.
294
295
	return $imgThumbName;
296
}
297
298
299
/**
300
 * dolRotateImage if image is a jpg file.
301
 * Currently use an autodetection to know if we can rotate.
302
 * TODO Introduce a new parameter to force rotate.
303
 *
304
 * @param 	string   $file_path      Full path to image to rotate
305
 * @return	boolean				     Success or not
306
 */
307
function dolRotateImage($file_path)
308
{
309
    $exif = @exif_read_data($file_path);
310
    if ($exif === false) {
311
        return false;
312
    }
313
    $orientation = intval(@$exif['Orientation']);
314
    if (!in_array($orientation, array(3, 6, 8))) {
315
        return false;
316
    }
317
    $image = @imagecreatefromjpeg($file_path);
318
    switch ($orientation) {
319
        case 3:
320
            $image = @imagerotate($image, 180, 0);
321
            break;
322
        case 6:
323
            $image = @imagerotate($image, 270, 0);
324
            break;
325
        case 8:
326
            $image = @imagerotate($image, 90, 0);
327
            break;
328
        default:
329
            return false;
330
    }
331
    $success = imagejpeg($image, $file_path);
332
    // Free up memory (imagedestroy does not delete files):
333
    @imagedestroy($image);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for imagedestroy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

333
    /** @scrutinizer ignore-unhandled */ @imagedestroy($image);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
334
    return $success;
335
}
336
337
338
339
/**
340
 *    	Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
341
 *      If file is myfile.jpg, new file may be myfile_small.jpg
342
 *
343
 *    	@param     string	$file           	Path of source file to resize
344
 *    	@param     int		$maxWidth       	Largeur maximum que dois faire la miniature (-1=unchanged, 160 by default)
345
 *    	@param     int		$maxHeight      	Hauteur maximum que dois faire l'image (-1=unchanged, 120 by default)
346
 *    	@param     string	$extName        	Extension to differenciate thumb file name ('_small', '_mini')
347
 *    	@param     int		$quality        	Quality of compression (0=worst, 100=best)
348
 *      @param     string	$outdir           	Directory where to store thumb
349
 *      @param     int		$targetformat     	New format of target (IMAGETYPE_GIF, IMAGETYPE_JPG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_WBMP ... or 0 to keep old format)
350
 *    	@return    string						Full path of thumb or '' if it fails or 'Error...' if it fails
351
 */
352
function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $quality = 50, $outdir = 'thumbs', $targetformat = 0)
353
{
354
	require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
355
356
	global $conf,$langs;
357
358
	dol_syslog("vignette file=".$file." extName=".$extName." maxWidth=".$maxWidth." maxHeight=".$maxHeight." quality=".$quality." outdir=".$outdir." targetformat=".$targetformat);
359
360
	// Clean parameters
361
	$file=trim($file);
362
363
	// Check parameters
364
	if (! $file)
365
	{
366
		// Si le fichier n'a pas ete indique
367
		return 'ErrorBadParameters';
368
	}
369
	elseif (! file_exists($file))
370
	{
371
		// Si le fichier passe en parametre n'existe pas
372
        dol_syslog($langs->trans("ErrorFileNotFound", $file), LOG_ERR);
373
	    return $langs->trans("ErrorFileNotFound", $file);
374
	}
375
	elseif(image_format_supported($file) < 0)
376
	{
377
        dol_syslog('This file '.$file.' does not seem to be an image format file name.', LOG_WARNING);
378
	    return 'ErrorBadImageFormat';
379
	}
380
	elseif(!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1){
1 ignored issue
show
introduced by
The condition is_numeric($maxWidth) is always true.
Loading history...
381
		// Si la largeur max est incorrecte (n'est pas numerique, est vide, ou est inferieure a 0)
382
        dol_syslog('Wrong value for parameter maxWidth', LOG_ERR);
383
	    return 'Error: Wrong value for parameter maxWidth';
384
	}
385
	elseif(!is_numeric($maxHeight) || empty($maxHeight) || $maxHeight < -1){
1 ignored issue
show
introduced by
The condition is_numeric($maxHeight) is always true.
Loading history...
386
		// Si la hauteur max est incorrecte (n'est pas numerique, est vide, ou est inferieure a 0)
387
        dol_syslog('Wrong value for parameter maxHeight', LOG_ERR);
388
	    return 'Error: Wrong value for parameter maxHeight';
389
	}
390
391
	$filetoread = realpath(dol_osencode($file)); 	// Chemin canonique absolu de l'image
392
393
	$infoImg = getimagesize($filetoread); // Recuperation des infos de l'image
394
	$imgWidth = $infoImg[0]; // Largeur de l'image
395
	$imgHeight = $infoImg[1]; // Hauteur de l'image
396
397
	if ($maxWidth  == -1) $maxWidth=$infoImg[0];	// If size is -1, we keep unchanged
398
	if ($maxHeight == -1) $maxHeight=$infoImg[1];	// If size is -1, we keep unchanged
399
400
	// Si l'image est plus petite que la largeur et la hauteur max, on ne cree pas de vignette
401
	if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight)
402
	{
403
		// On cree toujours les vignettes
404
		dol_syslog("File size is smaller than thumb size", LOG_DEBUG);
405
		//return 'Le fichier '.$file.' ne necessite pas de creation de vignette';
406
	}
407
408
	$imgfonction='';
409
	switch($infoImg[2])
410
	{
411
		case IMAGETYPE_GIF:	    // 1
412
			$imgfonction = 'imagecreatefromgif';
413
			break;
414
		case IMAGETYPE_JPEG:    // 2
415
			$imgfonction = 'imagecreatefromjpeg';
416
			break;
417
		case IMAGETYPE_PNG:	    // 3
418
			$imgfonction = 'imagecreatefrompng';
419
			break;
420
		case IMAGETYPE_BMP:	    // 6
421
            // Not supported by PHP GD
422
			break;
423
		case IMAGETYPE_WBMP:	// 15
424
			$imgfonction = 'imagecreatefromwbmp';
425
			break;
426
	}
427
	if ($imgfonction)
428
	{
429
		if (! function_exists($imgfonction))
430
		{
431
			// Fonctions de conversion non presente dans ce PHP
432
			return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction;
433
		}
434
	}
435
436
	// On cree le repertoire contenant les vignettes
437
	$dirthumb = dirname($file).($outdir?'/'.$outdir:''); 	// Chemin du dossier contenant les vignettes
438
	dol_mkdir($dirthumb);
439
440
	// Initialisation des variables selon l'extension de l'image
441
	$img=null;
442
	switch($infoImg[2])
443
	{
444
		case IMAGETYPE_GIF:	    // 1
445
			$img = imagecreatefromgif($filetoread);
446
			$extImg = '.gif'; // Extension de l'image
447
			break;
448
		case IMAGETYPE_JPEG:    // 2
449
			$img = imagecreatefromjpeg($filetoread);
450
			$extImg = (preg_match('/\.jpeg$/', $file)?'.jpeg':'.jpg'); // Extension de l'image
451
			break;
452
		case IMAGETYPE_PNG:	    // 3
453
			$img = imagecreatefrompng($filetoread);
454
			$extImg = '.png';
455
			break;
456
		case IMAGETYPE_BMP:	    // 6
457
            // Not supported by PHP GD
458
			$extImg = '.bmp';
459
			break;
460
		case IMAGETYPE_WBMP:	// 15
461
			$img = imagecreatefromwbmp($filetoread);
462
			$extImg = '.bmp';
463
			break;
464
	}
465
    if (! is_resource($img))
466
    {
467
        dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING);
468
        return 0;
469
    }
470
471
	// Initialisation des dimensions de la vignette si elles sont superieures a l'original
472
	if($maxWidth > $imgWidth){ $maxWidth = $imgWidth; }
473
	if($maxHeight > $imgHeight){ $maxHeight = $imgHeight; }
474
475
	$whFact = $maxWidth/$maxHeight; // Facteur largeur/hauteur des dimensions max de la vignette
476
	$imgWhFact = $imgWidth/$imgHeight; // Facteur largeur/hauteur de l'original
477
478
	// Fixe les dimensions de la vignette
479
	if($whFact < $imgWhFact)
480
	{
481
		// Si largeur determinante
482
		$thumbWidth  = $maxWidth;
483
		$thumbHeight = $thumbWidth / $imgWhFact;
484
	}
485
	else
486
	{
487
		// Si hauteur determinante
488
		$thumbHeight = $maxHeight;
489
		$thumbWidth  = $thumbHeight * $imgWhFact;
490
	}
491
	$thumbHeight=round($thumbHeight);
492
	$thumbWidth=round($thumbWidth);
493
494
    // Define target format
495
    if (empty($targetformat)) $targetformat=$infoImg[2];
496
497
	// Create empty image
498
	if ($targetformat == IMAGETYPE_GIF)
499
	{
500
		// Compatibilite image GIF
501
		$imgThumb = imagecreate($thumbWidth, $thumbHeight);
502
	}
503
	else
504
	{
505
		$imgThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
506
	}
507
508
	// Activate antialiasing for better quality
509
	if (function_exists('imageantialias'))
510
	{
511
		imageantialias($imgThumb, true);
512
	}
513
514
	// This is to keep transparent alpha channel if exists (PHP >= 4.2)
515
	if (function_exists('imagesavealpha'))
516
	{
517
		imagesavealpha($imgThumb, true);
518
	}
519
520
	// Initialisation des variables selon l'extension de l'image
521
	// $targetformat is 0 by default, in such case, we keep original extension
522
	switch($targetformat)
523
	{
524
		case IMAGETYPE_GIF:	    // 1
525
			$trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF
526
			imagecolortransparent($imgThumb, $trans_colour);
527
            $extImgTarget = '.gif';
528
            $newquality='NU';
529
            break;
530
		case IMAGETYPE_JPEG:    // 2
531
            $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
532
            $extImgTarget = (preg_match('/\.jpeg$/i', $file)?'.jpeg':'.jpg');
533
            $newquality=$quality;
534
            break;
535
		case IMAGETYPE_PNG:	    // 3
536
			imagealphablending($imgThumb, false); // Pour compatibilite sur certain systeme
537
			$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127);	// Keep transparent channel
538
            $extImgTarget = '.png';
539
            $newquality=$quality-100;
540
            $newquality=round(abs($quality-100)*9/100);
541
            break;
542
		case IMAGETYPE_BMP:	    // 6
543
            // Not supported by PHP GD
544
            $extImgTarget = '.bmp';
545
            $newquality='NU';
546
            break;
547
		case IMAGETYPE_WBMP:	// 15
548
			$trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
549
            $extImgTarget = '.bmp';
550
            $newquality='NU';
551
            break;
552
	}
553
	if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $trans_colour does not seem to be defined for all execution paths leading up to this point.
Loading history...
554
555
	dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extImg does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $newquality does not seem to be defined for all execution paths leading up to this point.
Loading history...
556
	//imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
557
	imagecopyresampled($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
558
559
	$fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i', '', $file);	// On enleve extension quelquesoit la casse
560
	$fileName = basename($fileName);
561
	//$imgThumbName = $dirthumb.'/'.getImageFileNameForSize(basename($file), $extName, $extImgTarget);   // Full path of thumb file
562
	$imgThumbName = getImageFileNameForSize($file, $extName, $extImgTarget);   // Full path of thumb file
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extImgTarget does not seem to be defined for all execution paths leading up to this point.
Loading history...
563
564
565
	// Check if permission are ok
566
	//$fp = fopen($imgThumbName, "w");
567
	//fclose($fp);
568
569
	// Create image on disk
570
	switch($targetformat)
571
	{
572
		case IMAGETYPE_GIF:	    // 1
573
			imagegif($imgThumb, $imgThumbName);
574
			break;
575
		case IMAGETYPE_JPEG:    // 2
576
			imagejpeg($imgThumb, $imgThumbName, $newquality);
577
			break;
578
		case IMAGETYPE_PNG:	    // 3
579
			imagepng($imgThumb, $imgThumbName, $newquality);
580
			break;
581
		case IMAGETYPE_BMP:	    // 6
582
            // Not supported by PHP GD
583
			break;
584
		case IMAGETYPE_WBMP:    // 15
585
			image2wbmp($imgThumb, $imgThumbName);
0 ignored issues
show
Deprecated Code introduced by
The function image2wbmp() has been deprecated: 7.3.0 Use imagewbmp() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

585
			/** @scrutinizer ignore-deprecated */ image2wbmp($imgThumb, $imgThumbName);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
586
			break;
587
	}
588
589
	// Set permissions on file
590
	if (! empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

590
	if (! empty($conf->global->MAIN_UMASK)) /** @scrutinizer ignore-unhandled */ @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
591
592
    // Free memory. This does not delete image.
593
    imagedestroy($img);
594
    imagedestroy($imgThumb);
595
596
	return $imgThumbName;
597
}
598