FileSize.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\WorkflowEngine\Check;
  7. use OCA\WorkflowEngine\Entity\File;
  8. use OCP\IL10N;
  9. use OCP\IRequest;
  10. use OCP\Util;
  11. use OCP\WorkflowEngine\ICheck;
  12. class FileSize implements ICheck {
  13. /** @var int */
  14. protected $size;
  15. /** @var IL10N */
  16. protected $l;
  17. /** @var IRequest */
  18. protected $request;
  19. /**
  20. * @param IL10N $l
  21. * @param IRequest $request
  22. */
  23. public function __construct(IL10N $l, IRequest $request) {
  24. $this->l = $l;
  25. $this->request = $request;
  26. }
  27. /**
  28. * @param string $operator
  29. * @param string $value
  30. * @return bool
  31. */
  32. public function executeCheck($operator, $value) {
  33. $size = $this->getFileSizeFromHeader();
  34. $value = Util::computerFileSize($value);
  35. if ($size !== false) {
  36. switch ($operator) {
  37. case 'less':
  38. return $size < $value;
  39. case '!less':
  40. return $size >= $value;
  41. case 'greater':
  42. return $size > $value;
  43. case '!greater':
  44. return $size <= $value;
  45. }
  46. }
  47. return false;
  48. }
  49. /**
  50. * @param string $operator
  51. * @param string $value
  52. * @throws \UnexpectedValueException
  53. */
  54. public function validateCheck($operator, $value) {
  55. if (!in_array($operator, ['less', '!less', 'greater', '!greater'])) {
  56. throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
  57. }
  58. if (!preg_match('/^[0-9]+[ ]?[kmgt]?b$/i', $value)) {
  59. throw new \UnexpectedValueException($this->l->t('The given file size is invalid'), 2);
  60. }
  61. }
  62. /**
  63. * @return string
  64. */
  65. protected function getFileSizeFromHeader() {
  66. if ($this->size !== null) {
  67. return $this->size;
  68. }
  69. $size = $this->request->getHeader('OC-Total-Length');
  70. if ($size === '') {
  71. if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
  72. $size = $this->request->getHeader('Content-Length');
  73. }
  74. }
  75. if ($size === '') {
  76. $size = false;
  77. }
  78. $this->size = $size;
  79. return $this->size;
  80. }
  81. public function supportedEntities(): array {
  82. return [ File::class ];
  83. }
  84. public function isAvailableForScope(int $scope): bool {
  85. return true;
  86. }
  87. }