1
0

Avatar.php 13 KB

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