Avatar.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. * Open Sans cap-height is 0.72 and we want a 200px caps height size (0.4 letter-to-total-height ratio, 500*0.4=200). 200/0.72 = 278px.
  61. * Since we start from the baseline (text-anchor) we need to shift the y axis by 100px (half the caps height): 500/2+100=350
  62. *
  63. * @var string
  64. */
  65. private $svgTemplate = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  66. <svg width="{size}" height="{size}" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
  67. <rect width="100%" height="100%" fill="#{fill}"></rect>
  68. <text x="50%" y="350" style="font-weight:600;font-size:278px;font-family:\'Open Sans\';text-anchor:middle;fill:#fff">{letter}</text>
  69. </svg>';
  70. /**
  71. * constructor
  72. *
  73. * @param ISimpleFolder $folder The folder where the avatars are
  74. * @param IL10N $l
  75. * @param User $user
  76. * @param ILogger $logger
  77. * @param IConfig $config
  78. */
  79. public function __construct(ISimpleFolder $folder,
  80. IL10N $l,
  81. $user,
  82. ILogger $logger,
  83. IConfig $config) {
  84. $this->folder = $folder;
  85. $this->l = $l;
  86. $this->user = $user;
  87. $this->logger = $logger;
  88. $this->config = $config;
  89. }
  90. /**
  91. * @inheritdoc
  92. */
  93. public function get($size = 64) {
  94. try {
  95. $file = $this->getFile($size);
  96. } catch (NotFoundException $e) {
  97. return false;
  98. }
  99. $avatar = new OC_Image();
  100. $avatar->loadFromData($file->getContent());
  101. return $avatar;
  102. }
  103. /**
  104. * Check if an avatar exists for the user
  105. *
  106. * @return bool
  107. */
  108. public function exists() {
  109. return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
  110. }
  111. /**
  112. * sets the users avatar
  113. * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
  114. * @throws \Exception if the provided file is not a jpg or png image
  115. * @throws \Exception if the provided image is not valid
  116. * @throws NotSquareException if the image is not square
  117. * @return void
  118. */
  119. public function set($data) {
  120. if ($data instanceof IImage) {
  121. $img = $data;
  122. $data = $img->data();
  123. } else {
  124. $img = new OC_Image();
  125. if (is_resource($data) && get_resource_type($data) === "gd") {
  126. $img->setResource($data);
  127. } elseif (is_resource($data)) {
  128. $img->loadFromFileHandle($data);
  129. } else {
  130. try {
  131. // detect if it is a path or maybe the images as string
  132. $result = @realpath($data);
  133. if ($result === false || $result === null) {
  134. $img->loadFromData($data);
  135. } else {
  136. $img->loadFromFile($data);
  137. }
  138. } catch (\Error $e) {
  139. $img->loadFromData($data);
  140. }
  141. }
  142. }
  143. $type = substr($img->mimeType(), -3);
  144. if ($type === 'peg') {
  145. $type = 'jpg';
  146. }
  147. if ($type !== 'jpg' && $type !== 'png') {
  148. throw new \Exception($this->l->t('Unknown filetype'));
  149. }
  150. if (!$img->valid()) {
  151. throw new \Exception($this->l->t('Invalid image'));
  152. }
  153. if (!($img->height() === $img->width())) {
  154. throw new NotSquareException($this->l->t('Avatar image is not square'));
  155. }
  156. $this->remove();
  157. $file = $this->folder->newFile('avatar.' . $type);
  158. $file->putContent($data);
  159. try {
  160. $generated = $this->folder->getFile('generated');
  161. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
  162. $generated->delete();
  163. } catch (NotFoundException $e) {
  164. //
  165. }
  166. $this->user->triggerChange('avatar', $file);
  167. }
  168. /**
  169. * remove the users avatar
  170. * @return void
  171. */
  172. public function remove() {
  173. $avatars = $this->folder->getDirectoryListing();
  174. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  175. (int) $this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1);
  176. foreach ($avatars as $avatar) {
  177. $avatar->delete();
  178. }
  179. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  180. $this->user->triggerChange('avatar', '');
  181. }
  182. /**
  183. * @inheritdoc
  184. */
  185. public function getFile($size) {
  186. try {
  187. $ext = $this->getExtension();
  188. } catch (NotFoundException $e) {
  189. if (!$data = $this->generateAvatarFromSvg(1024)) {
  190. $data = $this->generateAvatar($this->user->getDisplayName(), 1024);
  191. }
  192. $avatar = $this->folder->newFile('avatar.png');
  193. $avatar->putContent($data);
  194. $ext = 'png';
  195. $this->folder->newFile('generated');
  196. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  197. }
  198. if ($size === -1) {
  199. $path = 'avatar.' . $ext;
  200. } else {
  201. $path = 'avatar.' . $size . '.' . $ext;
  202. }
  203. try {
  204. $file = $this->folder->getFile($path);
  205. } catch (NotFoundException $e) {
  206. if ($size <= 0) {
  207. throw new NotFoundException;
  208. }
  209. if ($this->folder->fileExists('generated')) {
  210. if (!$data = $this->generateAvatarFromSvg($size)) {
  211. $data = $this->generateAvatar($this->user->getDisplayName(), $size);
  212. }
  213. } else {
  214. $avatar = new OC_Image();
  215. /** @var ISimpleFile $file */
  216. $file = $this->folder->getFile('avatar.' . $ext);
  217. $avatar->loadFromData($file->getContent());
  218. $avatar->resize($size);
  219. $data = $avatar->data();
  220. }
  221. try {
  222. $file = $this->folder->newFile($path);
  223. $file->putContent($data);
  224. } catch (NotPermittedException $e) {
  225. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  226. throw new NotFoundException();
  227. }
  228. }
  229. if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  230. $generated = $this->folder->fileExists('generated') ? 'true' : 'false';
  231. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  232. }
  233. return $file;
  234. }
  235. /**
  236. * Get the extension of the avatar. If there is no avatar throw Exception
  237. *
  238. * @return string
  239. * @throws NotFoundException
  240. */
  241. private function getExtension() {
  242. if ($this->folder->fileExists('avatar.jpg')) {
  243. return 'jpg';
  244. } elseif ($this->folder->fileExists('avatar.png')) {
  245. return 'png';
  246. }
  247. throw new NotFoundException;
  248. }
  249. /**
  250. * {size} = 500
  251. * {fill} = hex color to fill
  252. * {letter} = Letter to display
  253. *
  254. * Generate SVG avatar
  255. * @return string
  256. *
  257. */
  258. private function getAvatarVector(int $size): string {
  259. $userDisplayName = $this->user->getDisplayName();
  260. $bgRGB = $this->avatarBackgroundColor($userDisplayName);
  261. $bgHEX = sprintf("%02x%02x%02x", $bgRGB->r, $bgRGB->g, $bgRGB->b);
  262. $letter = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
  263. $toReplace = ['{size}', '{fill}', '{letter}'];
  264. return str_replace($toReplace, [$size, $bgHEX, $letter], $this->svgTemplate);
  265. }
  266. /**
  267. * Generate png avatar from svg with Imagick
  268. *
  269. * @param int $size
  270. * @return string|boolean
  271. */
  272. private function generateAvatarFromSvg(int $size) {
  273. if (!extension_loaded('imagick')) {
  274. return false;
  275. }
  276. try {
  277. $font = __DIR__ . '/../../core/fonts/OpenSans-Semibold.ttf';
  278. $svg = $this->getAvatarVector($size);
  279. $avatar = new Imagick();
  280. $avatar->setFont($font);
  281. $avatar->readImageBlob($svg);
  282. $avatar->setImageFormat('png');
  283. $image = new OC_Image();
  284. $image->loadFromData($avatar);
  285. return $image->data();
  286. } catch (\Exception $e) {
  287. return false;
  288. }
  289. }
  290. /**
  291. * Generate png avatar with GD
  292. *
  293. * @param string $userDisplayName
  294. * @param int $size
  295. * @return string
  296. */
  297. private function generateAvatar($userDisplayName, $size) {
  298. $text = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
  299. $backgroundColor = $this->avatarBackgroundColor($userDisplayName);
  300. $im = imagecreatetruecolor($size, $size);
  301. $background = imagecolorallocate($im, $backgroundColor->r, $backgroundColor->g, $backgroundColor->b);
  302. $white = imagecolorallocate($im, 255, 255, 255);
  303. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  304. $font = __DIR__ . '/../../core/fonts/OpenSans-Semibold.ttf';
  305. $fontSize = $size * 0.4;
  306. list($x, $y) = $this->imageTTFCenter($im, $text, $font, $fontSize);
  307. imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
  308. ob_start();
  309. imagepng($im);
  310. $data = ob_get_contents();
  311. ob_end_clean();
  312. return $data;
  313. }
  314. /**
  315. * Calculate real image ttf center
  316. *
  317. * @param resource $image
  318. * @param string $text text string
  319. * @param string $font font path
  320. * @param int $size font size
  321. * @param int $angle
  322. * @return Array
  323. */
  324. protected function imageTTFCenter($image, string $text, string $font, int $size, $angle = 0): array {
  325. // Image width & height
  326. $xi = imagesx($image);
  327. $yi = imagesy($image);
  328. // bounding box
  329. $box = imagettfbbox($size, $angle, $font, $text);
  330. // imagettfbbox can return negative int
  331. $xr = abs(max($box[2], $box[4]));
  332. $yr = abs(max($box[5], $box[7]));
  333. // calculate bottom left placement
  334. $x = intval(($xi - $xr) / 2);
  335. $y = intval(($yi + $yr) / 2);
  336. return array($x, $y);
  337. }
  338. /**
  339. * Calculate steps between two Colors
  340. * @param object Color $steps start color
  341. * @param object Color $ends end color
  342. * @return array [r,g,b] steps for each color to go from $steps to $ends
  343. */
  344. private function stepCalc($steps, $ends) {
  345. $step = array();
  346. $step[0] = ($ends[1]->r - $ends[0]->r) / $steps;
  347. $step[1] = ($ends[1]->g - $ends[0]->g) / $steps;
  348. $step[2] = ($ends[1]->b - $ends[0]->b) / $steps;
  349. return $step;
  350. }
  351. /**
  352. * Convert a string to an integer evenly
  353. * @param string $hash the text to parse
  354. * @param int $maximum the maximum range
  355. * @return int between 0 and $maximum
  356. */
  357. private function mixPalette($steps, $color1, $color2) {
  358. $count = $steps + 1;
  359. $palette = array($color1);
  360. $step = $this->stepCalc($steps, [$color1, $color2]);
  361. for ($i = 1; $i < $steps; $i++) {
  362. $r = intval($color1->r + ($step[0] * $i));
  363. $g = intval($color1->g + ($step[1] * $i));
  364. $b = intval($color1->b + ($step[2] * $i));
  365. $palette[] = new Color($r, $g, $b);
  366. }
  367. return $palette;
  368. }
  369. /**
  370. * Convert a string to an integer evenly
  371. * @param string $hash the text to parse
  372. * @param int $maximum the maximum range
  373. * @return int between 0 and $maximum
  374. */
  375. private function hashToInt($hash, $maximum) {
  376. $final = 0;
  377. $result = array();
  378. // Splitting evenly the string
  379. for ($i = 0; $i < strlen($hash); $i++) {
  380. // chars in md5 goes up to f, hex:16
  381. $result[] = intval(substr($hash, $i, 1), 16) % 16;
  382. }
  383. // Adds up all results
  384. foreach ($result as $value) {
  385. $final += $value;
  386. }
  387. // chars in md5 goes up to f, hex:16
  388. return intval($final % $maximum);
  389. }
  390. /**
  391. * @param string $hash
  392. * @return Color Object containting r g b int in the range [0, 255]
  393. */
  394. public function avatarBackgroundColor(string $hash) {
  395. // Normalize hash
  396. $hash = strtolower($hash);
  397. // Already a md5 hash?
  398. if( preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1 ) {
  399. $hash = md5($hash);
  400. }
  401. // Remove unwanted char
  402. $hash = preg_replace('/[^0-9a-f]+/', '', $hash);
  403. $red = new Color(182, 70, 157);
  404. $yellow = new Color(221, 203, 85);
  405. $blue = new Color(0, 130, 201); // Nextcloud blue
  406. // Number of steps to go from a color to another
  407. // 3 colors * 6 will result in 18 generated colors
  408. $steps = 6;
  409. $palette1 = $this->mixPalette($steps, $red, $yellow);
  410. $palette2 = $this->mixPalette($steps, $yellow, $blue);
  411. $palette3 = $this->mixPalette($steps, $blue, $red);
  412. $finalPalette = array_merge($palette1, $palette2, $palette3);
  413. return $finalPalette[$this->hashToInt($hash, $steps * 3)];
  414. }
  415. public function userChanged($feature, $oldValue, $newValue) {
  416. // We only change the avatar on display name changes
  417. if ($feature !== 'displayName') {
  418. return;
  419. }
  420. // If the avatar is not generated (so an uploaded image) we skip this
  421. if (!$this->folder->fileExists('generated')) {
  422. return;
  423. }
  424. $this->remove();
  425. }
  426. }