You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020 Robin Appelman <robin@icewind.nl>
  5. *
  6. * @author Robin Appelman <robin@icewind.nl>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OC\Files\Stream;
  25. use Icewind\Streams\Wrapper;
  26. class HashWrapper extends Wrapper {
  27. protected $callback;
  28. protected $hash;
  29. public static function wrap($source, string $algo, callable $callback) {
  30. $hash = hash_init($algo);
  31. $context = stream_context_create([
  32. 'hash' => [
  33. 'source' => $source,
  34. 'callback' => $callback,
  35. 'hash' => $hash,
  36. ],
  37. ]);
  38. return Wrapper::wrapSource($source, $context, 'hash', self::class);
  39. }
  40. protected function open() {
  41. $context = $this->loadContext('hash');
  42. $this->callback = $context['callback'];
  43. $this->hash = $context['hash'];
  44. return true;
  45. }
  46. public function dir_opendir($path, $options) {
  47. return $this->open();
  48. }
  49. public function stream_open($path, $mode, $options, &$opened_path) {
  50. return $this->open();
  51. }
  52. public function stream_read($count) {
  53. $result = parent::stream_read($count);
  54. hash_update($this->hash, $result);
  55. return $result;
  56. }
  57. public function stream_close() {
  58. if (is_callable($this->callback)) {
  59. call_user_func($this->callback, hash_final($this->hash));
  60. // prevent further calls by potential PHP 7 GC ghosts
  61. $this->callback = null;
  62. }
  63. return parent::stream_close();
  64. }
  65. }