FileSize.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. /**
  16. * @param IL10N $l
  17. * @param IRequest $request
  18. */
  19. public function __construct(
  20. protected IL10N $l,
  21. protected IRequest $request,
  22. ) {
  23. }
  24. /**
  25. * @param string $operator
  26. * @param string $value
  27. * @return bool
  28. */
  29. public function executeCheck($operator, $value) {
  30. $size = $this->getFileSizeFromHeader();
  31. $value = Util::computerFileSize($value);
  32. if ($size !== false) {
  33. switch ($operator) {
  34. case 'less':
  35. return $size < $value;
  36. case '!less':
  37. return $size >= $value;
  38. case 'greater':
  39. return $size > $value;
  40. case '!greater':
  41. return $size <= $value;
  42. }
  43. }
  44. return false;
  45. }
  46. /**
  47. * @param string $operator
  48. * @param string $value
  49. * @throws \UnexpectedValueException
  50. */
  51. public function validateCheck($operator, $value) {
  52. if (!in_array($operator, ['less', '!less', 'greater', '!greater'])) {
  53. throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
  54. }
  55. if (!preg_match('/^[0-9]+[ ]?[kmgt]?b$/i', $value)) {
  56. throw new \UnexpectedValueException($this->l->t('The given file size is invalid'), 2);
  57. }
  58. }
  59. /**
  60. * @return string
  61. */
  62. protected function getFileSizeFromHeader() {
  63. if ($this->size !== null) {
  64. return $this->size;
  65. }
  66. $size = $this->request->getHeader('OC-Total-Length');
  67. if ($size === '') {
  68. if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
  69. $size = $this->request->getHeader('Content-Length');
  70. }
  71. }
  72. if ($size === '') {
  73. $size = false;
  74. }
  75. $this->size = $size;
  76. return $this->size;
  77. }
  78. public function supportedEntities(): array {
  79. return [ File::class ];
  80. }
  81. public function isAvailableForScope(int $scope): bool {
  82. return true;
  83. }
  84. }