Completed
Push — master ( fb34ef...04f47a )
by Jan-Christoph
17:06
created

Avatar::avatarBackgroundColor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 13
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 21
rs 9.3142
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 * @copyright 2018 John Molakvoæ <[email protected]>
5
 *
6
 * @author Arthur Schiwon <[email protected]>
7
 * @author Christopher Schäpers <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Olivier Mehani <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Roeland Jago Douma <[email protected]>
13
 * @author Thomas Müller <[email protected]>
14
 *
15
 * @license AGPL-3.0
16
 *
17
 * This code is free software: you can redistribute it and/or modify
18
 * it under the terms of the GNU Affero General Public License, version 3,
19
 * as published by the Free Software Foundation.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License, version 3,
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
28
 *
29
 */
30
31
namespace OC;
32
33
use OC\User\User;
34
use OCP\Files\NotFoundException;
35
use OCP\Files\NotPermittedException;
36
use OCP\Files\SimpleFS\ISimpleFile;
37
use OCP\Files\SimpleFS\ISimpleFolder;
38
use OCP\IAvatar;
39
use OCP\IConfig;
40
use OCP\IImage;
41
use OCP\IL10N;
42
use OC_Image;
43
use OCP\ILogger;
44
45
class Color {
46
	public $r, $g, $b;
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
47
	public function __construct($r, $g, $b) {
48
		$this->r = $r;
49
		$this->g = $g;
50
		$this->b = $b;
51
	}
52
}
53
54
/**
55
 * This class gets and sets users avatars.
56
 */
57
58
class Avatar implements IAvatar {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
59
	/** @var ISimpleFolder */
60
	private $folder;
61
	/** @var IL10N */
62
	private $l;
63
	/** @var User */
64
	private $user;
65
	/** @var ILogger  */
66
	private $logger;
67
	/** @var IConfig */
68
	private $config;
69
70
	/**
71
	 * constructor
72
	 *
73
	 * @param ISimpleFolder $folder The folder where the avatars are
74
	 * @param IL10N $l
75
	 * @param User $user
76
	 * @param ILogger $logger
77
	 * @param IConfig $config
78
	 */
79 View Code Duplication
	public function __construct(ISimpleFolder $folder,
80
								IL10N $l,
81
								$user,
82
								ILogger $logger,
83
								IConfig $config) {
84
		$this->folder = $folder;
85
		$this->l = $l;
86
		$this->user = $user;
87
		$this->logger = $logger;
88
		$this->config = $config;
89
	}
90
91
	/**
92
	 * @inheritdoc
93
	 */
94
	public function get ($size = 64) {
95
		try {
96
			$file = $this->getFile($size);
97
		} catch (NotFoundException $e) {
98
			return false;
99
		}
100
101
		$avatar = new OC_Image();
102
		$avatar->loadFromData($file->getContent());
103
		return $avatar;
104
	}
105
106
	/**
107
	 * Check if an avatar exists for the user
108
	 *
109
	 * @return bool
110
	 */
111
	public function exists() {
112
113
		return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
114
	}
115
116
	/**
117
	 * sets the users avatar
118
	 * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
119
	 * @throws \Exception if the provided file is not a jpg or png image
120
	 * @throws \Exception if the provided image is not valid
121
	 * @throws NotSquareException if the image is not square
122
	 * @return void
123
	*/
124
	public function set ($data) {
125
126
		if($data instanceOf IImage) {
127
			$img = $data;
128
			$data = $img->data();
129
		} else {
130
			$img = new OC_Image();
131
			if (is_resource($data) && get_resource_type($data) === "gd") {
132
				$img->setResource($data);
0 ignored issues
show
Documentation introduced by
$data is of type resource, but the function expects a object<Returns>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
133
			} elseif(is_resource($data)) {
134
				$img->loadFromFileHandle($data);
135
			} else {
136
				try {
137
					// detect if it is a path or maybe the images as string
138
					$result = @realpath($data);
139
					if ($result === false || $result === null) {
140
						$img->loadFromData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 124 can also be of type resource; however, OC_Image::loadFromData() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
141
					} else {
142
						$img->loadFromFile($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 124 can also be of type resource; however, OC_Image::loadFromFile() does only seem to accept boolean|string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
143
					}
144
				} catch (\Error $e) {
0 ignored issues
show
Bug introduced by
The class Error does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
145
					$img->loadFromData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 124 can also be of type resource; however, OC_Image::loadFromData() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
146
				}
147
			}
148
		}
149
		$type = substr($img->mimeType(), -3);
150
		if ($type === 'peg') {
151
			$type = 'jpg';
152
		}
153
		if ($type !== 'jpg' && $type !== 'png') {
154
			throw new \Exception($this->l->t('Unknown filetype'));
155
		}
156
157
		if (!$img->valid()) {
158
			throw new \Exception($this->l->t('Invalid image'));
159
		}
160
161
		if (!($img->height() === $img->width())) {
162
			throw new NotSquareException($this->l->t('Avatar image is not square'));
163
		}
164
165
		$this->remove();
166
		$file = $this->folder->newFile('avatar.'.$type);
167
		$file->putContent($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 124 can also be of type resource; however, OCP\Files\SimpleFS\ISimpleFile::putContent() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
168
169
		try {
170
			$generated = $this->folder->getFile('generated');
171
			$this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
172
			$generated->delete();
173
		} catch (NotFoundException $e) {
174
			//
175
		}
176
		$this->user->triggerChange('avatar', $file);
177
	}
178
179
	/**
180
	 * remove the users avatar
181
	 * @return void
182
	*/
183
	public function remove () {
184
		$avatars = $this->folder->getDirectoryListing();
185
186
		$this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
187
			(int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1);
188
189
		foreach ($avatars as $avatar) {
190
			$avatar->delete();
191
		}
192
		$this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
193
		$this->user->triggerChange('avatar', '');
194
	}
195
196
	/**
197
	 * @inheritdoc
198
	 */
199
	public function getFile($size) {
200
		try {
201
			$ext = $this->getExtension();
202
		} catch (NotFoundException $e) {
203
			$data = $this->generateAvatar($this->user->getDisplayName(), 1024);
204
			$avatar = $this->folder->newFile('avatar.png');
205
			$avatar->putContent($data);
206
			$ext = 'png';
207
208
			$this->folder->newFile('generated');
209
			$this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
210
		}
211
212
		if ($size === -1) {
213
			$path = 'avatar.' . $ext;
214
		} else {
215
			$path = 'avatar.' . $size . '.' . $ext;
216
		}
217
218
		try {
219
			$file = $this->folder->getFile($path);
220
		} catch (NotFoundException $e) {
221
			if ($size <= 0) {
222
				throw new NotFoundException;
223
			}
224
225
			if ($this->folder->fileExists('generated')) {
226
				$data = $this->generateAvatar($this->user->getDisplayName(), $size);
227
228
			} else {
229
				$avatar = new OC_Image();
230
				/** @var ISimpleFile $file */
231
				$file = $this->folder->getFile('avatar.' . $ext);
232
				$avatar->loadFromData($file->getContent());
233
				$avatar->resize($size);
234
				$data = $avatar->data();
235
			}
236
237
			try {
238
				$file = $this->folder->newFile($path);
239
				$file->putContent($data);
240
			} catch (NotPermittedException $e) {
241
				$this->logger->error('Failed to save avatar for ' . $this->user->getUID());
242
				throw new NotFoundException();
243
			}
244
245
		}
246
247
		if($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
248
			$generated = $this->folder->fileExists('generated') ? 'true' : 'false';
249
			$this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
250
		}
251
252
		return $file;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $file; (OCP\Files\SimpleFS\ISimpleFile) is incompatible with the return type declared by the interface OCP\IAvatar::getFile of type OCP\Files\File.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
253
	}
254
255
	/**
256
	 * Get the extension of the avatar. If there is no avatar throw Exception
257
	 *
258
	 * @return string
259
	 * @throws NotFoundException
260
	 */
261
	private function getExtension() {
262
		if ($this->folder->fileExists('avatar.jpg')) {
263
			return 'jpg';
264
		} elseif ($this->folder->fileExists('avatar.png')) {
265
			return 'png';
266
		}
267
		throw new NotFoundException;
268
	}
269
270
	/**
271
	 * @param string $userDisplayName
272
	 * @param int $size
273
	 * @return string
274
	 */
275
	private function generateAvatar($userDisplayName, $size) {
276
		$text = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
277
		$backgroundColor = $this->avatarBackgroundColor($userDisplayName);
278
279
		$im = imagecreatetruecolor($size, $size);
280
		$background = imagecolorallocate($im, $backgroundColor->r, $backgroundColor->g, $backgroundColor->b);
281
		$white = imagecolorallocate($im, 255, 255, 255);
282
		imagefilledrectangle($im, 0, 0, $size, $size, $background);
283
284
		$font = __DIR__ . '/../../core/fonts/OpenSans-Semibold.ttf';
285
286
		$fontSize = $size * 0.4;
287
		$box = imagettfbbox($fontSize, 0, $font, $text);
288
289
		$x = ($size - ($box[2] - $box[0])) / 2;
290
		$y = ($size - ($box[1] - $box[7])) / 2;
291
		$x += 1;
292
		$y -= $box[7];
293
		imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
294
295
		ob_start();
296
		imagepng($im);
297
		$data = ob_get_contents();
298
		ob_end_clean();
299
300
		return $data;
301
	}
302
303
	/**
304
	 * Calculate steps between two Colors
305
	 * @param object Color $steps start color
306
	 * @param object Color $ends end color
307
	 * @return array [r,g,b] steps for each color to go from $steps to $ends
308
	 */
309
	private function stepCalc($steps, $ends) {
310
		$step = array();
311
		$step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
312
		$step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
313
		$step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
314
		return $step;
315
	}
316
	/**
317
	 * Convert a string to an integer evenly
318
	 * @param string $hash the text to parse
0 ignored issues
show
Bug introduced by
There is no parameter named $hash. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
319
	 * @param int $maximum the maximum range
0 ignored issues
show
Bug introduced by
There is no parameter named $maximum. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
320
	 * @return int between 0 and $maximum
321
	 */
322
	private function mixPalette($steps, $color1, $color2) {
323
		$count = $steps + 1;
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
324
		$palette = array($color1);
325
		$step = $this->stepCalc($steps, [$color1, $color2]);
326
		for ($i = 1; $i < $steps; $i++) {
327
			$r = intval($color1->r + ($step[0] * $i));
328
			$g = intval($color1->g + ($step[1] * $i));
329
			$b = intval($color1->b + ($step[2] * $i));
330
				$palette[] = new Color($r, $g, $b);
331
		}
332
		return $palette;
333
	}
334
335
336
	/**
337
	 * Convert a string to an integer evenly
338
	 * @param string $hash the text to parse
339
	 * @param int $maximum the maximum range
340
	 * @return int between 0 and $maximum
341
	 */
342
	private function hashToInt($hash, $maximum) {
343
		$final = 0;
344
		$result = array();
345
346
		// Splitting evenly the string
347
		for ($i=0; $i< strlen($hash); $i++) {
348
			// chars in md5 goes up to f, hex:16
349
			$result[] = intval(substr($hash, $i, 1), 16) % 16;
350
		}
351
		// Adds up all results
352
		foreach ($result as $value) {
353
			$final += $value;
354
		}
355
		// chars in md5 goes up to f, hex:16
356
		return intval($final % $maximum);
357
	}
358
359
360
	/**
361
	 * @param string $text
362
	 * @return Color Object containting r g b int in the range [0, 255]
363
	 */
364
	function avatarBackgroundColor($text) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
365
		$hash = preg_replace('/[^0-9a-f]+/', '', $text);
366
367
		$hash = md5($hash);
368
		$hashChars = str_split($hash);
0 ignored issues
show
Unused Code introduced by
$hashChars is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
369
370
		$red = new Color(182, 70, 157);
371
		$yellow = new Color(221, 203, 85);
372
		$blue = new Color(0, 130, 201); // Nextcloud blue
373
		// Number of steps to go from a color to another
374
		// 3 colors * 6 will result in 18 generated colors
375
		$steps = 6;
376
377
		$palette1 = $this->mixPalette($steps, $red, $yellow);
378
		$palette2 = $this->mixPalette($steps, $yellow, $blue);
379
		$palette3 = $this->mixPalette($steps, $blue, $red);
380
381
		$finalPalette = array_merge($palette1, $palette2, $palette3);
382
383
		return $finalPalette[$this->hashToInt($hash, $steps * 3 )];
384
	}
385
386
	public function userChanged($feature, $oldValue, $newValue) {
387
		// We only change the avatar on display name changes
388
		if ($feature !== 'displayName') {
389
			return;
390
		}
391
392
		// If the avatar is not generated (so an uploaded image) we skip this
393
		if (!$this->folder->fileExists('generated')) {
394
			return;
395
		}
396
397
		$this->remove();
398
	}
399
400
}
401