Avatar.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Avatar;
  9. use Imagick;
  10. use OCP\Color;
  11. use OCP\Files\NotFoundException;
  12. use OCP\IAvatar;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * This class gets and sets users avatars.
  16. */
  17. abstract class Avatar implements IAvatar {
  18. protected LoggerInterface $logger;
  19. /**
  20. * https://github.com/sebdesign/cap-height -- for 500px height
  21. * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
  22. * Noto Sans cap-height is 0.715 and we want a 200px caps height size
  23. * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.715 = 280px.
  24. * Since we start from the baseline (text-anchor) we need to
  25. * shift the y axis by 100px (half the caps height): 500/2+100=350
  26. */
  27. private string $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  28. <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
  29. <rect width="100%" height="100%" fill="#{fill}"></rect>
  30. <text x="50%" y="350" style="font-weight:normal;font-size:280px;font-family:\'Noto Sans\';text-anchor:middle;fill:#{fgFill}">{letter}</text>
  31. </svg>';
  32. public function __construct(LoggerInterface $logger) {
  33. $this->logger = $logger;
  34. }
  35. /**
  36. * Returns the user display name.
  37. */
  38. abstract public function getDisplayName(): string;
  39. /**
  40. * Returns the first letter of the display name, or "?" if no name given.
  41. */
  42. private function getAvatarText(): string {
  43. $displayName = $this->getDisplayName();
  44. if (empty($displayName) === true) {
  45. return '?';
  46. }
  47. $firstTwoLetters = array_map(function ($namePart) {
  48. return mb_strtoupper(mb_substr($namePart, 0, 1), 'UTF-8');
  49. }, explode(' ', $displayName, 2));
  50. return implode('', $firstTwoLetters);
  51. }
  52. /**
  53. * @inheritdoc
  54. */
  55. public function get(int $size = 64, bool $darkTheme = false) {
  56. try {
  57. $file = $this->getFile($size, $darkTheme);
  58. } catch (NotFoundException $e) {
  59. return false;
  60. }
  61. $avatar = new \OCP\Image();
  62. $avatar->loadFromData($file->getContent());
  63. return $avatar;
  64. }
  65. /**
  66. * {size} = 500
  67. * {fill} = hex color to fill
  68. * {letter} = Letter to display
  69. *
  70. * Generate SVG avatar
  71. *
  72. * @param int $size The requested image size in pixel
  73. * @return string
  74. *
  75. */
  76. protected function getAvatarVector(int $size, bool $darkTheme): string {
  77. $userDisplayName = $this->getDisplayName();
  78. $fgRGB = $this->avatarBackgroundColor($userDisplayName);
  79. $bgRGB = $fgRGB->alphaBlending(0.1, $darkTheme ? new Color(0, 0, 0) : new Color(255, 255, 255));
  80. $fill = sprintf('%02x%02x%02x', $bgRGB->red(), $bgRGB->green(), $bgRGB->blue());
  81. $fgFill = sprintf('%02x%02x%02x', $fgRGB->red(), $fgRGB->green(), $fgRGB->blue());
  82. $text = $this->getAvatarText();
  83. $toReplace = ['{size}', '{fill}', '{fgFill}', '{letter}'];
  84. return str_replace($toReplace, [$size, $fill, $fgFill, $text], $this->svgTemplate);
  85. }
  86. /**
  87. * Generate png avatar from svg with Imagick
  88. */
  89. protected function generateAvatarFromSvg(int $size, bool $darkTheme): ?string {
  90. if (!extension_loaded('imagick')) {
  91. return null;
  92. }
  93. $formats = Imagick::queryFormats();
  94. // Avatar generation breaks if RSVG format is enabled. Fall back to gd in that case
  95. if (in_array('RSVG', $formats, true)) {
  96. return null;
  97. }
  98. try {
  99. $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
  100. $svg = $this->getAvatarVector($size, $darkTheme);
  101. $avatar = new Imagick();
  102. $avatar->setFont($font);
  103. $avatar->readImageBlob($svg);
  104. $avatar->setImageFormat('png');
  105. $image = new \OCP\Image();
  106. $image->loadFromData((string)$avatar);
  107. return $image->data();
  108. } catch (\Exception $e) {
  109. return null;
  110. }
  111. }
  112. /**
  113. * Generate png avatar with GD
  114. * @throws \Exception when an error occurs in gd calls
  115. */
  116. protected function generateAvatar(string $userDisplayName, int $size, bool $darkTheme): string {
  117. $text = $this->getAvatarText();
  118. $textColor = $this->avatarBackgroundColor($userDisplayName);
  119. $backgroundColor = $textColor->alphaBlending(0.1, $darkTheme ? new Color(0, 0, 0) : new Color(255, 255, 255));
  120. $im = imagecreatetruecolor($size, $size);
  121. if ($im === false) {
  122. throw new \Exception('Failed to create avatar image');
  123. }
  124. $background = imagecolorallocate(
  125. $im,
  126. $backgroundColor->red(),
  127. $backgroundColor->green(),
  128. $backgroundColor->blue()
  129. );
  130. $textColor = imagecolorallocate($im,
  131. $textColor->red(),
  132. $textColor->green(),
  133. $textColor->blue()
  134. );
  135. if ($background === false || $textColor === false) {
  136. throw new \Exception('Failed to create avatar image color');
  137. }
  138. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  139. $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
  140. $fontSize = $size * 0.4;
  141. [$x, $y] = $this->imageTTFCenter(
  142. $im, $text, $font, (int)$fontSize
  143. );
  144. imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
  145. ob_start();
  146. imagepng($im);
  147. $data = ob_get_contents();
  148. ob_end_clean();
  149. return $data;
  150. }
  151. /**
  152. * Calculate real image ttf center
  153. *
  154. * @param \GdImage $image
  155. * @param string $text text string
  156. * @param string $font font path
  157. * @param int $size font size
  158. * @param int $angle
  159. * @return array
  160. */
  161. protected function imageTTFCenter(
  162. $image,
  163. string $text,
  164. string $font,
  165. int $size,
  166. int $angle = 0,
  167. ): array {
  168. // Image width & height
  169. $xi = imagesx($image);
  170. $yi = imagesy($image);
  171. // bounding box
  172. $box = imagettfbbox($size, $angle, $font, $text);
  173. // imagettfbbox can return negative int
  174. $xr = abs(max($box[2], $box[4]));
  175. $yr = abs(max($box[5], $box[7]));
  176. // calculate bottom left placement
  177. $x = intval(($xi - $xr) / 2);
  178. $y = intval(($yi + $yr) / 2);
  179. return [$x, $y];
  180. }
  181. /**
  182. * Convert a string to an integer evenly
  183. * @param string $hash the text to parse
  184. * @param int $maximum the maximum range
  185. * @return int between 0 and $maximum
  186. */
  187. private function hashToInt(string $hash, int $maximum): int {
  188. $final = 0;
  189. $result = [];
  190. // Splitting evenly the string
  191. for ($i = 0; $i < strlen($hash); $i++) {
  192. // chars in md5 goes up to f, hex:16
  193. $result[] = intval(substr($hash, $i, 1), 16) % 16;
  194. }
  195. // Adds up all results
  196. foreach ($result as $value) {
  197. $final += $value;
  198. }
  199. // chars in md5 goes up to f, hex:16
  200. return intval($final % $maximum);
  201. }
  202. /**
  203. * @return Color Object containing r g b int in the range [0, 255]
  204. */
  205. public function avatarBackgroundColor(string $hash): Color {
  206. // Normalize hash
  207. $hash = strtolower($hash);
  208. // Already a md5 hash?
  209. if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
  210. $hash = md5($hash);
  211. }
  212. // Remove unwanted char
  213. $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
  214. $red = new Color(182, 70, 157);
  215. $yellow = new Color(221, 203, 85);
  216. $blue = new Color(0, 130, 201); // Nextcloud blue
  217. // Number of steps to go from a color to another
  218. // 3 colors * 6 will result in 18 generated colors
  219. $steps = 6;
  220. $palette1 = Color::mixPalette($steps, $red, $yellow);
  221. $palette2 = Color::mixPalette($steps, $yellow, $blue);
  222. $palette3 = Color::mixPalette($steps, $blue, $red);
  223. $finalPalette = array_merge($palette1, $palette2, $palette3);
  224. return $finalPalette[$this->hashToInt($hash, $steps * 3)];
  225. }
  226. }