This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 289
/
class.FileHasher.php
executable file
·291 lines (265 loc) · 11.2 KB
/
class.FileHasher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://pyd.io/>.
*/
use Pydio\Access\Core\AbstractAccessDriver;
use Pydio\Access\Core\AJXP_MetaStreamWrapper;
use Pydio\Access\Core\Model\AJXP_Node;
use Pydio\Access\Core\Model\UserSelection;
use Pydio\Core\Exception\PydioException;
use Pydio\Core\Model\ContextInterface;
use Pydio\Core\Services\LocalCache;
use Pydio\Core\Controller\Controller;
use Pydio\Core\Utils\Utils;
use Pydio\Core\PluginFramework\PluginsService;
use Pydio\Core\Utils\TextEncoder;
use Pydio\Meta\Core\AJXP_AbstractMetaSource;
use Pydio\Metastore\Core\MetaStoreProvider;
defined('AJXP_EXEC') or die('Access not allowed');
/**
* Generates and caches and md5 hash of each file
* @package AjaXplorer_Plugins
* @subpackage Meta
*/
class FileHasher extends AJXP_AbstractMetaSource
{
const METADATA_HASH_NAMESPACE = "file_hahser";
/**
* @var MetaStoreProvider
*/
protected $metaStore;
public static function rsyncEnabled()
{
return function_exists("rsync_generate_signature");
}
public function getConfigs()
{
$data = parent::getConfigs();
$this->filterData($data);
return $data;
}
public function loadConfigs($data)
{
$this->filterData($data);
parent::loadConfigs($data);
}
private function filterData(&$data)
{
$data["RSYNC_SUPPORTED"] = self::rsyncEnabled();
}
public function parseSpecificContributions(ContextInterface $ctx, \DOMNode &$contribNode)
{
parent::parseSpecificContributions($ctx, $contribNode);
if (!self::rsyncEnabled() && $contribNode->nodeName == "actions") {
// REMOVE rsync actions, this will advertise the fact that
// rsync is not enabled.
$xp = new DOMXPath($contribNode->ownerDocument);
$children = $xp->query("action[contains(@name, 'filehasher')]", $contribNode);
foreach ($children as $child) {
$contribNode->removeChild($child);
}
}
if ($this->getContextualOption($ctx, "CACHE_XML_TREE") !== true && $contribNode->nodeName == "actions") {
// REMOVE pre and post process on LS action
$xp = new DOMXPath($contribNode->ownerDocument);
$children = $xp->query("action[@name='ls']", $contribNode);
foreach ($children as $child) {
$contribNode->removeChild($child);
}
}
}
/**
* @param ContextInterface $ctx
* @param AbstractAccessDriver $accessDriver
* @throws PydioException
*/
public function initMeta(ContextInterface $ctx, AbstractAccessDriver $accessDriver)
{
parent::initMeta($ctx, $accessDriver);
$store = PluginsService::getInstance($ctx)->getUniqueActivePluginForType("metastore");
if ($store === false) {
throw new PydioException("The 'meta.simple_lock' plugin requires at least one active 'metastore' plugin");
}
$this->metaStore = $store;
$this->metaStore->initMeta($ctx, $accessDriver);
}
public function switchActions($actionName, $httpVars, $fileVars, ContextInterface $ctx)
{
$selection = UserSelection::fromContext($ctx, $httpVars);
switch ($actionName) {
case "filehasher_signature":
$file = $selection->getUniqueNode();
if(!file_exists($file->getUrl())) break;
$cacheItem = LocalCache::getItem("signatures", $file->getUrl(), array($this, "generateSignature"));
$data = $cacheItem->getData();
header("Content-Type:application/octet-stream");
header("Content-Length", strlen($data));
echo($data);
break;
case "filehasher_delta":
case "filehasher_patch":
// HANDLE UPLOAD DATA
$this->logDebug("Received signature file, should compute delta now");
if (!isSet($fileVars) && !is_array($fileVars["userfile_0"])) {
throw new Exception("These action should find uploaded data");
}
$signature_delta_file = $fileVars["userfile_0"]["tmp_name"];
$fileUrl = $selection->getUniqueNode()->getUrl();
$file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true);
if ($actionName == "filehasher_delta") {
$deltaFile = tempnam(Utils::getAjxpTmpDir(), $actionName."-delta");
$this->logDebug("Received signature file, should compute delta now");
rsync_generate_delta($signature_delta_file, $file, $deltaFile);
$this->logDebug("Computed delta file, size is ".filesize($deltaFile));
header("Content-Type:application/octet-stream");
header("Content-Length:".filesize($deltaFile));
readfile($deltaFile);
unlink($deltaFile);
} else {
$patched = $file.".rdiff_patched";
rsync_patch_file($file, $signature_delta_file, $patched);
rename($patched, $file);
$node = $selection->getUniqueNode();
Controller::applyHook("node.change", array($node, $node, false));
header("Content-Type:text/plain");
echo md5_file($file);
}
break;
case "stat_hash" :
clearstatcache();
header("Content-type:application/json");
if ($selection->isUnique()) {
$node = $selection->getUniqueNode();
$stat = @stat($node->getUrl());
if (!$stat || !is_readable($node->getUrl())) {
print '{}';
} else {
if(is_file($node->getUrl())) {
if(isSet($_SERVER["HTTP_RANGE"])){
$fullSize = floatval($stat['size']);
$ranges = explode('=', $_SERVER["HTTP_RANGE"]);
$offsets = explode('-', $ranges[1]);
$offset = floatval($offsets[0]);
$length = floatval($offsets[1]) - $offset;
if (!$length) $length = $fullSize - $offset;
if ($length + $offset > $fullSize || $length < 0) $length = $fullSize - $offset;
$hash = $this->getPartialHash($node, $offset, $length);
}else{
$hash = $this->getFileHash($selection->getUniqueNode());
}
}
else $hash = 'directory';
$stat[13] = $stat["hash"] = $hash;
print json_encode($stat);
}
} else {
$files = $selection->getFiles();
print '{';
foreach ($files as $index => $path) {
$node = new AJXP_Node($selection->currentBaseUrl().$path);
$stat = @stat($selection->currentBaseUrl().$path);
if(!$stat || !is_readable($node->getUrl())) $stat = '{}';
else {
if(!is_dir($node->getUrl())) $hash = $this->getFileHash($node);
else $hash = 'directory';
$stat[13] = $stat["hash"] = $hash;
$stat = json_encode($stat);
}
print json_encode(TextEncoder::toUTF8($path)).':'.$stat . (($index < count($files) -1) ? "," : "");
}
print '}';
}
break;
break;
}
}
/**
* @param \Pydio\Access\Core\Model\AJXP_Node $node
* @return String md5
*/
public function getFileHash($node)
{
if ($node->isLeaf()) {
$md5 = null;
if ($this->metaStore != false) {
$hashMeta = $this->metaStore->retrieveMetadata(
$node,
FileHasher::METADATA_HASH_NAMESPACE,
false,
AJXP_METADATA_SCOPE_GLOBAL);
$mtime = filemtime($node->getUrl());
if(is_array($hashMeta)
&& array_key_exists("md5", $hashMeta)
&& array_key_exists("md5_mtime", $hashMeta)
&& $hashMeta["md5_mtime"] >= $mtime){
$md5 = $hashMeta["md5"];
}
if ($md5 == null) {
$md5 = md5_file($node->getUrl());
$hashMeta = array(
"md5" => $md5,
"md5_mtime" => $mtime
);
$this->metaStore->setMetadata($node, FileHasher::METADATA_HASH_NAMESPACE, $hashMeta, false, AJXP_METADATA_SCOPE_GLOBAL);
}
} else {
$md5 = md5_file($node->getUrl());
}
$node->mergeMetadata(array("md5" => $md5));
return $md5;
}else{
return 'directory';
}
}
/**
* @param \Pydio\Access\Core\Model\AJXP_Node $node
* @param float $offset
* @param float $length
* @return String md5
*/
public function getPartialHash($node, $offset, $length){
$this->logDebug('Getting partial hash from ' . $offset . ' to ' . $length );
$fp = fopen($node->getUrl(), "r");
$ctx = hash_init('md5');
if($offset > 0){
fseek($fp, $offset);
}
hash_update_stream($ctx, $fp, $length);
$hash = hash_final($ctx);
$this->logDebug('Partial hash is ' . $hash );
fclose($fp);
return $hash;
}
/**
* @param \Pydio\Access\Core\Model\AJXP_Node $oldNode
* @param \Pydio\Access\Core\Model\AJXP_Node $newNode
* @param bool $copy
*/
public function invalidateHash($oldNode = null, $newNode = null, $copy = false)
{
if($this->metaStore == false) return;
if ($oldNode != null) {
$this->metaStore->removeMetadata($oldNode, FileHasher::METADATA_HASH_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL);
}
}
public function generateSignature($masterFile, $targetFile)
{
rsync_generate_signature($masterFile, $targetFile);
}
}