Avatar.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Olivier Mehani <shtrom@ssji.net>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC;
  30. use OC\User\User;
  31. use OCP\Files\NotFoundException;
  32. use OCP\Files\NotPermittedException;
  33. use OCP\Files\SimpleFS\ISimpleFile;
  34. use OCP\Files\SimpleFS\ISimpleFolder;
  35. use OCP\IAvatar;
  36. use OCP\IConfig;
  37. use OCP\IImage;
  38. use OCP\IL10N;
  39. use OC_Image;
  40. use OCP\ILogger;
  41. /**
  42. * This class gets and sets users avatars.
  43. */
  44. class Avatar implements IAvatar {
  45. /** @var ISimpleFolder */
  46. private $folder;
  47. /** @var IL10N */
  48. private $l;
  49. /** @var User */
  50. private $user;
  51. /** @var ILogger */
  52. private $logger;
  53. /** @var IConfig */
  54. private $config;
  55. /**
  56. * constructor
  57. *
  58. * @param ISimpleFolder $folder The folder where the avatars are
  59. * @param IL10N $l
  60. * @param User $user
  61. * @param ILogger $logger
  62. * @param IConfig $config
  63. */
  64. public function __construct(ISimpleFolder $folder,
  65. IL10N $l,
  66. $user,
  67. ILogger $logger,
  68. IConfig $config) {
  69. $this->folder = $folder;
  70. $this->l = $l;
  71. $this->user = $user;
  72. $this->logger = $logger;
  73. $this->config = $config;
  74. }
  75. /**
  76. * @inheritdoc
  77. */
  78. public function get ($size = 64) {
  79. try {
  80. $file = $this->getFile($size);
  81. } catch (NotFoundException $e) {
  82. return false;
  83. }
  84. $avatar = new OC_Image();
  85. $avatar->loadFromData($file->getContent());
  86. return $avatar;
  87. }
  88. /**
  89. * Check if an avatar exists for the user
  90. *
  91. * @return bool
  92. */
  93. public function exists() {
  94. return $this->folder->fileExists('avatar.jpg') || $this->folder->fileExists('avatar.png');
  95. }
  96. /**
  97. * sets the users avatar
  98. * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar
  99. * @throws \Exception if the provided file is not a jpg or png image
  100. * @throws \Exception if the provided image is not valid
  101. * @throws NotSquareException if the image is not square
  102. * @return void
  103. */
  104. public function set ($data) {
  105. if($data instanceOf IImage) {
  106. $img = $data;
  107. $data = $img->data();
  108. } else {
  109. $img = new OC_Image();
  110. if (is_resource($data) && get_resource_type($data) === "gd") {
  111. $img->setResource($data);
  112. } elseif(is_resource($data)) {
  113. $img->loadFromFileHandle($data);
  114. } else {
  115. try {
  116. // detect if it is a path or maybe the images as string
  117. $result = @realpath($data);
  118. if ($result === false || $result === null) {
  119. $img->loadFromData($data);
  120. } else {
  121. $img->loadFromFile($data);
  122. }
  123. } catch (\Error $e) {
  124. $img->loadFromData($data);
  125. }
  126. }
  127. }
  128. $type = substr($img->mimeType(), -3);
  129. if ($type === 'peg') {
  130. $type = 'jpg';
  131. }
  132. if ($type !== 'jpg' && $type !== 'png') {
  133. throw new \Exception($this->l->t('Unknown filetype'));
  134. }
  135. if (!$img->valid()) {
  136. throw new \Exception($this->l->t('Invalid image'));
  137. }
  138. if (!($img->height() === $img->width())) {
  139. throw new NotSquareException($this->l->t('Avatar image is not square'));
  140. }
  141. $this->remove();
  142. $file = $this->folder->newFile('avatar.'.$type);
  143. $file->putContent($data);
  144. try {
  145. $generated = $this->folder->getFile('generated');
  146. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'false');
  147. $generated->delete();
  148. } catch (NotFoundException $e) {
  149. //
  150. }
  151. $this->user->triggerChange('avatar', $file);
  152. }
  153. /**
  154. * remove the users avatar
  155. * @return void
  156. */
  157. public function remove () {
  158. $avatars = $this->folder->getDirectoryListing();
  159. $this->config->setUserValue($this->user->getUID(), 'avatar', 'version',
  160. (int)$this->config->getUserValue($this->user->getUID(), 'avatar', 'version', 0) + 1);
  161. foreach ($avatars as $avatar) {
  162. $avatar->delete();
  163. }
  164. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  165. $this->user->triggerChange('avatar', '');
  166. }
  167. /**
  168. * @inheritdoc
  169. */
  170. public function getFile($size) {
  171. try {
  172. $ext = $this->getExtension();
  173. } catch (NotFoundException $e) {
  174. $data = $this->generateAvatar($this->user->getDisplayName(), 1024);
  175. $avatar = $this->folder->newFile('avatar.png');
  176. $avatar->putContent($data);
  177. $ext = 'png';
  178. $this->folder->newFile('generated');
  179. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true');
  180. }
  181. if ($size === -1) {
  182. $path = 'avatar.' . $ext;
  183. } else {
  184. $path = 'avatar.' . $size . '.' . $ext;
  185. }
  186. try {
  187. $file = $this->folder->getFile($path);
  188. } catch (NotFoundException $e) {
  189. if ($size <= 0) {
  190. throw new NotFoundException;
  191. }
  192. if ($this->folder->fileExists('generated')) {
  193. $data = $this->generateAvatar($this->user->getDisplayName(), $size);
  194. } else {
  195. $avatar = new OC_Image();
  196. /** @var ISimpleFile $file */
  197. $file = $this->folder->getFile('avatar.' . $ext);
  198. $avatar->loadFromData($file->getContent());
  199. $avatar->resize($size);
  200. $data = $avatar->data();
  201. }
  202. try {
  203. $file = $this->folder->newFile($path);
  204. $file->putContent($data);
  205. } catch (NotPermittedException $e) {
  206. $this->logger->error('Failed to save avatar for ' . $this->user->getUID());
  207. throw new NotFoundException();
  208. }
  209. }
  210. if($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) {
  211. $generated = $this->folder->fileExists('generated') ? 'true' : 'false';
  212. $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', $generated);
  213. }
  214. return $file;
  215. }
  216. /**
  217. * Get the extension of the avatar. If there is no avatar throw Exception
  218. *
  219. * @return string
  220. * @throws NotFoundException
  221. */
  222. private function getExtension() {
  223. if ($this->folder->fileExists('avatar.jpg')) {
  224. return 'jpg';
  225. } elseif ($this->folder->fileExists('avatar.png')) {
  226. return 'png';
  227. }
  228. throw new NotFoundException;
  229. }
  230. /**
  231. * @param string $userDisplayName
  232. * @param int $size
  233. * @return string
  234. */
  235. private function generateAvatar($userDisplayName, $size) {
  236. $text = mb_strtoupper(mb_substr($userDisplayName, 0, 1), 'UTF-8');
  237. $backgroundColor = $this->avatarBackgroundColor($userDisplayName);
  238. $im = imagecreatetruecolor($size, $size);
  239. $background = imagecolorallocate($im, $backgroundColor[0], $backgroundColor[1], $backgroundColor[2]);
  240. $white = imagecolorallocate($im, 255, 255, 255);
  241. imagefilledrectangle($im, 0, 0, $size, $size, $background);
  242. $font = __DIR__ . '/../../core/fonts/OpenSans-Semibold.ttf';
  243. $fontSize = $size * 0.4;
  244. $box = imagettfbbox($fontSize, 0, $font, $text);
  245. $x = ($size - ($box[2] - $box[0])) / 2;
  246. $y = ($size - ($box[1] - $box[7])) / 2;
  247. $x += 1;
  248. $y -= $box[7];
  249. imagettftext($im, $fontSize, 0, $x, $y, $white, $font, $text);
  250. ob_start();
  251. imagepng($im);
  252. $data = ob_get_contents();
  253. ob_end_clean();
  254. return $data;
  255. }
  256. /**
  257. * @param int $r
  258. * @param int $g
  259. * @param int $b
  260. * @return double[] Array containing h s l in [0, 1] range
  261. */
  262. private function rgbToHsl($r, $g, $b) {
  263. $r /= 255.0;
  264. $g /= 255.0;
  265. $b /= 255.0;
  266. $max = max($r, $g, $b);
  267. $min = min($r, $g, $b);
  268. $h = ($max + $min) / 2.0;
  269. $l = ($max + $min) / 2.0;
  270. if($max === $min) {
  271. $h = $s = 0; // Achromatic
  272. } else {
  273. $d = $max - $min;
  274. $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
  275. switch($max) {
  276. case $r:
  277. $h = ($g - $b) / $d + ($g < $b ? 6 : 0);
  278. break;
  279. case $g:
  280. $h = ($b - $r) / $d + 2.0;
  281. break;
  282. case $b:
  283. $h = ($r - $g) / $d + 4.0;
  284. break;
  285. }
  286. $h /= 6.0;
  287. }
  288. return [$h, $s, $l];
  289. }
  290. /**
  291. * @param string $text
  292. * @return int[] Array containting r g b in the range [0, 255]
  293. */
  294. private function avatarBackgroundColor($text) {
  295. $hash = preg_replace('/[^0-9a-f]+/', '', $text);
  296. $hash = md5($hash);
  297. $hashChars = str_split($hash);
  298. // Init vars
  299. $result = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
  300. $rgb = [0, 0, 0];
  301. $sat = 0.70;
  302. $lum = 0.68;
  303. $modulo = 16;
  304. // Splitting evenly the string
  305. foreach($hashChars as $i => $char) {
  306. $result[$i % $modulo] .= intval($char, 16);
  307. }
  308. // Converting our data into a usable rgb format
  309. // Start at 1 because 16%3=1 but 15%3=0 and makes the repartition even
  310. for($count = 1; $count < $modulo; $count++) {
  311. $rgb[$count%3] += (int)$result[$count];
  312. }
  313. // Reduce values bigger than rgb requirements
  314. $rgb[0] %= 255;
  315. $rgb[1] %= 255;
  316. $rgb[2] %= 255;
  317. $hsl = $this->rgbToHsl($rgb[0], $rgb[1], $rgb[2]);
  318. // Classic formula to check the brightness for our eye
  319. // If too bright, lower the sat
  320. $bright = sqrt(0.299 * ($rgb[0] ** 2) + 0.587 * ($rgb[1] ** 2) + 0.114 * ($rgb[2] ** 2));
  321. if ($bright >= 200) {
  322. $sat = 0.60;
  323. }
  324. return $this->hslToRgb($hsl[0], $sat, $lum);
  325. }
  326. /**
  327. * @param double $h Hue in range [0, 1]
  328. * @param double $s Saturation in range [0, 1]
  329. * @param double $l Lightness in range [0, 1]
  330. * @return int[] Array containing r g b in the range [0, 255]
  331. */
  332. private function hslToRgb($h, $s, $l){
  333. $hue2rgb = function ($p, $q, $t){
  334. if($t < 0) {
  335. $t += 1;
  336. }
  337. if($t > 1) {
  338. $t -= 1;
  339. }
  340. if($t < 1/6) {
  341. return $p + ($q - $p) * 6 * $t;
  342. }
  343. if($t < 1/2) {
  344. return $q;
  345. }
  346. if($t < 2/3) {
  347. return $p + ($q - $p) * (2/3 - $t) * 6;
  348. }
  349. return $p;
  350. };
  351. if($s === 0){
  352. $r = $l;
  353. $g = $l;
  354. $b = $l; // achromatic
  355. }else{
  356. $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
  357. $p = 2 * $l - $q;
  358. $r = $hue2rgb($p, $q, $h + 1/3);
  359. $g = $hue2rgb($p, $q, $h);
  360. $b = $hue2rgb($p, $q, $h - 1/3);
  361. }
  362. return array(round($r * 255), round($g * 255), round($b * 255));
  363. }
  364. public function userChanged($feature, $oldValue, $newValue) {
  365. // We only change the avatar on display name changes
  366. if ($feature !== 'displayName') {
  367. return;
  368. }
  369. // If the avatar is not generated (so an uploaded image) we skip this
  370. if (!$this->folder->fileExists('generated')) {
  371. return;
  372. }
  373. $this->remove();
  374. }
  375. }