Avatar.php 8.4 KB

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