Avatar.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. * @copyright 2018 John Molakvoæ <skjnldsv@protonmail.com>
  6. *
  7. * @author Christopher Schäpers <kondou@ts.unde.re>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ <skjnldsv@protonmail.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Michael Weimann <mail@michael-weimann.eu>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Sergey Shliakhov <husband.sergey@gmail.com>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC\Avatar;
  36. use Imagick;
  37. use OC\Color;
  38. use OC_Image;
  39. use OCP\Files\NotFoundException;
  40. use OCP\IAvatar;
  41. use Psr\Log\LoggerInterface;
  42. /**
  43. * This class gets and sets users avatars.
  44. */
  45. abstract class Avatar implements IAvatar {
  46. /** @var LoggerInterface */
  47. protected $logger;
  48. /**
  49. * https://github.com/sebdesign/cap-height -- for 500px height
  50. * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
  51. * Noto Sans cap-height is 0.715 and we want a 200px caps height size
  52. * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px.
  53. * Since we start from the baseline (text-anchor) we need to
  54. * shift the y axis by 100px (half the caps height): 500/2+100=350
  55. *
  56. * @var string
  57. */
  58. private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  59. <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
  60. <rect width="100%" height="100%" fill="#{fill}"></rect>
  61. <text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#fff">{letter}</text>
  62. </svg>';
  63. public function __construct(LoggerInterface $logger) {
  64. $this->logger = $logger;
  65. }
  66. /**
  67. * Returns the user display name.
  68. *
  69. * @return string
  70. */
  71. abstract public function getDisplayName(): string;
  72. /**
  73. * Returns the first letter of the display name, or "?" if no name given.
  74. *
  75. * @return string
  76. */
  77. private function getAvatarText(): string {
  78. $displayName = $this->getDisplayName();
  79. if (empty($displayName) === true) {
  80. return '?';
  81. }
  82. $firstTwoLetters = array_map(function ($namePart) {
  83. return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
  84. }, explode(' ', $displayName, 2));
  85. return implode('', $firstTwoLetters);
  86. }
  87. /**
  88. * @inheritdoc
  89. */
  90. public function get($size = 64) {
  91. $size = (int) $size;
  92. try {
  93. $file = $this->getFile($size);
  94. } catch (NotFoundException $e) {
  95. return false;
  96. }
  97. $avatar = new OC_Image();
  98. $avatar->loadFromData($file->getContent());
  99. return $avatar;
  100. }
  101. /**
  102. * {size} = 500
  103. * {fill} = hex color to fill
  104. * {letter} = Letter to display
  105. *
  106. * Generate SVG avatar
  107. *
  108. * @param int $size The requested image size in pixel
  109. * @return string
  110. *
  111. */
  112. protected function getAvatarVector(int $size): string {
  113. $userDisplayName = $this->getDisplayName();
  114. $bgRGB = $this->avatarBackgroundColor($userDisplayName);
  115. $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b);
  116. $text = $this->getAvatarText();
  117. $toReplace = ['{size}', '{fill}', '{letter}'];
  118. return str_replace($toReplace, [$size, $bgHEX, $text], $this->svgTemplate);
  119. }
  120. /**
  121. * Generate png avatar from svg with Imagick
  122. *
  123. * @param int $size
  124. * @return string|boolean
  125. */
  126. protected function generateAvatarFromSvg(int $size) {
  127. if (!extension_loaded('imagick')) {
  128. return false;
  129. }
  130. try {
  131. $font = __DIR__ . '/../../core/fonts/NotoSans-Regular.ttf';
  132. $svg = $this->getAvatarVector($size);
  133. $avatar = new Imagick();
  134. $avatar->setFont($font);
  135. $avatar->readImageBlob($svg);
  136. $avatar->setImageFormat('png');
  137. $image = new OC_Image();
  138. $image->loadFromData((string)$avatar);
  139. $data = $image->data();
  140. return $data === null ? false : $data;
  141. } catch (\Exception $e) {
  142. return false;
  143. }
  144. }
  145. /**
  146. * Generate png avatar with GD
  147. *
  148. * @param string $userDisplayName
  149. * @param int $size
  150. * @return string
  151. */
  152. protected function generateAvatar($userDisplayName, $size) {
  153. $text = $this->getAvatarText();
  154. $backgroundColor = $this->avatarBackgroundColor($userDisplayName);
  155. $im = imagecreatetruecolor($size, $size);
  156. $background = imagecolorallocate(
  157. $im,
  158. $backgroundColor->r,
  159. $backgroundColor->g,
  160. $backgroundColor->b
  161. );
  162. $white = imagecolorallocate($im, 255, 255, 255);
  163. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  164. $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
  165. $fontSize = $size * 0.4;
  166. [$x, $y] = $this->imageTTFCenter(
  167. $im, $text, $font, (int)$fontSize
  168. );
  169. imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
  170. ob_start();
  171. imagepng($im);
  172. $data = ob_get_contents();
  173. ob_end_clean();
  174. return $data;
  175. }
  176. /**
  177. * Calculate real image ttf center
  178. *
  179. * @param resource $image
  180. * @param string $text text string
  181. * @param string $font font path
  182. * @param int $size font size
  183. * @param int $angle
  184. * @return array
  185. */
  186. protected function imageTTFCenter(
  187. $image,
  188. string $text,
  189. string $font,
  190. int $size,
  191. $angle = 0
  192. ): array {
  193. // Image width & height
  194. $xi = imagesx($image);
  195. $yi = imagesy($image);
  196. // bounding box
  197. $box = imagettfbbox($size, $angle, $font, $text);
  198. // imagettfbbox can return negative int
  199. $xr = abs(max($box[2], $box[4]));
  200. $yr = abs(max($box[5], $box[7]));
  201. // calculate bottom left placement
  202. $x = intval(($xi - $xr) / 2);
  203. $y = intval(($yi + $yr) / 2);
  204. return [$x, $y];
  205. }
  206. /**
  207. * Calculate steps between two Colors
  208. * @param object Color $steps start color
  209. * @param object Color $ends end color
  210. * @return array [r,g,b] steps for each color to go from $steps to $ends
  211. */
  212. private function stepCalc($steps, $ends) {
  213. $step = [];
  214. $step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
  215. $step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
  216. $step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
  217. return $step;
  218. }
  219. /**
  220. * Convert a string to an integer evenly
  221. * @param string $hash the text to parse
  222. * @param int $maximum the maximum range
  223. * @return int[] between 0 and $maximum
  224. */
  225. private function mixPalette($steps, $color1, $color2) {
  226. $palette = [$color1];
  227. $step = $this->stepCalc($steps, [$color1, $color2]);
  228. for ($i = 1; $i < $steps; $i++) {
  229. $r = intval($color1->r + ($step[0] * $i));
  230. $g = intval($color1->g + ($step[1] * $i));
  231. $b = intval($color1->b + ($step[2] * $i));
  232. $palette[] = new Color($r, $g, $b);
  233. }
  234. return $palette;
  235. }
  236. /**
  237. * Convert a string to an integer evenly
  238. * @param string $hash the text to parse
  239. * @param int $maximum the maximum range
  240. * @return int between 0 and $maximum
  241. */
  242. private function hashToInt($hash, $maximum) {
  243. $final = 0;
  244. $result = [];
  245. // Splitting evenly the string
  246. for ($i = 0; $i < strlen($hash); $i++) {
  247. // chars in md5 goes up to f, hex:16
  248. $result[] = intval(substr($hash, $i, 1), 16) % 16;
  249. }
  250. // Adds up all results
  251. foreach ($result as $value) {
  252. $final += $value;
  253. }
  254. // chars in md5 goes up to f, hex:16
  255. return intval($final % $maximum);
  256. }
  257. /**
  258. * @param string $hash
  259. * @return Color Object containting r g b int in the range [0, 255]
  260. */
  261. public function avatarBackgroundColor(string $hash) {
  262. // Normalize hash
  263. $hash = strtolower($hash);
  264. // Already a md5 hash?
  265. if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
  266. $hash = md5($hash);
  267. }
  268. // Remove unwanted char
  269. $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
  270. $red = new Color(182, 70, 157);
  271. $yellow = new Color(221, 203, 85);
  272. $blue = new Color(0, 130, 201); // Nextcloud blue
  273. // Number of steps to go from a color to another
  274. // 3 colors * 6 will result in 18 generated colors
  275. $steps = 6;
  276. $palette1 = $this->mixPalette($steps, $red, $yellow);
  277. $palette2 = $this->mixPalette($steps, $yellow, $blue);
  278. $palette3 = $this->mixPalette($steps, $blue, $red);
  279. $finalPalette = array_merge($palette1, $palette2, $palette3);
  280. return $finalPalette[$this->hashToInt($hash, $steps * 3)];
  281. }
  282. }