avatar.php 2.1 KB

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