You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
8.7 KiB

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