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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
|
<?php
/**
* @author Robin Appelman
* @copyright 2011 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library 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 this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* provide caching for filesystem info in the database
*
* not used by OC_Filesystem for reading filesystem info,
* instread apps should use OC_FileCache::get where possible
*
* It will try to keep the data up to date but changes from outside ownCloud can invalidate the cache
*/
class OC_FileCache{
private static $savedData=array();
/**
* get the filesystem info from the cache
* @param string path
* @param string root (optional)
* @return array
*
* returns an assiciative array with the following keys:
* - size
* - mtime
* - ctime
* - mimetype
* - encrypted
* - versioned
*/
public static function get($path,$root=''){
if(self::isUpdated($path,$root)){
if(!$root){//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path));
}else{
self::fileSystemWatcherWrite(array('path'=>$path),$root);
}
}
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$path;
$query=OC_DB::prepare('SELECT ctime,mtime,mimetype,size,encrypted,versioned,writable FROM *PREFIX*fscache WHERE path_hash=?');
$result=$query->execute(array(md5($path)))->fetchRow();
if(is_array($result)){
return $result;
}else{
OC_Log::write('get(): file not found in cache ('.$path.')','core',OC_Log::DEBUG);
return false;
}
}
/**
* put filesystem info in the cache
* @param string $path
* @param array data
* @param string root (optional)
*
* $data is an assiciative array in the same format as returned by get
*/
public static function put($path,$data,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$path;
if($path=='/'){
$parent=-1;
}else{
$parent=self::getFileId(dirname($path));
}
$id=self::getFileId($path);
if($id!=-1){
self::update($id,$data);
return;
}
if(isset(self::$savedData[$path])){
$data=array_merge($data,self::$savedData[$path]);
unset(self::$savedData[$path]);
}
if(!isset($data['size']) or !isset($data['mtime'])){//save incomplete data for the next time we write it
self::$savedData[$path]=$data;
return;
}
if(!isset($data['encrypted'])){
$data['encrypted']=false;
}
if(!isset($data['versioned'])){
$data['versioned']=false;
}
$mimePart=dirname($data['mimetype']);
$user=OC_User::getUser();
$query=OC_DB::prepare('INSERT INTO *PREFIX*fscache(parent, name, path, path_hash, size, mtime, ctime, mimetype, mimepart,user,writable,encrypted,versioned) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)');
$result=$query->execute(array($parent,basename($path),$path,md5($path),$data['size'],$data['mtime'],$data['ctime'],$data['mimetype'],$mimePart,$user,$data['writable'],$data['encrypted'],$data['versioned']));
if(OC_DB::isError($result)){
OC_Log::write('files','error while writing file('.$path.') to cache',OC_Log::ERROR);
}
}
/**
* update filesystem info of a file
* @param int $id
* @param array $data
*/
private static function update($id,$data){
$arguments=array();
$queryParts=array();
foreach(array('size','mtime','ctime','mimetype','encrypted','versioned','writable') as $attribute){
if(isset($data[$attribute])){
$arguments[]=$data[$attribute];
$queryParts[]=$attribute.'=?';
}
}
if(isset($data['mimetype'])){
$arguments[]=dirname($data['mimetype']);
$queryParts[]='mimepart=?';
}
$arguments[]=$id;
$sql = 'UPDATE *PREFIX*fscache SET '.implode(' , ',$queryParts).' WHERE id=?';
$query=OC_DB::prepare($sql);
$result=$query->execute($arguments);
if(OC_DB::isError($result)){
OC_Log::write('files','error while updating file('.$path.') in cache',OC_Log::ERROR);
}
}
/**
* register a file move in the cache
* @param string oldPath
* @param string newPath
* @param string root (optional)
*/
public static function move($oldPath,$newPath,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$oldPath=$root.$oldPath;
$newPath=$root.$newPath;
$newParent=self::getParentId($newPath);
$query=OC_DB::prepare('UPDATE *PREFIX*fscache SET parent=? ,name=?, path=?, path_hash=? WHERE path_hash=?');
$query->execute(array($newParent,basename($newPath),$newPath,md5($newPath),md5($oldPath)));
}
/**
* delete info from the cache
* @param string/int $file
* @param string root (optional)
*/
public static function delete($file,$root=''){
if(!is_numeric($file)){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$file;
self::delete(self::getFileId($path));
}elseif($file!=-1){
$query=OC_DB::prepare('SELECT id FROM *PREFIX*fscache WHERE parent=?');
$result=$query->execute(array($file));
while($child=$result->fetchRow()){
self::delete(intval($child['id']));
}
$query=OC_DB::prepare('DELETE FROM *PREFIX*fscache WHERE id=?');
$query->execute(array($file));
}
}
/**
* return array of filenames matching the querty
* @param string $query
* @param boolean $returnData
* @param string root (optional)
* @return array of filepaths
*/
public static function search($search,$returnData=false,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$rootLen=strlen($root);
if(!$returnData){
$query=OC_DB::prepare('SELECT path FROM *PREFIX*fscache WHERE name LIKE ? AND user=?');
}else{
$query=OC_DB::prepare('SELECT * FROM *PREFIX*fscache WHERE name LIKE ? AND user=?');
}
$result=$query->execute(array("%$search%",OC_User::getUser()));
$names=array();
while($row=$result->fetchRow()){
if(!$returnData){
$names[]=substr($row['path'],$rootLen);
}else{
$row['path']=substr($row['path'],$rootLen);
$names[]=$row;
}
}
return $names;
}
/**
* get all files and folders in a folder
* @param string path
* @param string root (optional)
* @return array
*
* returns an array of assiciative arrays with the following keys:
* - name
* - size
* - mtime
* - ctime
* - mimetype
* - encrypted
* - versioned
*/
public static function getFolderContent($path,$root='',$mimetype_filter=''){
if(self::isUpdated($path,$root)){
self::updateFolder($path,$root);
}
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$path;
$parent=self::getFileId($path);
$query=OC_DB::prepare('SELECT name,ctime,mtime,mimetype,size,encrypted,versioned,writable FROM *PREFIX*fscache WHERE parent=? AND (mimetype LIKE ? OR mimetype = ?)');
$result=$query->execute(array($parent, $mimetype_filter.'%', 'httpd/unix-directory'))->fetchAll();
if(is_array($result)){
return $result;
}else{
OC_Log::write('getFolderContent(): file not found in cache ('.$path.')','core',OC_Log::DEBUG);
return false;
}
}
/**
* check if a file or folder is in the cache
* @param string $path
* @param string root (optional)
* @return bool
*/
public static function inCache($path,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$path;
return self::getFileId($path)!=-1;
}
/**
* get the file id as used in the cache
* unlike the public getId, full paths are used here (/usename/files/foo instead of /foo)
* @param string $path
* @return int
*/
private static function getFileId($path){
$query=OC_DB::prepare('SELECT id FROM *PREFIX*fscache WHERE path_hash=?');
if(OC_DB::isError($query)){
OC_Log::write('files','error while getting file id of '.$path,OC_Log::ERROR);
return -1;
}
$result=$query->execute(array(md5($path)));
if(OC_DB::isError($result)){
OC_Log::write('files','error while getting file id of '.$path,OC_Log::ERROR);
return -1;
}
$result=$result->fetchRow();
if(is_array($result)){
return $result['id'];
}else{
OC_Log::write('getFileId(): file not found in cache ('.$path.')','core',OC_Log::DEBUG);
return -1;
}
}
/**
* get the file id as used in the cache
* @param string path
* @param string root (optional)
* @return int
*/
public static function getId($path,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$root.$path;
return self::getFileId($path);
}
/**
* get the file path from the id, relative to the home folder of the user
* @param int id
* @param string user (optional)
* @return string
*/
public static function getPath($id,$user=''){
if(!$user){
$user=OC_User::getUser();
}
$query=OC_DB::prepare('SELECT path FROM *PREFIX*fscache WHERE id=? AND user=?');
$result=$query->execute(array($id,$user));
$row=$result->fetchRow();
return $row['path'];
}
/**
* get the file id of the parent folder, taking into account '/' has no parent
* @param string $path
* @return int
*/
private static function getParentId($path){
if($path=='/'){
return -1;
}else{
return self::getFileId(dirname($path));
}
}
/**
* called when changes are made to files
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherWrite($params,$root=''){
if(!$root){
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView(($root=='/')?'':$root);
}
$path=$params['path'];
$fullPath=$view->getRoot().$path;
$mimetype=$view->getMimeType($path);
$dir=$view->is_dir($path.'/');
//dont use self::get here, we don't want inifinte loops when a file has changed
$cachedSize=self::getCachedSize($path,$root);
$size=0;
if($dir){
if(self::inCache($path,$root)){
$parent=self::getFileId($fullPath);
$query=OC_DB::prepare('SELECT size FROM *PREFIX*fscache WHERE parent=?');
$result=$query->execute(array($parent));
while($row=$result->fetchRow()){
$size+=$row['size'];
}
$mtime=$view->filemtime($path);
$ctime=$view->filectime($path);
$writable=$view->is_writable($path);
self::put($path,array('size'=>$size,'mtime'=>$mtime,'ctime'=>$ctime,'mimetype'=>$mimetype,'writable'=>$writable));
}else{
$count=0;
self::scan($path,null,$count,$root);
}
}else{
$size=self::scanFile($path,$root);
}
self::increaseSize(dirname($fullPath),$size-$cachedSize);
}
public static function getCached($path,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}else{
if($root=='/'){
$root='';
}
}
$path=$root.$path;
$query=OC_DB::prepare('SELECT ctime,mtime,mimetype,size,encrypted,versioned,writable FROM *PREFIX*fscache WHERE path_hash=?');
$result=$query->execute(array(md5($path)))->fetchRow();
if(is_array($result)){
if(isset(self::$savedData[$path])){
$result=array_merge($result,self::$savedData[$path]);
}
return $result;
}else{
OC_Log::write('get(): file not found in cache ('.$path.')','core',OC_Log::DEBUG);
return false;
}
}
private static function getCachedSize($path,$root){
if(!$root){
$root=OC_Filesystem::getRoot();
}else{
if($root=='/'){
$root='';
}
}
$path=$root.$path;
$query=OC_DB::prepare('SELECT size FROM *PREFIX*fscache WHERE path_hash=?');
$result=$query->execute(array(md5($path)));
if($row=$result->fetchRow()){
return $row['size'];
}else{//file not in cache
return 0;
}
}
/**
* called when files are deleted
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherDelete($params,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$path=$params['path'];
$fullPath=$root.$path;
if(self::getFileId($fullPath)==-1){
return;
}
$size=self::getCachedSize($path,$root);
self::increaseSize(dirname($fullPath),-$size);
self::delete($path);
}
/**
* called when files are deleted
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherRename($params,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
}
if($root=='/'){
$root='';
}
$oldPath=$params['oldpath'];
$newPath=$params['newpath'];
$fullOldPath=$root.$oldPath;
$fullNewPath=$root.$newPath;
if(($id=self::getFileId($fullOldPath))!=-1){
$oldSize=self::getCachedSize($oldPath,$root);
}else{
return;
}
$size=OC_Filesystem::filesize($newPath);
self::increaseSize(dirname($fullOldPath),-$oldSize);
self::increaseSize(dirname($fullNewPath),$oldSize);
self::move($oldPath,$newPath);
}
/**
* adjust the size of the parent folders
* @param string $path
* @param int $sizeDiff
*/
private static function increaseSize($path,$sizeDiff){
if($sizeDiff==0) return;
while(($id=self::getFileId($path))!=-1){//walk up the filetree increasing the size of all parent folders
$query=OC_DB::prepare('UPDATE *PREFIX*fscache SET size=size+? WHERE id=?');
$query->execute(array($sizeDiff,$id));
$path=dirname($path);
}
}
/**
* recursively scan the filesystem and fill the cache
* @param string $path
* @param OC_EventSource $enventSource (optional)
* @param int count (optional)
* @param string root (optionak)
*/
public static function scan($path,$eventSource=false,&$count=0,$root=''){
if($eventSource){
$eventSource->send('scanning',array('file'=>$path,'count'=>$count));
}
$lastSend=$count;
if(!$root){
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView(($root=='/')?'':$root);
}
self::scanFile($path,$root);
$dh=$view->opendir($path.'/');
$totalSize=0;
if($dh){
while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){
$file=$path.'/'.$filename;
if($view->is_dir($file.'/')){
self::scan($file,$eventSource,$count,$root);
}else{
$totalSize+=self::scanFile($file,$root);
$count++;
if($count>$lastSend+25 and $eventSource){
$lastSend=$count;
$eventSource->send('scanning',array('file'=>$path,'count'=>$count));
}
}
}
}
}
self::increaseSize($view->getRoot().$path,$totalSize);
}
/**
* scan a single file
* @param string path
* @param string root (optional)
* @return int size of the scanned file
*/
public static function scanFile($path,$root=''){
if(!$root){
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView(($root=='/')?'':$root);
}
if(!$view->is_readable($path)) return; //cant read, nothing we can do
$stat=$view->stat($path);
$mimetype=$view->getMimeType($path);
$writable=$view->is_writable($path);
$stat['mimetype']=$mimetype;
$stat['writable']=$writable;
if($path=='/'){
$path='';
}
self::put($path,$stat,$root);
return $stat['size'];
}
/**
* find files by mimetype
* @param string $part1
* @param string $part2 (optional)
* @param string root (optional)
* @return array of file paths
*
* $part1 and $part2 together form the complete mimetype.
* e.g. searchByMime('text','plain')
*
* seccond mimetype part can be ommited
* e.g. searchByMime('audio')
*/
public static function searchByMime($part1,$part2=null,$root=null){
if(!$root){
$root=OC_Filesystem::getRoot();
}elseif($root=='/'){
$root='';
}
$rootLen=strlen($root);
$root .= '%';
$user=OC_User::getUser();
if(!$part2){
$query=OC_DB::prepare('SELECT path FROM *PREFIX*fscache WHERE mimepart=? AND user=? AND path LIKE ?');
$result=$query->execute(array($part1,$user, $root));
}else{
$query=OC_DB::prepare('SELECT path FROM *PREFIX*fscache WHERE mimetype=? AND user=? AND path LIKE ? ');
$result=$query->execute(array($part1.'/'.$part2,$user, $root));
}
$names=array();
while($row=$result->fetchRow()){
$names[]=substr($row['path'],$rootLen);
}
return $names;
}
/**
* check if a file or folder is updated outside owncloud
* @param string path
* @param string root (optional)
* @return bool
*/
public static function isUpdated($path,$root=''){
if(!$root){
$root=OC_Filesystem::getRoot();
$view=OC_Filesystem::getView();
}else{
if($root=='/'){
$root='';
}
$view=new OC_FilesystemView($root);
}
if(!$view->file_exists($path)){
return false;
}
$mtime=$view->filemtime($path);
$isDir=$view->is_dir($path);
$path=$root.$path;
$query=OC_DB::prepare('SELECT mtime FROM *PREFIX*fscache WHERE path_hash=?');
$result=$query->execute(array(md5($path)));
if($row=$result->fetchRow()){
$cachedMTime=$row['mtime'];
return ($mtime>$cachedMTime);
}else{//file not in cache, so it has to be updated
return !($isDir);//new folders are handeled sperate
}
}
/**
* update the cache according to changes in the folder
* @param string path
* @param string root (optional)
*/
private static function updateFolder($path,$root=''){
if(!$root){
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView(($root=='/')?'':$root);
}
$dh=$view->opendir($path);
if($dh){//check for changed/new files
while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){
$file=$path.'/'.$filename;
if(self::isUpdated($file,$root)){
if(!$root){//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$file));
}else{
self::fileSystemWatcherWrite(array('path'=>$file),$root);
}
}
}
}
}
//check for removed files, not using getFolderContent to prevent loops
$parent=self::getFileId($view->getRoot().$path);
$query=OC_DB::prepare('SELECT name FROM *PREFIX*fscache WHERE parent=?');
$result=$query->execute(array($parent));
while($row=$result->fetchRow()){
$file=$path.'/'.$row['name'];
if(!$view->file_exists($file)){
if(!$root){//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_delete',array('path'=>$file));
}else{
self::fileSystemWatcherDelete(array('path'=>$file),$root);
}
}
}
//update the folder last, so we can calculate the size correctly
if(!$root){//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path));
}else{
self::fileSystemWatcherWrite(array('path'=>$path),$root);
}
}
/**
* clean old pre-path_hash entries
*/
public static function clean(){
$query=OC_DB::prepare('DELETE FROM *PREFIX*fscache WHERE LENGTH(path_hash)<30');
$query->execute();
}
}
//watch for changes and try to keep the cache up to date
OC_Hook::connect('OC_Filesystem','post_write','OC_FileCache','fileSystemWatcherWrite');
OC_Hook::connect('OC_Filesystem','post_delete','OC_FileCache','fileSystemWatcherDelete');
OC_Hook::connect('OC_Filesystem','post_rename','OC_FileCache','fileSystemWatcherRename');
|