avatar.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. /**
  9. * This class gets and sets users avatars.
  10. */
  11. class OC_Avatar implements \OCP\IAvatar {
  12. private $view;
  13. /**
  14. * @brief constructor
  15. * @param $user string user to do avatar-management with
  16. */
  17. public function __construct ($user) {
  18. $this->view = new \OC\Files\View('/'.$user);
  19. }
  20. /**
  21. * @brief get the users avatar
  22. * @param $size integer size in px of the avatar, avatars are square, defaults to 64
  23. * @return boolean|\OC_Image containing the avatar or false if there's no image
  24. */
  25. public function get ($size = 64) {
  26. if ($this->view->file_exists('avatar.jpg')) {
  27. $ext = 'jpg';
  28. } elseif ($this->view->file_exists('avatar.png')) {
  29. $ext = 'png';
  30. } else {
  31. return false;
  32. }
  33. $avatar = new OC_Image();
  34. $avatar->loadFromData($this->view->file_get_contents('avatar.'.$ext));
  35. $avatar->resize($size);
  36. return $avatar;
  37. }
  38. /**
  39. * @brief sets the users avatar
  40. * @param $data mixed OC_Image, imagedata or path to set a new avatar
  41. * @throws Exception if the provided file is not a jpg or png image
  42. * @throws Exception if the provided image is not valid
  43. * @throws \OC\NotSquareException if the image is not square
  44. * @return void
  45. */
  46. public function set ($data) {
  47. if($data instanceOf OC_Image) {
  48. $img = $data;
  49. $data = $img->data();
  50. } else {
  51. $img = new OC_Image($data);
  52. }
  53. $type = substr($img->mimeType(), -3);
  54. if ($type === 'peg') {
  55. $type = 'jpg';
  56. }
  57. if ($type !== 'jpg' && $type !== 'png') {
  58. $l = \OC_L10N::get('lib');
  59. throw new \Exception($l->t("Unknown filetype"));
  60. }
  61. if (!$img->valid()) {
  62. $l = \OC_L10N::get('lib');
  63. throw new \Exception($l->t("Invalid image"));
  64. }
  65. if (!($img->height() === $img->width())) {
  66. throw new \OC\NotSquareException();
  67. }
  68. $this->view->unlink('avatar.jpg');
  69. $this->view->unlink('avatar.png');
  70. $this->view->file_put_contents('avatar.'.$type, $data);
  71. }
  72. /**
  73. * @brief remove the users avatar
  74. * @return void
  75. */
  76. public function remove () {
  77. $this->view->unlink('avatar.jpg');
  78. $this->view->unlink('avatar.png');
  79. }
  80. }