avatar.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 {
  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, 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 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 (\OC_App::isEnabled('files_encryption')) {
  48. $l = \OC_L10N::get('lib');
  49. throw new \Exception($l->t("Custom profile pictures don't work with encryption yet"));
  50. }
  51. $img = new OC_Image($data);
  52. $type = substr($img->mimeType(), -3);
  53. if ($type === 'peg') { $type = 'jpg'; }
  54. if ($type !== 'jpg' && $type !== 'png') {
  55. $l = \OC_L10N::get('lib');
  56. throw new \Exception($l->t("Unknown filetype"));
  57. }
  58. if (!$img->valid()) {
  59. $l = \OC_L10N::get('lib');
  60. throw new \Exception($l->t("Invalid image"));
  61. }
  62. if (!($img->height() === $img->width())) {
  63. throw new \OC\NotSquareException();
  64. }
  65. $this->view->unlink('avatar.jpg');
  66. $this->view->unlink('avatar.png');
  67. $this->view->file_put_contents('avatar.'.$type, $data);
  68. }
  69. /**
  70. * @brief remove the users avatar
  71. * @return void
  72. */
  73. public function remove () {
  74. $this->view->unlink('avatar.jpg');
  75. $this->view->unlink('avatar.png');
  76. }
  77. }