summaryrefslogtreecommitdiffstats
path: root/l10n/my_MM/settings.po
blob: ade1a7d73e5b64f2dfe395cda01059916a9325bf (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
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# 
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: ownCloud\n"
"Report-Msgid-Bugs-To: http://bugs.owncloud.org/\n"
"POT-Creation-Date: 2013-02-21 00:14+0100\n"
"PO-Revision-Date: 2011-07-25 16:05+0000\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: Burmese (Myanmar) (http://www.transifex.com/projects/p/owncloud/language/my_MM/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: my_MM\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: ajax/apps/ocs.php:20
msgid "Unable to load list from App Store"
msgstr ""

#: ajax/changedisplayname.php:23 ajax/removeuser.php:15 ajax/setquota.php:15
#: ajax/togglegroups.php:18
msgid "Authentication error"
msgstr ""

#: ajax/changedisplayname.php:32
msgid "Unable to change display name"
msgstr ""

#: ajax/creategroup.php:10
msgid "Group already exists"
msgstr ""

#: ajax/creategroup.php:19
msgid "Unable to add group"
msgstr ""

#: ajax/enableapp.php:11
msgid "Could not enable app. "
msgstr ""

#: ajax/lostpassword.php:12
msgid "Email saved"
msgstr ""

#: ajax/lostpassword.php:14
msgid "Invalid email"
msgstr ""

#: ajax/removegroup.php:13
msgid "Unable to delete group"
msgstr ""

#: ajax/removeuser.php:24
msgid "Unable to delete user"
msgstr ""

#: ajax/setlanguage.php:15
msgid "Language changed"
msgstr ""

#: ajax/setlanguage.php:17 ajax/setlanguage.php:20
msgid "Invalid request"
msgstr ""

#: ajax/togglegroups.php:12
msgid "Admins can't remove themself from the admin group"
msgstr ""

#: ajax/togglegroups.php:28
#, php-format
msgid "Unable to add user to group %s"
msgstr ""

#: ajax/togglegroups.php:34
#, php-format
msgid "Unable to remove user from group %s"
msgstr ""

#: ajax/updateapp.php:14
msgid "Couldn't update app."
msgstr ""

#: js/apps.js:30
msgid "Update to {appversion}"
msgstr ""

#: js/apps.js:36 js/apps.js:76
msgid "Disable"
msgstr ""

#: js/apps.js:36 js/apps.js:64
msgid "Enable"
msgstr ""

#: js/apps.js:55
msgid "Please wait...."
msgstr ""

#: js/apps.js:84
msgid "Updating...."
msgstr ""

#: js/apps.js:87
msgid "Error while updating app"
msgstr ""

#: js/apps.js:87
msgid "Error"
msgstr ""

#: js/apps.js:90
msgid "Updated"
msgstr ""

#: js/personal.js:96
msgid "Saving..."
msgstr ""

#: js/users.js:30
msgid "deleted"
msgstr ""

#: js/users.js:30
msgid "undo"
msgstr ""

#: js/users.js:62
msgid "Unable to remove user"
msgstr ""

#: js/users.js:75 templates/users.php:26 templates/users.php:80
#: templates/users.php:105
msgid "Groups"
msgstr ""

#: js/users.js:78 templates/users.php:82 templates/users.php:119
msgid "Group Admin"
msgstr ""

#: js/users.js:99 templates/users.php:161
msgid "Delete"
msgstr ""

#: js/users.js:191
msgid "add group"
msgstr ""

#: js/users.js:352
msgid "A valid username must be provided"
msgstr ""

#: js/users.js:353 js/users.js:359 js/users.js:374
msgid "Error creating user"
msgstr ""

#: js/users.js:358
msgid "A valid password must be provided"
msgstr ""

#: personal.php:29 personal.php:30
msgid "__language_name__"
msgstr ""

#: templates/admin.php:15
msgid "Security Warning"
msgstr ""

#: templates/admin.php:18
msgid ""
"Your data directory and your files are probably accessible from the "
"internet. The .htaccess file that ownCloud provides is not working. We "
"strongly suggest that you configure your webserver in a way that the data "
"directory is no longer accessible or you move the data directory outside the"
" webserver document root."
msgstr ""

#: templates/admin.php:29
msgid "Setup Warning"
msgstr ""

#: templates/admin.php:32
msgid ""
"Your web server is not yet properly setup to allow files synchronization "
"because the WebDAV interface seems to be broken."
msgstr ""

#: templates/admin.php:33
#, php-format
msgid "Please double check the <a href='%s'>installation guides</a>."
msgstr ""

#: templates/admin.php:44
msgid "Module 'fileinfo' missing"
msgstr ""

#: templates/admin.php:47
msgid ""
"The PHP module 'fileinfo' is missing. We strongly recommend to enable this "
"module to get best results with mime-type detection."
msgstr ""

#: templates/admin.php:58
msgid "Locale not working"
msgstr ""

#: templates/admin.php:61
msgid ""
"This ownCloud server can't set system locale to "
"\"en_US.UTF-8\"/\"en_US.UTF8\". This means that there might be problems with"
" certain characters in file names. We strongly suggest to install the "
"required packages on your system to support en_US.UTF-8/en_US.UTF8."
msgstr ""

#: templates/admin.php:72
msgid "Internet connection not working"
msgstr ""

#: templates/admin.php:75
msgid ""
"This ownCloud server has no working internet connection. This means that "
"some of the features like mounting of external storage, notifications about "
"updates or installation of 3rd party apps don´t work. Accessing files from "
"remote and sending of notification emails might also not work. We suggest to"
" enable internet connection for this server if you want to have all features"
" of ownCloud."
msgstr ""

#: templates/admin.php:89
msgid "Cron"
msgstr ""

#: templates/admin.php:98
msgid "Execute one task with each page loaded"
msgstr ""

#: templates/admin.php:108
msgid ""
"cron.php is registered at a webcron service. Call the cron.php page in the "
"owncloud root once a minute over http."
msgstr ""

#: templates/admin.php:118
msgid ""
"Use systems cron service. Call the cron.php file in the owncloud folder via "
"a system cronjob once a minute."
msgstr ""

#: templates/admin.php:125
msgid "Sharing"
msgstr ""

#: templates/admin.php:131
msgid "Enable Share API"
msgstr ""

#: templates/admin.php:132
msgid "Allow apps to use the Share API"
msgstr ""

#: templates/admin.php:139
msgid "Allow links"
msgstr ""

#: templates/admin.php:140
msgid "Allow users to share items to the public with links"
msgstr ""

#: templates/admin.php:147
msgid "Allow resharing"
msgstr ""

#: templates/admin.php:148
msgid "Allow users to share items shared with them again"
msgstr ""

#: templates/admin.php:155
msgid "Allow users to share with anyone"
msgstr ""

#: templates/admin.php:158
msgid "Allow users to only share with users in their groups"
msgstr ""

#: templates/admin.php:165
msgid "Security"
msgstr ""

#: templates/admin.php:178
msgid "Enforce HTTPS"
msgstr ""

#: templates/admin.php:179
msgid ""
"Enforces the clients to connect to ownCloud via an encrypted connection."
msgstr ""

#: templates/admin.php:182
msgid ""
"Please connect to this ownCloud instance via HTTPS to enable or disable the "
"SSL enforcement."
msgstr ""

#: templates/admin.php:192
msgid "Log"
msgstr ""

#: templates/admin.php:193
msgid "Log level"
msgstr ""

#: templates/admin.php:220
msgid "More"
msgstr ""

#: templates/admin.php:227 templates/personal.php:98
msgid "Version"
msgstr ""

#: templates/admin.php:230 templates/personal.php:100
msgid ""
"Developed by the <a href=\"http://ownCloud.org/contact\" "
"target=\"_blank\">ownCloud community</a>, the <a "
"href=\"https://github.com/owncloud\" target=\"_blank\">source code</a> is "
"licensed under the <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" "
"target=\"_blank\"><abbr title=\"Affero General Public "
"License\">AGPL</abbr></a>."
msgstr ""

#: templates/apps.php:10
msgid "Add your App"
msgstr ""

#: templates/apps.php:11
msgid "More Apps"
msgstr ""

#: templates/apps.php:24
msgid "Select an App"
msgstr ""

#: templates/apps.php:28
msgid "See application page at apps.owncloud.com"
msgstr ""

#: templates/apps.php:29
msgid "<span class=\"licence\"></span>-licensed by <span class=\"author\"></span>"
msgstr ""

#: templates/apps.php:31
msgid "Update"
msgstr ""

#: templates/help.php:3
msgid "User Documentation"
msgstr ""

#: templates/help.php:4
msgid "Administrator Documentation"
msgstr ""

#: templates/help.php:6
msgid "Online Documentation"
msgstr ""

#: templates/help.php:7
msgid "Forum"
msgstr ""

#: templates/help.php:9
msgid "Bugtracker"
msgstr ""

#: templates/help.php:11
msgid "Commercial Support"
msgstr ""

#: templates/personal.php:8
#, php-format
msgid "You have used <strong>%s</strong> of the available <strong>%s</strong>"
msgstr ""

#: templates/personal.php:14
msgid "Get the apps to sync your files"
msgstr ""

#: templates/personal.php:25
msgid "Show First Run Wizard again"
msgstr ""

#: templates/personal.php:36 templates/users.php:23 templates/users.php:79
msgid "Password"
msgstr ""

#: templates/personal.php:37
msgid "Your password was changed"
msgstr ""

#: templates/personal.php:38
msgid "Unable to change your password"
msgstr ""

#: templates/personal.php:39
msgid "Current password"
msgstr ""

#: templates/personal.php:40
msgid "New password"
msgstr ""

#: templates/personal.php:42
msgid "Change password"
msgstr ""

#: templates/personal.php:54 templates/users.php:78
msgid "Display Name"
msgstr ""

#: templates/personal.php:55
msgid "Your display name was changed"
msgstr ""

#: templates/personal.php:56
msgid "Unable to change your display name"
msgstr ""

#: templates/personal.php:59
msgid "Change display name"
msgstr ""

#: templates/personal.php:68
msgid "Email"
msgstr ""

#: templates/personal.php:69
msgid "Your email address"
msgstr ""

#: templates/personal.php:70
msgid "Fill in an email address to enable password recovery"
msgstr ""

#: templates/personal.php:76 templates/personal.php:77
msgid "Language"
msgstr ""

#: templates/personal.php:82
msgid "Help translate"
msgstr ""

#: templates/personal.php:87
msgid "WebDAV"
msgstr ""

#: templates/personal.php:89
msgid "Use this address to connect to your ownCloud in your file manager"
msgstr ""

#: templates/users.php:21 templates/users.php:77
msgid "Login Name"
msgstr ""

#: templates/users.php:32
msgid "Create"
msgstr ""

#: templates/users.php:35
msgid "Default Storage"
msgstr ""

#: templates/users.php:41 templates/users.php:139
msgid "Unlimited"
msgstr ""

#: templates/users.php:59 templates/users.php:154
msgid "Other"
msgstr ""

#: templates/users.php:84
msgid "Storage"
msgstr ""

#: templates/users.php:95
msgid "change display name"
msgstr ""

#: templates/users.php:99
msgid "set new password"
msgstr ""

#: templates/users.php:134
msgid "Default"
msgstr ""
a> 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
<?php
/**
 * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file. */

namespace Test\Files;

use OC\Cache\CappedMemoryCache;
use OC\Files\Cache\Watcher;
use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
use OC\Files\SetupManager;
use OC\Files\Storage\Common;
use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OC\Files\View;
use OCP\Constants;
use OCP\Files\Config\IMountProvider;
use OCP\Files\FileInfo;
use OCP\Files\GenericFileException;
use OCP\Files\Mount\IMountManager;
use OCP\Files\Storage\IStorage;
use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
use OCP\Share\IShare;
use OCP\Util;
use Test\HookHelper;
use Test\TestMoveableMountPoint;
use Test\Traits\UserTrait;

class TemporaryNoTouch extends Temporary {
	public function touch($path, $mtime = null) {
		return false;
	}
}

class TemporaryNoCross extends Temporary {
	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = null) {
		return Common::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime);
	}

	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
		return Common::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
	}
}

class TemporaryNoLocal extends Temporary {
	public function instanceOfStorage($className) {
		if ($className === '\OC\Files\Storage\Local') {
			return false;
		} else {
			return parent::instanceOfStorage($className);
		}
	}
}

/**
 * Class ViewTest
 *
 * @group DB
 *
 * @package Test\Files
 */
class ViewTest extends \Test\TestCase {
	use UserTrait;

	/**
	 * @var \OC\Files\Storage\Storage[] $storages
	 */
	private $storages = [];

	/**
	 * @var string
	 */
	private $user;

	/**
	 * @var \OCP\IUser
	 */
	private $userObject;

	/**
	 * @var \OCP\IGroup
	 */
	private $groupObject;

	/** @var \OC\Files\Storage\Storage */
	private $tempStorage;

	protected function setUp(): void {
		parent::setUp();
		\OC_Hook::clear();

		\OC_User::clearBackends();
		\OC_User::useBackend(new \Test\Util\User\Dummy());

		//login
		$userManager = \OC::$server->getUserManager();
		$groupManager = \OC::$server->getGroupManager();
		$this->user = 'test';
		$this->userObject = $userManager->createUser('test', 'test');

		$this->groupObject = $groupManager->createGroup('group1');
		$this->groupObject->addUser($this->userObject);

		self::loginAsUser($this->user);

		/** @var IMountManager $manager */
		$manager = \OC::$server->get(IMountManager::class);
		$manager->removeMount('/test');

		$this->tempStorage = null;
	}

	protected function tearDown(): void {
		\OC_User::setUserId($this->user);
		foreach ($this->storages as $storage) {
			$cache = $storage->getCache();
			$ids = $cache->getAll();
			$cache->clear();
		}

		if ($this->tempStorage) {
			system('rm -rf ' . escapeshellarg($this->tempStorage->getDataDir()));
		}

		self::logout();

		/** @var SetupManager $setupManager */
		$setupManager = \OC::$server->get(SetupManager::class);
		$setupManager->setupRoot();

		$this->userObject->delete();
		$this->groupObject->delete();

		$mountProviderCollection = \OC::$server->getMountProviderCollection();
		self::invokePrivate($mountProviderCollection, 'providers', [[]]);

		parent::tearDown();
	}

	/**
	 * @medium
	 */
	public function testCacheAPI() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$storage3 = $this->getTestStorage();
		$root = self::getUniqueID('/');
		Filesystem::mount($storage1, [], $root . '/');
		Filesystem::mount($storage2, [], $root . '/substorage');
		Filesystem::mount($storage3, [], $root . '/folder/anotherstorage');
		$textSize = strlen("dummy file data\n");
		$imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
		$storageSize = $textSize * 2 + $imageSize;

		$storageInfo = $storage3->getCache()->get('');
		$this->assertEquals($storageSize, $storageInfo['size']);

		$rootView = new View($root);

		$cachedData = $rootView->getFileInfo('/foo.txt');
		$this->assertEquals($textSize, $cachedData['size']);
		$this->assertEquals('text/plain', $cachedData['mimetype']);
		$this->assertNotEquals(-1, $cachedData['permissions']);

		$cachedData = $rootView->getFileInfo('/');
		$this->assertEquals($storageSize * 3, $cachedData['size']);
		$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);

		// get cached data excluding mount points
		$cachedData = $rootView->getFileInfo('/', false);
		$this->assertEquals($storageSize, $cachedData['size']);
		$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);

		$cachedData = $rootView->getFileInfo('/folder');
		$this->assertEquals($storageSize + $textSize, $cachedData['size']);
		$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);

		$folderData = $rootView->getDirectoryContent('/');
		/**
		 * expected entries:
		 * folder
		 * foo.png
		 * foo.txt
		 * substorage
		 */
		$this->assertCount(4, $folderData);
		$this->assertEquals('folder', $folderData[0]['name']);
		$this->assertEquals('foo.png', $folderData[1]['name']);
		$this->assertEquals('foo.txt', $folderData[2]['name']);
		$this->assertEquals('substorage', $folderData[3]['name']);

		$this->assertEquals($storageSize + $textSize, $folderData[0]['size']);
		$this->assertEquals($imageSize, $folderData[1]['size']);
		$this->assertEquals($textSize, $folderData[2]['size']);
		$this->assertEquals($storageSize, $folderData[3]['size']);

		$folderData = $rootView->getDirectoryContent('/substorage');
		/**
		 * expected entries:
		 * folder
		 * foo.png
		 * foo.txt
		 */
		$this->assertCount(3, $folderData);
		$this->assertEquals('folder', $folderData[0]['name']);
		$this->assertEquals('foo.png', $folderData[1]['name']);
		$this->assertEquals('foo.txt', $folderData[2]['name']);

		$folderView = new View($root . '/folder');
		$this->assertEquals($rootView->getFileInfo('/folder'), $folderView->getFileInfo('/'));

		$cachedData = $rootView->getFileInfo('/foo.txt');
		$this->assertFalse($cachedData['encrypted']);
		$id = $rootView->putFileInfo('/foo.txt', ['encrypted' => true]);
		$cachedData = $rootView->getFileInfo('/foo.txt');
		$this->assertTrue($cachedData['encrypted']);
		$this->assertEquals($cachedData['fileid'], $id);

		$this->assertFalse($rootView->getFileInfo('/non/existing'));
		$this->assertEquals([], $rootView->getDirectoryContent('/non/existing'));
	}

	/**
	 * @medium
	 */
	public function testGetPath() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$storage3 = $this->getTestStorage();

		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');
		Filesystem::mount($storage3, [], '/folder/anotherstorage');

		$rootView = new View('');


		$cachedData = $rootView->getFileInfo('/foo.txt');
		/** @var int $id1 */
		$id1 = $cachedData['fileid'];
		$this->assertEquals('/foo.txt', $rootView->getPath($id1));

		$cachedData = $rootView->getFileInfo('/substorage/foo.txt');
		/** @var int $id2 */
		$id2 = $cachedData['fileid'];
		$this->assertEquals('/substorage/foo.txt', $rootView->getPath($id2));

		$folderView = new View('/substorage');
		$this->assertEquals('/foo.txt', $folderView->getPath($id2));
	}


	public function testGetPathNotExisting() {
		$this->expectException(\OCP\Files\NotFoundException::class);

		$storage1 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');

		$rootView = new View('');
		$cachedData = $rootView->getFileInfo('/foo.txt');
		/** @var int $id1 */
		$id1 = $cachedData['fileid'];
		$folderView = new View('/substorage');
		$this->assertNull($folderView->getPath($id1));
	}

	/**
	 * @medium
	 */
	public function testMountPointOverwrite() {
		$storage1 = $this->getTestStorage(false);
		$storage2 = $this->getTestStorage();
		$storage1->mkdir('substorage');
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');

		$rootView = new View('');
		$folderContent = $rootView->getDirectoryContent('/');
		$this->assertCount(4, $folderContent);
	}

	public function sharingDisabledPermissionProvider() {
		return [
			['no', '', true],
			['yes', 'group1', false],
		];
	}

	/**
	 * @dataProvider sharingDisabledPermissionProvider
	 */
	public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable) {
		// Reset sharing disabled for users cache
		self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);

		$config = \OC::$server->getConfig();
		$oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no');
		$oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
		$config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups);
		$config->setAppValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList);

		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/mount');

		$view = new View('/');

		$folderContent = $view->getDirectoryContent('');
		$this->assertEquals($expectedShareable, $folderContent[0]->isShareable());

		$folderContent = $view->getDirectoryContent('mount');
		$this->assertEquals($expectedShareable, $folderContent[0]->isShareable());

		$config->setAppValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag);
		$config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList);

		// Reset sharing disabled for users cache
		self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
	}

	public function testCacheIncompleteFolder() {
		$storage1 = $this->getTestStorage(false);
		Filesystem::mount($storage1, [], '/incomplete');
		$rootView = new View('/incomplete');

		$entries = $rootView->getDirectoryContent('/');
		$this->assertCount(3, $entries);

		// /folder will already be in the cache but not scanned
		$entries = $rootView->getDirectoryContent('/folder');
		$this->assertCount(1, $entries);
	}

	public function testAutoScan() {
		$storage1 = $this->getTestStorage(false);
		$storage2 = $this->getTestStorage(false);
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');
		$textSize = strlen("dummy file data\n");

		$rootView = new View('');

		$cachedData = $rootView->getFileInfo('/');
		$this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
		$this->assertEquals(-1, $cachedData['size']);

		$folderData = $rootView->getDirectoryContent('/substorage/folder');
		$this->assertEquals('text/plain', $folderData[0]['mimetype']);
		$this->assertEquals($textSize, $folderData[0]['size']);
	}

	/**
	 * @medium
	 */
	public function testSearch() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$storage3 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');
		Filesystem::mount($storage3, [], '/folder/anotherstorage');

		$rootView = new View('');

		$results = $rootView->search('foo');
		$this->assertCount(6, $results);
		$paths = [];
		foreach ($results as $result) {
			$this->assertEquals($result['path'], Filesystem::normalizePath($result['path']));
			$paths[] = $result['path'];
		}
		$this->assertContains('/foo.txt', $paths);
		$this->assertContains('/foo.png', $paths);
		$this->assertContains('/substorage/foo.txt', $paths);
		$this->assertContains('/substorage/foo.png', $paths);
		$this->assertContains('/folder/anotherstorage/foo.txt', $paths);
		$this->assertContains('/folder/anotherstorage/foo.png', $paths);

		$folderView = new View('/folder');
		$results = $folderView->search('bar');
		$this->assertCount(2, $results);
		$paths = [];
		foreach ($results as $result) {
			$paths[] = $result['path'];
		}
		$this->assertContains('/anotherstorage/folder/bar.txt', $paths);
		$this->assertContains('/bar.txt', $paths);

		$results = $folderView->search('foo');
		$this->assertCount(2, $results);
		$paths = [];
		foreach ($results as $result) {
			$paths[] = $result['path'];
		}
		$this->assertContains('/anotherstorage/foo.txt', $paths);
		$this->assertContains('/anotherstorage/foo.png', $paths);

		$this->assertCount(6, $rootView->searchByMime('text'));
		$this->assertCount(3, $folderView->searchByMime('text'));
	}

	/**
	 * @medium
	 */
	public function testWatcher() {
		$storage1 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		$storage1->getWatcher()->setPolicy(Watcher::CHECK_ALWAYS);

		$rootView = new View('');

		$cachedData = $rootView->getFileInfo('foo.txt');
		$this->assertEquals(16, $cachedData['size']);

		$rootView->putFileInfo('foo.txt', ['storage_mtime' => 10]);
		$storage1->file_put_contents('foo.txt', 'foo');
		clearstatcache();

		$cachedData = $rootView->getFileInfo('foo.txt');
		$this->assertEquals(3, $cachedData['size']);
	}

	/**
	 * @medium
	 */
	public function testCopyBetweenStorageNoCross() {
		$storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
		$storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
		$this->copyBetweenStorages($storage1, $storage2);
	}

	/**
	 * @medium
	 */
	public function testCopyBetweenStorageCross() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$this->copyBetweenStorages($storage1, $storage2);
	}

	/**
	 * @medium
	 */
	public function testCopyBetweenStorageCrossNonLocal() {
		$storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
		$storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
		$this->copyBetweenStorages($storage1, $storage2);
	}

	public function copyBetweenStorages($storage1, $storage2) {
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');

		$rootView = new View('');
		$rootView->mkdir('substorage/emptyfolder');
		$rootView->copy('substorage', 'anotherfolder');
		$this->assertTrue($rootView->is_dir('/anotherfolder'));
		$this->assertTrue($rootView->is_dir('/substorage'));
		$this->assertTrue($rootView->is_dir('/anotherfolder/emptyfolder'));
		$this->assertTrue($rootView->is_dir('/substorage/emptyfolder'));
		$this->assertTrue($rootView->file_exists('/anotherfolder/foo.txt'));
		$this->assertTrue($rootView->file_exists('/anotherfolder/foo.png'));
		$this->assertTrue($rootView->file_exists('/anotherfolder/folder/bar.txt'));
		$this->assertTrue($rootView->file_exists('/substorage/foo.txt'));
		$this->assertTrue($rootView->file_exists('/substorage/foo.png'));
		$this->assertTrue($rootView->file_exists('/substorage/folder/bar.txt'));
	}

	/**
	 * @medium
	 */
	public function testMoveBetweenStorageNoCross() {
		$storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
		$storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
		$this->moveBetweenStorages($storage1, $storage2);
	}

	/**
	 * @medium
	 */
	public function testMoveBetweenStorageCross() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$this->moveBetweenStorages($storage1, $storage2);
	}

	/**
	 * @medium
	 */
	public function testMoveBetweenStorageCrossNonLocal() {
		$storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
		$storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
		$this->moveBetweenStorages($storage1, $storage2);
	}

	public function moveBetweenStorages($storage1, $storage2) {
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');

		$rootView = new View('');
		$rootView->rename('foo.txt', 'substorage/folder/foo.txt');
		$this->assertFalse($rootView->file_exists('foo.txt'));
		$this->assertTrue($rootView->file_exists('substorage/folder/foo.txt'));
		$rootView->rename('substorage/folder', 'anotherfolder');
		$this->assertFalse($rootView->is_dir('substorage/folder'));
		$this->assertTrue($rootView->file_exists('anotherfolder/foo.txt'));
		$this->assertTrue($rootView->file_exists('anotherfolder/bar.txt'));
	}

	/**
	 * @medium
	 */
	public function testUnlink() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');

		$rootView = new View('');
		$rootView->file_put_contents('/foo.txt', 'asd');
		$rootView->file_put_contents('/substorage/bar.txt', 'asd');

		$this->assertTrue($rootView->file_exists('foo.txt'));
		$this->assertTrue($rootView->file_exists('substorage/bar.txt'));

		$this->assertTrue($rootView->unlink('foo.txt'));
		$this->assertTrue($rootView->unlink('substorage/bar.txt'));

		$this->assertFalse($rootView->file_exists('foo.txt'));
		$this->assertFalse($rootView->file_exists('substorage/bar.txt'));
	}

	public function rmdirOrUnlinkDataProvider() {
		return [['rmdir'], ['unlink']];
	}

	/**
	 * @dataProvider rmdirOrUnlinkDataProvider
	 */
	public function testRmdir($method) {
		$storage1 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');

		$rootView = new View('');
		$rootView->mkdir('sub');
		$rootView->mkdir('sub/deep');
		$rootView->file_put_contents('/sub/deep/foo.txt', 'asd');

		$this->assertTrue($rootView->file_exists('sub/deep/foo.txt'));

		$this->assertTrue($rootView->$method('sub'));

		$this->assertFalse($rootView->file_exists('sub'));
	}

	/**
	 * @medium
	 */
	public function testUnlinkRootMustFail() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], '/substorage');

		$rootView = new View('');
		$rootView->file_put_contents('/foo.txt', 'asd');
		$rootView->file_put_contents('/substorage/bar.txt', 'asd');

		$this->assertFalse($rootView->unlink(''));
		$this->assertFalse($rootView->unlink('/'));
		$this->assertFalse($rootView->unlink('substorage'));
		$this->assertFalse($rootView->unlink('/substorage'));
	}

	/**
	 * @medium
	 */
	public function testTouch() {
		$storage = $this->getTestStorage(true, TemporaryNoTouch::class);

		Filesystem::mount($storage, [], '/');

		$rootView = new View('');
		$oldCachedData = $rootView->getFileInfo('foo.txt');

		$rootView->touch('foo.txt', 500);

		$cachedData = $rootView->getFileInfo('foo.txt');
		$this->assertEquals(500, $cachedData['mtime']);
		$this->assertEquals($oldCachedData['storage_mtime'], $cachedData['storage_mtime']);

		$rootView->putFileInfo('foo.txt', ['storage_mtime' => 1000]); //make sure the watcher detects the change
		$rootView->file_put_contents('foo.txt', 'asd');
		$cachedData = $rootView->getFileInfo('foo.txt');
		$this->assertGreaterThanOrEqual($oldCachedData['mtime'], $cachedData['mtime']);
		$this->assertEquals($cachedData['storage_mtime'], $cachedData['mtime']);
	}

	/**
	 * @medium
	 */
	public function testTouchFloat() {
		$storage = $this->getTestStorage(true, TemporaryNoTouch::class);

		Filesystem::mount($storage, [], '/');

		$rootView = new View('');
		$oldCachedData = $rootView->getFileInfo('foo.txt');

		$rootView->touch('foo.txt', 500.5);

		$cachedData = $rootView->getFileInfo('foo.txt');
		$this->assertEquals(500, $cachedData['mtime']);
	}

	/**
	 * @medium
	 */
	public function testViewHooks() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$defaultRoot = Filesystem::getRoot();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], $defaultRoot . '/substorage');
		\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');

		$rootView = new View('');
		$subView = new View($defaultRoot . '/substorage');
		$this->hookPath = null;

		$rootView->file_put_contents('/foo.txt', 'asd');
		$this->assertNull($this->hookPath);

		$subView->file_put_contents('/foo.txt', 'asd');
		$this->assertEquals('/substorage/foo.txt', $this->hookPath);
	}

	private $hookPath;

	public function dummyHook($params) {
		$this->hookPath = $params['path'];
	}

	public function testSearchNotOutsideView() {
		$storage1 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');
		$storage1->rename('folder', 'foo');
		$scanner = $storage1->getScanner();
		$scanner->scan('');

		$view = new View('/foo');

		$result = $view->search('.txt');
		$this->assertCount(1, $result);
	}

	/**
	 * @param bool $scan
	 * @param string $class
	 * @return \OC\Files\Storage\Storage
	 */
	private function getTestStorage($scan = true, $class = Temporary::class) {
		/**
		 * @var \OC\Files\Storage\Storage $storage
		 */
		$storage = new $class([]);
		$textData = "dummy file data\n";
		$imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png');
		$storage->mkdir('folder');
		$storage->file_put_contents('foo.txt', $textData);
		$storage->file_put_contents('foo.png', $imgData);
		$storage->file_put_contents('folder/bar.txt', $textData);

		if ($scan) {
			$scanner = $storage->getScanner();
			$scanner->scan('');
		}
		$this->storages[] = $storage;
		return $storage;
	}

	/**
	 * @medium
	 */
	public function testViewHooksIfRootStartsTheSame() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$defaultRoot = Filesystem::getRoot();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], $defaultRoot . '_substorage');
		\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');

		$subView = new View($defaultRoot . '_substorage');
		$this->hookPath = null;

		$subView->file_put_contents('/foo.txt', 'asd');
		$this->assertNull($this->hookPath);
	}

	private $hookWritePath;
	private $hookCreatePath;
	private $hookUpdatePath;

	public function dummyHookWrite($params) {
		$this->hookWritePath = $params['path'];
	}

	public function dummyHookUpdate($params) {
		$this->hookUpdatePath = $params['path'];
	}

	public function dummyHookCreate($params) {
		$this->hookCreatePath = $params['path'];
	}

	public function testEditNoCreateHook() {
		$storage1 = $this->getTestStorage();
		$storage2 = $this->getTestStorage();
		$defaultRoot = Filesystem::getRoot();
		Filesystem::mount($storage1, [], '/');
		Filesystem::mount($storage2, [], $defaultRoot);
		\OC_Hook::connect('OC_Filesystem', 'post_create', $this, 'dummyHookCreate');
		\OC_Hook::connect('OC_Filesystem', 'post_update', $this, 'dummyHookUpdate');
		\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHookWrite');

		$view = new View($defaultRoot);
		$this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;

		$view->file_put_contents('/asd.txt', 'foo');
		$this->assertEquals('/asd.txt', $this->hookCreatePath);
		$this->assertNull($this->hookUpdatePath);
		$this->assertEquals('/asd.txt', $this->hookWritePath);

		$this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;

		$view->file_put_contents('/asd.txt', 'foo');
		$this->assertNull($this->hookCreatePath);
		$this->assertEquals('/asd.txt', $this->hookUpdatePath);
		$this->assertEquals('/asd.txt', $this->hookWritePath);

		\OC_Hook::clear('OC_Filesystem', 'post_create');
		\OC_Hook::clear('OC_Filesystem', 'post_update');
		\OC_Hook::clear('OC_Filesystem', 'post_write');
	}

	/**
	 * @dataProvider resolvePathTestProvider
	 */
	public function testResolvePath($expected, $pathToTest) {
		$storage1 = $this->getTestStorage();
		Filesystem::mount($storage1, [], '/');

		$view = new View('');

		$result = $view->resolvePath($pathToTest);
		$this->assertEquals($expected, $result[1]);

		$exists = $view->file_exists($pathToTest);
		$this->assertTrue($exists);

		$exists = $view->file_exists($result[1]);
		$this->assertTrue($exists);
	}

	public function resolvePathTestProvider() {
		return [
			['foo.txt', 'foo.txt'],
			['foo.txt', '/foo.txt'],
			['folder', 'folder'],
			['folder', '/folder'],
			['folder', 'folder/'],
			['folder', '/folder/'],
			['folder/bar.txt', 'folder/bar.txt'],
			['folder/bar.txt', '/folder/bar.txt'],
			['', ''],
			['', '/'],
		];
	}

	public function testUTF8Names() {
		$names = ['虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'];

		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');

		$rootView = new View('');
		foreach ($names as $name) {
			$rootView->file_put_contents('/' . $name, 'dummy content');
		}

		$list = $rootView->getDirectoryContent('/');

		$this->assertCount(count($names), $list);
		foreach ($list as $item) {
			$this->assertContains($item['name'], $names);
		}

		$cache = $storage->getCache();
		$scanner = $storage->getScanner();
		$scanner->scan('');

		$list = $cache->getFolderContents('');

		$this->assertCount(count($names), $list);
		foreach ($list as $item) {
			$this->assertContains($item['name'], $names);
		}
	}

	public function xtestLongPath() {
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');

		$rootView = new View('');

		$longPath = '';
		$ds = DIRECTORY_SEPARATOR;
		/*
		 * 4096 is the maximum path length in file_cache.path in *nix
		 * 1024 is the max path length in mac
		 */
		$folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
		$tmpdirLength = strlen(\OC::$server->getTempManager()->getTemporaryFolder());
		if (\OC_Util::runningOnMac()) {
			$depth = ((1024 - $tmpdirLength) / 57);
		} else {
			$depth = ((4000 - $tmpdirLength) / 57);
		}
		foreach (range(0, $depth - 1) as $i) {
			$longPath .= $ds . $folderName;
			$result = $rootView->mkdir($longPath);
			$this->assertTrue($result, "mkdir failed on $i - path length: " . strlen($longPath));

			$result = $rootView->file_put_contents($longPath . "{$ds}test.txt", 'lorem');
			$this->assertEquals(5, $result, "file_put_contents failed on $i");

			$this->assertTrue($rootView->file_exists($longPath));
			$this->assertTrue($rootView->file_exists($longPath . "{$ds}test.txt"));
		}

		$cache = $storage->getCache();
		$scanner = $storage->getScanner();
		$scanner->scan('');

		$longPath = $folderName;
		foreach (range(0, $depth - 1) as $i) {
			$cachedFolder = $cache->get($longPath);
			$this->assertTrue(is_array($cachedFolder), "No cache entry for folder at $i");
			$this->assertEquals($folderName, $cachedFolder['name'], "Wrong cache entry for folder at $i");

			$cachedFile = $cache->get($longPath . '/test.txt');
			$this->assertTrue(is_array($cachedFile), "No cache entry for file at $i");
			$this->assertEquals('test.txt', $cachedFile['name'], "Wrong cache entry for file at $i");

			$longPath .= $ds . $folderName;
		}
	}

	public function testTouchNotSupported() {
		$storage = new TemporaryNoTouch([]);
		$scanner = $storage->getScanner();
		Filesystem::mount($storage, [], '/test/');
		$past = time() - 100;
		$storage->file_put_contents('test', 'foobar');
		$scanner->scan('');
		$view = new View('');
		$info = $view->getFileInfo('/test/test');

		$view->touch('/test/test', $past);
		$scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG);

		$info2 = $view->getFileInfo('/test/test');
		$this->assertSame($info['etag'], $info2['etag']);
	}

	public function testWatcherEtagCrossStorage() {
		$storage1 = new Temporary([]);
		$storage2 = new Temporary([]);
		$scanner1 = $storage1->getScanner();
		$scanner2 = $storage2->getScanner();
		$storage1->mkdir('sub');
		Filesystem::mount($storage1, [], '/test/');
		Filesystem::mount($storage2, [], '/test/sub/storage');

		$past = time() - 100;
		$storage2->file_put_contents('test.txt', 'foobar');
		$scanner1->scan('');
		$scanner2->scan('');
		$view = new View('');

		$storage2->getWatcher('')->setPolicy(Watcher::CHECK_ALWAYS);

		$oldFileInfo = $view->getFileInfo('/test/sub/storage/test.txt');
		$oldFolderInfo = $view->getFileInfo('/test');

		$storage2->getCache()->update($oldFileInfo->getId(), [
			'storage_mtime' => $past,
		]);

		$oldEtag = $oldFolderInfo->getEtag();

		$view->getFileInfo('/test/sub/storage/test.txt');
		$newFolderInfo = $view->getFileInfo('/test');

		$this->assertNotEquals($newFolderInfo->getEtag(), $oldEtag);
	}

	/**
	 * @dataProvider absolutePathProvider
	 */
	public function testGetAbsolutePath($expectedPath, $relativePath) {
		$view = new View('/files');
		$this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
	}

	public function testPartFileInfo() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		Filesystem::mount($storage, [], '/test/');
		$storage->file_put_contents('test.part', 'foobar');
		$scanner->scan('');
		$view = new View('/test');
		$info = $view->getFileInfo('test.part');

		$this->assertInstanceOf('\OCP\Files\FileInfo', $info);
		$this->assertNull($info->getId());
		$this->assertEquals(6, $info->getSize());
	}

	public function absolutePathProvider() {
		return [
			['/files/', ''],
			['/files/0', '0'],
			['/files/false', 'false'],
			['/files/true', 'true'],
			['/files/', '/'],
			['/files/test', 'test'],
			['/files/test', '/test'],
		];
	}

	/**
	 * @dataProvider chrootRelativePathProvider
	 */
	public function testChrootGetRelativePath($root, $absolutePath, $expectedPath) {
		$view = new View('/files');
		$view->chroot($root);
		$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
	}

	public function chrootRelativePathProvider() {
		return $this->relativePathProvider('/');
	}

	/**
	 * @dataProvider initRelativePathProvider
	 */
	public function testInitGetRelativePath($root, $absolutePath, $expectedPath) {
		$view = new View($root);
		$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
	}

	public function initRelativePathProvider() {
		return $this->relativePathProvider(null);
	}

	public function relativePathProvider($missingRootExpectedPath) {
		return [
			// No root - returns the path
			['', '/files', '/files'],
			['', '/files/', '/files/'],

			// Root equals path - /
			['/files/', '/files/', '/'],
			['/files/', '/files', '/'],
			['/files', '/files/', '/'],
			['/files', '/files', '/'],

			// False negatives: chroot fixes those by adding the leading slash.
			// But setting them up with this root (instead of chroot($root))
			// will fail them, although they should be the same.
			// TODO init should be fixed, so it also adds the leading slash
			['files/', '/files/', $missingRootExpectedPath],
			['files', '/files/', $missingRootExpectedPath],
			['files/', '/files', $missingRootExpectedPath],
			['files', '/files', $missingRootExpectedPath],

			// False negatives: Paths provided to the method should have a leading slash
			// TODO input should be checked to have a leading slash
			['/files/', 'files/', null],
			['/files', 'files/', null],
			['/files/', 'files', null],
			['/files', 'files', null],

			// with trailing slashes
			['/files/', '/files/0', '0'],
			['/files/', '/files/false', 'false'],
			['/files/', '/files/true', 'true'],
			['/files/', '/files/test', 'test'],
			['/files/', '/files/test/foo', 'test/foo'],

			// without trailing slashes
			// TODO false expectation: Should match "with trailing slashes"
			['/files', '/files/0', '/0'],
			['/files', '/files/false', '/false'],
			['/files', '/files/true', '/true'],
			['/files', '/files/test', '/test'],
			['/files', '/files/test/foo', '/test/foo'],

			// leading slashes
			['/files/', '/files_trashbin/', null],
			['/files', '/files_trashbin/', null],
			['/files/', '/files_trashbin', null],
			['/files', '/files_trashbin', null],

			// no leading slashes
			['files/', 'files_trashbin/', null],
			['files', 'files_trashbin/', null],
			['files/', 'files_trashbin', null],
			['files', 'files_trashbin', null],

			// mixed leading slashes
			['files/', '/files_trashbin/', null],
			['/files/', 'files_trashbin/', null],
			['files', '/files_trashbin/', null],
			['/files', 'files_trashbin/', null],
			['files/', '/files_trashbin', null],
			['/files/', 'files_trashbin', null],
			['files', '/files_trashbin', null],
			['/files', 'files_trashbin', null],

			['files', 'files_trashbin/test', null],
			['/files', '/files_trashbin/test', null],
			['/files', 'files_trashbin/test', null],
		];
	}

	public function testFileView() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$storage->file_put_contents('foo.txt', 'bar');
		Filesystem::mount($storage, [], '/test/');
		$scanner->scan('');
		$view = new View('/test/foo.txt');

		$this->assertEquals('bar', $view->file_get_contents(''));
		$fh = tmpfile();
		fwrite($fh, 'foo');
		rewind($fh);
		$view->file_put_contents('', $fh);
		$this->assertEquals('foo', $view->file_get_contents(''));
	}

	/**
	 * @dataProvider tooLongPathDataProvider
	 */
	public function testTooLongPath($operation, $param0 = null) {
		$this->expectException(\OCP\Files\InvalidPathException::class);


		$longPath = '';
		// 4000 is the maximum path length in file_cache.path
		$folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
		$depth = (4000 / 57);
		foreach (range(0, $depth + 1) as $i) {
			$longPath .= '/' . $folderName;
		}

		$storage = new Temporary([]);
		$this->tempStorage = $storage; // for later hard cleanup
		Filesystem::mount($storage, [], '/');

		$rootView = new View('');

		if ($param0 === '@0') {
			$param0 = $longPath;
		}

		if ($operation === 'hash') {
			$param0 = $longPath;
			$longPath = 'md5';
		}

		call_user_func([$rootView, $operation], $longPath, $param0);
	}

	public function tooLongPathDataProvider() {
		return [
			['getAbsolutePath'],
			['getRelativePath'],
			['getMountPoint'],
			['resolvePath'],
			['getLocalFile'],
			['getLocalFolder'],
			['mkdir'],
			['rmdir'],
			['opendir'],
			['is_dir'],
			['is_file'],
			['stat'],
			['filetype'],
			['filesize'],
			['readfile'],
			['isCreatable'],
			['isReadable'],
			['isUpdatable'],
			['isDeletable'],
			['isSharable'],
			['file_exists'],
			['filemtime'],
			['touch'],
			['file_get_contents'],
			['unlink'],
			['deleteAll'],
			['toTmpFile'],
			['getMimeType'],
			['free_space'],
			['getFileInfo'],
			['getDirectoryContent'],
			['getOwner'],
			['getETag'],
			['file_put_contents', 'ipsum'],
			['rename', '@0'],
			['copy', '@0'],
			['fopen', 'r'],
			['fromTmpFile', '@0'],
			['hash'],
			['hasUpdated', 0],
			['putFileInfo', []],
		];
	}

	public function testRenameCrossStoragePreserveMtime() {
		$storage1 = new Temporary([]);
		$storage2 = new Temporary([]);
		$storage1->mkdir('sub');
		$storage1->mkdir('foo');
		$storage1->file_put_contents('foo.txt', 'asd');
		$storage1->file_put_contents('foo/bar.txt', 'asd');
		Filesystem::mount($storage1, [], '/test/');
		Filesystem::mount($storage2, [], '/test/sub/storage');

		$view = new View('');
		$time = time() - 200;
		$view->touch('/test/foo.txt', $time);
		$view->touch('/test/foo', $time);
		$view->touch('/test/foo/bar.txt', $time);

		$view->rename('/test/foo.txt', '/test/sub/storage/foo.txt');

		$this->assertEquals($time, $view->filemtime('/test/sub/storage/foo.txt'));

		$view->rename('/test/foo', '/test/sub/storage/foo');

		$this->assertEquals($time, $view->filemtime('/test/sub/storage/foo/bar.txt'));
	}

	public function testRenameFailDeleteTargetKeepSource() {
		$this->doTestCopyRenameFail('rename');
	}

	public function testCopyFailDeleteTargetKeepSource() {
		$this->doTestCopyRenameFail('copy');
	}

	private function doTestCopyRenameFail($operation) {
		$storage1 = new Temporary([]);
		/** @var \PHPUnit\Framework\MockObject\MockObject|Temporary $storage2 */
		$storage2 = $this->getMockBuilder(TemporaryNoCross::class)
			->setConstructorArgs([[]])
			->setMethods(['fopen', 'writeStream'])
			->getMock();

		$storage2->method('writeStream')
			->willThrowException(new GenericFileException("Failed to copy stream"));

		$storage1->mkdir('sub');
		$storage1->file_put_contents('foo.txt', '0123456789ABCDEFGH');
		$storage1->mkdir('dirtomove');
		$storage1->file_put_contents('dirtomove/indir1.txt', '0123456'); // fits
		$storage1->file_put_contents('dirtomove/indir2.txt', '0123456789ABCDEFGH'); // doesn't fit
		$storage2->file_put_contents('existing.txt', '0123');
		$storage1->getScanner()->scan('');
		$storage2->getScanner()->scan('');
		Filesystem::mount($storage1, [], '/test/');
		Filesystem::mount($storage2, [], '/test/sub/storage');

		// move file
		$view = new View('');
		$this->assertTrue($storage1->file_exists('foo.txt'));
		$this->assertFalse($storage2->file_exists('foo.txt'));
		$this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/foo.txt'));
		$this->assertFalse($storage2->file_exists('foo.txt'));
		$this->assertFalse($storage2->getCache()->get('foo.txt'));
		$this->assertTrue($storage1->file_exists('foo.txt'));

		// if target exists, it will be deleted too
		$this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/existing.txt'));
		$this->assertFalse($storage2->file_exists('existing.txt'));
		$this->assertFalse($storage2->getCache()->get('existing.txt'));
		$this->assertTrue($storage1->file_exists('foo.txt'));

		// move folder
		$this->assertFalse($view->$operation('/test/dirtomove/', '/test/sub/storage/dirtomove/'));
		// since the move failed, the full source tree is kept
		$this->assertTrue($storage1->file_exists('dirtomove/indir1.txt'));
		$this->assertTrue($storage1->file_exists('dirtomove/indir2.txt'));
		// second file not moved/copied
		$this->assertFalse($storage2->file_exists('dirtomove/indir2.txt'));
		$this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
	}

	public function testDeleteFailKeepCache() {
		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setConstructorArgs([[]])
			->setMethods(['unlink'])
			->getMock();
		$storage->expects($this->once())
			->method('unlink')
			->willReturn(false);
		$scanner = $storage->getScanner();
		$cache = $storage->getCache();
		$storage->file_put_contents('foo.txt', 'asd');
		$scanner->scan('');
		Filesystem::mount($storage, [], '/test/');

		$view = new View('/test');

		$this->assertFalse($view->unlink('foo.txt'));
		$this->assertTrue($cache->inCache('foo.txt'));
	}

	public function directoryTraversalProvider() {
		return [
			['../test/'],
			['..\\test\\my/../folder'],
			['/test/my/../foo\\'],
		];
	}

	/**
	 * @dataProvider directoryTraversalProvider
	 * @param string $root
	 */
	public function testConstructDirectoryTraversalException($root) {
		$this->expectException(\Exception::class);

		new View($root);
	}

	public function testRenameOverWrite() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$storage->mkdir('sub');
		$storage->mkdir('foo');
		$storage->file_put_contents('foo.txt', 'asd');
		$storage->file_put_contents('foo/bar.txt', 'asd');
		$scanner->scan('');
		Filesystem::mount($storage, [], '/test/');
		$view = new View('');
		$this->assertTrue($view->rename('/test/foo.txt', '/test/foo/bar.txt'));
	}

	public function testSetMountOptionsInStorage() {
		$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
		Filesystem::getMountManager()->addMount($mount);
		/** @var \OC\Files\Storage\Common $storage */
		$storage = $mount->getStorage();
		$this->assertEquals($storage->getMountOption('foo'), 'bar');
	}

	public function testSetMountOptionsWatcherPolicy() {
		$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
		Filesystem::getMountManager()->addMount($mount);
		/** @var \OC\Files\Storage\Common $storage */
		$storage = $mount->getStorage();
		$watcher = $storage->getWatcher();
		$this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
	}

	public function testGetAbsolutePathOnNull() {
		$view = new View();
		$this->assertNull($view->getAbsolutePath(null));
	}

	public function testGetRelativePathOnNull() {
		$view = new View();
		$this->assertNull($view->getRelativePath(null));
	}


	public function testNullAsRoot() {
		$this->expectException(\InvalidArgumentException::class);

		new View(null);
	}

	/**
	 * e.g. reading from a folder that's being renamed
	 *
	 *
	 * @dataProvider dataLockPaths
	 *
	 * @param string $rootPath
	 * @param string $pathPrefix
	 */
	public function testReadFromWriteLockedPath($rootPath, $pathPrefix) {
		$this->expectException(\OCP\Lock\LockedException::class);

		$rootPath = str_replace('{folder}', 'files', $rootPath);
		$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);

		$view = new View($rootPath);
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
		$view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED);
	}

	/**
	 * Reading from a files_encryption folder that's being renamed
	 *
	 * @dataProvider dataLockPaths
	 *
	 * @param string $rootPath
	 * @param string $pathPrefix
	 */
	public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix) {
		$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
		$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);

		$view = new View($rootPath);
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
		$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED));
	}

	/**
	 * e.g. writing a file that's being downloaded
	 *
	 *
	 * @dataProvider dataLockPaths
	 *
	 * @param string $rootPath
	 * @param string $pathPrefix
	 */
	public function testWriteToReadLockedFile($rootPath, $pathPrefix) {
		$this->expectException(\OCP\Lock\LockedException::class);

		$rootPath = str_replace('{folder}', 'files', $rootPath);
		$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);

		$view = new View($rootPath);
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
		$view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE);
	}

	/**
	 * Writing a file that's being downloaded
	 *
	 * @dataProvider dataLockPaths
	 *
	 * @param string $rootPath
	 * @param string $pathPrefix
	 */
	public function testWriteToReadUnlockableFile($rootPath, $pathPrefix) {
		$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
		$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);

		$view = new View($rootPath);
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
		$this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
	}

	/**
	 * Test that locks are on mount point paths instead of mount root
	 */
	public function testLockLocalMountPointPathInsteadOfStorageRoot() {
		$lockingProvider = \OC::$server->getLockingProvider();
		$view = new View('/testuser/files/');
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$mountedStorage = new Temporary([]);
		Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');

		$this->assertTrue(
			$view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, true),
			'Can lock mount point'
		);

		// no exception here because storage root was not locked
		$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);

		$thrown = false;
		try {
			$storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
		} catch (LockedException $e) {
			$thrown = true;
		}
		$this->assertTrue($thrown, 'Mount point path was locked on root storage');

		$lockingProvider->releaseAll();
	}

	/**
	 * Test that locks are on mount point paths and also mount root when requested
	 */
	public function testLockStorageRootButNotLocalMountPoint() {
		$lockingProvider = \OC::$server->getLockingProvider();
		$view = new View('/testuser/files/');
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$mountedStorage = new Temporary([]);
		Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');

		$this->assertTrue(
			$view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, false),
			'Can lock mount point'
		);

		$thrown = false;
		try {
			$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
		} catch (LockedException $e) {
			$thrown = true;
		}
		$this->assertTrue($thrown, 'Mount point storage root was locked on original storage');

		// local mount point was not locked
		$storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);

		$lockingProvider->releaseAll();
	}

	/**
	 * Test that locks are on mount point paths and also mount root when requested
	 */
	public function testLockMountPointPathFailReleasesBoth() {
		$lockingProvider = \OC::$server->getLockingProvider();
		$view = new View('/testuser/files/');
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');
		$mountedStorage = new Temporary([]);
		Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint.txt');

		// this would happen if someone is writing on the mount point
		$mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);

		$thrown = false;
		try {
			// this actually acquires two locks, one on the mount point and one on the storage root,
			// but the one on the storage root will fail
			$view->lockFile('/mountpoint.txt', ILockingProvider::LOCK_SHARED);
		} catch (LockedException $e) {
			$thrown = true;
		}
		$this->assertTrue($thrown, 'Cannot acquire shared lock because storage root is already locked');

		// from here we expect that the lock on the local mount point was released properly
		// so acquiring an exclusive lock will succeed
		$storage->acquireLock('/testuser/files/mountpoint.txt', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);

		$lockingProvider->releaseAll();
	}

	public function dataLockPaths() {
		return [
			['/testuser/{folder}', ''],
			['/testuser', '/{folder}'],
			['', '/testuser/{folder}'],
		];
	}

	public function pathRelativeToFilesProvider() {
		return [
			['admin/files', ''],
			['admin/files/x', 'x'],
			['/admin/files', ''],
			['/admin/files/sub', 'sub'],
			['/admin/files/sub/', 'sub'],
			['/admin/files/sub/sub2', 'sub/sub2'],
			['//admin//files/sub//sub2', 'sub/sub2'],
		];
	}

	/**
	 * @dataProvider pathRelativeToFilesProvider
	 */
	public function testGetPathRelativeToFiles($path, $expectedPath) {
		$view = new View();
		$this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
	}

	public function pathRelativeToFilesProviderExceptionCases() {
		return [
			[''],
			['x'],
			['files'],
			['/files'],
			['/admin/files_versions/abc'],
		];
	}

	/**
	 * @dataProvider pathRelativeToFilesProviderExceptionCases
	 * @param string $path
	 */
	public function testGetPathRelativeToFilesWithInvalidArgument($path) {
		$this->expectException(\InvalidArgumentException::class);
		$this->expectExceptionMessage('$absolutePath must be relative to "files"');

		$view = new View();
		$view->getPathRelativeToFiles($path);
	}

	public function testChangeLock() {
		$view = new View('/testuser/files/');
		$storage = new Temporary([]);
		Filesystem::mount($storage, [], '/');

		$view->lockFile('/test/sub', ILockingProvider::LOCK_SHARED);
		$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
		$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));

		$view->changeLock('//test/sub', ILockingProvider::LOCK_EXCLUSIVE);
		$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));

		$view->changeLock('test/sub', ILockingProvider::LOCK_SHARED);
		$this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));

		$view->unlockFile('/test/sub/', ILockingProvider::LOCK_SHARED);

		$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
		$this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
	}

	public function hookPathProvider() {
		return [
			['/foo/files', '/foo', true],
			['/foo/files/bar', '/foo', true],
			['/foo', '/foo', false],
			['/foo', '/files/foo', true],
			['/foo', 'filesfoo', false],
			['', '/foo/files', true],
			['', '/foo/files/bar.txt', true],
		];
	}

	/**
	 * @dataProvider hookPathProvider
	 * @param $root
	 * @param $path
	 * @param $shouldEmit
	 */
	public function testHookPaths($root, $path, $shouldEmit) {
		$filesystemReflection = new \ReflectionClass(Filesystem::class);
		$defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
		$defaultRootValue->setAccessible(true);
		$oldRoot = $defaultRootValue->getValue();
		$defaultView = new View('/foo/files');
		$defaultRootValue->setValue($defaultView);
		$view = new View($root);
		$result = self::invokePrivate($view, 'shouldEmitHooks', [$path]);
		$defaultRootValue->setValue($oldRoot);
		$this->assertEquals($shouldEmit, $result);
	}

	/**
	 * Create test movable mount points
	 *
	 * @param array $mountPoints array of mount point locations
	 * @return array array of MountPoint objects
	 */
	private function createTestMovableMountPoints($mountPoints) {
		$mounts = [];
		foreach ($mountPoints as $mountPoint) {
			$storage = $this->getMockBuilder(Storage::class)
				->setMethods([])
				->setConstructorArgs([[]])
				->getMock();
			$storage->method('getId')->willReturn('non-null-id');

			$mounts[] = $this->getMockBuilder(TestMoveableMountPoint::class)
				->setMethods(['moveMount'])
				->setConstructorArgs([$storage, $mountPoint])
				->getMock();
		}

		/** @var IMountProvider|\PHPUnit\Framework\MockObject\MockObject $mountProvider */
		$mountProvider = $this->createMock(IMountProvider::class);
		$mountProvider->expects($this->any())
			->method('getMountsForUser')
			->willReturn($mounts);

		$mountProviderCollection = \OC::$server->getMountProviderCollection();
		$mountProviderCollection->registerProvider($mountProvider);

		return $mounts;
	}

	/**
	 * Test mount point move
	 */
	public function testMountPointMove() {
		self::loginAsUser($this->user);

		[$mount1, $mount2] = $this->createTestMovableMountPoints([
			$this->user . '/files/mount1',
			$this->user . '/files/mount2',
		]);
		$mount1->expects($this->once())
			->method('moveMount')
			->willReturn(true);

		$mount2->expects($this->once())
			->method('moveMount')
			->willReturn(true);

		$view = new View('/' . $this->user . '/files/');
		$view->mkdir('sub');

		$this->assertTrue($view->rename('mount1', 'renamed_mount'), 'Can rename mount point');
		$this->assertTrue($view->rename('mount2', 'sub/moved_mount'), 'Can move a mount point into a subdirectory');
	}

	/**
	 * Test that moving a mount point into another is forbidden
	 */
	public function testMoveMountPointIntoAnother() {
		self::loginAsUser($this->user);

		[$mount1, $mount2] = $this->createTestMovableMountPoints([
			$this->user . '/files/mount1',
			$this->user . '/files/mount2',
		]);

		$mount1->expects($this->never())
			->method('moveMount');

		$mount2->expects($this->never())
			->method('moveMount');

		$view = new View('/' . $this->user . '/files/');

		$this->assertFalse($view->rename('mount1', 'mount2'), 'Cannot overwrite another mount point');
		$this->assertFalse($view->rename('mount1', 'mount2/sub'), 'Cannot move a mount point into another');
	}

	/**
	 * Test that moving a mount point into a shared folder is forbidden
	 */
	public function testMoveMountPointIntoSharedFolder() {
		self::loginAsUser($this->user);

		[$mount1] = $this->createTestMovableMountPoints([
			$this->user . '/files/mount1',
		]);

		$mount1->expects($this->never())
			->method('moveMount');

		$view = new View('/' . $this->user . '/files/');
		$view->mkdir('shareddir');
		$view->mkdir('shareddir/sub');
		$view->mkdir('shareddir/sub2');

		$fileId = $view->getFileInfo('shareddir')->getId();
		$userObject = \OC::$server->getUserManager()->createUser('test2', 'IHateNonMockableStaticClasses');

		$userFolder = \OC::$server->getUserFolder($this->user);
		$shareDir = $userFolder->get('shareddir');
		$shareManager = \OC::$server->getShareManager();
		$share = $shareManager->newShare();
		$share->setSharedWith('test2')
			->setSharedBy($this->user)
			->setShareType(IShare::TYPE_USER)
			->setPermissions(\OCP\Constants::PERMISSION_READ)
			->setId(42)
			->setProviderId('foo')
			->setNode($shareDir);
		$shareManager->createShare($share);

		$this->assertFalse($view->rename('mount1', 'shareddir'), 'Cannot overwrite shared folder');
		$this->assertFalse($view->rename('mount1', 'shareddir/sub'), 'Cannot move mount point into shared folder');
		$this->assertFalse($view->rename('mount1', 'shareddir/sub/sub2'), 'Cannot move mount point into shared subfolder');

		$shareManager->deleteShare($share);
		$userObject->delete();
	}

	public function basicOperationProviderForLocks() {
		return [
			// --- write hook ----
			[
				'touch',
				['touch-create.txt'],
				'touch-create.txt',
				'create',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				ILockingProvider::LOCK_SHARED,
			],
			[
				'fopen',
				['test-write.txt', 'w'],
				'test-write.txt',
				'write',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				null,
				// exclusive lock stays until fclose
				ILockingProvider::LOCK_EXCLUSIVE,
			],
			[
				'mkdir',
				['newdir'],
				'newdir',
				'write',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				ILockingProvider::LOCK_SHARED,
			],
			[
				'file_put_contents',
				['file_put_contents.txt', 'blah'],
				'file_put_contents.txt',
				'write',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				ILockingProvider::LOCK_SHARED,
			],

			// ---- delete hook ----
			[
				'rmdir',
				['dir'],
				'dir',
				'delete',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				ILockingProvider::LOCK_SHARED,
			],
			[
				'unlink',
				['test.txt'],
				'test.txt',
				'delete',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_EXCLUSIVE,
				ILockingProvider::LOCK_SHARED,
			],

			// ---- read hook (no post hooks) ----
			[
				'file_get_contents',
				['test.txt'],
				'test.txt',
				'read',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_SHARED,
				null,
			],
			[
				'fopen',
				['test.txt', 'r'],
				'test.txt',
				'read',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_SHARED,
				null,
			],
			[
				'opendir',
				['dir'],
				'dir',
				'read',
				ILockingProvider::LOCK_SHARED,
				ILockingProvider::LOCK_SHARED,
				null,
			],

			// ---- no lock, touch hook ---
			['touch', ['test.txt'], 'test.txt', 'touch', null, null, null],

			// ---- no hooks, no locks ---
			['is_dir', ['dir'], 'dir', null],
			['is_file', ['dir'], 'dir', null],
			['stat', ['dir'], 'dir', null],
			['filetype', ['dir'], 'dir', null],
			['filesize', ['dir'], 'dir', null],
			['isCreatable', ['dir'], 'dir', null],
			['isReadable', ['dir'], 'dir', null],
			['isUpdatable', ['dir'], 'dir', null],
			['isDeletable', ['dir'], 'dir', null],
			['isSharable', ['dir'], 'dir', null],
			['file_exists', ['dir'], 'dir', null],
			['filemtime', ['dir'], 'dir', null],
		];
	}

	/**
	 * Test whether locks are set before and after the operation
	 *
	 * @dataProvider basicOperationProviderForLocks
	 *
	 * @param string $operation operation name on the view
	 * @param array $operationArgs arguments for the operation
	 * @param string $lockedPath path of the locked item to check
	 * @param string $hookType hook type
	 * @param int $expectedLockBefore expected lock during pre hooks
	 * @param int $expectedLockDuring expected lock during operation
	 * @param int $expectedLockAfter expected lock during post hooks
	 * @param int $expectedStrayLock expected lock after returning, should
	 * be null (unlock) for most operations
	 */
	public function testLockBasicOperation(
		$operation,
		$operationArgs,
		$lockedPath,
		$hookType,
		$expectedLockBefore = ILockingProvider::LOCK_SHARED,
		$expectedLockDuring = ILockingProvider::LOCK_SHARED,
		$expectedLockAfter = ILockingProvider::LOCK_SHARED,
		$expectedStrayLock = null
	) {
		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods([$operation])
			->getMock();

		Filesystem::mount($storage, [], $this->user . '/');

		// work directly on disk because mkdir might be mocked
		$realPath = $storage->getSourcePath('');
		mkdir($realPath . '/files');
		mkdir($realPath . '/files/dir');
		file_put_contents($realPath . '/files/test.txt', 'blah');
		$storage->getScanner()->scan('files');

		$storage->expects($this->once())
			->method($operation)
			->willReturnCallback(
				function () use ($view, $lockedPath, &$lockTypeDuring) {
					$lockTypeDuring = $this->getFileLockType($view, $lockedPath);

					return true;
				}
			);

		$this->assertNull($this->getFileLockType($view, $lockedPath), 'File not locked before operation');

		$this->connectMockHooks($hookType, $view, $lockedPath, $lockTypePre, $lockTypePost);

		// do operation
		call_user_func_array([$view, $operation], $operationArgs);

		if ($hookType !== null) {
			$this->assertEquals($expectedLockBefore, $lockTypePre, 'File locked properly during pre-hook');
			$this->assertEquals($expectedLockAfter, $lockTypePost, 'File locked properly during post-hook');
			$this->assertEquals($expectedLockDuring, $lockTypeDuring, 'File locked properly during operation');
		} else {
			$this->assertNull($lockTypeDuring, 'File not locked during operation');
		}

		$this->assertEquals($expectedStrayLock, $this->getFileLockType($view, $lockedPath));
	}

	/**
	 * Test locks for file_put_content with stream.
	 * This code path uses $storage->fopen instead
	 */
	public function testLockFilePutContentWithStream() {
		$view = new View('/' . $this->user . '/files/');

		$path = 'test_file_put_contents.txt';
		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods(['fopen'])
			->getMock();

		Filesystem::mount($storage, [], $this->user . '/');
		$storage->mkdir('files');

		$storage->expects($this->once())
			->method('fopen')
			->willReturnCallback(
				function () use ($view, $path, &$lockTypeDuring) {
					$lockTypeDuring = $this->getFileLockType($view, $path);

					return fopen('php://temp', 'r+');
				}
			);

		$this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);

		$this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');

		// do operation
		$view->file_put_contents($path, fopen('php://temp', 'r+'));

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePost, 'File locked properly during post-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');

		$this->assertNull($this->getFileLockType($view, $path));
	}

	/**
	 * Test locks for fopen with fclose at the end
	 */
	public function testLockFopen() {
		$view = new View('/' . $this->user . '/files/');

		$path = 'test_file_put_contents.txt';
		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods(['fopen'])
			->getMock();

		Filesystem::mount($storage, [], $this->user . '/');
		$storage->mkdir('files');

		$storage->expects($this->once())
			->method('fopen')
			->willReturnCallback(
				function () use ($view, $path, &$lockTypeDuring) {
					$lockTypeDuring = $this->getFileLockType($view, $path);

					return fopen('php://temp', 'r+');
				}
			);

		$this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);

		$this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');

		// do operation
		$res = $view->fopen($path, 'w');

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
		$this->assertNull($lockTypePost, 'No post hook, no lock check possible');

		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File still locked after fopen');

		fclose($res);

		$this->assertNull($this->getFileLockType($view, $path), 'File unlocked after fclose');
	}

	/**
	 * Test locks for fopen with fclose at the end
	 *
	 * @dataProvider basicOperationProviderForLocks
	 *
	 * @param string $operation operation name on the view
	 * @param array $operationArgs arguments for the operation
	 * @param string $path path of the locked item to check
	 */
	public function testLockBasicOperationUnlocksAfterException(
		$operation,
		$operationArgs,
		$path
	) {
		if ($operation === 'touch') {
			$this->markTestSkipped("touch handles storage exceptions internally");
		}
		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods([$operation])
			->getMock();

		Filesystem::mount($storage, [], $this->user . '/');

		// work directly on disk because mkdir might be mocked
		$realPath = $storage->getSourcePath('');
		mkdir($realPath . '/files');
		mkdir($realPath . '/files/dir');
		file_put_contents($realPath . '/files/test.txt', 'blah');
		$storage->getScanner()->scan('files');

		$storage->expects($this->once())
			->method($operation)
			->willReturnCallback(
				function () {
					throw new \Exception('Simulated exception');
				}
			);

		$thrown = false;
		try {
			call_user_func_array([$view, $operation], $operationArgs);
		} catch (\Exception $e) {
			$thrown = true;
			$this->assertEquals('Simulated exception', $e->getMessage());
		}
		$this->assertTrue($thrown, 'Exception was rethrown');
		$this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
	}

	public function testLockBasicOperationUnlocksAfterLockException() {
		$view = new View('/' . $this->user . '/files/');

		$storage = new Temporary([]);

		Filesystem::mount($storage, [], $this->user . '/');

		$storage->mkdir('files');
		$storage->mkdir('files/dir');
		$storage->file_put_contents('files/test.txt', 'blah');
		$storage->getScanner()->scan('files');

		// get a shared lock
		$handle = $view->fopen('test.txt', 'r');

		$thrown = false;
		try {
			// try (and fail) to get a write lock
			$view->unlink('test.txt');
		} catch (\Exception $e) {
			$thrown = true;
			$this->assertInstanceOf(LockedException::class, $e);
		}
		$this->assertTrue($thrown, 'Exception was rethrown');

		// clean shared lock
		fclose($handle);

		$this->assertNull($this->getFileLockType($view, 'test.txt'), 'File got unlocked');
	}

	/**
	 * Test locks for fopen with fclose at the end
	 *
	 * @dataProvider basicOperationProviderForLocks
	 *
	 * @param string $operation operation name on the view
	 * @param array $operationArgs arguments for the operation
	 * @param string $path path of the locked item to check
	 * @param string $hookType hook type
	 */
	public function testLockBasicOperationUnlocksAfterCancelledHook(
		$operation,
		$operationArgs,
		$path,
		$hookType
	) {
		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods([$operation])
			->getMock();

		Filesystem::mount($storage, [], $this->user . '/');
		$storage->mkdir('files');

		Util::connectHook(
			Filesystem::CLASSNAME,
			$hookType,
			HookHelper::class,
			'cancellingCallback'
		);

		call_user_func_array([$view, $operation], $operationArgs);

		$this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
	}

	public function lockFileRenameOrCopyDataProvider() {
		return [
			['rename', ILockingProvider::LOCK_EXCLUSIVE],
			['copy', ILockingProvider::LOCK_SHARED],
		];
	}

	/**
	 * Test locks for rename or copy operation
	 *
	 * @dataProvider lockFileRenameOrCopyDataProvider
	 *
	 * @param string $operation operation to be done on the view
	 * @param int $expectedLockTypeSourceDuring expected lock type on source file during
	 * the operation
	 */
	public function testLockFileRename($operation, $expectedLockTypeSourceDuring) {
		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods([$operation, 'getMetaData', 'filemtime'])
			->getMock();

		$storage->expects($this->any())
			->method('getMetaData')
			->will($this->returnValue([
				'mtime' => 1885434487,
				'etag' => '',
				'mimetype' => 'text/plain',
				'permissions' => Constants::PERMISSION_ALL,
				'size' => 3
			]));
		$storage->expects($this->any())
			->method('filemtime')
			->willReturn(123456789);

		$sourcePath = 'original.txt';
		$targetPath = 'target.txt';

		Filesystem::mount($storage, [], $this->user . '/');
		$storage->mkdir('files');
		$view->file_put_contents($sourcePath, 'meh');

		$storage->expects($this->once())
			->method($operation)
			->willReturnCallback(
				function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
					$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
					$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);

					return true;
				}
			);

		$this->connectMockHooks($operation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
		$this->connectMockHooks($operation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
		$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');

		$view->$operation($sourcePath, $targetPath);

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
		$this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
		$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
	}

	/**
	 * simulate a failed copy operation.
	 * We expect that we catch the exception, free the lock and re-throw it.
	 *
	 */
	public function testLockFileCopyException() {
		$this->expectException(\Exception::class);

		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods(['copy'])
			->getMock();

		$sourcePath = 'original.txt';
		$targetPath = 'target.txt';

		Filesystem::mount($storage, [], $this->user . '/');
		$storage->mkdir('files');
		$view->file_put_contents($sourcePath, 'meh');

		$storage->expects($this->once())
			->method('copy')
			->willReturnCallback(
				function () {
					throw new \Exception();
				}
			);

		$this->connectMockHooks('copy', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
		$this->connectMockHooks('copy', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
		$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');

		try {
			$view->copy($sourcePath, $targetPath);
		} catch (\Exception $e) {
			$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
			$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
			throw $e;
		}
	}

	/**
	 * Test rename operation: unlock first path when second path was locked
	 */
	public function testLockFileRenameUnlockOnException() {
		self::loginAsUser('test');

		$view = new View('/' . $this->user . '/files/');

		$sourcePath = 'original.txt';
		$targetPath = 'target.txt';
		$view->file_put_contents($sourcePath, 'meh');

		// simulate that the target path is already locked
		$view->lockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file is locked before operation');

		$thrown = false;
		try {
			$view->rename($sourcePath, $targetPath);
		} catch (LockedException $e) {
			$thrown = true;
		}

		$this->assertTrue($thrown, 'LockedException thrown');

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file still locked after operation');

		$view->unlockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
	}

	/**
	 * Test rename operation: unlock first path when second path was locked
	 */
	public function testGetOwner() {
		self::loginAsUser('test');

		$view = new View('/test/files/');

		$path = 'foo.txt';
		$view->file_put_contents($path, 'meh');

		$this->assertEquals('test', $view->getFileInfo($path)->getOwner()->getUID());

		$folderInfo = $view->getDirectoryContent('');
		$folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
			return $info->getName() === 'foo.txt';
		}));

		$this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());

		$subStorage = new Temporary();
		Filesystem::mount($subStorage, [], '/test/files/asd');

		$folderInfo = $view->getDirectoryContent('');
		$folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
			return $info->getName() === 'asd';
		}));

		$this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
	}

	public function lockFileRenameOrCopyCrossStorageDataProvider() {
		return [
			['rename', 'moveFromStorage', ILockingProvider::LOCK_EXCLUSIVE],
			['copy', 'copyFromStorage', ILockingProvider::LOCK_SHARED],
		];
	}

	/**
	 * Test locks for rename or copy operation cross-storage
	 *
	 * @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
	 *
	 * @param string $viewOperation operation to be done on the view
	 * @param string $storageOperation operation to be mocked on the storage
	 * @param int $expectedLockTypeSourceDuring expected lock type on source file during
	 * the operation
	 */
	public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring) {
		$view = new View('/' . $this->user . '/files/');

		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
		$storage = $this->getMockBuilder(Temporary::class)
			->setMethods([$storageOperation])
			->getMock();
		/** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage2 */
		$storage2 = $this->getMockBuilder(Temporary::class)
			->setMethods([$storageOperation, 'getMetaData', 'filemtime'])
			->getMock();

		$storage2->expects($this->any())
			->method('getMetaData')
			->will($this->returnValue([
				'mtime' => 1885434487,
				'etag' => '',
				'mimetype' => 'text/plain',
				'permissions' => Constants::PERMISSION_ALL,
				'size' => 3
			]));
		$storage2->expects($this->any())
			->method('filemtime')
			->willReturn(123456789);

		$sourcePath = 'original.txt';
		$targetPath = 'substorage/target.txt';

		Filesystem::mount($storage, [], $this->user . '/');
		Filesystem::mount($storage2, [], $this->user . '/files/substorage');
		$storage->mkdir('files');
		$view->file_put_contents($sourcePath, 'meh');

		$storage->expects($this->never())
			->method($storageOperation);
		$storage2->expects($this->once())
			->method($storageOperation)
			->willReturnCallback(
				function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
					$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
					$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);

					return true;
				}
			);

		$this->connectMockHooks($viewOperation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
		$this->connectMockHooks($viewOperation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
		$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');

		$view->$viewOperation($sourcePath, $targetPath);

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
		$this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');

		$this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
		$this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
	}

	/**
	 * Test locks when moving a mount point
	 */
	public function testLockMoveMountPoint() {
		self::loginAsUser('test');

		[$mount] = $this->createTestMovableMountPoints([
			$this->user . '/files/substorage',
		]);

		$view = new View('/' . $this->user . '/files/');
		$view->mkdir('subdir');

		$sourcePath = 'substorage';
		$targetPath = 'subdir/substorage_moved';

		$mount->expects($this->once())
			->method('moveMount')
			->willReturnCallback(
				function ($target) use ($mount, $view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring, &$lockTypeSharedRootDuring) {
					$lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath, true);
					$lockTypeTargetDuring = $this->getFileLockType($view, $targetPath, true);

					$lockTypeSharedRootDuring = $this->getFileLockType($view, $sourcePath, false);

					$mount->setMountPoint($target);

					return true;
				}
			);

		$this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost, true);
		$this->connectMockHooks('rename', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost, true);
		// in pre-hook, mount point is still on $sourcePath
		$this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSharedRootPre, $dummy, false);
		// in post-hook, mount point is now on $targetPath
		$this->connectMockHooks('rename', $view, $targetPath, $dummy, $lockTypeSharedRootPost, false);

		$this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked before operation');
		$this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked before operation');
		$this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked before operation');

		$view->rename($sourcePath, $targetPath);

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source path locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeSourceDuring, 'Source path locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source path locked properly during post-hook');

		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target path locked properly during pre-hook');
		$this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target path locked properly during operation');
		$this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target path locked properly during post-hook');

		$this->assertNull($lockTypeSharedRootPre, 'Shared storage root not locked during pre-hook');
		$this->assertNull($lockTypeSharedRootDuring, 'Shared storage root not locked during move');
		$this->assertNull($lockTypeSharedRootPost, 'Shared storage root not locked during post-hook');

		$this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked after operation');
		$this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked after operation');
		$this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked after operation');
	}

	/**
	 * Connect hook callbacks for hook type
	 *
	 * @param string $hookType hook type or null for none
	 * @param View $view view to check the lock on
	 * @param string $path path for which to check the lock
	 * @param int $lockTypePre variable to receive lock type that was active in the pre-hook
	 * @param int $lockTypePost variable to receive lock type that was active in the post-hook
	 * @param bool $onMountPoint true to check the mount point instead of the
	 * mounted storage
	 */
	private function connectMockHooks($hookType, $view, $path, &$lockTypePre, &$lockTypePost, $onMountPoint = false) {
		if ($hookType === null) {
			return;
		}

		$eventHandler = $this->getMockBuilder(\stdclass::class)
			->setMethods(['preCallback', 'postCallback'])
			->getMock();

		$eventHandler->expects($this->any())
			->method('preCallback')
			->willReturnCallback(
				function () use ($view, $path, $onMountPoint, &$lockTypePre) {
					$lockTypePre = $this->getFileLockType($view, $path, $onMountPoint);
				}
			);
		$eventHandler->expects($this->any())
			->method('postCallback')
			->willReturnCallback(
				function () use ($view, $path, $onMountPoint, &$lockTypePost) {
					$lockTypePost = $this->getFileLockType($view, $path, $onMountPoint);
				}
			);

		if ($hookType !== null) {
			Util::connectHook(
				Filesystem::CLASSNAME,
				$hookType,
				$eventHandler,
				'preCallback'
			);
			Util::connectHook(
				Filesystem::CLASSNAME,
				'post_' . $hookType,
				$eventHandler,
				'postCallback'
			);
		}
	}

	/**
	 * Returns the file lock type
	 *
	 * @param View $view view
	 * @param string $path path
	 * @param bool $onMountPoint true to check the mount point instead of the
	 * mounted storage
	 *
	 * @return int lock type or null if file was not locked
	 */
	private function getFileLockType(View $view, $path, $onMountPoint = false) {
		if ($this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE, $onMountPoint)) {
			return ILockingProvider::LOCK_EXCLUSIVE;
		} elseif ($this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED, $onMountPoint)) {
			return ILockingProvider::LOCK_SHARED;
		}
		return null;
	}


	public function testRemoveMoveableMountPoint() {
		$mountPoint = '/' . $this->user . '/files/mount/';

		// Mock the mount point
		/** @var TestMoveableMountPoint|\PHPUnit\Framework\MockObject\MockObject $mount */
		$mount = $this->createMock(TestMoveableMountPoint::class);
		$mount->expects($this->once())
			->method('getMountPoint')
			->willReturn($mountPoint);
		$mount->expects($this->once())
			->method('removeMount')
			->willReturn('foo');
		$mount->expects($this->any())
			->method('getInternalPath')
			->willReturn('');

		// Register mount
		Filesystem::getMountManager()->addMount($mount);

		// Listen for events
		$eventHandler = $this->getMockBuilder(\stdclass::class)
			->setMethods(['umount', 'post_umount'])
			->getMock();
		$eventHandler->expects($this->once())
			->method('umount')
			->with([Filesystem::signal_param_path => '/mount']);
		$eventHandler->expects($this->once())
			->method('post_umount')
			->with([Filesystem::signal_param_path => '/mount']);
		Util::connectHook(
			Filesystem::CLASSNAME,
			'umount',
			$eventHandler,
			'umount'
		);
		Util::connectHook(
			Filesystem::CLASSNAME,
			'post_umount',
			$eventHandler,
			'post_umount'
		);

		//Delete the mountpoint
		$view = new View('/' . $this->user . '/files');
		$this->assertEquals('foo', $view->rmdir('mount'));
	}

	public function mimeFilterProvider() {
		return [
			[null, ['test1.txt', 'test2.txt', 'test3.md', 'test4.png']],
			['text/plain', ['test1.txt', 'test2.txt']],
			['text/markdown', ['test3.md']],
			['text', ['test1.txt', 'test2.txt', 'test3.md']],
		];
	}

	/**
	 * @param string $filter
	 * @param string[] $expected
	 * @dataProvider mimeFilterProvider
	 */
	public function testGetDirectoryContentMimeFilter($filter, $expected) {
		$storage1 = new Temporary();
		$root = self::getUniqueID('/');
		Filesystem::mount($storage1, [], $root . '/');
		$view = new View($root);

		$view->file_put_contents('test1.txt', 'asd');
		$view->file_put_contents('test2.txt', 'asd');
		$view->file_put_contents('test3.md', 'asd');
		$view->file_put_contents('test4.png', '');

		$content = $view->getDirectoryContent('', $filter);

		$files = array_map(function (FileInfo $info) {
			return $info->getName();
		}, $content);
		sort($files);

		$this->assertEquals($expected, $files);
	}

	public function testFilePutContentsClearsChecksum() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$storage->file_put_contents('foo.txt', 'bar');
		Filesystem::mount($storage, [], '/test/');
		$scanner->scan('');

		$view = new View('/test/foo.txt');
		$view->putFileInfo('.', ['checksum' => '42']);

		$this->assertEquals('bar', $view->file_get_contents(''));
		$fh = tmpfile();
		fwrite($fh, 'fooo');
		rewind($fh);
		clearstatcache();
		$view->file_put_contents('', $fh);
		$this->assertEquals('fooo', $view->file_get_contents(''));
		$data = $view->getFileInfo('.');
		$this->assertEquals('', $data->getChecksum());
	}

	public function testDeleteGhostFile() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$cache = $storage->getCache();
		$storage->file_put_contents('foo.txt', 'bar');
		Filesystem::mount($storage, [], '/test/');
		$scanner->scan('');

		$storage->unlink('foo.txt');

		$this->assertTrue($cache->inCache('foo.txt'));

		$view = new View('/test');
		$rootInfo = $view->getFileInfo('');
		$this->assertEquals(3, $rootInfo->getSize());
		$view->unlink('foo.txt');
		$newInfo = $view->getFileInfo('');

		$this->assertFalse($cache->inCache('foo.txt'));
		$this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
		$this->assertEquals(0, $newInfo->getSize());
	}

	public function testDeleteGhostFolder() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$cache = $storage->getCache();
		$storage->mkdir('foo');
		$storage->file_put_contents('foo/foo.txt', 'bar');
		Filesystem::mount($storage, [], '/test/');
		$scanner->scan('');

		$storage->rmdir('foo');

		$this->assertTrue($cache->inCache('foo'));
		$this->assertTrue($cache->inCache('foo/foo.txt'));

		$view = new View('/test');
		$rootInfo = $view->getFileInfo('');
		$this->assertEquals(3, $rootInfo->getSize());
		$view->rmdir('foo');
		$newInfo = $view->getFileInfo('');

		$this->assertFalse($cache->inCache('foo'));
		$this->assertFalse($cache->inCache('foo/foo.txt'));
		$this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
		$this->assertEquals(0, $newInfo->getSize());
	}

	public function testCreateParentDirectories() {
		$view = $this->getMockBuilder(View::class)
			->disableOriginalConstructor()
			->setMethods([
				'is_file',
				'file_exists',
				'mkdir',
			])
			->getMock();

		$view->expects($this->exactly(3))
			->method('is_file')
			->withConsecutive(
				['/new'],
				['/new/folder'],
				['/new/folder/structure'],
			)
			->willReturn(false);
		$view->expects($this->exactly(3))
			->method('file_exists')
			->withConsecutive(
				['/new'],
				['/new/folder'],
				['/new/folder/structure'],
			)->willReturnOnConsecutiveCalls(
				true,
				false,
				false,
			);
		$view->expects($this->exactly(2))
			->method('mkdir')
			->withConsecutive(
				['/new/folder'],
				['/new/folder/structure'],
			);

		$this->assertTrue(self::invokePrivate($view, 'createParentDirectories', ['/new/folder/structure']));
	}

	public function testCreateParentDirectoriesWithExistingFile() {
		$view = $this->getMockBuilder(View::class)
			->disableOriginalConstructor()
			->setMethods([
				'is_file',
				'file_exists',
				'mkdir',
			])
			->getMock();

		$view
			->expects($this->once())
			->method('is_file')
			->with('/file.txt')
			->willReturn(true);
		$this->assertFalse(self::invokePrivate($view, 'createParentDirectories', ['/file.txt/folder/structure']));
	}

	public function testCacheExtension() {
		$storage = new Temporary([]);
		$scanner = $storage->getScanner();
		$storage->file_put_contents('foo.txt', 'bar');
		$scanner->scan('');

		Filesystem::mount($storage, [], '/test/');
		$view = new View('/test');

		$info = $view->getFileInfo('/foo.txt');
		$this->assertEquals(0, $info->getUploadTime());
		$this->assertEquals(0, $info->getCreationTime());

		$view->putFileInfo('/foo.txt', ['upload_time' => 25]);

		$info = $view->getFileInfo('/foo.txt');
		$this->assertEquals(25, $info->getUploadTime());
		$this->assertEquals(0, $info->getCreationTime());
	}
}