Avatar.php 8.4 KB

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