File: kstandarddirs.cpp

package info (click to toggle)
kde4libs 4:4.14.2-5+deb8u2
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 82,428 kB
  • ctags: 99,415
  • sloc: cpp: 761,864; xml: 12,344; ansic: 6,295; java: 4,060; perl: 2,938; yacc: 2,507; python: 1,207; sh: 1,179; ruby: 337; lex: 278; makefile: 29
file content (2159 lines) | stat: -rw-r--r-- 68,793 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
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
/* This file is part of the KDE libraries
   Copyright (C) 1999 Sirtaj Singh Kang <taj@kde.org>
   Copyright (C) 1999,2007 Stephan Kulow <coolo@kde.org>
   Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
   Copyright (C) 2009 David Faure <faure@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

/*
 * Author: Stephan Kulow <coolo@kde.org> and Sirtaj Singh Kang <taj@kde.org>
 * Generated: Thu Mar  5 16:05:28 EST 1998
 */

#include "kstandarddirs.h"
#include "kconfig.h"
#include "kconfiggroup.h"
#include "kdebug.h"
#include "kcomponentdata.h"
#include "kshell.h"
#include "kuser.h"
#include "kde_file.h"
#include "kkernel_win.h"
#include "kkernel_mac.h"
#include "klocale.h"

#include <config.h>
#include <config-prefix.h>
#include <config-kstandarddirs.h>

#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/param.h>
#include <sys/types.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#ifdef Q_WS_WIN
#include <windows.h>
#ifdef _WIN32_WCE
#include <basetyps.h>
#endif
#ifdef Q_WS_WIN64
// FIXME: did not find a reliable way to fix with kdewin mingw header
#define interface struct
#endif
#include <shlobj.h>
#include <QtCore/QVarLengthArray>
#endif

#include <QtCore/QMutex>
#include <QtCore/QRegExp>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>

#ifdef Q_OS_WIN
static Qt::CaseSensitivity cs = Qt::CaseInsensitive;
#else
static Qt::CaseSensitivity cs = Qt::CaseSensitive;
#endif

#ifndef MAXPATHLEN
# define MAXPATHLEN 1024
#endif

class KStandardDirs::KStandardDirsPrivate
{
public:
    KStandardDirsPrivate(KStandardDirs* qq)
        : m_restrictionsActive(false),
          m_checkRestrictions(true),
          m_cacheMutex(QMutex::Recursive), // resourceDirs is recursive
          q(qq)
    { }

    bool hasDataRestrictions(const QString &relPath) const;
    QStringList resourceDirs(const char* type, const QString& subdirForRestrictions);
    void createSpecialResource(const char*);

    bool m_restrictionsActive : 1;
    bool m_checkRestrictions : 1;
    QMap<QByteArray, bool> m_restrictions;

    QStringList xdgdata_prefixes;
    QStringList xdgconf_prefixes;
    QStringList m_prefixes;

    // Directory dictionaries
    QMap<QByteArray, QStringList> m_absolutes; // For each resource type, the list of absolute paths, from most local (most priority) to most global
    QMap<QByteArray, QStringList> m_relatives; // Same with relative paths
    // The search path is "all relative paths" < "all absolute paths", from most priority to least priority.

    // Caches (protected by mutex in const methods, cf ctor docu)
    QMap<QByteArray, QStringList> m_dircache;
    QMap<QByteArray, QString> m_savelocations;
    QMutex m_cacheMutex;

    KStandardDirs* q;
};

/* If you add a new resource type here, make sure to
 * 1) regenerate using "kdesdk/scripts/generate_string_table.pl types < tmpfile" with the data below in tmpfile.
 * 2) update the KStandardDirs class documentation
 * 3) update the list in kde-config.cpp

data
share/apps
html
share/doc/HTML
icon
share/icons
config
share/config
pixmap
share/pixmaps
apps
share/applnk
sound
share/sounds
locale
share/locale
services
share/kde4/services
servicetypes
share/kde4/servicetypes
mime
share/mimelnk
cgi
cgi-bin
wallpaper
share/wallpapers
templates
share/templates
exe
bin
module
%lib/kde4
qtplugins
%lib/kde4/plugins
kcfg
share/config.kcfg
emoticons
share/emoticons
xdgdata-apps
applications
xdgdata-icon
icons
xdgdata-pixmap
pixmaps
xdgdata-dirs
desktop-directories
xdgdata-mime
mime
xdgconf-menu
menus
xdgconf-autostart
autostart
kdeinit
%lib
*/

static const char types_string[] =
    "data\0"
    "share/apps\0"
    "html\0"
    "share/doc/HTML\0"
    "icon\0"
    "share/icons\0"
    "config\0"
    "share/config\0"
    "pixmap\0"
    "share/pixmaps\0"
    "apps\0"
    "share/applnk\0"
    "sound\0"
    "share/sounds\0"
    "locale\0"
    "share/locale\0"
    "services\0"
    "share/kde4/services\0"
    "servicetypes\0"
    "share/kde4/servicetypes\0"
    "mime\0"
    "share/mimelnk\0"
    "cgi\0"
    "cgi-bin\0"
    "wallpaper\0"
    "share/wallpapers\0"
    "templates\0"
    "share/templates\0"
    "exe\0"
    "bin\0"
    "module\0"
    "%lib/kde4\0"
    "qtplugins\0"
    "%lib/kde4/plugins\0"
    "kcfg\0"
    "share/config.kcfg\0"
    "emoticons\0"
    "share/emoticons\0"
    "xdgdata-apps\0"
    "applications\0"
    "xdgdata-icon\0"
    "icons\0"
    "xdgdata-pixmap\0"
    "pixmaps\0"
    "xdgdata-dirs\0"
    "desktop-directories\0"
    "xdgdata-mime\0"
    "xdgconf-menu\0"
    "menus\0"
    "xdgconf-autostart\0"
    "autostart\0"
    "kdeinit\0"
    "%lib\0"
    "\0";

static const int types_indices[] = {
    0,    5,   16,   21,   36,   41,   53,   60,
    73,   80,   94,   99,  112,  118,  131,  138,
    151,  160,  180,  193,  217,  222,  236,  240,
    248,  258,  275,  285,  301,  305,  309,  316,
    326,  336,  354,  359,  377,  387,  403,  416,
    429,  442,  448,  463,  471,  484,  504,  217,
    517,  530,  536,  554,  564,  572,   -1
};

static void tokenize(QStringList& token, const QString& str,
                     const QString& delim);

KStandardDirs::KStandardDirs()
    : d(new KStandardDirsPrivate(this))
{
    addKDEDefaults();
}

KStandardDirs::~KStandardDirs()
{
    delete d;
}

bool KStandardDirs::isRestrictedResource(const char *type, const QString& relPath) const
{
    if (!d->m_restrictionsActive)
        return false;

    if (d->m_restrictions.value(type, false))
        return true;

    if (strcmp(type, "data")==0 && d->hasDataRestrictions(relPath))
        return true;

    return false;
}

bool KStandardDirs::KStandardDirsPrivate::hasDataRestrictions(const QString &relPath) const
{
    QString key;
    const int i = relPath.indexOf(QLatin1Char('/'));
    if (i != -1)
        key = QString::fromLatin1("data_") + relPath.left(i);
    else
        key = QString::fromLatin1("data_") + relPath;

    return m_restrictions.value(key.toLatin1(), false);
}


QStringList KStandardDirs::allTypes() const
{
    QStringList list;
    for (int i = 0; types_indices[i] != -1; i += 2)
        list.append(QLatin1String(types_string + types_indices[i]));
    // Those are added manually by addKDEDefaults
    list.append(QString::fromLatin1("lib"));
    //list.append(QString::fromLatin1("home")); // undocumented on purpose, said Waldo in r113855.

    // Those are handled by resourceDirs() itself
    list.append(QString::fromLatin1("socket"));
    list.append(QString::fromLatin1("tmp"));
    list.append(QString::fromLatin1("cache"));
    // Those are handled by installPath()
    list.append(QString::fromLatin1("include"));

    // If you add anything here, make sure kde-config.cpp has a description for it.

    return list;
}

static void priorityAdd(QStringList &prefixes, const QString& dir, bool priority)
{
    if (priority && !prefixes.isEmpty())
    {
        // Add in front but behind $KDEHOME
        QStringList::iterator it = prefixes.begin();
        ++it;
        prefixes.insert(it, dir);
    }
    else
    {
        prefixes.append(dir);
    }
}

void KStandardDirs::addPrefix( const QString& _dir )
{
    addPrefix(_dir, false);
}

void KStandardDirs::addPrefix( const QString& _dir, bool priority )
{
    if (_dir.isEmpty())
        return;

    QString dir = _dir;
    if (dir.at(dir.length() - 1) != QLatin1Char('/'))
        dir += QLatin1Char('/');

    if (!d->m_prefixes.contains(dir, cs)) {
        priorityAdd(d->m_prefixes, dir, priority);
        d->m_dircache.clear();
    }
}

void KStandardDirs::addXdgConfigPrefix( const QString& _dir )
{
    addXdgConfigPrefix(_dir, false);
}

void KStandardDirs::addXdgConfigPrefix( const QString& _dir, bool priority )
{
    if (_dir.isEmpty())
        return;

    QString dir = _dir;
    if (dir.at(dir.length() - 1) != QLatin1Char('/'))
        dir += QLatin1Char('/');

    if (!d->xdgconf_prefixes.contains(dir, cs)) {
        priorityAdd(d->xdgconf_prefixes, dir, priority);
        d->m_dircache.clear();
    }
}

void KStandardDirs::addXdgDataPrefix( const QString& _dir )
{
    addXdgDataPrefix(_dir, false);
}

void KStandardDirs::addXdgDataPrefix( const QString& _dir, bool priority )
{
    if (_dir.isEmpty())
        return;

    QString dir = _dir;
    if (dir.at(dir.length() - 1) != QLatin1Char('/'))
        dir += QLatin1Char('/');

    if (!d->xdgdata_prefixes.contains(dir, cs)) {
        priorityAdd(d->xdgdata_prefixes, dir, priority);
        d->m_dircache.clear();
    }
}

QString KStandardDirs::kfsstnd_prefixes()
{
    return d->m_prefixes.join(QString(QLatin1Char(KPATH_SEPARATOR)));
}

QString KStandardDirs::kfsstnd_xdg_conf_prefixes()
{
    return d->xdgconf_prefixes.join(QString(QLatin1Char(KPATH_SEPARATOR)));
}

QString KStandardDirs::kfsstnd_xdg_data_prefixes()
{
    return d->xdgdata_prefixes.join(QString(QLatin1Char(KPATH_SEPARATOR)));
}

#ifndef KDE_NO_DEPRECATED
bool KStandardDirs::addResourceType( const char *type,
                                     const QString& relativename,
                                     bool priority )
{
    return addResourceType( type, 0, relativename, priority);
}
#endif

bool KStandardDirs::addResourceType( const char *type,
                                     const char *basetype,
                                     const QString& relativename,
                                     bool priority )
{
    if (relativename.isEmpty())
        return false;

    QString copy = relativename;
    if (basetype)
        copy = QLatin1Char('%') + QString::fromLatin1(basetype) + QLatin1Char('/') + relativename;

    if (!copy.endsWith(QLatin1Char('/')))
        copy += QLatin1Char('/');

    QByteArray typeBa = type;
    QStringList& rels = d->m_relatives[typeBa]; // find or insert

    if (!rels.contains(copy, cs)) {
        if (priority)
            rels.prepend(copy);
        else
            rels.append(copy);
        // clean the caches
        d->m_dircache.remove(typeBa);
        d->m_savelocations.remove(typeBa);
        return true;
    }
    return false;
}

bool KStandardDirs::addResourceDir( const char *type,
                                    const QString& absdir,
                                    bool priority)
{
    if (absdir.isEmpty() || !type)
      return false;
    // find or insert entry in the map
    QString copy = absdir;
    if (copy.at(copy.length() - 1) != QLatin1Char('/'))
        copy += QLatin1Char('/');

    QByteArray typeBa = type;
    QStringList &paths = d->m_absolutes[typeBa];
    if (!paths.contains(copy, cs)) {
        if (priority)
            paths.prepend(copy);
        else
            paths.append(copy);
        // clean the caches
        d->m_dircache.remove(typeBa);
        d->m_savelocations.remove(typeBa);
        return true;
    }
    return false;
}

QString KStandardDirs::findResource( const char *type,
                                     const QString& _filename ) const
{
    if (!QDir::isRelativePath(_filename))
      return !KGlobal::hasLocale() ? _filename // absolute dirs are absolute dirs, right? :-/
                                   : KGlobal::locale()->localizedFilePath(_filename); // -- almost.

#if 0
    kDebug(180) << "Find resource: " << type;
    for (QStringList::ConstIterator pit = m_prefixes.begin();
         pit != m_prefixes.end();
         ++pit)
    {
        kDebug(180) << "Prefix: " << *pit;
    }
#endif

    QString filename(_filename);
#ifdef Q_OS_WIN
    if(strcmp(type, "exe") == 0) {
      if(!filename.endsWith(QLatin1String(".exe"), Qt::CaseInsensitive))
        filename += QLatin1String(".exe");
    }
#endif
    const QString dir = findResourceDir(type, filename);
    if (dir.isEmpty())
      return dir;
    else
      return !KGlobal::hasLocale() ? dir + filename
                                   : KGlobal::locale()->localizedFilePath(dir + filename);
}

static quint32 updateHash(const QString &file, quint32 hash)
{
    KDE_struct_stat buff;
    if ((KDE::access(file, R_OK) == 0) && (KDE::stat(file, &buff) == 0) && (S_ISREG(buff.st_mode))) {
        hash = hash + static_cast<quint32>(buff.st_ctime);
    }
    return hash;
}

quint32 KStandardDirs::calcResourceHash( const char *type,
                                         const QString& filename,
                                         SearchOptions options ) const
{
    quint32 hash = 0;

    if (!QDir::isRelativePath(filename))
    {
        // absolute dirs are absolute dirs, right? :-/
        return updateHash(filename, hash);
    }
    QStringList candidates = d->resourceDirs(type, filename);

    foreach ( const QString& candidate, candidates )
    {
        hash = updateHash(candidate + filename, hash);
        if (  !( options & Recursive ) && hash ) {
            return hash;
        }
    }
    return hash;
}


QStringList KStandardDirs::findDirs( const char *type,
                                     const QString& reldir ) const
{
    QDir testdir;
    QStringList list;
    if (!QDir::isRelativePath(reldir))
    {
        testdir.setPath(reldir);
        if (testdir.exists())
        {
            if (reldir.endsWith(QLatin1Char('/')))
                list.append(reldir);
            else
                list.append(reldir+QLatin1Char('/'));
        }
        return list;
    }

    const QStringList candidates = d->resourceDirs(type, reldir);

    for (QStringList::ConstIterator it = candidates.begin();
         it != candidates.end(); ++it) {
        testdir.setPath(*it + reldir);
        if (testdir.exists())
            list.append(testdir.absolutePath() + QLatin1Char('/'));
    }

    return list;
}

QString KStandardDirs::findResourceDir( const char *type,
                                        const QString& _filename) const
{
#ifndef NDEBUG
    if (_filename.isEmpty()) {
        kWarning() << "filename for type " << type << " in KStandardDirs::findResourceDir is not supposed to be empty!!";
        return QString();
    }
#endif

    QString filename(_filename);
#ifdef Q_OS_WIN
    if(strcmp(type, "exe") == 0) {
      if(!filename.endsWith(QLatin1String(".exe"), Qt::CaseInsensitive))
        filename += QLatin1String(".exe");
    }
#endif
    const QStringList candidates = d->resourceDirs(type, filename);

    for (QStringList::ConstIterator it = candidates.begin();
         it != candidates.end(); ++it) {
        if (exists(*it + filename)) {
            return *it;
        }
    }

#ifndef NDEBUG
    if(false && strcmp(type, "locale"))
        kDebug(180) << "KStdDirs::findResDir(): can't find \"" << filename << "\" in type \"" << type << "\".";
#endif

    return QString();
}

bool KStandardDirs::exists(const QString &fullPath)
{
#ifdef Q_OS_WIN
    // access() and stat() give a stupid error message to the user
    // if the path is not accessible at all (e.g. no disk in A:/ and
    // we do stat("A:/.directory")
    if (fullPath.endsWith(QLatin1Char('/')))
        return QDir(fullPath).exists();
    return QFileInfo(fullPath).exists();
#else
    KDE_struct_stat buff;
    QByteArray cFullPath = QFile::encodeName(fullPath);
    if (access(cFullPath, R_OK) == 0 && KDE_stat( cFullPath, &buff ) == 0) {
        if (!fullPath.endsWith(QLatin1Char('/'))) {
            if (S_ISREG( buff.st_mode ))
                return true;
        } else
            if (S_ISDIR( buff.st_mode ))
                return true;
    }
    return false;
#endif
}

static void lookupDirectory(const QString& path, const QString &relPart,
                            const QRegExp &regexp,
                            QStringList& list,
                            QStringList& relList,
                            bool recursive, bool unique)
{
    const QString pattern = regexp.pattern();
    if (recursive || pattern.contains(QLatin1Char('?')) || pattern.contains(QLatin1Char('*')))
    {
        if (path.isEmpty()) //for sanity
            return;
#ifdef Q_WS_WIN
        QString path_ = path + QLatin1String( "*.*" );
        WIN32_FIND_DATA findData;
        HANDLE hFile = FindFirstFile( (LPWSTR)path_.utf16(), &findData );
        if( hFile == INVALID_HANDLE_VALUE )
            return;
        do {
            const int len = wcslen( findData.cFileName );
            if (!( findData.cFileName[0] == '.' &&
                   findData.cFileName[1] == '\0' ) &&
                !( findData.cFileName[0] == '.' &&
                   findData.cFileName[1] == '.' &&
                   findData.cFileName[2] == '\0' ) &&
                 ( findData.cFileName[len-1] != '~' ) ) {
                QString fn = QString::fromUtf16( (const unsigned short*)findData.cFileName );
                if (!recursive && !regexp.exactMatch(fn))
                    continue; // No match
                QString pathfn = path + fn;
                bool bIsDir = ( ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == FILE_ATTRIBUTE_DIRECTORY );
                if ( recursive ) {
                    if ( bIsDir ) {
                        lookupDirectory(pathfn + QLatin1Char('/'),
                                        relPart + fn + QLatin1Char('/'),
                                        regexp, list, relList, recursive, unique);
                    }
                    if (!regexp.exactMatch(fn))
                        continue; // No match
                }
                if ( !bIsDir )
                {
                    if ( !unique || !relList.contains(relPart + fn, cs) )
                    {
                        list.append( pathfn );
                        relList.append( relPart + fn );
                    }
                }
            }
        } while( FindNextFile( hFile, &findData ) != 0 );
        FindClose( hFile );
#else
        // We look for a set of files.
        DIR *dp = opendir( QFile::encodeName(path));
        if (!dp)
            return;

        assert(path.endsWith(QLatin1Char('/')));

        struct dirent *ep;

        while( ( ep = readdir( dp ) ) != 0L )
        {
            QString fn( QFile::decodeName(ep->d_name));
            if (fn == QString::fromLatin1(".") || fn == QString::fromLatin1("..") || fn.at(fn.length() - 1) == QLatin1Char('~'))
                continue;

            if (!recursive && !regexp.exactMatch(fn))
                continue; // No match

            bool isDir;
            bool isReg;

            QString pathfn = path + fn;
#ifdef HAVE_DIRENT_D_TYPE
            isDir = ep->d_type == DT_DIR;
            isReg = ep->d_type == DT_REG;

            if (ep->d_type == DT_UNKNOWN || ep->d_type == DT_LNK)
#endif
            {
                KDE_struct_stat buff;
                if ( KDE::stat( pathfn, &buff ) != 0 ) {
                    kDebug(180) << "Error stat'ing " << pathfn << " : " << perror;
                    continue; // Couldn't stat (e.g. no read permissions)
                }
                isReg = S_ISREG (buff.st_mode);
                isDir = S_ISDIR (buff.st_mode);
            }

            if ( recursive ) {
                if ( isDir ) {
                    lookupDirectory(pathfn + QLatin1Char('/'), relPart + fn + QLatin1Char('/'), regexp, list, relList, recursive, unique);
                }
                if (!regexp.exactMatch(fn))
                    continue; // No match
            }
            if ( isReg )
            {
                if (!unique || !relList.contains(relPart + fn, cs))
                {
                    list.append( pathfn );
                    relList.append( relPart + fn );
                }
            }
        }
        closedir( dp );
#endif
    }
    else
    {
        // We look for a single file.
        QString fn = pattern;
        QString pathfn = path + fn;
        KDE_struct_stat buff;
        if ( KDE::stat( pathfn, &buff ) != 0 )
            return; // File not found
        if ( S_ISREG( buff.st_mode))
        {
            if (!unique || !relList.contains(relPart + fn, cs))
            {
                list.append( pathfn );
                relList.append( relPart + fn );
            }
        }
    }
}

static void lookupPrefix(const QString& prefix, const QString& relpath,
                         const QString& relPart,
                         const QRegExp &regexp,
                         QStringList& list,
                         QStringList& relList,
                         bool recursive, bool unique)
{
    if (relpath.isEmpty()) {
        if (recursive)
            Q_ASSERT(prefix != QLatin1String("/")); // we don't want to recursively list the whole disk!
        lookupDirectory(prefix, relPart, regexp, list,
                        relList, recursive, unique);
        return;
    }
    QString path;
    QString rest;

    int slash = relpath.indexOf(QLatin1Char('/'));
    if (slash < 0)
        rest = relpath.left(relpath.length() - 1);
    else {
        path = relpath.left(slash);
        rest = relpath.mid(slash + 1);
    }

    if (prefix.isEmpty()) //for sanity
        return;
#ifndef Q_WS_WIN
    // what does this assert check ?
    assert(prefix.endsWith(QLatin1Char('/')));
#endif
    if (path.contains(QLatin1Char('*')) || path.contains(QLatin1Char('?'))) {

        QRegExp pathExp(path, Qt::CaseSensitive, QRegExp::Wildcard);

#ifdef Q_WS_WIN
        QString prefix_ = prefix + QLatin1String( "*.*" );
        WIN32_FIND_DATA findData;
        HANDLE hFile = FindFirstFile( (LPWSTR)prefix_.utf16(), &findData );
        if( hFile == INVALID_HANDLE_VALUE )
            return;
        do {
            const int len = wcslen( findData.cFileName );
            if (!( findData.cFileName[0] == '.' &&
                   findData.cFileName[1] == '\0' ) &&
                !( findData.cFileName[0] == '.' &&
                   findData.cFileName[1] == '.' &&
                   findData.cFileName[2] == '\0' ) &&
                 ( findData.cFileName[len-1] != '~' ) ) {
                const QString fn = QString::fromUtf16( (const unsigned short*)findData.cFileName );
                if ( !pathExp.exactMatch(fn) )
                    continue; // No match
                if ( ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == FILE_ATTRIBUTE_DIRECTORY )
                    lookupPrefix(prefix + fn + QLatin1Char('/'),
                                 rest, relPart + fn + QLatin1Char('/'),
                                 regexp, list, relList, recursive, unique);
            }
        } while( FindNextFile( hFile, &findData ) != 0 );
        FindClose( hFile );
#else
        DIR *dp = opendir( QFile::encodeName(prefix) );
        if (!dp) {
            return;
        }

        struct dirent *ep;

        while( ( ep = readdir( dp ) ) != 0L )
        {
            QString fn( QFile::decodeName(ep->d_name));
            if (fn == QLatin1String(".") || fn == QLatin1String("..") || fn.at(fn.length() - 1) == QLatin1Char('~'))
                continue;

            if ( !pathExp.exactMatch(fn) )
                continue; // No match
            QString rfn = relPart+fn;
            fn = prefix + fn;

            bool isDir;

#ifdef HAVE_DIRENT_D_TYPE
            isDir = ep->d_type == DT_DIR;

            if (ep->d_type == DT_UNKNOWN || ep->d_type == DT_LNK)
#endif
            {
                QString pathfn = path + fn;
                KDE_struct_stat buff;
                if ( KDE::stat( fn, &buff ) != 0 ) {
                    kDebug(180) << "Error stat'ing " << fn << " : " << perror;
                    continue; // Couldn't stat (e.g. no read permissions)
                }
                isDir = S_ISDIR (buff.st_mode);
            }
            if ( isDir )
                lookupPrefix(fn + QLatin1Char('/'), rest, rfn + QLatin1Char('/'), regexp, list, relList, recursive, unique);
        }

        closedir( dp );
#endif
    } else {
        // Don't stat, if the dir doesn't exist we will find out
        // when we try to open it.
        lookupPrefix(prefix + path + QLatin1Char('/'), rest,
                     relPart + path + QLatin1Char('/'), regexp, list,
                     relList, recursive, unique);
    }
}

QStringList
KStandardDirs::findAllResources( const char *type,
                                 const QString& filter,
                                 SearchOptions options,
                                 QStringList &relList) const
{
    QString filterPath;
    QString filterFile;

    if ( !filter.isEmpty() )
    {
        int slash = filter.lastIndexOf(QLatin1Char('/'));
        if (slash < 0) {
            filterFile = filter;
        } else {
            filterPath = filter.left(slash + 1);
            filterFile = filter.mid(slash + 1);
        }
    }

    QStringList candidates;
    if ( !QDir::isRelativePath(filter) ) // absolute path
    {
#ifdef Q_OS_WIN
        candidates << filterPath.left(3); //e.g. "C:\"
        filterPath = filterPath.mid(3);
#else
        candidates << QString::fromLatin1("/");
        filterPath = filterPath.mid(1);
#endif
    }
    else
    {
        candidates = d->resourceDirs(type, filter);
    }

    if (filterFile.isEmpty()) {
        filterFile = QString(QLatin1Char('*'));
    }

    QRegExp regExp(filterFile, Qt::CaseSensitive, QRegExp::Wildcard);

    QStringList list;
    foreach ( const QString& candidate, candidates )
    {
        lookupPrefix(candidate, filterPath, QString(), regExp, list,
                     relList, options & Recursive, options & NoDuplicates);
    }

    return list;
}

QStringList
KStandardDirs::findAllResources( const char *type,
                                 const QString& filter,
                                 SearchOptions options ) const
{
    QStringList relList;
    return findAllResources(type, filter, options, relList);
}

// ####### KDE4: should this be removed, in favor of QDir::canonicalPath()?
// aseigo: QDir::canonicalPath returns QString() if the dir doesn't exist
//         and this method is often used with the expectation for it to work
//         even if the directory doesn't exist. so ... no, we can't drop this
//         yet
QString
KStandardDirs::realPath(const QString &dirname)
{
#ifdef Q_WS_WIN
    const QString strRet = realFilePath(dirname);
    if (!strRet.endsWith(QLatin1Char('/')))
        return strRet + QLatin1Char('/');
    return strRet;
#else
    if (dirname.isEmpty() || (dirname.size() == 1 && dirname.at(0) == QLatin1Char('/')))
       return dirname;

    if (dirname.at(0) != QLatin1Char('/')) {
        qWarning("realPath called with a relative path '%s', please fix", qPrintable(dirname));
        return dirname;
    }

    char realpath_buffer[MAXPATHLEN + 1];
    memset(realpath_buffer, 0, MAXPATHLEN + 1);

    /* If the path contains symlinks, get the real name */
    if (realpath( QFile::encodeName(dirname).constData(), realpath_buffer) != 0) {
        // success, use result from realpath
        int len = strlen(realpath_buffer);
        realpath_buffer[len] = '/';
        realpath_buffer[len+1] = 0;
        return QFile::decodeName(realpath_buffer);
    }

    // Does not exist yet; resolve symlinks in parent dirs then.
    // This ensures that once the directory exists, it will still be resolved
    // the same way, so that the general rule that KStandardDirs always returns
    // canonical paths stays true, and app code can compare paths more easily.
    QString dir = dirname;
    if (!dir.endsWith(QLatin1Char('/')))
        dir += QLatin1Char('/');
    QString relative;
    while (!KStandardDirs::exists(dir)) {
        //qDebug() << "does not exist:" << dir;
        const int pos = dir.lastIndexOf(QLatin1Char('/'), -2);
        Q_ASSERT(pos >= 0); // what? even "/" doesn't exist?
        relative.prepend(dir.mid(pos+1)); // keep "subdir/"
        dir = dir.left(pos+1);
        Q_ASSERT(dir.endsWith(QLatin1Char('/')));
    }
    Q_ASSERT(!relative.isEmpty()); // infinite recursion ahead
    if (!relative.isEmpty()) {
        //qDebug() << "done, resolving" << dir << "and adding" << relative;
        dir = realPath(dir) + relative;
    }
    return dir;
#endif
}

// ####### KDE4: should this be removed, in favor of QDir::canonicalPath()?
// aseigo: QDir::canonicalPath returns QString() if the dir doesn't exist
//         and this method is often used with the expectation for it to work
//         even if the directory doesn't exist. so ... no, we can't drop this
//         yet
QString
KStandardDirs::realFilePath(const QString &filename)
{
#ifdef Q_WS_WIN
    LPCWSTR lpIn = (LPCWSTR)filename.utf16();
    QVarLengthArray<WCHAR, MAX_PATH> buf(MAX_PATH);
    DWORD len = GetFullPathNameW(lpIn, buf.size(), buf.data(), NULL);
    if (len > (DWORD)buf.size()) {
        buf.resize(len);
        len = GetFullPathNameW(lpIn, buf.size(), buf.data(), NULL);
    }
    if (len == 0)
        return QString();
    return QString::fromUtf16((const unsigned short*)buf.data()).replace(QLatin1Char('\\'),QLatin1Char('/'));
#else
    char realpath_buffer[MAXPATHLEN + 1];
    memset(realpath_buffer, 0, MAXPATHLEN + 1);

    /* If the path contains symlinks, get the real name */
    if (realpath( QFile::encodeName(filename).constData(), realpath_buffer) != 0) {
        // success, use result from realpath
        return QFile::decodeName(realpath_buffer);
    }

    return filename;
#endif
}


void KStandardDirs::KStandardDirsPrivate::createSpecialResource(const char *type)
{
    char hostname[256];
    hostname[0] = 0;
    gethostname(hostname, 255);
    const QString localkdedir = m_prefixes.first();
    QString dir = localkdedir + QString::fromLatin1(type) + QLatin1Char('-') + QString::fromLocal8Bit(hostname);
    char link[1024];
    link[1023] = 0;
    int result = readlink(QFile::encodeName(dir).constData(), link, 1023);
    bool relink = (result == -1) && (errno == ENOENT);
    if (result > 0)
    {
        link[result] = 0;
        if (!QDir::isRelativePath(QFile::decodeName(link)))
        {
            KDE_struct_stat stat_buf;
            int res = KDE::lstat(QFile::decodeName(link), &stat_buf);
            if ((res == -1) && (errno == ENOENT))
            {
                relink = true;
            }
            else if ((res == -1) || (!S_ISDIR(stat_buf.st_mode)))
            {
                fprintf(stderr, "Error: \"%s\" is not a directory.\n", link);
                relink = true;
            }
            else if (stat_buf.st_uid != getuid())
            {
                fprintf(stderr, "Error: \"%s\" is owned by uid %d instead of uid %d.\n", link, stat_buf.st_uid, getuid());
                relink = true;
            }
        }
    }
#ifdef Q_WS_WIN
    if (relink)
    {
        if (!makeDir(dir, 0700))
            fprintf(stderr, "failed to create \"%s\"", qPrintable(dir));
        else
            result = readlink(QFile::encodeName(dir).constData(), link, 1023);
    }
#else //UNIX
    if (relink)
    {
        QString srv = findExe(QLatin1String("lnusertemp"), installPath("libexec"));
        if (srv.isEmpty())
            srv = findExe(QLatin1String("lnusertemp"));
        if (!srv.isEmpty())
        {
            if (system(QByteArray(QFile::encodeName(srv) + ' ' + type)) == -1) {
                fprintf(stderr, "Error: unable to launch lnusertemp command" );
            }
            result = readlink(QFile::encodeName(dir).constData(), link, 1023);
        }
    }
    if (result > 0)
    {
        link[result] = 0;
        if (link[0] == '/')
            dir = QFile::decodeName(link);
        else
            dir = QDir::cleanPath(dir + QFile::decodeName(link));
    }
#endif
    q->addResourceDir(type, dir + QLatin1Char('/'), false);
}

QStringList KStandardDirs::resourceDirs(const char *type) const
{
    return d->resourceDirs(type, QString());
}

QStringList KStandardDirs::KStandardDirsPrivate::resourceDirs(const char* type, const QString& subdirForRestrictions)
{
    QMutexLocker lock(&m_cacheMutex);
    const bool dataRestrictionActive = m_restrictionsActive
                                       && (strcmp(type, "data") == 0)
                                       && hasDataRestrictions(subdirForRestrictions);

    QMap<QByteArray, QStringList>::const_iterator dirCacheIt = m_dircache.constFind(type);

    QStringList candidates;

    if (dirCacheIt != m_dircache.constEnd() && !dataRestrictionActive) {
        //qDebug() << this << "resourceDirs(" << type << "), in cache already";
        candidates = *dirCacheIt;
    }
    else // filling cache
    {
        //qDebug() << this << "resourceDirs(" << type << "), not in cache";
        if (strcmp(type, "socket") == 0)
            createSpecialResource(type);
        else if (strcmp(type, "tmp") == 0)
            createSpecialResource(type);
        else if (strcmp(type, "cache") == 0)
            createSpecialResource(type);

        QDir testdir;

        bool restrictionActive = false;
        if (m_restrictionsActive) {
            if (dataRestrictionActive)
                restrictionActive = true;
            if (m_restrictions.value("all", false))
                restrictionActive = true;
            else if (m_restrictions.value(type, false))
                restrictionActive = true;
        }

        const QStringList dirs = m_relatives.value(type);
        const QString typeInstallPath = installPath(type); // could be empty
        const QString installdir = typeInstallPath.isEmpty() ? QString() : realPath(typeInstallPath);
        const QString installprefix = installPath("kdedir");
        if (!dirs.isEmpty())
        {
            bool local = true;

            for (QStringList::ConstIterator it = dirs.constBegin();
                 it != dirs.constEnd(); ++it)
            {
                if ((*it).startsWith(QLatin1Char('%'))) {
                    // grab the "data" from "%data/apps"
                    const int pos = (*it).indexOf(QLatin1Char('/'));
                    QString rel = (*it).mid(1, pos - 1);
                    QString rest = (*it).mid(pos + 1);
                    const QStringList basedirs = resourceDirs(rel.toUtf8().constData(), subdirForRestrictions);
                    for (QStringList::ConstIterator it2 = basedirs.begin();
                         it2 != basedirs.end(); ++it2)
                    {
                        const QString path = realPath( *it2 + rest );
                        testdir.setPath(path);
                        if ((local || testdir.exists()) && !candidates.contains(path, cs))
                            candidates.append(path);
                        local = false;
                    }
                }
            }

            const QStringList *prefixList = 0;
            if (strncmp(type, "xdgdata-", 8) == 0)
                prefixList = &(xdgdata_prefixes);
            else if (strncmp(type, "xdgconf-", 8) == 0)
                prefixList = &(xdgconf_prefixes);
            else
                prefixList = &m_prefixes;

            for (QStringList::ConstIterator pit = prefixList->begin();
                 pit != prefixList->end();
                 ++pit)
            {
            if((*pit).compare(installprefix, cs) != 0 || installdir.isEmpty())
            {
                    for (QStringList::ConstIterator it = dirs.constBegin();
                         it != dirs.constEnd(); ++it)
                    {
                        if ((*it).startsWith(QLatin1Char('%')))
                            continue;
                        const QString path = realPath( *pit + *it );
                        testdir.setPath(path);
                        if (local && restrictionActive)
                            continue;
                        if ((local || testdir.exists()) && !candidates.contains(path, cs))
                            candidates.append(path);
                    }
                    // UGLY HACK - forward porting Chris CHeney's HACK - Rex Dieter
                    if ( local && (!strcmp("config", type)))  // local is used as a "homedir marker"
                        candidates.append(QLatin1String("/etc/kde4/"));
                    //
                    local = false;
                }
            else
            {
                    // we have a custom install path, so use this instead of <installprefix>/<relative dir>
                testdir.setPath(installdir);
                    if(testdir.exists() && ! candidates.contains(installdir, cs))
                        candidates.append(installdir);
            }
        }
        }

        // make sure we find the path where it's installed
        if (!installdir.isEmpty()) {
            bool ok = true;
            foreach (const QString &s, candidates) {
                if (installdir.startsWith(s, cs)) {
                    ok = false;
                    break;
                }
            }
            if (ok)
                candidates.append(installdir);
        }

        const QStringList absDirs = m_absolutes.value(type);
        for (QStringList::ConstIterator it = absDirs.constBegin();
             it != absDirs.constEnd(); ++it)
        {
            testdir.setPath(*it);
            if (testdir.exists()) {
                const QString filename = realPath( *it );
                if (!candidates.contains(filename, cs)) {
                    candidates.append(filename);
                }
            }
        }

        // Insert result into the cache for next time.
        // Exception: data_subdir restrictions are per-subdir, so we can't store such results
        if (!dataRestrictionActive) {
            //kDebug() << this << "Inserting" << type << candidates << "into dircache";
            m_dircache.insert(type, candidates);
        }
    }

#if 0
    kDebug(180) << "found dirs for resource" << type << ":" << candidates;
#endif

    return candidates;
}

#ifdef Q_OS_WIN
static QStringList executableExtensions()
{
    QStringList ret = QString::fromLocal8Bit(qgetenv("PATHEXT")).split(QLatin1Char(';'));
    if (!ret.contains(QLatin1String(".exe"), Qt::CaseInsensitive)) {
        // If %PATHEXT% does not contain .exe, it is either empty, malformed, or distorted in ways that we cannot support, anyway.
        ret.clear();
        ret << QLatin1String(".exe")
            << QLatin1String(".com")
            << QLatin1String(".bat")
            << QLatin1String(".cmd");
    }
    return ret;
}
#endif

QStringList KStandardDirs::systemPaths( const QString& pstr )
{
    QStringList tokens;
    QString p = pstr;

    if( p.isEmpty() )
    {
        p = QString::fromLocal8Bit( qgetenv( "PATH" ) );
    }

    QString delimiters(QLatin1Char(KPATH_SEPARATOR));
    delimiters += QLatin1Char('\b');
    tokenize( tokens, p, delimiters );

    QStringList exePaths;

    // split path using : or \b as delimiters
    for( int i = 0; i < tokens.count(); i++ )
    {
        exePaths << KShell::tildeExpand( tokens[ i ] );
    }

    return exePaths;
}

#ifdef Q_WS_MAC
static QString getBundle( const QString& path, bool ignore )
{
    //kDebug(180) << "getBundle(" << path << ", " << ignore << ") called";
    QFileInfo info;
    QString bundle = path;
    bundle += QLatin1String(".app/Contents/MacOS/") + bundle.section(QLatin1Char('/'), -1);
    info.setFile( bundle );
    FILE *file;
    if (file = fopen(info.absoluteFilePath().toUtf8().constData(), "r")) {
        fclose(file);
        struct stat _stat;
        if ((stat(info.absoluteFilePath().toUtf8().constData(), &_stat)) < 0) {
            return QString();
        }
        if ( ignore || (_stat.st_mode & S_IXUSR) ) {
            if ( ((_stat.st_mode & S_IFMT) == S_IFREG) || ((_stat.st_mode & S_IFMT) == S_IFLNK) ) {
                //kDebug(180) << "getBundle(): returning " << bundle;
                return bundle;
            }
        }
    }
    return QString();
}
#endif

static QString checkExecutable( const QString& path, bool ignoreExecBit )
{
#ifdef Q_WS_MAC
    QString bundle = getBundle( path, ignoreExecBit );
    if ( !bundle.isEmpty() ) {
        //kDebug(180) << "findExe(): returning " << bundle;
        return bundle;
    }
#endif
    QFileInfo info( path );
    QFileInfo orig = info;
#if defined(Q_OS_DARWIN) || defined(Q_OS_MAC)
    FILE *file;
    if (file = fopen(orig.absoluteFilePath().toUtf8().constData(), "r")) {
        fclose(file);
        struct stat _stat;
        if ((stat(orig.absoluteFilePath().toUtf8().constData(), &_stat)) < 0) {
            return QString();
        }
        if ( ignoreExecBit || (_stat.st_mode & S_IXUSR) ) {
            if ( ((_stat.st_mode & S_IFMT) == S_IFREG) || ((_stat.st_mode & S_IFMT) == S_IFLNK) ) {
                orig.makeAbsolute();
                return orig.filePath();
            }
        }
    }
    return QString();
#else
    if( info.exists() && info.isSymLink() )
        info = QFileInfo( info.canonicalFilePath() );
    if( info.exists() && ( ignoreExecBit || info.isExecutable() ) && info.isFile() ) {
        // return absolute path, but without symlinks resolved in order to prevent
        // problems with executables that work differently depending on name they are
        // run as (for example gunzip)
        orig.makeAbsolute();
        return orig.filePath();
    }
    //kDebug(180) << "checkExecutable(): failed, returning empty string";
    return QString();
#endif
}

QString KStandardDirs::findExe( const QString& appname,
                                const QString& pstr,
                                SearchOptions options )
{
    //kDebug(180) << "findExe(" << appname << ", pstr, " << ignoreExecBit << ") called";

#ifdef Q_OS_WIN
    QStringList executable_extensions = executableExtensions();
    if (!executable_extensions.contains(appname.section(QLatin1Char('.'), -1, -1, QString::SectionIncludeLeadingSep), Qt::CaseInsensitive)) {
        QString found_exe;
        foreach (const QString& extension, executable_extensions) {
            found_exe = findExe(appname + extension, pstr, options);
            if (!found_exe.isEmpty()) {
                return found_exe;
            }
        }
        return QString();
    }
#endif
    QFileInfo info;

    // absolute or relative path?
    if (appname.contains(QDir::separator()))
    {
        //kDebug(180) << "findExe(): absolute path given";
        QString path = checkExecutable(appname, options & IgnoreExecBit);
        return path;
    }

    //kDebug(180) << "findExe(): relative path given";

    QString p = installPath("libexec") + appname;
    QString result = checkExecutable(p, options & IgnoreExecBit);
    if (!result.isEmpty()) {
        //kDebug(180) << "findExe(): returning " << result;
        return result;
    }

    //kDebug(180) << "findExe(): checking system paths";
    const QStringList exePaths = systemPaths( pstr );
    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); ++it)
    {
        p = (*it) + QLatin1Char('/');
        p += appname;

        // Check for executable in this tokenized path
        result = checkExecutable(p, options & IgnoreExecBit);
        if (!result.isEmpty()) {
            //kDebug(180) << "findExe(): returning " << result;
            return result;
        }
    }

    // Not found in PATH, look into the KDE-specific bin dir ("exe" resource)
    p = installPath("exe");
    p += appname;
    result = checkExecutable(p, options & IgnoreExecBit);
    if (!result.isEmpty()) {
        //kDebug(180) << "findExe(): returning " << result;
        return result;
    }

    // If we reach here, the executable wasn't found.
    // So return empty string.

    //kDebug(180) << "findExe(): failed, nothing matched";
    return QString();
}

int KStandardDirs::findAllExe( QStringList& list, const QString& appname,
                               const QString& pstr, SearchOptions options )
{
#ifdef Q_OS_WIN
    QStringList executable_extensions = executableExtensions();
    if (!executable_extensions.contains(appname.section(QLatin1Char('.'), -1, -1, QString::SectionIncludeLeadingSep), Qt::CaseInsensitive)) {
        int total = 0;
        foreach (const QString& extension, executable_extensions) {
            total += findAllExe (list, appname + extension, pstr, options);
        }
        return total;
    }
#endif
    QFileInfo info;
    QString p;
    list.clear();

    const QStringList exePaths = systemPaths( pstr );
    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); ++it)
    {
        p = (*it) + QLatin1Char('/');
        p += appname;

#ifdef Q_WS_MAC
        QString bundle = getBundle( p, (options & IgnoreExecBit) );
        if ( !bundle.isEmpty() ) {
            //kDebug(180) << "findExe(): returning " << bundle;
            list.append( bundle );
        }
#endif

        info.setFile( p );

        if( info.exists() && ( ( options & IgnoreExecBit ) || info.isExecutable())
            && info.isFile() ) {
            list.append( p );
        }
    }

    return list.count();
}

static inline QString equalizePath(QString &str)
{
#ifdef Q_WS_WIN
    // filter pathes through QFileInfo to have always
    // the same case for drive letters
    QFileInfo f(str);
    if (f.isAbsolute())
        return f.absoluteFilePath();
    else
#endif
        return str;
}

static void tokenize(QStringList& tokens, const QString& str,
                    const QString& delim)
{
    const int len = str.length();
    QString token;

    for(int index = 0; index < len; index++) {
        if (delim.contains(str[index])) {
            tokens.append(equalizePath(token));
            token.clear();
        } else {
            token += str[index];
        }
    }
    if (!token.isEmpty()) {
        tokens.append(equalizePath(token));
    }
}

#ifndef KDE_NO_DEPRECATED
QString KStandardDirs::kde_default(const char *type)
{
    return QString(QLatin1Char('%')) + QString::fromLatin1(type) + QLatin1Char('/');
}
#endif

QString KStandardDirs::saveLocation(const char *type,
                                    const QString& suffix,
                                    bool create) const
{
    QMutexLocker lock(&d->m_cacheMutex);
    QString path = d->m_savelocations.value(type);
    if (path.isEmpty())
    {
        QStringList dirs = d->m_relatives.value(type);
        if (dirs.isEmpty() && (
                (strcmp(type, "socket") == 0) ||
                (strcmp(type, "tmp") == 0) ||
                (strcmp(type, "cache") == 0) ))
        {
            (void) resourceDirs(type); // Generate socket|tmp|cache resource.
            dirs = d->m_relatives.value(type); // Search again.
        }
        if (!dirs.isEmpty())
        {
            path = dirs.first();

            if (path.startsWith(QLatin1Char('%'))) {
                // grab the "data" from "%data/apps"
                const int pos = path.indexOf(QLatin1Char('/'));
                QString rel = path.mid(1, pos - 1);
                QString rest = path.mid(pos + 1);
                QString basepath = saveLocation(rel.toUtf8().constData());
                path = basepath + rest;
            } else

                // Check for existence of typed directory + suffix
                if (strncmp(type, "xdgdata-", 8) == 0) {
                    path = realPath( localxdgdatadir() + path ) ;
                } else if (strncmp(type, "xdgconf-", 8) == 0) {
                    path = realPath( localxdgconfdir() + path );
                } else {
                    path = realPath( localkdedir() + path );
                }
        }
        else {
            dirs = d->m_absolutes.value(type);
            if (dirs.isEmpty()) {
                qFatal("KStandardDirs: The resource type %s is not registered", type);
            } else {
                path = realPath(dirs.first());
            }
        }

        d->m_savelocations.insert(type, path.endsWith(QLatin1Char('/')) ? path : path + QLatin1Char('/'));
    }
    QString fullPath = path + suffix;

    KDE_struct_stat st;
    if (KDE::stat(fullPath, &st) != 0 || !(S_ISDIR(st.st_mode))) {
        if(!create) {
#ifndef NDEBUG
            // Too much noise from kbuildsycoca4 -- it's fine if this happens from KConfig
            // when parsing global files without a local equivalent.
            //kDebug(180) << QString("save location %1 doesn't exist").arg(fullPath);
#endif
            return fullPath;
        }
        if(!makeDir(fullPath, 0700)) {
            return fullPath;
        }
        d->m_dircache.remove(type);
    }
    if (!fullPath.endsWith(QLatin1Char('/')))
        fullPath += QLatin1Char('/');
    return fullPath;
}

// KDE5: make the method const
QString KStandardDirs::relativeLocation(const char *type, const QString &absPath)
{
    QString fullPath = absPath;
    int i = absPath.lastIndexOf(QLatin1Char('/'));
    if (i != -1) {
        fullPath = realFilePath(absPath); // Normalize
    }

    const QStringList candidates = resourceDirs(type);

    for (QStringList::ConstIterator it = candidates.begin();
         it != candidates.end(); ++it) {
        if (fullPath.startsWith(*it, cs)) {
            return fullPath.mid((*it).length());
        }
    }
    return absPath;
}


bool KStandardDirs::makeDir(const QString& dir, int mode)
{
    // we want an absolute path
    if (QDir::isRelativePath(dir))
        return false;

#ifdef Q_WS_WIN
    return QDir().mkpath(dir);
#else
    QString target = dir;
    uint len = target.length();

    // append trailing slash if missing
    if (dir.at(len - 1) != QLatin1Char('/'))
        target += QLatin1Char('/');

    QString base;
    uint i = 1;

    while( i < len )
    {
        KDE_struct_stat st;
        int pos = target.indexOf(QLatin1Char('/'), i);
        base += target.mid(i - 1, pos - i + 1);
        QByteArray baseEncoded = QFile::encodeName(base);
        // bail out if we encountered a problem
        if (KDE_stat(baseEncoded, &st) != 0)
        {
            // Directory does not exist....
            // Or maybe a dangling symlink ?
            if (KDE_lstat(baseEncoded, &st) == 0)
                (void)unlink(baseEncoded); // try removing

            if (KDE_mkdir(baseEncoded, static_cast<mode_t>(mode)) != 0) {
                baseEncoded.prepend( "trying to create local folder " );
                perror(baseEncoded.constData());
                return false; // Couldn't create it :-(
            }
        }
        i = pos + 1;
    }
    return true;
#endif
}

static QString readEnvPath(const char *env)
{
    QByteArray c_path;
#ifndef _WIN32_WCE
    c_path = qgetenv(env);
    if (c_path.isEmpty())
        return QString();
#else
    bool ok;
    QString retval = getWin32RegistryValue(HKEY_LOCAL_MACHINE, "Software\\kde", "KDEDIRS", &ok);
    if (!ok){
        return QString();
    } else {
        c_path = retval.toLatin1();
    }
#endif
    return QDir::fromNativeSeparators(QFile::decodeName(c_path));
}

#ifdef __linux__
static QString executablePrefix()
{
    char path_buffer[MAXPATHLEN + 1];
    path_buffer[MAXPATHLEN] = 0;
    int length = readlink ("/proc/self/exe", path_buffer, MAXPATHLEN);
    if (length == -1)
        return QString();

    path_buffer[length] = '\0';

    QString path = QFile::decodeName(path_buffer);

    if(path.isEmpty())
        return QString();

    int pos = path.lastIndexOf(QLatin1Char('/')); // Skip filename
    if(pos <= 0)
        return QString();
    pos = path.lastIndexOf(QLatin1Char('/'), pos - 1); // Skip last directory
    if(pos <= 0)
        return QString();

    return path.left(pos);
}
#endif

void KStandardDirs::addResourcesFrom_krcdirs()
{
    QString localFile = QDir::currentPath() + QLatin1String("/.krcdirs");
    if (!QFile::exists(localFile))
        return;

    QSettings iniFile(localFile, QSettings::IniFormat);
    iniFile.beginGroup(QString::fromLatin1("KStandardDirs"));
    const QStringList resources = iniFile.allKeys();
    foreach(const QString &key, resources)
    {
        QDir path(iniFile.value(key).toString());
        if (!path.exists())
            continue;

        if(path.makeAbsolute())
            addResourceDir(key.toLatin1(), path.path(), false);
    }
}

void KStandardDirs::addKDEDefaults()
{
    addResourcesFrom_krcdirs();

    QStringList kdedirList;
    // begin KDEDIRS
    QString kdedirs = readEnvPath("KDEDIRS");

    if (!kdedirs.isEmpty())
    {
        tokenize(kdedirList, kdedirs, QString(QLatin1Char(KPATH_SEPARATOR)));
    }
    kdedirList.append(installPath("kdedir"));

    QString execPrefix(QFile::decodeName(EXEC_INSTALL_PREFIX));
    if (!execPrefix.isEmpty() && !kdedirList.contains(execPrefix, cs))
        kdedirList.append(execPrefix);
#ifdef __linux__
    const QString linuxExecPrefix = executablePrefix();
    if ( !linuxExecPrefix.isEmpty() )
        kdedirList.append( linuxExecPrefix );
#endif

    // We treat root differently to prevent a "su" shell messing up the
    // file permissions in the user's home directory.
    QString localKdeDir = readEnvPath(getuid() ? "KDEHOME" : "KDEROOTHOME");
    if (!localKdeDir.isEmpty()) {
        if (!localKdeDir.endsWith(QLatin1Char('/')))
            localKdeDir += QLatin1Char('/');
    } else {
        // TODO KDE5: make localKdeDir equal to localXdgDir (which is determined further below and
        // defaults to ~/.config) + '/' + $KDECONFIG (which would default to e.g. "KDE")
        // This would mean ~/.config/KDE/ by default, more xdg-compliant.

#if defined(Q_WS_MACX)
        localKdeDir =  QDir::homePath() + QLatin1String("/Library/Preferences/KDE/");
#elif defined(Q_WS_WIN)
#ifndef _WIN32_WCE
        WCHAR wPath[MAX_PATH+1];
        if ( SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, wPath) == S_OK) {
          localKdeDir = QDir::fromNativeSeparators(QString::fromUtf16((const ushort *) wPath)) + QLatin1Char('/') + QString::fromLatin1(KDE_DEFAULT_HOME) + QLatin1Char('/');
        } else {
#endif
          localKdeDir =  QDir::homePath() + QLatin1Char('/') + QString::fromLatin1(KDE_DEFAULT_HOME) + QLatin1Char('/');
#ifndef _WIN32_WCE
        }
#endif
#else
        localKdeDir =  QDir::homePath() + QLatin1Char('/') + QString::fromLatin1(KDE_DEFAULT_HOME) + QLatin1Char('/');
#endif
    }

    if (localKdeDir != QLatin1String("-/"))
    {
        localKdeDir = KShell::tildeExpand(localKdeDir);
        addPrefix(localKdeDir);
    }

#ifdef Q_WS_MACX
    // Adds the "Contents" directory of the current application bundle to
    // the search path. This way bundled resources can be found.
    QDir bundleDir(mac_app_filename());
    if (bundleDir.dirName() == QLatin1String("MacOS")) { // just to be sure we're in a bundle
        bundleDir.cdUp();
        // now dirName should be "Contents". In there we can find our normal
        // dir-structure, beginning with "share"
        addPrefix(bundleDir.absolutePath());
    }
#endif

    QStringList::ConstIterator end(kdedirList.end());
    for (QStringList::ConstIterator it = kdedirList.constBegin();
         it != kdedirList.constEnd(); ++it)
    {
        const QString dir = KShell::tildeExpand(*it);
        addPrefix(dir);
    }
    // end KDEDIRS

    // begin XDG_CONFIG_XXX
    QStringList xdgdirList;
    QString xdgdirs = readEnvPath("XDG_CONFIG_DIRS");
    if (!xdgdirs.isEmpty())
    {
        tokenize(xdgdirList, xdgdirs, QString(QLatin1Char(KPATH_SEPARATOR)));
    }
    else
    {
        xdgdirList.clear();
        xdgdirList.append(QString::fromLatin1("/etc/xdg"));
#ifdef Q_WS_WIN
        xdgdirList.append(installPath("kdedir") + QString::fromLatin1("etc/xdg"));
#else
        xdgdirList.append(QFile::decodeName(KDESYSCONFDIR "/xdg"));
#endif
    }

    QString localXdgDir = readEnvPath("XDG_CONFIG_HOME");
    if (!localXdgDir.isEmpty()) {
        if (!localXdgDir.endsWith(QLatin1Char('/')))
            localXdgDir += QLatin1Char('/');
    } else {
#ifdef Q_WS_MACX
        localXdgDir = QDir::homePath() + QString::fromLatin1("/Library/Preferences/XDG/");
#else
        localXdgDir = QDir::homePath() + QString::fromLatin1("/.config/");
#endif
    }

    localXdgDir = KShell::tildeExpand(localXdgDir);
    addXdgConfigPrefix(localXdgDir);

    for (QStringList::ConstIterator it = xdgdirList.constBegin();
         it != xdgdirList.constEnd(); ++it)
    {
        QString dir = KShell::tildeExpand(*it);
        addXdgConfigPrefix(dir);
    }
    // end XDG_CONFIG_XXX

    // begin XDG_DATA_XXX
    QStringList kdedirDataDirs;
    for (QStringList::ConstIterator it = kdedirList.constBegin();
         it != kdedirList.constEnd(); ++it) {
        QString dir = *it;
        if (!dir.endsWith(QLatin1Char('/')))
            dir += QLatin1Char('/');
        kdedirDataDirs.append(dir + QLatin1String("share/"));
    }

    xdgdirs = readEnvPath("XDG_DATA_DIRS");
    if (!xdgdirs.isEmpty()) {
        tokenize(xdgdirList, xdgdirs, QString(QLatin1Char(KPATH_SEPARATOR)));
        // Ensure the kdedirDataDirs are in there too,
        // otherwise resourceDirs() will add kdedir/share/applications/kde4
        // as returned by installPath(), and that's incorrect.
        Q_FOREACH(const QString& dir, kdedirDataDirs) {
            if (!xdgdirList.contains(dir, cs))
                xdgdirList.append(dir);
        }
    } else {
        xdgdirList = kdedirDataDirs;
#ifndef Q_WS_WIN
        xdgdirList.append(QString::fromLatin1("/usr/local/share/"));
        xdgdirList.append(QString::fromLatin1("/usr/share/"));
#endif
    }

    localXdgDir = readEnvPath("XDG_DATA_HOME");
    if (!localXdgDir.isEmpty())
    {
        if (localXdgDir[localXdgDir.length()-1] != QLatin1Char('/'))
            localXdgDir += QLatin1Char('/');
    }
    else
    {
        localXdgDir = QDir::homePath() + QLatin1String("/.local/share/");
    }

    localXdgDir = KShell::tildeExpand(localXdgDir);
    addXdgDataPrefix(localXdgDir);

    for (QStringList::ConstIterator it = xdgdirList.constBegin();
         it != xdgdirList.constEnd(); ++it)
    {
        QString dir = KShell::tildeExpand(*it);
        addXdgDataPrefix(dir);
    }
    // end XDG_DATA_XXX


    addResourceType("lib", 0, "lib" KDELIBSUFF "/");

    addResourceType("qtplugins", "lib", "plugins");

    uint index = 0;
    while (types_indices[index] != -1) {
        addResourceType(types_string + types_indices[index], 0, types_string + types_indices[index+1], true);
        index+=2;
    }
    addResourceType("exe", "lib", "kde4/libexec", true );

    addResourceDir("home", QDir::homePath(), false);

    addResourceType("autostart", "xdgconf-autostart", "/"); // merge them, start with xdg autostart
    addResourceType("autostart", NULL, "share/autostart"); // KDE ones are higher priority
}

static QStringList lookupProfiles(const QString &mapFile)
{
    QStringList profiles;

    if (mapFile.isEmpty() || !QFile::exists(mapFile))
    {
        profiles << QString::fromLatin1("default");
        return profiles;
    }

    struct passwd *pw = getpwuid(geteuid());
    if (!pw)
    {
        profiles << QString::fromLatin1("default");
        return profiles; // Not good
    }

    QByteArray user = pw->pw_name;

    gid_t sup_gids[512];
    int sup_gids_nr = getgroups(512, sup_gids);

    KConfig mapCfgFile(mapFile);
    KConfigGroup mapCfg(&mapCfgFile, "Users");
    if (mapCfg.hasKey(user.constData()))
    {
        profiles = mapCfg.readEntry(user.constData(), QStringList());
        return profiles;
    }

    const KConfigGroup generalGrp(&mapCfgFile, "General");
    const QStringList groups = generalGrp.readEntry("groups", QStringList());

    const KConfigGroup groupsGrp(&mapCfgFile, "Groups");

    for( QStringList::ConstIterator it = groups.begin();
         it != groups.end(); ++it )
    {
        QByteArray grp = (*it).toUtf8();
        // Check if user is in this group
        struct group *grp_ent = getgrnam(grp);
        if (!grp_ent) continue;
        gid_t gid = grp_ent->gr_gid;
        if (pw->pw_gid == gid)
        {
            // User is in this group --> add profiles
            profiles += groupsGrp.readEntry(*it, QStringList());
        }
        else
        {
            for(int i = 0; i < sup_gids_nr; i++)
            {
                if (sup_gids[i] == gid)
                {
                    // User is in this group --> add profiles
                    profiles += groupsGrp.readEntry(*it, QStringList());
                    break;
                }
            }
        }
    }

    if (profiles.isEmpty())
        profiles << QString::fromLatin1("default");
    return profiles;
}

extern bool kde_kiosk_admin;

bool KStandardDirs::addCustomized(KConfig *config)
{
    if (!d->m_checkRestrictions) // there are already customized entries
        return false; // we just quit and hope they are the right ones

    // save the numbers of config directories. If this changes,
    // we will return true to give KConfig a chance to reparse
    int configdirs = resourceDirs("config").count();

    if (true)
    {
        // reading the prefixes in
        QString group = QLatin1String("Directories");
        KConfigGroup cg(config, group);

        QString kioskAdmin = cg.readEntry("kioskAdmin");
        if (!kioskAdmin.isEmpty() && !kde_kiosk_admin)
        {
            int i = kioskAdmin.indexOf(QLatin1Char(':'));
            QString user = kioskAdmin.left(i);
            QString host = kioskAdmin.mid(i+1);

            KUser thisUser;
            char hostname[ 256 ];
            hostname[ 0 ] = '\0';
            if (!gethostname( hostname, 255 ))
                hostname[sizeof(hostname)-1] = '\0';

            if ((user == thisUser.loginName()) &&
                (host.isEmpty() || (host == QLatin1String(hostname))))
            {
                kde_kiosk_admin = true;
            }
        }

        bool readProfiles = true;

        if (kde_kiosk_admin && !qgetenv("KDE_KIOSK_NO_PROFILES").isEmpty())
            readProfiles = false;

        QString userMapFile = cg.readEntry("userProfileMapFile");
        QString profileDirsPrefix = cg.readEntry("profileDirsPrefix");
        if (!profileDirsPrefix.isEmpty() && !profileDirsPrefix.endsWith(QLatin1Char('/')))
            profileDirsPrefix.append(QLatin1Char('/'));

        QStringList profiles;
        if (readProfiles)
            profiles = lookupProfiles(userMapFile);
        QString profile;

        bool priority = false;
        while(true)
        {
            KConfigGroup cg(config, group);
            const QStringList list = cg.readEntry("prefixes", QStringList());
            for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
            {
                addPrefix(*it, priority);
                addXdgConfigPrefix(*it + QLatin1String("/etc/xdg"), priority);
                addXdgDataPrefix(*it + QLatin1String("/share"), priority);
            }
            // If there are no prefixes defined, check if there is a directory
            // for this profile under <profileDirsPrefix>
            if (list.isEmpty() && !profile.isEmpty() && !profileDirsPrefix.isEmpty())
            {
                QString dir = profileDirsPrefix + profile;
                addPrefix(dir, priority);
                addXdgConfigPrefix(dir + QLatin1String("/etc/xdg"), priority);
                addXdgDataPrefix(dir + QLatin1String("/share"), priority);
            }

            // iterating over all entries in the group Directories
            // to find entries that start with dir_$type
            const QMap<QString, QString> entries = config->entryMap(group);
            for (QMap<QString, QString>::ConstIterator it2 = entries.begin();
                 it2 != entries.end(); ++it2)
            {
                const QString key = it2.key();
                if (key.startsWith(QLatin1String("dir_"))) {
                    // generate directory list, there may be more than 1.
                    const QStringList dirs = (*it2).split(QString(QLatin1Char(',')));
                    QStringList::ConstIterator sIt(dirs.begin());
                    QString resType = key.mid(4);
                    for (; sIt != dirs.end(); ++sIt)
                    {
                        addResourceDir(resType.toLatin1(), *sIt, priority);
                    }
                }
            }
            if (profiles.isEmpty())
                break;
            profile = profiles.back();
            group = QString::fromLatin1("Directories-%1").arg(profile);
            profiles.pop_back();
            priority = true;
        }
    }

    // Process KIOSK restrictions.
    if (!kde_kiosk_admin || qgetenv("KDE_KIOSK_NO_RESTRICTIONS").isEmpty())
    {
        KConfigGroup cg(config, "KDE Resource Restrictions");
        const QMap<QString, QString> entries = cg.entryMap();
        for (QMap<QString, QString>::ConstIterator it2 = entries.begin();
             it2 != entries.end(); ++it2)
        {
            const QString key = it2.key();
            if (!cg.readEntry(key, true))
            {
                d->m_restrictionsActive = true;
                const QByteArray cKey = key.toLatin1();
                d->m_restrictions.insert(cKey, true);
                d->m_dircache.remove(cKey);
                d->m_savelocations.remove(cKey);
            }
        }
    }

    // check if the number of config dirs changed
    bool configDirsChanged = (resourceDirs("config").count() != configdirs);
    // If the config dirs changed, we check kiosk restrictions again.
    d->m_checkRestrictions = configDirsChanged;
    // return true if the number of config dirs changed: reparse config file
    return configDirsChanged;
}

QString KStandardDirs::localkdedir() const
{
    // Return the prefix to use for saving
    return d->m_prefixes.first();
}

QString KStandardDirs::localxdgdatadir() const
{
    // Return the prefix to use for saving
    return d->xdgdata_prefixes.first();
}

QString KStandardDirs::localxdgconfdir() const
{
    // Return the prefix to use for saving
    return d->xdgconf_prefixes.first();
}


// just to make code more readable without macros
QString KStandardDirs::locate( const char *type,
                               const QString& filename, const KComponentData &cData)
{
    return cData.dirs()->findResource(type, filename);
}

QString KStandardDirs::locateLocal( const char *type,
                                    const QString& filename, const KComponentData &cData)
{
    return locateLocal(type, filename, true, cData);
}

QString KStandardDirs::locateLocal( const char *type,
                                    const QString& filename, bool createDir,
                                    const KComponentData &cData)
{
    // try to find slashes. If there are some, we have to
    // create the subdir first
    int slash = filename.lastIndexOf(QLatin1Char('/')) + 1;
    if (!slash) { // only one filename
        return cData.dirs()->saveLocation(type, QString(), createDir) + filename;
    }

    // split path from filename
    QString dir = filename.left(slash);
    QString file = filename.mid(slash);
    return cData.dirs()->saveLocation(type, dir, createDir) + file;
}

bool KStandardDirs::checkAccess(const QString& pathname, int mode)
{
    int accessOK = KDE::access( pathname, mode );
    if ( accessOK == 0 )
        return true;  // OK, I can really access the file

    // else
    // if we want to write the file would be created. Check, if the
    // user may write to the directory to create the file.
    if ( (mode & W_OK) == 0 )
        return false;   // Check for write access is not part of mode => bail out


    if (!KDE::access( pathname, F_OK)) // if it already exists
        return false;

    //strip the filename (everything until '/' from the end
    QString dirName(pathname);
    int pos = dirName.lastIndexOf(QLatin1Char('/'));
    if ( pos == -1 )
        return false;   // No path in argument. This is evil, we won't allow this
    else if ( pos == 0 ) // don't turn e.g. /root into an empty string
        pos = 1;

    dirName.truncate(pos); // strip everything starting from the last '/'

    accessOK = KDE::access( dirName, W_OK );
    // -?- Can I write to the accessed diretory
    if ( accessOK == 0 )
        return true;  // Yes
    else
        return false; // No
}