filechunking.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. class OC_FileChunking {
  9. protected $info;
  10. protected $cache;
  11. static public function decodeName($name) {
  12. preg_match('/(?P<name>.*)-chunking-(?P<transferid>\d+)-(?P<chunkcount>\d+)-(?P<index>\d+)/', $name, $matches);
  13. return $matches;
  14. }
  15. public function __construct($info) {
  16. $this->info = $info;
  17. }
  18. public function getPrefix() {
  19. $name = $this->info['name'];
  20. $transferid = $this->info['transferid'];
  21. return $name.'-chunking-'.$transferid.'-';
  22. }
  23. protected function getCache() {
  24. if (!isset($this->cache)) {
  25. $this->cache = new OC_Cache_File();
  26. }
  27. return $this->cache;
  28. }
  29. public function store($index, $data) {
  30. $cache = $this->getCache();
  31. $name = $this->getPrefix().$index;
  32. $cache->set($name, $data);
  33. }
  34. public function isComplete() {
  35. $prefix = $this->getPrefix();
  36. $parts = 0;
  37. $cache = $this->getCache();
  38. for($i=0; $i < $this->info['chunkcount']; $i++) {
  39. if ($cache->hasKey($prefix.$i)) {
  40. $parts ++;
  41. }
  42. }
  43. return $parts == $this->info['chunkcount'];
  44. }
  45. public function assemble($f) {
  46. $cache = $this->getCache();
  47. $prefix = $this->getPrefix();
  48. for($i=0; $i < $this->info['chunkcount']; $i++) {
  49. $chunk = $cache->get($prefix.$i);
  50. $cache->remove($prefix.$i);
  51. fwrite($f,$chunk);
  52. }
  53. fclose($f);
  54. }
  55. public function signature_split($orgfile, $input) {
  56. $info = unpack('n', fread($input, 2));
  57. $blocksize = $info[1];
  58. $this->info['transferid'] = mt_rand();
  59. $count = 0;
  60. $needed = array();
  61. $cache = $this->getCache();
  62. $prefix = $this->getPrefix();
  63. while (!feof($orgfile)) {
  64. $new_md5 = fread($input, 16);
  65. if (feof($input)) {
  66. break;
  67. }
  68. $data = fread($orgfile, $blocksize);
  69. $org_md5 = md5($data, true);
  70. if ($org_md5 == $new_md5) {
  71. $cache->set($prefix.$count, $data);
  72. } else {
  73. $needed[] = $count;
  74. }
  75. $count++;
  76. }
  77. return array(
  78. 'transferid' => $this->info['transferid'],
  79. 'needed' => $needed,
  80. 'count' => $count,
  81. );
  82. }
  83. }