Avatar.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright 2018 John Molakvoæ <skjnldsv@protonmail.com>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christopher Schäpers <kondou@ts.unde.re>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Olivier Mehani <shtrom@ssji.net>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author John Molakvoæ <skjnldsv@protonmail.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC;
  32. use OCP\Files\NotFoundException;
  33. use OCP\Files\NotPermittedException;
  34. use OCP\Files\SimpleFS\ISimpleFile;
  35. use OCP\Files\SimpleFS\ISimpleFolder;
  36. use OCP\IAvatar;
  37. use OCP\IConfig;
  38. use OCP\IImage;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  41. use OC\User\User;
  42. use OC_Image;
  43. use Imagick;
  44. /**
  45. * This class gets and sets users avatars.
  46. */
  47. class Avatar implements IAvatar {
  48. /** @var ISimpleFolder */
  49. private $folder;
  50. /** @var IL10N */
  51. private $l;
  52. /** @var User */
  53. private $user;
  54. /** @var ILogger */
  55. private $logger;
  56. /** @var IConfig */
  57. private $config;
  58. /**
  59. * https://github.com/sebdesign/cap-height -- for 500px height
  60. * Automated check: https://codepen.io/skjnldsv/pen/PydLBK/
  61. * Nunito cap-height is 0.716 and we want a 200px caps height size
  62. * (0.4 letter-to-total-height ratio, 500*0.4=200), so: 200/0.716 = 279px.
  63. * Since we start from the baseline (text-anchor) we need to
  64. * shift the y axis by 100px (half the caps height): 500/2+100=350
  65. *
  66. * @var string
  67. */
  68. private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  69. <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
  70. <rect width="100%" height="100%" fill="#{fill}"></rect>
  71. <text x="50%" y="350" style="font-weight:normal;font-size:279px;font-family:\'Nunito\';text-anchor:middle;fill:#fff">{letter}</text>
  72. </svg>';
  73. /**
  74. * constructor
  75. *
  76. * @param ISimpleFolder $folder The folder where the avatars are
  77. * @param IL10N $l
  78. * @param User $user
  79. * @param ILogger $logger
  80. * @param IConfig $config
  81. */
  82. public function __construct(ISimpleFolder $folder,
  83. IL10N $l,
  84. $user,
  85. ILogger $logger,
  86. IConfig $config) {
  87. $this->folder = $folder;
  88. $this->l = $l;
  89. $this->user = $user;
  90. $this->logger = $logger;
  91. $this->config = $config;
  92. }
  93. /**
  94. * @inheritdoc
  95. */
  96. public function get($size = 64) {
  97. try {
  98. $file = $this->getFile($size);
  99. } catch (NotFoundException $e) {
  100. return false;
  101. }
  102. $avatar = new OC_Image();
  103. $avatar->loadFromData($file->getContent());
  104. return $avatar;
  105. }
  106. /**
  107. * Check if an avatar exists for the user
  108. *
  109. * @return bool
  110. */
  111. public function exists() {
  112. return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
  113. }
  114. /**
  115. * Check if the avatar of a user is a custom uploaded one
  116. *
  117. * @return bool
  118. */
  119. public function isCustomAvatar(): bool {
  120. return $this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', 'false') !== 'true';
  121. }
  122. /**
  123. * sets the users avatar
  124. * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
  125. * @throws \Exception if the provided file is not a jpg or png image
  126. * @throws \Exception if the provided image is not valid
  127. * @throws NotSquareException if the image is not square
  128. * @return void
  129. */
  130. public function set($data) {
  131. if ($data instanceof IImage) {
  132. $img = $data;
  133. $data = $img->data();
  134. } else {
  135. $img = new OC_Image();
  136. if (is_resource($data) && get_resource_type($data) === "gd") {
  137. $img->setResource($data);
  138. } elseif (is_resource($data)) {
  139. $img->loadFromFileHandle($data);
  140. } else {
  141. try {
  142. // detect if it is a path or maybe the images as string
  143. $result = @realpath($data);
  144. if ($result === false || $result === null) {
  145. $img->loadFromData($data);
  146. } else {
  147. $img->loadFromFile($data);
  148. }
  149. } catch (\Error $e) {
  150. $img->loadFromData($data);
  151. }
  152. }
  153. }
  154. $type = substr($img->mimeType(), -3);
  155. if ($type === 'peg') {
  156. $type = 'jpg';
  157. }
  158. if ($type !== 'jpg' && $type !== 'png') {
  159. throw new \Exception($this->l->t('Unknown filetype'));
  160. }
  161. if (!$img->valid()) {
  162. throw new \Exception($this->l->t('Invalid image'));
  163. }
  164. if (!($img->height() === $img->width())) {
  165. throw new NotSquareException($this->l->t('Avatar image is not square'));
  166. }
  167. $this->remove();
  168. $file = $this->folder->newFile('avatar.' . $type);
  169. $file->putContent($data);
  170. try {
  171. $generated = $this->folder->getFile('generated');
  172. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
  173. $generated->delete();
  174. } catch (NotFoundException $e) {
  175. //
  176. }
  177. $this->user->triggerChange('avatar', $file);
  178. }
  179. /**
  180. * remove the users avatar
  181. * @return void
  182. */
  183. public function remove() {
  184. $avatars = $this->folder->getDirectoryListing();
  185. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  186. (int) $this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1);
  187. foreach ($avatars as $avatar) {
  188. $avatar->delete();
  189. }
  190. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  191. $this->user->triggerChange('avatar', '');
  192. }
  193. /**
  194. * @inheritdoc
  195. */
  196. public function getFile($size) {
  197. try {
  198. $ext = $this->getExtension();
  199. } catch (NotFoundException $e) {
  200. if (!$data = $this->generateAvatarFromSvg(1024)) {
  201. $data = $this->generateAvatar($this->user->getDisplayName(), 1024);
  202. }
  203. $avatar = $this->folder->newFile('avatar.png');
  204. $avatar->putContent($data);
  205. $ext = 'png';
  206. $this->folder->newFile('generated');
  207. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  208. }
  209. if ($size === -1) {
  210. $path = 'avatar.' . $ext;
  211. } else {
  212. $path = 'avatar.' . $size . '.' . $ext;
  213. }
  214. try {
  215. $file = $this->folder->getFile($path);
  216. } catch (NotFoundException $e) {
  217. if ($size <= 0) {
  218. throw new NotFoundException;
  219. }
  220. if ($this->folder->fileExists('generated')) {
  221. if (!$data = $this->generateAvatarFromSvg($size)) {
  222. $data = $this->generateAvatar($this->user->getDisplayName(), $size);
  223. }
  224. } else {
  225. $avatar = new OC_Image();
  226. /** @var ISimpleFile $file */
  227. $file = $this->folder->getFile('avatar.' . $ext);
  228. $avatar->loadFromData($file->getContent());
  229. $avatar->resize($size);
  230. $data = $avatar->data();
  231. }
  232. try {
  233. $file = $this->folder->newFile($path);
  234. $file->putContent($data);
  235. } catch (NotPermittedException $e) {
  236. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  237. throw new NotFoundException();
  238. }
  239. }
  240. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  241. $generated = $this->folder->fileExists('generated') ? 'true' : 'false';
  242. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  243. }
  244. return $file;
  245. }
  246. /**
  247. * Get the extension of the avatar. If there is no avatar throw Exception
  248. *
  249. * @return string
  250. * @throws NotFoundException
  251. */
  252. private function getExtension() {
  253. if ($this->folder->fileExists('avatar.jpg')) {
  254. return 'jpg';
  255. } elseif ($this->folder->fileExists('avatar.png')) {
  256. return 'png';
  257. }
  258. throw new NotFoundException;
  259. }
  260. /**
  261. * {size} = 500
  262. * {fill} = hex color to fill
  263. * {letter} = Letter to display
  264. *
  265. * Generate SVG avatar
  266. * @return string
  267. *
  268. */
  269. private function getAvatarVector(int $size): string {
  270. $userDisplayName = $this->user->getDisplayName();
  271. $bgRGB = $this->avatarBackgroundColor($userDisplayName);
  272. $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b);
  273. $letter = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
  274. $toReplace = ['{size}', '{fill}', '{letter}'];
  275. return str_replace($toReplace, [$size, $bgHEX, $letter], $this->svgTemplate);
  276. }
  277. /**
  278. * Generate png avatar from svg with Imagick
  279. *
  280. * @param int $size
  281. * @return string|boolean
  282. */
  283. private function generateAvatarFromSvg(int $size) {
  284. if (!extension_loaded('imagick')) {
  285. return false;
  286. }
  287. try {
  288. $font = __DIR__ . '/../../core/fonts/Nunito-Regular.ttf';
  289. $svg = $this->getAvatarVector($size);
  290. $avatar = new Imagick();
  291. $avatar->setFont($font);
  292. $avatar->readImageBlob($svg);
  293. $avatar->setImageFormat('png');
  294. $image = new OC_Image();
  295. $image->loadFromData($avatar);
  296. return $image->data();
  297. } catch (\Exception $e) {
  298. return false;
  299. }
  300. }
  301. /**
  302. * Generate png avatar with GD
  303. *
  304. * @param string $userDisplayName
  305. * @param int $size
  306. * @return string
  307. */
  308. private function generateAvatar($userDisplayName, $size) {
  309. $text = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
  310. $backgroundColor = $this->avatarBackgroundColor($userDisplayName);
  311. $im = imagecreatetruecolor($size, $size);
  312. $background = imagecolorallocate($im, $backgroundColor->r, $backgroundColor->g, $backgroundColor->b);
  313. $white = imagecolorallocate($im, 255, 255, 255);
  314. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  315. $font = __DIR__ . '/../../core/fonts/Nunito-Regular.ttf';
  316. $fontSize = $size * 0.4;
  317. list($x, $y) = $this->imageTTFCenter($im, $text, $font, $fontSize);
  318. imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
  319. ob_start();
  320. imagepng($im);
  321. $data = ob_get_contents();
  322. ob_end_clean();
  323. return $data;
  324. }
  325. /**
  326. * Calculate real image ttf center
  327. *
  328. * @param resource $image
  329. * @param string $text text string
  330. * @param string $font font path
  331. * @param int $size font size
  332. * @param int $angle
  333. * @return array
  334. */
  335. protected function imageTTFCenter($image, string $text, string $font, int $size, $angle = 0): array {
  336. // Image width & height
  337. $xi = imagesx($image);
  338. $yi = imagesy($image);
  339. // bounding box
  340. $box = imagettfbbox($size, $angle, $font, $text);
  341. // imagettfbbox can return negative int
  342. $xr = abs(max($box[2], $box[4]));
  343. $yr = abs(max($box[5], $box[7]));
  344. // calculate bottom left placement
  345. $x = intval(($xi - $xr) / 2);
  346. $y = intval(($yi + $yr) / 2);
  347. return array($x, $y);
  348. }
  349. /**
  350. * Calculate steps between two Colors
  351. * @param object Color $steps start color
  352. * @param object Color $ends end color
  353. * @return array [r,g,b] steps for each color to go from $steps to $ends
  354. */
  355. private function stepCalc($steps, $ends) {
  356. $step = array();
  357. $step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
  358. $step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
  359. $step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
  360. return $step;
  361. }
  362. /**
  363. * Convert a string to an integer evenly
  364. * @param string $hash the text to parse
  365. * @param int $maximum the maximum range
  366. * @return int between 0 and $maximum
  367. */
  368. private function mixPalette($steps, $color1, $color2) {
  369. $count = $steps + 1;
  370. $palette = array($color1);
  371. $step = $this->stepCalc($steps, [$color1, $color2]);
  372. for ($i = 1; $i < $steps; $i++) {
  373. $r = intval($color1->r + ($step[0] * $i));
  374. $g = intval($color1->g + ($step[1] * $i));
  375. $b = intval($color1->b + ($step[2] * $i));
  376. $palette[] = new Color($r, $g, $b);
  377. }
  378. return $palette;
  379. }
  380. /**
  381. * Convert a string to an integer evenly
  382. * @param string $hash the text to parse
  383. * @param int $maximum the maximum range
  384. * @return int between 0 and $maximum
  385. */
  386. private function hashToInt($hash, $maximum) {
  387. $final = 0;
  388. $result = array();
  389. // Splitting evenly the string
  390. for ($i = 0; $i < strlen($hash); $i++) {
  391. // chars in md5 goes up to f, hex:16
  392. $result[] = intval(substr($hash, $i, 1), 16) % 16;
  393. }
  394. // Adds up all results
  395. foreach ($result as $value) {
  396. $final += $value;
  397. }
  398. // chars in md5 goes up to f, hex:16
  399. return intval($final % $maximum);
  400. }
  401. /**
  402. * @param string $hash
  403. * @return Color Object containting r g b int in the range [0, 255]
  404. */
  405. public function avatarBackgroundColor(string $hash) {
  406. // Normalize hash
  407. $hash = strtolower($hash);
  408. // Already a md5 hash?
  409. if( preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1 ) {
  410. $hash = md5($hash);
  411. }
  412. // Remove unwanted char
  413. $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
  414. $red = new Color(182, 70, 157);
  415. $yellow = new Color(221, 203, 85);
  416. $blue = new Color(0, 130, 201); // Nextcloud blue
  417. // Number of steps to go from a color to another
  418. // 3 colors * 6 will result in 18 generated colors
  419. $steps = 6;
  420. $palette1 = $this->mixPalette($steps, $red, $yellow);
  421. $palette2 = $this->mixPalette($steps, $yellow, $blue);
  422. $palette3 = $this->mixPalette($steps, $blue, $red);
  423. $finalPalette = array_merge($palette1, $palette2, $palette3);
  424. return $finalPalette[$this->hashToInt($hash, $steps * 3)];
  425. }
  426. public function userChanged($feature, $oldValue, $newValue) {
  427. // We only change the avatar on display name changes
  428. if ($feature !== 'displayName') {
  429. return;
  430. }
  431. // If the avatar is not generated (so an uploaded image) we skip this
  432. if (!$this->folder->fileExists('generated')) {
  433. return;
  434. }
  435. $this->remove();
  436. }
  437. }