summaryrefslogtreecommitdiff
path: root/lib/drivers/seafile/seafile_file_storage.php
blob: 6463ea119d393a1815030899e548195da29cc00e (plain)
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
<?php
/*
 +--------------------------------------------------------------------------+
 | This file is part of the Kolab File API                                  |
 |                                                                          |
 | Copyright (C) 2012-2014, Kolab Systems AG                                |
 |                                                                          |
 | This program 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.                                      |
 |                                                                          |
 | This program 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 program. If not, see <http://www.gnu.org/licenses/>      |
 +--------------------------------------------------------------------------+
 | Author: Aleksander Machniak <machniak@kolabsys.com>                      |
 +--------------------------------------------------------------------------+
*/

class seafile_file_storage implements file_storage
{
    /**
     * @var rcube
     */
    protected $rc;

    /**
     * @var array
     */
    protected $config = array();

    /**
     * @var seafile_api
     */
    protected $api;

    /**
     * List of SeaFile libraries
     *
     * @var array
     */
    protected $libraries;

    /**
     * Instance title (mount point)
     *
     * @var string
     */
    protected $title;


    /**
     * Class constructor
     */
    public function __construct()
    {
        $this->rc = rcube::get_instance();
    }

    /**
     * Authenticates a user
     *
     * @param string $username User name
     * @param string $password User password
     *
     * @param bool True on success, False on failure
     */
    public function authenticate($username, $password)
    {
        $this->init(true);

        $token = $this->api->authenticate($username, $password);

        if ($token) {
            $_SESSION[$this->title . 'seafile_user']  = $username;
            $_SESSION[$this->title . 'seafile_token'] = $this->rc->encrypt($token);
            $_SESSION[$this->title . 'seafile_pass']  = $this->rc->encrypt($password);

            return true;
        }

        $this->api = false;

        return false;
    }

    /**
     * Initialize SeaFile Web API connection
     */
    protected function init($skip_auth = false)
    {
        if ($this->api !== null) {
            return $this->api !== false;
        }

        // read configuration
        $config = array(
            'host'            => $this->rc->config->get('fileapi_seafile_host', 'localhost'),
            'ssl_verify_peer' => $this->rc->config->get('fileapi_seafile_ssl_verify_peer', true),
            'ssl_verify_host' => $this->rc->config->get('fileapi_seafile_ssl_verify_host', true),
            'cache'           => $this->rc->config->get('fileapi_seafile_cache'),
            'cache_ttl'       => $this->rc->config->get('fileapi_seafile_cache', '14d'),
            'debug'           => $this->rc->config->get('fileapi_seafile_debug', false),
        );

        $this->config = array_merge($config, $this->config);

        // initialize Web API
        $this->api = new seafile_api($this->config);

        if ($skip_auth) {
            return true;
        }

        // try session token
        if ($_SESSION[$this->title . 'seafile_token']
            && ($token = $this->rc->decrypt($_SESSION[$this->title . 'seafile_token']))
        ) {
            $valid = $this->api->ping($token);
        }

        if (!$valid) {
            // already authenticated in session
            if ($_SESSION[$this->title . 'seafile_user']) {
                $user = $_SESSION[$this->title . 'seafile_user'];
                $pass = $this->rc->decrypt($_SESSION[$this->title . 'seafile_pass']);
            }
            // try user/pass of the main driver
            else {
                $user = $this->config['username'];
                $pass = $this->config['password'];
            }

            if ($user) {
                $valid = $this->authenticate($user, $pass);
            }
        }

        // throw special exception, so we can ask user for the credentials
        if (!$valid && empty($_SESSION[$this->title . 'seafile_user'])) {
            throw new Exception("User credentials not provided", file_storage::ERROR_NOAUTH);
        }
        else if (!$valid && $this->api->is_error() == seafile_api::TOO_MANY_REQUESTS) {
            throw new Exception("SeaFile storage temporarily unavailable (too many requests)", file_storage::ERROR);
        }

        return $valid;
    }

    /**
     * Configures environment
     *
     * @param array  $config Configuration
     * @param string $title  Source identifier
     */
    public function configure($config, $title = null)
    {
        $this->config = array_merge($this->config, $config);
        $this->title  = $title;
    }

    /**
     * Returns current instance title
     *
     * @return string Instance title (mount point)
     */
    public function title()
    {
        return $this->title;
    }

    /**
     * Storage driver capabilities
     *
     * @return array List of capabilities
     */
    public function capabilities()
    {
        // find max filesize value
        $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
        $max_postsize = parse_bytes(ini_get('post_max_size'));
        if ($max_postsize && $max_postsize < $max_filesize) {
            $max_filesize = $max_postsize;
        }

        return array(
            file_storage::CAPS_MAX_UPLOAD => $max_filesize,
            file_storage::CAPS_QUOTA      => true,
            file_storage::CAPS_LOCKS      => true,
        );
    }

    /**
     * Save configuration of external driver (mount point)
     *
     * @param array $driver Driver data
     *
     * @throws Exception
     */
    public function driver_create($driver)
    {
        throw new Exception("Not implemented", file_storage::ERROR_UNSUPPORTED);
    }

    /**
     * Delete configuration of external driver (mount point)
     *
     * @param string $name Driver instance name
     *
     * @throws Exception
     */
    public function driver_delete($name)
    {
        throw new Exception("Not implemented", file_storage::ERROR_UNSUPPORTED);
    }

    /**
     * Return list of registered drivers (mount points)
     *
     * @return array List of drivers data
     * @throws Exception
     */
    public function driver_list()
    {
        throw new Exception("Not implemented", file_storage::ERROR_UNSUPPORTED);
    }

    /**
     * Update configuration of external driver (mount point)
     *
     * @param string $name   Driver instance name
     * @param array  $driver Driver data
     *
     * @throws Exception
     */
    public function driver_update($name, $driver)
    {
        throw new Exception("Not implemented", file_storage::ERROR_UNSUPPORTED);
    }

    /**
     * Returns metadata of the driver
     *
     * @return array Driver meta data (image, name, form)
     */
    public function driver_metadata()
    {
        $image_content = file_get_contents(__DIR__ . '/seafile.png');

        $metadata = array(
            'image' => 'data:image/png;base64,' . base64_encode($image_content),
            'name'  => 'SeaFile',
            'ref'   => 'http://seafile.com',
            'description' => 'Storage implementing SeaFile API access',
            'form'  => array(
                'host'     => 'hostname',
                'username' => 'username',
                'password' => 'password',
            ),
        );

        // these are returned when authentication on folders list fails
        if ($this->config['username']) {
            $metadata['form_values'] = array(
                'host'     => $this->config['host'],
                'username' => $this->config['username'],
            );
        }

        return $metadata;
    }

    /**
     * Validate metadata (config) of the driver
     *
     * @param array $metadata Driver metadata
     *
     * @return array Driver meta data to be stored in configuration
     * @throws Exception
     */
    public function driver_validate($metadata)
    {
        if (!is_string($metadata['username']) || !strlen($metadata['username'])) {
            throw new Exception("Missing user name.", file_storage::ERROR);
        }

        if (!is_string($metadata['password']) || !strlen($metadata['password'])) {
            throw new Exception("Missing user password.", file_storage::ERROR);
        }

        if (!is_string($metadata['host']) || !strlen($metadata['host'])) {
            throw new Exception("Missing host name.", file_storage::ERROR);
        }

        $this->config['host'] = $metadata['host'];

        if (!$this->authenticate($metadata['username'], $metadata['password'])) {
            throw new Exception("Unable to authenticate user", file_storage::ERROR_NOAUTH);
        }

        return array(
            'host'     => $metadata['host'],
            'username' => $metadata['username'],
            'password' => $metadata['password'],
        );
    }

    /**
     * Create a file.
     *
     * @param string $file_name Name of a file (with folder path)
     * @param array  $file      File data (path, type)
     *
     * @throws Exception
     */
    public function file_create($file_name, $file)
    {
        list($fn, $repo_id) = $this->find_library($file_name);

        if (empty($repo_id)) {
            throw new Exception("Storage error. Folder not found.", file_storage::ERROR);
        }

        if ($file['path']) {
            $file['data'] = $file['path'];
        }
        else if (is_resource($file['content'])) {
            $file['data'] = $file['content'];
        }
        else {
            $fp = fopen('php://temp', 'wb');
            fwrite($fp, $file['content'], strlen($file['content']));
            $file['data'] = $fp;
            unset($file['content']);
        }

        $created = $this->api->file_upload($repo_id, $fn, $file);

        if ($fp) {
            fclose($fp);
        }

        if (!$created) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error saving file to SeaFile server"),
                true, false);

            throw new Exception("Storage error. Saving file failed.", file_storage::ERROR);
        }
    }

    /**
     * Update a file.
     *
     * @param string $file_name Name of a file (with folder path)
     * @param array  $file      File data (path, type)
     *
     * @throws Exception
     */
    public function file_update($file_name, $file)
    {
        list($fn, $repo_id) = $this->find_library($file_name);

        if (empty($repo_id)) {
            throw new Exception("Storage error. Folder not found.", file_storage::ERROR);
        }

        if ($file['path']) {
            $file['data'] = $file['path'];
        }
        else if (is_resource($file['content'])) {
            $file['data'] = $file['content'];
        }
        else {
            $fp = fopen('php://temp', 'wb');
            fwrite($fp, $file['content'], strlen($file['content']));
            $file['data'] = $fp;
            unset($file['content']);
        }

        $saved = $this->api->file_update($repo_id, $fn, $file);

        if ($fp) {
            fclose($fp);
        }

        if (!$saved) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error saving file to SeaFile server"),
                true, false);

            throw new Exception("Storage error. Saving file failed.", file_storage::ERROR);
        }
    }

    /**
     * Delete a file.
     *
     * @param string $file_name Name of a file (with folder path)
     *
     * @throws Exception
     */
    public function file_delete($file_name)
    {
        list($file_name, $repo_id) = $this->find_library($file_name);

        if ($repo_id && $file_name != '/') {
            $deleted = $this->api->file_delete($repo_id, $file_name);
        }

        if (!$deleted) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error deleting object from SeaFile server"),
                true, false);

            throw new Exception("Storage error. Deleting file failed.", file_storage::ERROR);
        }
    }

    /**
     * Return file body.
     *
     * @param string   $file_name Name of a file (with folder path)
     * @param array    $params    Parameters (force-download)
     * @param resource $fp        Print to file pointer instead (send no headers)
     *
     * @throws Exception
     */
    public function file_get($file_name, $params = array(), $fp = null)
    {
        list($fn, $repo_id) = $this->find_library($file_name);

        $file = $this->api->file_info($repo_id, $fn);

        if (empty($file)) {
            throw new Exception("Storage error. File not found.", file_storage::ERROR);
        }

        $file = $this->from_file_object($file);

        // get file location on SeaFile server for download
        if ($file['size']) {
            $link = $this->api->file_get($repo_id, $fn);
        }

        // write to file pointer, send no headers
        if ($fp) {
            if ($file['size']) {
                $this->save_file_content($link, $fp);
            }

            return;
        }

        if (!empty($params['force-download'])) {
            $disposition = 'attachment';
            header("Content-Type: application/octet-stream");
// @TODO
//            if ($browser->ie)
//                header("Content-Type: application/force-download");
        }
        else {
            $mimetype    = file_utils::real_mimetype($params['force-type'] ? $params['force-type'] : $file['type']);
            $disposition = 'inline';

            header("Content-Transfer-Encoding: binary");
            header("Content-Type: $mimetype");
        }

        $filename = addcslashes($file['name'], '"');

        // Workaround for nasty IE bug (#1488844)
        // If Content-Disposition header contains string "attachment" e.g. in filename
        // IE handles data as attachment not inline
/*
@TODO
        if ($disposition == 'inline' && $browser->ie && $browser->ver < 9) {
            $filename = str_ireplace('attachment', 'attach', $filename);
        }
*/
        header("Content-Length: " . $file['size']);
        header("Content-Disposition: $disposition; filename=\"$filename\"");

        // just send redirect to SeaFile server
        if ($file['size']) {
            header("Location: $link");
        }
        die;
    }

    /**
     * Returns file metadata.
     *
     * @param string $file_name Name of a file (with folder path)
     *
     * @throws Exception
     */
    public function file_info($file_name)
    {
        list($file, $repo_id) = $this->find_library($file_name);

        $file = $this->api->file_info($repo_id, $file);

        if (empty($file)) {
            throw new Exception("Storage error. File not found.", file_storage::ERROR);
        }

        $file = $this->from_file_object($file);

        return array(
            'name'     => $file['name'],
            'size'     => (int) $file['size'],
            'type'     => (string) $file['type'],
            'mtime'    => $file['changed'] ? $file['changed']->format($this->config['date_format']) : '',
            'ctime'    => $file['created'] ? $file['created']->format($this->config['date_format']) : '',
            'modified' => $file['changed'] ? $file['changed']->format('U') : 0,
            'created'  => $file['created'] ? $file['created']->format('U') : 0,
        );
    }

    /**
     * List files in a folder.
     *
     * @param string $folder_name Name of a folder with full path
     * @param array  $params      List parameters ('sort', 'reverse', 'search', 'prefix')
     *
     * @return array List of files (file properties array indexed by filename)
     * @throws Exception
     */
    public function file_list($folder_name, $params = array())
    {
        list($folder, $repo_id) = $this->find_library($folder_name);

        // prepare search filter
        if (!empty($params['search'])) {
            foreach ($params['search'] as $idx => $value) {
                if ($idx == 'name') {
                    $params['search'][$idx] = mb_strtoupper($value);
                }
                else if ($idx == 'class') {
                    $params['search'][$idx] = file_utils::class2mimetypes($value);
                }
            }
        }

        // get directory entries
        $entries = $this->api->directory_entries($repo_id, $folder);
        $result  = array();

        foreach ((array) $entries as $idx => $file) {
            if ($file['type'] != 'file') {
                continue;
            }

            $file = $this->from_file_object($file);

            // search filter
            if (!empty($params['search'])) {
                foreach ($params['search'] as $idx => $value) {
                    if ($idx == 'name') {
                        if (strpos(mb_strtoupper($file['name']), $value) === false) {
                            continue 2;
                        }
                    }
                    else if ($idx == 'class') {
                        foreach ($value as $v) {
                            if (stripos($file['type'], $v) === 0) {
                                break 2;
                            }
                        }

                        continue 2;
                    }
                }
            }

            $filename = $params['prefix'] . $folder_name . file_storage::SEPARATOR . $file['name'];

            $result[$filename] = array(
                'name'     => $file['name'],
                'size'     => (int) $file['size'],
                'type'     => (string) $file['type'],
                'mtime'    => $file['changed'] ? $file['changed']->format($this->config['date_format']) : '',
                'ctime'    => $file['created'] ? $file['created']->format($this->config['date_format']) : '',
                'modified' => $file['changed'] ? $file['changed']->format('U') : 0,
                'created'  => $file['created'] ? $file['created']->format('U') : 0,
            );

            unset($files[$idx]);
        }

        // @TODO: pagination, search (by filename, mimetype)

        // Sorting
        $sort  = !empty($params['sort']) ? $params['sort'] : 'name';
        $index = array();

        if ($sort == 'mtime') {
            $sort = 'modified';
        }

        if (in_array($sort, array('name', 'size', 'modified'))) {
            foreach ($result as $key => $val) {
                $index[$key] = $val[$sort];
            }
            array_multisort($index, SORT_ASC, SORT_NUMERIC, $result);
        }

        if ($params['reverse']) {
            $result = array_reverse($result, true);
        }

        return $result;
    }

    /**
     * Copy a file.
     *
     * @param string $file_name Name of a file (with folder path)
     * @param string $new_name  New name of a file (with folder path)
     *
     * @throws Exception
     */
    public function file_copy($file_name, $new_name)
    {
        list($src_name, $repo_id)     = $this->find_library($file_name);
        list($dst_name, $dst_repo_id) = $this->find_library($new_name);

        if ($repo_id && $dst_repo_id) {
            $path_src = explode('/', $src_name);
            $path_dst = explode('/', $dst_name);
            $f_src    = array_pop($path_src);
            $f_dst    = array_pop($path_dst);
            $src_dir  = '/' . ltrim(implode('/', $path_src), '/');
            $dst_dir  = '/' . ltrim(implode('/', $path_dst), '/');

            $success = $this->api->file_copy($repo_id, $f_old, $src_dir, $dst_dir, $dst_repo_id);

            // now rename the file if needed
            if ($success && $f_src != $f_dst) {
                $success = $this->api->file_rename($dst_repo_id, rtrim($dst_dir, '/') . '/' . $f_src, $f_dst);
            }
        }

        if (!$saved) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error copying file on SeaFile server"),
                true, false);

            throw new Exception("Storage error. File copying failed.", file_storage::ERROR);
        }
    }

    /**
     * Move (or rename) a file.
     *
     * @param string $file_name Name of a file (with folder path)
     * @param string $new_name  New name of a file (with folder path)
     *
     * @throws Exception
     */
    public function file_move($file_name, $new_name)
    {
        list($src_name, $repo_id)     = $this->find_library($file_name);
        list($dst_name, $dst_repo_id) = $this->find_library($new_name);

        if ($repo_id && $dst_repo_id) {
            $path_src = explode('/', $src_name);
            $path_dst = explode('/', $dst_name);
            $f_src    = array_pop($path_src);
            $f_dst    = array_pop($path_dst);
            $src_dir  = '/' . ltrim(implode('/', $path_src), '/');
            $dst_dir  = '/' . ltrim(implode('/', $path_dst), '/');

            if ($src_dir == $dst_dir && $repo_id == $dst_repo_id) {
                $success = true;
            }
            else {
                $success = $this->api->file_move($repo_id, $src_name, $dst_dir, $dst_repo_id);
            }

            // now rename the file if needed
            if ($success && $f_src != $f_dst) {
                $success = $this->api->file_rename($dst_repo_id, rtrim($dst_dir, '/') . '/' . $f_src, $f_dst);
            }
        }

        if (!$success) {
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "Error moving file on SeaFile server"),
                true, false);

            throw new Exception("Storage error. File rename failed.", file_storage::ERROR);
        }
    }

    /**
     * Create a folder.
     *
     * @param string $folder_name Name of a folder with full path
     *
     * @throws Exception on error
     */
    public function folder_create($folder_name)
    {
        list($folder, $repo_id) = $this->find_library($folder_name, true);

        if (empty($repo_id)) {
            $success = $this->api->library_create($folder_name);
        }
        else if ($folder != '/') {
            $success = $this->api->directory_create($repo_id, $folder);
        }

        if (!$success) {
            throw new Exception("Storage error. Unable to create folder", file_storage::ERROR);
        }

        // clear the cache
        if (empty($repo_id)) {
            $this->libraries = null;
        }
    }

    /**
     * Delete a folder.
     *
     * @param string $folder_name Name of a folder with full path
     *
     * @throws Exception on error
     */
    public function folder_delete($folder_name)
    {
        list($folder, $repo_id) = $this->find_library($folder_name, true);

        if ($repo_id && $folder == '/') {
            $success = $this->api->library_delete($repo_id);
        }
        else if ($repo_id) {
            $success = $this->api->directory_delete($repo_id, $folder);
        }

        if (!$success) {
            throw new Exception("Storage error. Unable to delete folder.", file_storage::ERROR);
        }
    }

    /**
     * Move/Rename a folder.
     *
     * @param string $folder_name Name of a folder with full path
     * @param string $new_name    New name of a folder with full path
     *
     * @throws Exception on error
     */
    public function folder_move($folder_name, $new_name)
    {
        list($folder, $repo_id, $library) = $this->find_library($folder_name, true);
        list($dest_folder, $dest_repo_id) = $this->find_library($new_name, true);

        // folders rename/move is possible only in the same library and folder
        // @TODO: support folder move between libraries and folders
        // @TODO: support converting library into a folder and vice-versa

        // library rename
        if ($repo_id && !$dest_repo_id && $folder == '/' && strpos($new_name, '/') === false) {
            $success = $this->api->library_rename($repo_id, $new_name, $library['desc']);
        }
        // folder rename
        else if ($folder != '/' && $dest_folder != '/' && $repo_id && $repo_id == $dest_repo_id) {
            $path_src = explode('/', $folder);
            $path_dst = explode('/', $dest_folder);
            $f_src    = array_pop($path_src);
            $f_dst    = array_pop($path_dst);
            $src_dir  = implode('/', $path_src);
            $dst_dir  = implode('/', $path_dst);

            if ($src_dir == $dst_dir) {
                $success = $this->api->directory_rename($repo_id, $folder, $f_dst);
            }
        }

        if (!$success) {
            throw new Exception("Storage error. Unable to rename/move folder", file_storage::ERROR);
        }
    }

    /**
     * Returns list of folders.
     *
     * @return array List of folders
     * @throws Exception
     */
    public function folder_list()
    {
        $libraries = $this->libraries();
        $folders   = array();

        if ($this->config['cache']) {
            $cache = $this->rc->get_cache('seafile_' . $this->title,
                $this->config['cache'], $this->config['cache_ttl'], true);

            if ($cache) {
                $cached = $cache->get('folders');
            }
        }

        foreach ($this->libraries as $library) {
            if ($library['virtual'] || $library['encrypted']) {
                continue;
            }

            $folders[$library['name']] = $library['mtime'];

            if ($folder_tree = $this->folders_tree($library, '', $library, $cached)) {
                $folders = array_merge($folders, $folder_tree);
            }
        }

        if (empty($folders)) {
            throw new Exception("Storage error. Unable to get folders list.", file_storage::ERROR);
        }

        if ($cache) {
            $cache->set('folders', $folders);
        }

        // sort folders
        $folders = array_keys($folders);
        usort($folders, array($this, 'sort_folder_comparator'));

        return $folders;
    }

    /**
     * Returns a list of locks
     *
     * This method should return all the locks for a particular URI, including
     * locks that might be set on a parent URI.
     *
     * If child_locks is set to true, this method should also look for
     * any locks in the subtree of the URI for locks.
     *
     * @param string $uri         URI
     * @param bool   $child_locks Enables subtree checks
     *
     * @return array List of locks
     * @throws Exception
     */
    public function lock_list($uri, $child_locks = false)
    {
        $this->init_lock_db();

        // convert URI to global resource string
        $uri = $this->uri2resource($uri);

        // get locks list
        $list = $this->lock_db->lock_list($uri, $child_locks);

        // convert back resource string into URIs
        foreach ($list as $idx => $lock) {
            $list[$idx]['uri'] = $this->resource2uri($lock['uri']);
        }

        return $list;
    }

    /**
     * Locks a URI
     *
     * @param string $uri  URI
     * @param array  $lock Lock data
     *                     - depth: 0/'infinite'
     *                     - scope: 'shared'/'exclusive'
     *                     - owner: string
     *                     - token: string
     *                     - timeout: int
     *
     * @throws Exception
     */
    public function lock($uri, $lock)
    {
        $this->init_lock_db();

        // convert URI to global resource string
        $uri = $this->uri2resource($uri);

        if (!$this->lock_db->lock($uri, $lock)) {
            throw new Exception("Database error. Unable to create a lock.", file_storage::ERROR);
        }
    }

    /**
     * Removes a lock from a URI
     *
     * @param string $path URI
     * @param array  $lock Lock data
     *
     * @throws Exception
     */
    public function unlock($uri, $lock)
    {
        $this->init_lock_db();

        // convert URI to global resource string
        $uri = $this->uri2resource($uri);

        if (!$this->lock_db->unlock($uri, $lock)) {
            throw new Exception("Database error. Unable to remove a lock.", file_storage::ERROR);
        }
    }

    /**
     * Return disk quota information for specified folder.
     *
     * @param string $folder_name Name of a folder with full path
     *
     * @return array Quota
     * @throws Exception
     */
    public function quota($folder)
    {
        if (!$this->init()) {
            throw new Exception("Storage error. Unable to get SeaFile account info.", file_storage::ERROR);
        }

        $account_info = $this->api->account_info();

        if (empty($account_info)) {
            throw new Exception("Storage error. Unable to get SeaFile account info.", file_storage::ERROR);
        }

        $quota = array(
            // expected values in kB
            'total' => intval($account_info['total'] / 1024),
            'used'  => intval($account_info['usage'] / 1024),
        );

        return $quota;
    }

    /**
     * Recursively builds folders list
     */
    protected function folders_tree($library, $path, $folder, $cached)
    {
        $folders = array();
        $fname  = strlen($path) ? $path . $folder['name'] : '/';
        $root   = $library['name'] . ($fname != '/' ? $fname : '');

        // nothing changed, use cached folders tree of this folder
        if ($cached && $cached[$root] && $cached[$root] == $folder['mtime']) {
            foreach ($cached as $folder_name => $mtime) {
                if (strpos($folder_name, $root . '/') === 0) {
                    $folders[$folder_name] = $mtime;
                }
            }
        }
        // get folder content (files and sub-folders)
        // there's no API method to get only folders
        else if ($content = $this->api->directory_entries($library['id'], $fname)) {
            if ($fname != '/') {
                $fname .= '/';
            }

            foreach ($content as $item) {
                if ($item['type'] == 'dir' && strlen($item['name'])) {
                    $folders[$root . '/' . $item['name']] = $item['mtime'];

                    // get subfolders recursively
                    $folders_tree = $this->folders_tree($library, $fname, $item, $cached);
                    if (!empty($folders_tree)) {
                        $folders = array_merge($folders, $folders_tree);
                    }
                }
            }
        }

        return $folders;
    }

    /**
     * Callback for uasort() that implements correct
     * locale-aware case-sensitive sorting
     */
    protected function sort_folder_comparator($str1, $str2)
    {
        $path1 = explode('/', $str1);
        $path2 = explode('/', $str2);

        foreach ($path1 as $idx => $folder1) {
            $folder2 = $path2[$idx];

            if ($folder1 === $folder2) {
                continue;
            }

            return strcoll($folder1, $folder2);
        }
    }

    /**
     * Get list of SeaFile libraries
     */
    protected function libraries()
    {
        // get from memory, @TODO: cache in rcube_cache?
        if ($this->libraries !== null) {
            return $this->libraries;
        }

        if (!$this->init()) {
            throw new Exception("Storage error. Unable to get list of SeaFile libraries.", file_storage::ERROR);
        }

        if ($list = $this->api->library_list()) {
            $this->libraries = $list;
        }
        else {
            $this->libraries = array();
        }

        return $this->libraries;
    }

    /**
     * Find library ID from folder name
     */
    protected function find_library($folder_name, $no_exception = false)
    {
        $libraries = $this->libraries();

        foreach ($libraries as $lib) {
            $path = $lib['name'] . '/';

            if ($folder_name == $lib['name'] || strpos($folder_name, $path) === 0) {
                if (empty($library) || strlen($library['name']) < strlen($lib['name'])) {
                    $library = $lib;
                }
            }
        }

        if (empty($library)) {
            if (!$no_exception) {
                throw new Exception("Storage error. Library not found.", file_storage::ERROR);
            }
        }
        else {
            $folder = substr($folder_name, strlen($library['name']) + 1);
        }

        return array(
            '/' . ($folder ? $folder : ''),
            $library['id'],
            $library
        );
    }

    /**
     * Get file object.
     *
     * @param string               $file_name Name of a file (with folder path)
     * @param kolab_storage_folder $folder    Reference to folder object
     *
     * @return array File data
     * @throws Exception
     */
    protected function get_file_object(&$file_name, &$folder = null)
    {
        // extract file path and file name
        $path        = explode(file_storage::SEPARATOR, $file_name);
        $file_name   = array_pop($path);
        $folder_name = implode(file_storage::SEPARATOR, $path);

        if ($folder_name === '') {
            throw new Exception("Missing folder name", file_storage::ERROR);
        }

        // get folder object
        $folder = $this->get_folder_object($folder_name);
        $files  = $folder->select(array(
            array('type', '=', 'file'),
            array('filename', '=', $file_name)
        ));

        return $files[0];
    }

    /**
     * Simplify internal structure of the file object
     */
    protected function from_file_object($file)
    {
        if ($file['type'] != 'file') {
            return null;
        }

        // file modification time
        if ($file['mtime']) {
            try {
                $file['changed'] = new DateTime('@' . $file['mtime']);
            }
            catch (Exception $e) { }
        }

        // find file mimetype from extension
        $file['type'] = file_utils::ext_to_type($file['name']);

        unset($file['id']);
        unset($file['mtime']);

        return $file;
    }

    /**
     * Save remote file into file pointer
     */
    protected function save_file_content($location, $fp)
    {
        if (!$fp || !$location) {
            return false;
        }

        $config  = array_merge($this->config, array('store_bodies' => true));
        $request = seafile_api::http_request($config);

        if (!$request) {
            return false;
        }

        $observer = new seafile_request_observer();
        $observer->set_fp($fp);

        try {
            $request->setUrl($location);
            $request->attach($observer);

            $response = $request->send();
            $status   = $response->getStatus();

            $response->getBody(); // returns nothing
            $request->detach($observer);

            if ($status != 200) {
                throw new Exception("Unable to save file. Status $status.");
            }
        }
        catch (Exception $e) {
            rcube::raise_error($e, true, false);
            return false;
        }

        return true;
    }

    protected function uri2resource($uri)
    {
        list($file, $repo_id, $library) = $this->find_library($uri);

        // convert to imap charset (to be safe to store in DB)
        $uri = rcube_charset::convert($uri, RCUBE_CHARSET, 'UTF7-IMAP');

        return 'seafile://' . urlencode($library['owner']) . '@' . $this->config['host'] . '/' . $uri;
    }

    protected function resource2uri($resource)
    {
        if (!preg_match('|^seafile://([^@]+)@([^/]+)/(.*)$|', $resource, $matches)) {
            throw new Exception("Internal storage error. Unexpected data format.", file_storage::ERROR);
        }

        $user = urldecode($matches[1]);
        $uri  = $matches[3];

        // convert from imap charset (to be safe to store in DB)
        $uri = rcube_charset::convert($uri, 'UTF7-IMAP', RCUBE_CHARSET);

        return $uri;
    }

    /**
     * Initializes file_locks object
     */
    protected function init_lock_db()
    {
        if (!$this->lock_db) {
            $this->lock_db = new file_locks;
        }
    }
}