Avatar.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. */
  142. protected function generateAvatar(string $userDisplayName, int $size, bool $darkTheme): string {
  143. $text = $this->getAvatarText();
  144. $textColor = $this->avatarBackgroundColor($userDisplayName);
  145. $backgroundColor = $textColor->alphaBlending(0.1, $darkTheme ? new Color(0, 0, 0) : new Color(255, 255, 255));
  146. $im = imagecreatetruecolor($size, $size);
  147. $background = imagecolorallocate(
  148. $im,
  149. $backgroundColor->red(),
  150. $backgroundColor->green(),
  151. $backgroundColor->blue()
  152. );
  153. $textColor = imagecolorallocate($im,
  154. $textColor->red(),
  155. $textColor->green(),
  156. $textColor->blue()
  157. );
  158. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  159. $font = __DIR__ . '/../../../core/fonts/NotoSans-Regular.ttf';
  160. $fontSize = $size * 0.4;
  161. [$x, $y] = $this->imageTTFCenter(
  162. $im, $text, $font, (int)$fontSize
  163. );
  164. imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
  165. ob_start();
  166. imagepng($im);
  167. $data = ob_get_contents();
  168. ob_end_clean();
  169. return $data;
  170. }
  171. /**
  172. * Calculate real image ttf center
  173. *
  174. * @param resource $image
  175. * @param string $text text string
  176. * @param string $font font path
  177. * @param int $size font size
  178. * @param int $angle
  179. * @return array
  180. */
  181. protected function imageTTFCenter(
  182. $image,
  183. string $text,
  184. string $font,
  185. int $size,
  186. int $angle = 0
  187. ): array {
  188. // Image width & height
  189. $xi = imagesx($image);
  190. $yi = imagesy($image);
  191. // bounding box
  192. $box = imagettfbbox($size, $angle, $font, $text);
  193. // imagettfbbox can return negative int
  194. $xr = abs(max($box[2], $box[4]));
  195. $yr = abs(max($box[5], $box[7]));
  196. // calculate bottom left placement
  197. $x = intval(($xi - $xr) / 2);
  198. $y = intval(($yi + $yr) / 2);
  199. return [$x, $y];
  200. }
  201. /**
  202. * Convert a string to an integer evenly
  203. * @param string $hash the text to parse
  204. * @param int $maximum the maximum range
  205. * @return int between 0 and $maximum
  206. */
  207. private function hashToInt(string $hash, int $maximum): int {
  208. $final = 0;
  209. $result = [];
  210. // Splitting evenly the string
  211. for ($i = 0; $i < strlen($hash); $i++) {
  212. // chars in md5 goes up to f, hex:16
  213. $result[] = intval(substr($hash, $i, 1), 16) % 16;
  214. }
  215. // Adds up all results
  216. foreach ($result as $value) {
  217. $final += $value;
  218. }
  219. // chars in md5 goes up to f, hex:16
  220. return intval($final % $maximum);
  221. }
  222. /**
  223. * @return Color Object containing r g b int in the range [0, 255]
  224. */
  225. public function avatarBackgroundColor(string $hash): Color {
  226. // Normalize hash
  227. $hash = strtolower($hash);
  228. // Already a md5 hash?
  229. if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) {
  230. $hash = md5($hash);
  231. }
  232. // Remove unwanted char
  233. $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
  234. $red = new Color(182, 70, 157);
  235. $yellow = new Color(221, 203, 85);
  236. $blue = new Color(0, 130, 201); // Nextcloud blue
  237. // Number of steps to go from a color to another
  238. // 3 colors * 6 will result in 18 generated colors
  239. $steps = 6;
  240. $palette1 = Color::mixPalette($steps, $red, $yellow);
  241. $palette2 = Color::mixPalette($steps, $yellow, $blue);
  242. $palette3 = Color::mixPalette($steps, $blue, $red);
  243. $finalPalette = array_merge($palette1, $palette2, $palette3);
  244. return $finalPalette[$this->hashToInt($hash, $steps * 3)];
  245. }
  246. }